2

Using Symfony2.3.4.

I'm trying to create a form without using a type, it is actually a very small form, only two selects loading their options from the database, so far it works, what I can not do is to get the form data(in the controller) when it is submitted. I tried to follow the instruction here but I can't get it right.

Here is my code so far:

Controller: function to pass the data to the form:

public function selectAction($id, $id_actpost){
        $em = $this->getDoctrine()->getManager();

        $entity = $em->getRepository('ActPostBundle:Edition')->find($id);
        $students = $em->getRepository('PersonBundle:Students')->findAll();
        $students2 = $em->getRepository('PersonBundle:ForeignStudents')->findAll();

        if (!$entity) {
            throw $this->createNotFoundException('Unable to find Edicion entity.');
        }

        return $this->render('ActPostBundle:Edition:select.html.twig', array(
                    'entity' => $entity,
                    'id_actpost' => $id_actpost,
                    'students' => $students,
                    'foreignstudents' => $students2,
        ));
    }

html fragment regarding the form itself:

    <form class="form-horizontal sf_admin_form_area"
              action="{{ path('edition_update_selected',
           { 'id': entity.id, 'id_actpost': id_actpost }) }}"
              method="post" enctype="multipart/form-data">
            <div  style="margin-left: 80px" class="row-fluid">
                <div class="span12">
                   <select name="students" multiple="multiple">
                   {% for s in students %}
                     <option {%if s in entity.students%}selected="selected"{%endif%}>
                      {{s}}</option>
                   {%endfor%}
                   </select>
                </div>
            </div>

            <div class="row-fluid">
               <select name="students2" multiple="multiple">
                  {% for s in students2 %}
                     <option {%if s in entity.foreignstudents%}selected="selected"
                       {%endif%}>{{s}}</option>
                  {%endfor%}
               </select>
            </div>
            <div class="form-actions">
                <button type="submit" class="btn btn-primary">
                    <i class="glyphicon-refresh"></i> {{'Update' | trans}}</button>
                <a class="btn" href="{{ path('edition', {'id_actpost' : id_actpost }) }}">
                    <i class="glyphicon-ban-circle"></i> {{'Cancel' | trans }}
                </a>
            </div>
        </form>

and here is what I read from the link posted at the beginning: function to get the submitted data and update the database, although the database part can stay ignored until I manage to get the data from the form:

public function update_selectedAction(Request $request, $id, $id_actpost) {
        $em = $this->getDoctrine()->getManager();

        $entity = $em->getRepository('ActPostBundle:Edition')->find($id);

        if (!$entity) {
            throw $this->createNotFoundException('Unable to find Edicion entity.');
        }

        $defaultData = array('message' => 'Type here');
        $editForm = $this->createFormBuilder($defaultData)
                ->add('students','choice')
                ->add('students2', 'choice')
                ->getForm();

        $editForm->handleRequest($request);

I would like to know if what I read is actually what I need, because although I think it is I might be wrong, so any insights regarding this matter or even any other way to do it will be really appreciated.

1 Answer 1

3

You should use symfony's form builder to build the form in your update_selectedAction() like

public function update_selectedAction(Request $request, $id, $id_actpost)
{
    $em = $this->getDoctrine()->getManager();
    $entity = $em->getRepository('ActPostBundle:Edition')->find($id);
    if (!$entity) {
        throw $this->createNotFoundException('Unable to find Edicion entity.');
    }
    $defaultData = array('message' => 'Type here');
    $form = $this->createFormBuilder($defaultData)
        ->add('students', 'entity',array('class' => 'PersonBundle:Students',
            'property' => 'students','expanded'=>false,'multiple'=>false))
        ->add('students2', 'entity',array('class' => 'PersonBundle:ForeignStudents',
                    'property' => 'foreignstudents','expanded'=>false,'multiple'=>false))
    ->add('submit','submit')
    ->getForm();
    if ($request->getMethod() == "POST") {
        $form->submit($request);
        if ($form->isValid()) {
            $postData = current($request->request->all());
            var_dump($postData); /* All post data is here */
           /* echo  $postData['students']; */
           /* echo  $postData['students2']; */
            /*
             * do you update stuff here
             * */
        }
    }
    return $this->render('ActPostBundle:Edition:select.html.twig', array('form'=>$form->createView()));
} 

In your twig i.e ActPostBundle:Edition:select.html.twig render your form

{{ form(form) }}

Edit from comments

In your twig file render your form like

{{ form_errors(form) }}
{{ form_row(form.students) }}
{{ form_row(form.students2) }}
{{ form_row (form._token) }}
<input type="submit"> /* your submit button */

Edit from comments 2

IF you want to put the text in value attribute of selectbox you can use choice field type

$students = $em->getRepository('PersonBundle:Students')->findAll();
$students2 = $em->getRepository('PersonBundle:ForeignStudents')->findAll();
$studentsArray=array();
$students2Array=array();
foreach($students as $s){
$studentsArray[$s->getStudents()]=$s->getStudents();
}
foreach($students2 as $s){
$students2Array[$s->getForeignstudents()]=$s->getForeignstudents();
/* here array key part will be the value of selectbox like  $students2Array['your val to get in post data'] */
}
$form = $this->createFormBuilder($defaultData)
  ->add('students', 'choice',array('choices' => $studentsArray,'expanded'=>false,'multiple'=>false))
  ->add('students2', 'choice',array('choices' => $students2Array,'expanded'=>false,'multiple'=>false))
        ->add('submit','submit')
        ->getForm();
Sign up to request clarification or add additional context in comments.

7 Comments

but if I do it that way, I would have to modify selectAction as well, right? because as it is, it is not sending the form variable to the .twig. Remember, selectAction is to load the current info to the form and update_selectedAction to get the submitted data and they both have to interact with the .twig.
After using this approach You don't need the selectAction you can directly use update_selectedAction to build form and also for saving form
well, I just did what you told me, now the thing is $request->getMethod() == "POST" is not true, so I tried the $editForm->submit($request); without the if before it and then var_dump($editForm->getErrors());die(); to check for errors and I got this error Object with some attributes, one of those was: 'message' => 'The CSRF token is invalid. Please try to resubmit the form.' ring any bells...?
@jmiguel how your are rendering your form through form(form) ? or putting individual field if you are rendering individual fields then you also need {{ form_row (form._token) }} to render
you got it, thanks a lot man, learned a lot and it was most helpful!
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.