简体   繁体   中英

How to dynamically modify child form of 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?

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM