dongshen9058 2016-12-23 10:37
浏览 34

Symfony2表单ChoiceType [单选按钮] [重复]

This question already has an answer here:

I'm here with a quick question, because I can't figure out if I'm doing something wrong or Symfony2 Forms component does not work consistently. The scenario is as follows:

  • I have a form with custom form type [ChoiceType "child" type] with some predefined values
  • I need this custom form type to have default value selected when no value has been selected before [so the form has not yet been submitted]
  • Then again, I may also have this form prepopulated based on user's settings [preferences]

What I would expect to happen:

  1. No user preferences - form field has default value [0]
  2. User preferences available - form field has value passed in $data parameter [0-7]
  3. Form is being submitted - the value of form field is the one that has been submitted [0-7]

What actually happens:

  • If form field is set to be select ['expanded' => false] it works as expected for both display (first value [0] is selected - probably because it's the first one) and submission (0 is being submitted)
  • If form field is radio button list ['expanded' => true] none of the values are selected to begin with and submitting the form does not submit any value either.

Can someone explain me how to make radio button selected? I can use empty_data to set the value if none is submitted, but what about initial form display? It would be perfect to make the selection (for both select boxes and radio buttons) based on empty_value.

I also can't use data option, because it will overwrite any data passed to form (see point 2 above) as well as data submitted.

@EDIT

I would like to avoid two things:

  • using JavaScript is definitely not an option
  • overriding the template is something I'd like to avoid as well, mainly because I'm currently using bootstrap theme as a foundation which is going to be replaced by proper frontend / templates later
</div>
  • 写回答

1条回答 默认 最新

  • duanou1904 2016-12-23 10:58
    关注

    I'm not sure to understand your question. To manage the form default value, you only need to set the property of the object mapped.

    For example:

    $formObject->child->attributeDefault = "defaultValue";
    if($hasPreference) {
      $formObject->child->attribute1 = "preferenceDefautlValue"
    }
    $form = $this->createForm(new YourFormType(), $formObject);
    
    $form->handleRequest($request) //overide default value by submitted one
    
    评论

报告相同问题?

悬赏问题

  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本