How to import CSV into Symfony2

2

I am trying to create a generic form to import the CSV the $ data represents a complete line of csv data.

I'm trying to generate a response to register the data using form

public function save(\Symfony\Component\Form\Form $form, $data ){

    // Campos do formulário
    $fields = $form->all();
    $i = 0;
    $r = new Request();
    $r->setMethod('POST');
    foreach ($fields as $f) {
        $r->request->set($f, $data[$i++]);
    }

    $form->submit($r);
    $form->handleRequest($r);

    if (!$form->isValid()) {
        throw new Exception($form->getErrors());
    }

    $entity = $form->getData();
    $em = $this->getDoctrine()->getManager();
    $em->persist($entity);
    $em->flush();
    return true;
}

The form is always invalid, this is a generic function. The main purpose of it is to receive a form to save the data, popular the entity related to it and after, write to the persistence layer, how can I do this by getting Form as parameter?

    
asked by anonymous 20.03.2015 / 11:56

1 answer

0

I do not know if it would be worth testing, but you tried not to create the request, but to use what is injected into the action?

public function saveAction(Request $request)
{
   $form = $this->createForm(new YourForm());
   $form->handleRequest($request);
   // Aqui você chamaria seu método
   $this->save($form, $data);
   //...
}

I think when you're creating the request at hand, it loses CRFS references and protections.

Could you test and see what happens?

Hugs,

    
26.03.2015 / 19:31