Reputation: 770
I'm trying to set a variable in the view for my controller as so:
This is Users/add action
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.'));
}
}
}
When using Debugger::dump($usertype); I get this
array( (int) 1 => 'Staff', (int) 2 => 'Administrator', (int) 3 => 'Coordinator' )
So $usertype is definitely set correctly. In my view found at /View/Users/add.ctp I attempt to access to variable like so:
This is View/Users/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>
However I get an error "Undefined variable: usertype [APP/View/Users/add.ctp, line 10]"
I'm relatively new to CakePHP, I am doing something wrong here?
Upvotes: 0
Views: 3962
Reputation: 912
you are setting variable $usertype inside if, it means when request is POST but when you hit url request type is by default is GET.
Upvotes: 0
Reputation: 9398
you have to set your variable outside the if
(before or after) otherwise the variable is set, bu then you are redirected to another page
Upvotes: 2