简体   繁体   English

Symfony2:为扩展的多项选择字段设置“设置”值(复选框)

[英]Symfony2: setting “set” value for expanded multiple choice field (checkbox)

When form is submitted and after refresh shown again, Request is binded to form and show selected values. 提交表单后,再次显示刷新后,请求将绑定到表单并显示选定的值。 I want to hydrate form with data from external array (session in my case) if the form was not submited before. 如果表单之前未提交过,我想使用外部数组(在我的情况下为会话)中的数据来合并表单。 Form is array type, not connected to any entity, as it works as db filter. 窗体是数组类型,未连接到任何实体,因为它可以用作数据库过滤器。

I have choice form field expanded, multiple (checkbox) configured as below: 我将选择表单字段展开,将多个(复选框)配置如下:

    $categoryForm = array();
    $form = $this->createFormBuilder( $categoryForm )
                 ->add( 'id', 'choice', array( 'choices' => $arrayOfChoices,
                                               'multiple' => true,
                                               'expanded' => true ) )
                 ->getForm();
    if ( $request->getMethod() == 'POST' ) {
        $form->bindRequest( $request );
    }

您必须将变量传递给表单(在控件中),然后在builder类中使用传递的变量。

it is not easy case but after hours of thinking I managed to do it. 这不是一件容易的事,但经过数小时的思考,我设法做到了。 Below I show mine code working great to move data from session to form and vice versa 下面我展示了我的代码非常有效,可以将数据从会话移到表单,反之亦然

    //bind filters from session to form
    $sessionFilter = $session->get('filter');
    if ( !is_null( $sessionFilter ) ) {
       $form->bind( $sessionFilter );
    }

    if ( $request->getMethod() == 'POST' ) {
        $form->bindRequest( $request );
        $formData = $form->getData();

        if ( count($formData) > 0 ) {
            foreach ( $formData as $fdkey => $data ) {
                if ( $fdkey == 'id' OR $fdkey == 'morezero' ) {
                    foreach ( $data as $value ) {
                        $sessionData[$fdkey][$value] = $value ;
                    }
                }
            }
            $session->set( 'filter', $sessionData );
        }
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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