如果验证失败,带有字段集的ZF2表单集将保持旧状态

时间:2013-11-30 17:18:58

标签: php forms validation collections zend-framework2

我有一个带有以下集合元素的表单对象:

$languageSkills = new Collection('languageSkills');
$languageSkills->allowAdd();
$languageSkills->allowRemove();
$languageSkills->setLabel('LANGUAGES_SKILLS_QUESTION');
$languageSkills->setCount(0);
$languageSkills->setShouldCreateTemplate(true);
/* @var $fieldset LanguageSkillFieldset */
$fieldset = new LanguageSkillFieldset();
$fieldset->setMasterDataService($masterDataService);
$fieldset->init();
$languageSkills->setTargetElement($fieldset);
$this->add($languageSkills);

字段集本身包含隐藏字段和选择框。 现在,如果我更改字段集中的值或我动态添加/删除字段集(使用js),发送表单并且某些内容无效,则集合将显示在其旧/先前状态(没有任何更改)。所有其他元素都具有正确的值。

我做错了什么?

控制器部分:

$form = $this->getSkillForm();
$prg = $this->prg($this->url()->fromRoute('langroute/freelancer/profile/skills/save', array(), array(), true), true);
// check PRG plugin for redirect to send
if ($prg instanceof Response) {
    return $prg;
} elseif ($prg !== false) {
    $flashMessenger = $this->flashMessenger();
    // if none is selected, there is no entry in array
    if (empty($prg['driversLicenses'])) {
        $prg['driversLicenses'] = array();
    }
    if (empty($prg['languageSkills'])) {
        $prg['languageSkills'] = array();
    }
    $form->setData($prg);
    $form->bind($this->getFreelancer());
    try {
        $this->getFreelancerService()->updateFreelancer($form->getValidatedObject());
        return new JsonModel(array('success' => 1));
    } catch (Exception $ex) {
        $flashMessenger->addErrorMessage($ex->getMessage());
    }
}
$model = $this->getSkillsEditViewModel();
$model->setVariable('form', $form);
return $model;

- >在getValidatedObject()方法中(我的类AbstractForm扩展Form):

if(!$this->isValid()) {
    throw new ValidationException($message, $this->getInputFilter());
}
return $this->getObject();

1 个答案:

答案 0 :(得分:1)

过了一会儿,我找到了解决这个问题的方法。在绑定对象之前,请小心验证表单 !在进行进一步处理(如持久等)之前,将其绑定在之后。无论如何,这就是重点......