Orm/Yaml
Subject:
type: entity
repositoryClass: My\SampleBundle\Repository\SubjectRepository
id:
id:
type: integer
generator: { strategy: AUTO }
fields:
body:
type: text
oneToMany:
choices:
targetEntity: Choice
mappedBy: subject
cascade: ["persist", "remove"]
Choice:
type: entity
repositoryClass: My\SampleBundle\Repository\ChoiceRepository
id:
id:
type: integer
generator: { strategy: AUTO }
fields:
choice:
type: text
manyToOne:
subject:
targetEntity: Subject
inversedBy: choices
joinColumn:
name: subject_id
referencedColumnName: id
看法
<form action="{{ path('path_create or path_edit', {'id': id}) }}" method="post" {{ form_enctype(form) }}>
// ...
<ul id="choice-list" data-prototype="{{ form_widget(form.choices.vars.prototype.choice) | e }}">
{% for choice in form.choices %}
<li>
<div class="errors">
{{ form_errors(choice.choice) }}
</div>
{{ form_widget(choice.choice) }}
</li>
{% endfor %}
</ul>
<!-- ## The field can be added by JavaScript. -->
<span class="add-another-choice">Add another choice</span>
{{ form_rest(form) }}
<input type="submit" class="_button" />
</form>
形式/类型
class SubjectType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('body', 'textarea');
$builder->add('choices', 'collection', array(
'type' => new ChoiceType(),
'options' => array(
'required' => false
),
'allow_add' => true,
'by_reference' => false,
'allow_delete' => true,
'prototype' => true
));
}
// ...
}
class ChoiceType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('choice', 'textarea');
}
// ...
}
验证
Subject:
properties:
body:
- NotBlank: ~
- MinLength: 8
choices:
- Valid: ~
Choice:
properties:
choice:
- NotBlank: ~
控制器
public function createAction(Request $request, $id)
{
$em = $this->get('doctrine')->getEntityManager();
$subject = new Subject();
$subject->getChoices()->add(new Choice());
$form = $this->createForm(new SubjectType(), $subject);
if ($request->getMethod() == 'POST') {
$form->bindRequest($request); //<= error on this point. Why?
// if there is the empty field.
if ($form->isValid()) {
return // ...
}
}
return $this->render('MySampleBundle:Subject:create.html.twig', array(
'form' => $form->createView(),
));
}
我尝试 symfony2 的集合形式。
但是,当通过Javascript增加字段时,如果有空字段,它将失败。
当字段增加时,它在执行验证之前并成为错误。(可捕获的致命错误:))
我怎样才能做到这一点?
编辑:
如果设置了该值,则两个或多个注册将成功。
如果有一个项目没有设置值,两个或多个注册会出错。
bindRequest 函数失败。
如果只有部分空值添加实体,则成功。
但是,这似乎不是正确的方法。