maaz
maaz

Reputation: 3664

Cakephp FormHelper Create select box

i am cakephp beginner.

My Employee Model,

         class Employee extends AppModel {
            var $belongsTo = array(
                'Department'=>array(
                'className'=>'Department',
                'foreignKey'=>'department_id',
                'conditions'=>null,
                'fields'=>null
               )
         );
          blah--

now in employee add.ctp i want to create a select box which list all the department. i was going through official cakephp 2.1 documentation (here) it tells me to add

  $this->set('departments', $this->Employee->Department->find('list')); 

in my controller..

i have no idea to put in which controller ? is it in EmployeesController or DepartmentsController? and in which action of controller?

view to create select box (in add.ctp)

         echo $this->Form->input('Department');

Upvotes: 1

Views: 3058

Answers (1)

mark
mark

Reputation: 21743

you were almost correct - only a minor glitch:

echo $this->Form->input('department_id');

you need to name the fields as they are in the database. and if it is a BelongsTo relation than there should be a department_id foreign key in your employees table.

PS: cake knows that if you pass down $departments that this array will need to be the options for this form field. so no additional configuration necessary!

// in your add action at the very bottom
$departments = $this->Employee->Department->find('list');
$this->set(compact('departments')); 

Upvotes: 4

Related Questions