我有一个 3 层的表格:第一层是游戏的容器:
class GameListType extends AbstractType {
public function buildForm(FormBuilderInterface $builder, array $options) {
$builder->add('games', 'collection', array(
'required' => false,
'allow_add' => true,
'prototype' => true,
'by_reference' => false,
'type' => new GameBetType(),
))
;
}
public function setDefaultOptions(OptionsResolverInterface $resolver) {
parent::setDefaultOptions($resolver);
$resolver->setDefaults(array(
'cascade_validation' => true,
));
}
}
第二层是游戏本身,因为我不打算改变游戏,但它的赌注,它只包括赌注的形式:
class GameBetType extends AbstractType {
public function buildForm(FormBuilderInterface $builder, array $options) {
$builder->add('bet', new BetType());
}
public function setDefaultOptions(\Symfony\Component\OptionsResolver\OptionsResolverInterface $resolver) {
parent::setDefaultOptions($resolver);
$resolver->setDefaults(array(
'data_class' => 'Strego\TippBundle\Entity\Game',
'cascade_validation' => true,
));
}
}
第三层是下注的形式:
class BetType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('scoreT1' , 'text')
->add('scoreT2' , 'text');
;
}
public function setDefaultOptions(\Symfony\Component\OptionsResolver\OptionsResolverInterface $resolver) {
parent::setDefaultOptions($resolver);
$resolver->setDefaults(array(
'data_class' => 'Strego\TippBundle\Entity\Bet',
));
}
}
问题是,如果第三级存在验证约束,根表单始终有效,但如果我专门验证投注实体,我会在控制器中获得正确的违规列表:
// Form processing
$form = $this->createForm(new GameListType(), $entity);
$request = $this->getRequest();
if ($request->getMethod() == 'POST') {
$form->bind($request);
$entity = $form->getData();
if ($form->isValid()) {
foreach ($entity->getGames() as $game) {
if($game->hasBet()){
$bet = $game->getBet();
$bet->setUser($user);
$validator = $this->container->get('validator');
$errors = $validator->validate($bet);
var_dump($errors) //<-- i see there are errors
if(count($errors) == 0){
print($bet. ' gets persisted<br>');
$em->persist($bet);
}
}
}
$em->flush();
}
}
另一个问题是,即使我不调用$em->persist($bet)
实体也会被持久化。我没有看到该行中描述的输出
print($bet.'gets persisted<br>');
但是表单输入仍然保存在数据库中。
所以我的两个问题:
如果对表单的投注验证失败,我如何得到错误(我不希望整个表单无效,因为 3 个投注中只有 1 个无效)。
为什么即使我不跟注,赌注仍然存在
$em-persist($bet)
,这是绑定发生的一些魔法吗?