如果输入的用户名存在,则搜索字段输出到 /users/view/#。 CakePHP 3.5 中是否需要控制器操作?
Search field with output to /users/view/# if the entered user name exists. Is controller action necessary in CakePHP 3.5?
在我的首页上,我想要一个带有按钮 "Find member" 的搜索字段。如果输入名称的成员存在,按下按钮将重定向到 /users/view/N
,其中 N 是用户 id
。如果不是 - 即时消息 Could not find user with username %s', $username.
我有 table 个用户 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)
全部在模板中,不使用控制器。没有任何效果。如果需要控制器,应该放什么?
这应该有效:
<div class="search">
<?= $this->Form->create(null) ?>
<?= $this->Form->input('username') ?>
<?= $this->Form->button('Search') ?>
<?= $this->Form->end() ?>
</div>
然后在对应的controller中
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 论坛的各位。
在我的首页上,我想要一个带有按钮 "Find member" 的搜索字段。如果输入名称的成员存在,按下按钮将重定向到 /users/view/N
,其中 N 是用户 id
。如果不是 - 即时消息 Could not find user with username %s', $username.
我有 table 个用户 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)
全部在模板中,不使用控制器。没有任何效果。如果需要控制器,应该放什么?
这应该有效:
<div class="search">
<?= $this->Form->create(null) ?>
<?= $this->Form->input('username') ?>
<?= $this->Form->button('Search') ?>
<?= $this->Form->end() ?>
</div>
然后在对应的controller中
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 论坛的各位。