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
View
<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>
Form/Type
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');
}
// ...
}
Validation
Subject:
properties:
body:
- NotBlank: ~
- MinLength: 8
choices:
- Valid: ~
Choice:
properties:
choice:
- NotBlank: ~
Controller
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(),
));
}
I try collection form of symfony2.
But, when the field is increased by Javascript, it will fail, if there is the empty field.
When the field is increased, it is before execution of validation and becomes an error. (Catchable Fatal Error:))
How can I manage to achieve that?
EDIT:
If the value is set up, two or more registration will be successful.
If there is an item to which the value is not set, two or more registration will go wrong.
bindRequest function failed.
If only the part of an empty value adds an entity, it will be successful.
However, it seems that it is not right way.
Remove required=false from choice form field or add nullable=true to schema choice field