目的:
用户自定义数目的记录,有内容的input则插入数据库,没内容则忽略
例子:

已经embed的字段要用unset()才不会插入数据库
/lib/.../xxForm.class.php
...
public function addNewTargets($number) {
$targets = new sfForm();
for($i=0;$i<$number;$i++) {
$target = new WeightTarget();
$target->setWeightWatcher($this->getObject());
$target_from = new WeightTargetForm($target);
$targets->embedForm($i, $target_from);
}
$this->embedForm('new', $targets);
}
public function bind(array $taintedValues = null, array $taintedFiles = null){
$new_targets = new sfForm();
$taintedValues['user_simple_id'] = sfContext::getInstance()->getUser()->getGuardUser()->getId();
foreach($taintedValues['new'] as $key => $new_target){
if(!empty ($new_target['title'])){
$target = new WeightTarget();
$target->setWeightWatcher($this->getObject());
$target_form = new WeightTargetForm($target);
$new_targets->embedForm($key,$target_form);
}else{ //字段为空则unset()
unset ($taintedValues['new'][$key]);
}
}
$this->embedForm('new',$new_targets);
}
parent::bind($taintedValues, $taintedFiles);
}
#.apps/.../actions.class.php
public function executeNew(sfWebRequest $request)
{
$this->number = 5;#显示5条执行事项
$this->form = new WeightWatcherForm();
$this->form->addNewTargets($this->number);
}
#template
...
<?php include_partial('addTargets', array('form'=>$form,'number'=>$number))?>
...
#partial
<?php for($i=0;$i<$number;$i++):?>
<tr>
<th scope=”row”><?php if($i<9) echo ’0′.($i+1); else echo $i+1;?>.</th>
<td>
<?php echo $form['new'][$i]['title']->render(array(‘class’=>’target_list’))?>
</td>
</tr>
<?php endfor;?>
如果提交create时发现有非法字段,我们会发现提示错误。因为现在的记录数已经不是5条。所以我们要重新设置记录数:
...
public function executeCreate(sfWebRequest $request)
{
$post = $request->getPostParameters();
$this->number = count($post['weight_watcher']['new']);#显示5条执行事项
$this->form = new WeightWatcherForm();
$this->form->addNewTargets($this->number);
...
}
...
就ok了。