2017-09-06 8 views
0

在我的頭版我想要一個帶有「查找成員」按鈕的搜索字段。如果存在輸入名稱的成員,則按下按鈕應重定向至/users/view/N,其中N是用戶id。如果沒有 - 閃存消息Could not find user with username %s', $username.我有一個表用戶idusername如果輸入的用戶名存在,則輸出爲/ users/view /#的搜索字段。 CakePHP 3.5中需要控制器操作嗎?

我嘗試這樣做:

$this->Html->link((h($user->username)), ['controller' => 'Users','action' => 'view', $user->id]) 

$user = $this->Users->newEntity(); 
    if ($this->request->is('post') 
     $username = trim($this->request->getData('User.username')); 
$user = $this->Users->find()->where(['Users.username LIKE ', $username . '%'])->select(['Users.id', 'Users.username'])->first()); 
if ($user instanceof \Cake\ORM\Entity) { return $this->redirect(['action' => 'view', 'id' => $user->username]); } 
else { $this->Flash->warning(sprintf('Could not find user with username %s', $username)); } 

    $this->set(compact('user')); 
$this->Form->create($user) 

所有模板,無需使用控制器。沒有工作。如果控制器是必要的,那麼應該去那裏?

回答

0

這應該工作:

<div class="search"> 
    <?= $this->Form->create(null) ?> 
    <?= $this->Form->input('username') ?> 
    <?= $this->Form->button('Search') ?> 
    <?= $this->Form->end() ?> 
</div> 

然後在相應的控制器

if ($this->request->is('post')) { 
     $username = $this->request->getData('username'); 

     $user = $this->Users->find()->where(['username' => $username])->first(); 
      if ($user) { 
       $this->Flash->success(__('The user is found.')); 

       return $this->redirect(['action' => 'view', $user->id]); 
      } 
      $this->Flash->error(__('This user does not exist.')); 

     } 

得益於CakePHP的論壇的傢伙。

相關問題