表单类型
在您的情况下,我们需要为 PersonaDocumento 创建 formType。想象一下,这个实体有字段 documentName:
class PersonaDocumentoType extends AbstractType
{
/**
* @param FormBuilderInterface $builder
* @param array $options
* @SuppressWarnings(unused)
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('documentName', TextType::class, [
'label' => false,
'translation_domain' => 'messages'
])
;
}
/**
* @return string
*/
public function getName()
{
return 'app_persona_documento_type';
}
/**
* @return null|string
*/
public function getBlockPrefix()
{
return 'app_persona_documento';
}
/**
* @param OptionsResolver $resolver
*/
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(array(
'data_class' => PersonaDocumento::class,
'csrf_protection' => true,
'validation' => true,
));
}
}
包含集合的表单
考虑你的实体Formulario。它与 PersonaDocumento 具有 OneToMany 关系。表格将是:
class FormularioFormType extends AbstractType
{
/**
* @param FormBuilderInterface $builder
* @param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
// ...
$builder
->add('documentos', CollectionType::class, [
'entry_type' => PersonaDocumentoType::class,
'entry_options' => [
'label' => false,
],
'label' => false,
'allow_add' => true,
'allow_delete' => true,
'by_reference' => false, // Very important thing!
])
;
}
// ...
}
收集小部件
我们有一个表单 (FormularioFormType),其中包含类型为 PersonaDocumentoType 的小表单集合。
您可以使用标准小部件在文件中创建新小部件,以及 file is fields.html.twig 的名称:path_to_your_project/src/AppBundle/Resources/views/Form/fields.html.twig。
区块名称为app_persona_documento_widget。
因此,fields.html.twig 的示例:
{% trans_default_domain 'messages' %}
{% block app_persona_documento_widget %}
{% spaceless %}
<div class="form-group" {{ block('widget_container_attributes') }}>
<div class="col-sm-12">
{{ form_widget(form.name, {'attr' : { 'placeholder' : 'app.form.label.name'|trans , 'class' : 'form-control' }}) }}
</div>
</div>
{% endspaceless %}
{% endblock app_persona_documento_widget %}
还要注意“app_persona_documento_widget”——由你的PersonaDocumentoType 的getBlockPrefix() 加上字符串“_widget”组装而成
在 config.yml 中注册新的表单主题
# Twig Configuration
twig:
debug: '%kernel.debug%'
strict_variables: '%kernel.debug%'
form_themes:
# other form themes
# ...
- 'AppBundle:Form:fields.html.twig'
以父表单呈现集合
{{ form_start(formulario_form) }}
<div class="form-group">
<label for="" class="col-sm-2 control-label">
Label
</label>
<div class="col-sm-10 documentos" data-prototype="{{ form_widget(formulario_form.documentos.vars.prototype)|e('html_attr') }}">
{% for document in formulario_form.documentos %}
<div>
{{ form_widget(document) }}
</div>
{% endfor %}
</div>
</div>
<span>
{{ form_errors(formulario_form) }}
</span>
{# Here you can add another fields of form #}
{{ form_end(formulario_form) }}
当然,您还需要按钮:每个“Documento”项目都有一个“添加另一个文档”按钮和“删除”按钮。
Symfony 文档建议我们为此目的使用 JavaScript。
你可以阅读更多here in official docs
你也可以安装Ninsuo/symfony-collection - 一个管理从 Symfony 集合中添加、删除和移动元素的 jQuery 插件