【问题标题】:Populate a zend multiselect box while editing form在编辑表单时填充 zend 多选框
【发布时间】:2011-04-25 15:53:52
【问题描述】:

我的 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')

我在添加用户时选择了前 2 个兴趣。

现在在编辑时,我从数据库查询中获取用户数据。这个数据数组是用来填充表单的,这个数组结构是这样的:

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

如您所见,应该在我的编辑表单中选择兴趣“博客”和“游泳”。但我看到只有“游泳”选项被选中。

【问题讨论】:

  • 您填充的数据数组是否包含interest 键?
  • 是的,它确实包含“兴趣”键。请参阅我更新的问题。

标签: php zend-framework zend-form


【解决方案1】:
$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);
【解决方案2】:

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

【讨论】:

  • 提交表单后,我将 $form->getValues() 作为一个数组,其中键为表单元素名称,但值为 null。但是我要填充的数组格式为:Array ([0] => 1 [1] => 2),但只选择了最后一个选项(游泳)
  • 我的意思是:根据需要设置值(即选中所需的复选框),然后提交表单并使用填充数据转储结果(= $_POST)。然后值不应该为空,但它应该显示你应该作为 $data 数组发布到 populate() 方法的内容。
【解决方案3】:

好吧,我可以在 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>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-03-04
    • 2018-09-06
    • 1970-01-01
    • 2016-02-05
    • 2012-10-08
    • 2014-06-19
    • 1970-01-01
    相关资源
    最近更新 更多