试试这样的东西(未经测试):
class BulkUserForm extends Zend_Form
{
private $_howMany = 1;
public function __construct( $howMany, $options )
{
$this->_howMany = (int) $howMany;
parent::__construct( $options );
}
public function init()
{
for( $i = 1; $i <= $this->_howMany; $i++ )
{
$userForm = new YourOriginalUserForm();
$userForm->setElementsBelongTo( 'user' . $i ); // not sure this is actually necessary anymore, because of the second param to addSubForm
$this->addSubForm( $userForm, 'user' . $i, $i );
}
}
}
用法:
$form = new BulkUserForm( 25 /* [, $options ] */ );
echo $form;
// validation:
$form->isValid( $this->getRequest()->getPost() ); // or something similar
解释:
对子表单的setElementsBelongTo() 调用应该创建与此类似的符号(当然是简化的):
<input type="radio" name="user1[salutation]">
<input type="text" name="user1[firstName]">
<input type="text" name="user1[lastName]">
<input type="text" name="user1[email]">
您的表单应该能够在验证时自动识别提交的 POST 值。
当然,您可能还应该研究子表单的布局/装饰,但我将把它留给您作为练习。 ;-)
编辑
抱歉,addSubForm() 的第二个参数是强制性的(现在添加,还添加了可选的 $order 参数)。我相信它还应该自动将子表单设置为已经属于正确的命名空间。虽然不完全确定。看看如果您在子表单中省略 setElementsBelongTo() 调用会发生什么。