将子表单的前缀添加到子表单元素。我使用前缀“child”来表示子表单。每个子表单将被创建为 child1、child2 等等。
public function clonerecursivegroupAction()
{
//.. Other code
$subform = new Zend_Form_SubForm();
$subform->setIsArray(true);
$subform->setName("child$id");
$Element1 = $subform->createElement('text', "newfield$id");
$Element1->setLabel("newfield$id")
->setRequired(true);
$subform->addElement($Element1);
$Element1 = $subform->createElement('text', "nextfield$id");
$Element1->setLabel("nextfield$id")
->setRequired(true);
$subform->addElement($Element1);
$this->view->field = $subform;
// Rest of your statements
}
然后,在 preValidation 函数中,使用子表单前缀而不是字段名称来过滤子表单:
public function preValidation(array $data) {
// array_filter callback
function findForms($field) {
// return field names that include 'child'
if (strpos($field, 'child') !== false) {
return $field;
}
}
$subForms = array_filter(array_keys($data), 'findForms'); //filter the subform elements
$children = array();
foreach ($subForms as $subform) {
if (is_array($data[$subform])) {
$children[$subform] = $data[$subform];
}
}
//Iterate the children
foreach ($children as $key => $fields) { //$key = subformname, $field=array containing fiend names and values
// strip the id number off of the field name and use it to set new order
$order = ltrim($key, 'child') + 2;
$this->addNewForm($key, $fields, $order);
}
}
添加新表单函数创建每个子表单并附加到主表单:
public function addNewForm($form, $elements, $order) {
$subform = new Zend_Form_SubForm();
$subform->setIsArray(true);
foreach ($elements as $key => $el) {
$Element1 = $subform->createElement('text', $key);
$Element1->setLabel($form.$key)
->setValue($el)
->setRequired(true);
$subform->addElement($Element1);
}
$this->addSubForm($subform, $form, $order);
}
[编辑] 对子表单使用 setIsArray 将子表单的每个元素创建为数组元素。它简化了 preValidate 函数。编辑代码以利用此功能。
See the 完整代码在pastebin中 http://pastebin.com/CqCNhKjx
这是使用belongsTo的另一个解决方案,为子表单元素提供数组表示法:http://www.stephenrhoades.com/?p=364 http://www.stephenrhoades.com/?p=364