简体   繁体   中英

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

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