在我的首页上,我想要一个带有按钮的搜索字段"查找成员"。如果存在具有输入名称的成员,则按下该按钮应重定向到/users/view/N
,其中N是用户id
。如果不是 - flash消息Could not find user with username %s', $username.
我有一个用户id
和username
。
我试过了:
$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 :(得分: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论坛的人们。