cakePHP 使用 html 输入助手从 2 个数组中分配选定的值


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

我从模型中创建 2 个数组,其中 1 个是用户已经选择的值,第二个可用值是用户也可以选择的。这适用于编辑页面。我想用两个模型的值填充多选输入框,但希望突出显示已选择的值(第一个数组)。它很好地创建了模型,并且使用 array_merge() 合并了两个数组作为选项,但所选字段没有突出显示正确的字段。有什么提示吗?

 // 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>'
        ));

如果您将$this->request->data设置为您当前正在编辑的记录,CakePHP 将自动为您填充此数据!

// 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
);