mauzilla
mauzilla

Reputation: 3592

cakePHP assign selected values from 2 arrays using the html input helper

I create 2 arrays from a model, 1 being already selected values from the user, and the 2nd available values which the user can then also select. This is for an edit page. I want to populate a multi-select input box with the values of both models, but want the already chosen values (1st array) highlighted. It creates the models fine, and using array_merge() I merge both the arrays as the options, but the selected does not highlight the correct fields. Any tips?

 // Controller:
 $ivrNumbersAvail = $this->Survey->SurveyIvrNumber->find("list",array("conditions" => array("OR" => array("SurveyIvrNumber.survey_id" => array($id)))));
 $ivrNumbersSelected = $this->Survey->SurveyIvrNumber->find("list",array("conditions" => array("OR" => array("SurveyIvrNumber.survey_id" => array(0)))));

 // In the view:
 echo $this->Form->input('SurveyIvrNumbers.id',array(
                            'empty' => '-- Select IVR Number(s) --',
                            'options' => array_merge($ivrNumbersAvail,$ivrNumbersSelected),
                            'selected' => $ivrNumbersSelected,
            'class' => 'textbox',
                            'multiple' => true,
            'div' => array(
                    'class' => 'field'
            ),
                'label' => array(
                'class' => 'label-tooltip',
                'title' => '', //tool tips
                'text' => 'IVR Numbers: (you can select multiple numbers)'

                ),
                'after' => '<p class="field-help"></p>'
        ));

Upvotes: 0

Views: 620

Answers (1)

Dunhamzzz
Dunhamzzz

Reputation: 14798

If you set $this->request->data to the record you are currently editing CakePHP will automatically populate this data for you!

// CONTROLLER
// this line sets the data
$this->request->data = $this->Survey->read(null, $id); 

// this passes the SurveyIvrNumbers to the view, (you can put any options on to this)
$this->set('SurveyIvrNumber',$this->Survey->SurveyIvrNumber->find('all')); 

// VIEW
// CakePHP does the rest
echo $this->Form->input('SurveyIvrNumbers',array( 
    'empty' => '-- Select IVR Number(s) --', // plus other options
);

Upvotes: 1

Related Questions