Symfony2 - Set a selected value for the entity field

前端 未结 4 673
忘了有多久
忘了有多久 2020-12-20 14:59

I\'m trying to set a selected value inside an entity field. In accordance with many discussions I\'ve seen about this topic, I tried to set the data option but

4条回答
  •  暖寄归人
    2020-12-20 15:33

    When you use the query_builder option, and the data option expects an collection instance, and you don't want to touch your controller by adding setDatas for only certain fields, and you already have your querybuilder and the ids of the repopulating options in your form type class, you can repopulate a selection as following:

    // Querybuilder instance with filtered selectable options
    $entities = $qb_all; 
    // Querybuilder instance filtered by repopulating options (those that must be marked as selected)
    $entities_selected = $qb_filtered; 
    

    Then in your add() Method

    'data' => $entities_selected->getQuery()->getResult(), // Repopulation
    'query_builder' => $entities,
    

    EDIT: Real use case example

    You want to repopulate a checkbox group rendered with following elements:

    Label: What is your favourite meal?

    4 Checkboxes: Pasta, Pizza, Spaghetti, Steak

    And you want to repopulate 2 Checkboxes:

    Pizza, Steak

    $qb_all would be a QueryBuilder instance with the all 4 selectable Checkboxes

    $qb_filtered would be a new additional QueryBuilder instance with the repopulating Checkboxes Pizza, Steak. So a "filtered" version of the previous one.

提交回复
热议问题