CakePHP multiple select “selected” is not working

橙三吉。 提交于 2019-12-06 18:58:35

问题


I have a multiple select input in my edit form:-

<?php echo $this->Form->input('Article.tags', array('type' => 'select', 'multiple' => true, 'options' => $tags, 'selected' => array($selected))); ?>

When echo-ed, the $selected variable will look like this:-

"MySQL", "PHP"

However, the input does not automatically select the option that matches the tag.

However, when I manually put in the selected option, it will automatically select that two option; e.g.

<?php echo $this->Form->input('Article.tags', array('type' => 'select', 'multiple' => true, 'options' => $tags, 'selected' => array("MySQL", "PHP"))); ?>

Is there anyway to fix this? Thanks.


回答1:


Ahh, I got this fixed.

I was looking at the wrong direction. I assumed that the selected values should be in string form with quotes and comma separated. (e.g. "MySQL", "PHP", "jQuery").

Instead, it should be in array format without any quote and comma. e.g.

Array
(
    [0] => MySQL
    [1] => PHP
    [2] => jQuery
)

Once I've got the array sorted out I pass it into view; e.g. $this->set('selected', $myArray);

Then on the form, I would just have to echo it out like this:-

<?php echo $this->Form->input('Article.tags', array('type' => 'select', 'multiple' => true, 'options' => $tags, 'selected' => $selected)); ?>



回答2:


Use default keyword:

<?php echo $this->Form->input('Article.tags',array('options'=>$tags,'type'=>'select','label'=>'TDSP','class'=>'distributeSelect','multiple'=> 'true','default' => $selected));?>



回答3:


In CakePHP 3.x version, You can set value to preselect from the lists

echo $this->Form->select(
    'Article.tags',
    ['PHP','MySQL','jQuery','AJAX'],
    [
        'multiple' => true,
        'value' => ['MySQL','AJAX']
    ]
);

HTML elements with values MySQL and AJAX will be rendered as preselected




回答4:


No need to do selected attribute

For e.g:

in controller:

$this->request->data = $this->Article->read(null, $id);

$this->set(array(
        'centers' => $this->Center->find('list'),
        'shopCategories' => $this->ShopCategory->find('list'),
        'brands' => $this->Brand->find('list')
    ));

in view:

echo $this->Form->input('Center', array('multiple' => 'multiple')); 

that's all!




回答5:


cake php is totaly based on naming convention and array formating..

try to do like this:-

<?php echo $this->Form->input('Article.tags',array('options'=>$tags,'type'=>'select','label'=>'TDSP','class'=>'distributeSelect','multiple'=> 'true','selected' => $selected));?>


来源:https://stackoverflow.com/questions/10243537/cakephp-multiple-select-selected-is-not-working

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!