我正试图在控制器的视图中设置一个变量,如下所示:
这是用户/添加操作
public function add() {
if ($this->request->is('post')) {
$usertype = $this->User->Usertypes->find('list', array('fields' => array('id', 'description')));
$this->set('usertype', $usertype);
$this->User->create();
if ($this->User->save($this->request->data)) {
$this->Session->setFlash(__('The user has been saved.'));
return $this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash(__('The user could not be saved. Please, try again.'));
}
}
}
使用Debugger :: dump($ usertype)时;我明白了
array( (int) 1 => 'Staff', (int) 2 => 'Administrator', (int) 3 => 'Coordinator' )
所以$ usertype肯定是正确设置的。在我的视图中找到/View/Users/add.ctp我试图像这样访问变量:
这是查看/用户/ add.ctp
<div class="users form">
<?php echo $this->Form->create('User'); ?>
<fieldset>
<legend><?php echo __('Add User'); ?></legend>
<?php
echo $this->Form->input('firstName');
echo $this->Form->input('lastName');
echo $this->Form->input('email');
echo $this->Form->input('password');
echo $this->Form->input('usertypes_id',array('options'=>$usertype));
?>
</fieldset>
<?php echo $this->Form->end(__('Submit')); ?>
</div>
但是我收到错误“Undefined variable:usertype [APP / View / Users / add.ctp,line 10]”
我对CakePHP比较陌生,我在这里做错了什么?
答案 0 :(得分:2)
您必须将变量设置在if
之外(之前或之后),否则设置变量,然后重定向到另一页
答案 1 :(得分:0)
你在内部设置变量$ usertype,这意味着当请求是POST时,但是当你点击url请求类型时默认是GET。