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

问题描述:

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 );
    }

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 );
        }
    }

You must pass the variable to the form(in controler), and then use the passed variable in the builder class.