编辑表单时填充Zend多选框

4

我有一个Zend表单中的多选框(兴趣爱好),在添加用户时我会从中选择多个选项。

现在当我编辑此用户时,我需要默认设置一些选项为已选状态(这些选项是我在添加用户时选择的)。

我该如何实现这个功能?我在控制器的更新操作中使用了populate(Array),但它不起作用。

以下是用户添加/编辑表单中多选框的代码:

$interests = new Zend_Form_Element_Multiselect('interest');
$days->setLabel('Interests')
->addMultiOptions($user_interests)
->setRequired(true)
->addValidator('NotEmpty');

在表单中添加“兴趣”选项时,$user_interests数组为:

array(1=>'Blogging', 2=>'Swimming', 3=>'Cricket', 4=>'Yoga')

在添加用户时,我已经选择了前两个兴趣爱好。

现在在编辑时,我从数据库查询中获取用户数据。这个数据数组用于填充表单,其结构如下:

Array ( 
[username] => john 
[user_dob] => 1981-03-12 
[email] => john@gmail.com 
[interest] => Array ( [0] => 1 [1] => 2 ) 
)

如您所见,在我的编辑表单中,应该选择“博客”和“游泳”这两个兴趣爱好。但我发现只有“游泳”选项被选中了。


你正在填充的数据数组中是否包含 interest 键? - Vika
是的,它包含“interest”关键字。请查看我的更新问题。 - shasi kanth
3个回答

6
$interest_data = $users->getUserInterests($id);

 foreach($interest_data as $r)
 {
   $interests[$r['interest_id']] = $r['interest'];
 }

 $this->view->interests_selected = $interests;

接下来我们可以在控制器中像这样使用

$form->interest_id->setValue($interests);

希望这能帮助到某些人。

$form->interest->setValue($interests); - Sathish Kumar Balan

1

在这种情况下测试的最佳方法是使用选择的元素提交表单,转储$form->getValues()数组并将其与您要填充的内容进行比较。如果相同,则您的代码可能存在其他错误。


提交表单后,我得到的 $form->getValues() 是一个数组,其中键是表单元素名称,但值为 null。但我正在尝试填充的数组形式为:Array ( [0] => 1 [1] => 2 ),但只有最后一个选项(游泳)被选中 - shasi kanth
我的意思是:根据你的需求设置值(例如勾选所需的复选框),然后提交表单并转储带有填充数据的结果(= $_POST)。然后这些值不应该为空,而是应该显示你应该将什么作为$data数组发布到populate()方法。 - Tomáš Fejfar

0

嗯,我在使用jquery和javascript的帮助下找到了一个解决方案。

首先,在我的控制器中,我查询了数据库并获取了正在编辑的用户ID的所有兴趣。然后,我将这个数组分配给相应的视图:

$interest_data = $users->getUserInterests($id);

foreach($interest_data as $r)
{
 $interests[$r['interest_id']] = $r['interest'];
}

$this->view->interests_selected = $interests;

现在在视图中,在文件的顶部,jquery的文档就绪函数内部,我将分配的php数组转换为javascript数组,然后循环遍历该数组,以标记所有选项中选择的选项:

<script>
$(document).ready(function() {

<?php
// array of assigned interests to user
$arr = $this->interests_selected;
?>

// convert from php to js array
var jsArray = ["<?php echo join("\", \"", $arr); ?>"];

var optionsToSelect = jsArray;
var select = document.getElementById( 'interest_id' ); // interests dropdown

// loop through all the select box options and mark those in the jsArray as selected

for ( var i = 0, l = select.options.length, o; i < l; i++ )
{
  o = select.options[i];
  if ( optionsToSelect.indexOf( o.text ) != -1 )
  {
    o.selected = true;
  }
}

});
</script>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接