如何动态修改sonata_type_collection的子表单?

如何动态修改sonata_type_collection的子表单?

问题描述:

I have a field of 'sonata_type_collection' in a form which is defined in a Sonata Admin class. I need to modify the children of that form based on child's position. In my particular case, each row in the collection has a 'Delete' checkbox, and I'd like to disable that checkbox only for the first element of the collection. Any idea how to achieve this?

我在一个Sonata Admin类中定义的表单中有一个'sonata_type_collection'字段。 我需要根据孩子的位置修改该表单的子项。 在我的特定情况下,集合中的每一行都有一个“删除”复选框,我想仅为集合的第一个元素禁用该复选框。 任何想法如何实现这一目标? p> div>

The only way that I found is by overriding the form_admin_fields.html.twig and add your own blocks.

You can override the template by modifying the related configuration file : https://sonata-project.org/bundles/doctrine-orm-admin/2-2/doc/reference/configuration.html#full-configuration-options or use the SonataEasyExtendsBundle to extend SonataDoctrineOrmBundle.

You have to create 2 block one for you collection and one for your relation type (OneToMany or ManyToMany).

The annoying part is to find the name of your block, it's formed by your admin service name + field name + 'sonata_type_collection_widget'.

It depends of your Sonata version but here is a collection block example that I use :

{% block sonata_admin_challenge_organizers_sonata_type_collection_widget %}
    {% if sonata_admin.field_description.mappingtype == constant('Doctrine\\ORM\\Mapping\\ClassMetadataInfo::ONE_TO_MANY') %}
        {{ block('sonata_admin_challenge_organizers_orm_one_to_many_widget') }}
    {% elseif sonata_admin.field_description.mappingtype == constant('Doctrine\\ORM\\Mapping\\ClassMetadataInfo::MANY_TO_MANY') %}
        {{ block('sonata_admin_orm_many_to_many_widget') }}
    {% else %}
        INVALID MODE : {{ id }} - type : sonata_type_collection - mapping : {{ sonata_admin.field_description.mappingtype }}
    {% endif %}
{% endblock %}

Once your collection block is done you have to add a new block for the oneToMany or ManyToMany, you simply copy the template used in your Sonata version and customize it to your need : https://github.com/sonata-project/SonataDoctrineORMAdminBundle/blob/master/Resources/views/CRUD/edit_orm_one_to_many.html.twig

In your case, you simply have to add an if statement based on the loop.index value to display or not the delete field : https://github.com/sonata-project/SonataDoctrineORMAdminBundle/blob/master/Resources/views/CRUD/edit_orm_one_to_many.html.twig#L26.