How to import CSV into Symfony2

Asked

Viewed 159 times

2

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

I am trying to generate a answer to register the data using the 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. Its main purpose is to receive a form to write the data, popular the Entity related to it and after, write to the persistence layer, how can I do this by receiving the Form parameter?

  • I don’t understand. Why do you want to do this?

  • @Rodrigorigotti I’m importing CSV, I’m looking to create something generic, the $data is actually a line of csv. This way I can edit the CRUD Skeleton of Symfony and already have by default the import of CSV, I want to take advantage of the standard rule of validation and insertion, my initial intention was even to pass the Response to createAction.

  • I’ll research a way to do that :)

1 answer

0

Well I don’t know if it would be worth testing, but you already tried not to create the request, but to use what is injected in 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 are creating the request at hand, it loses the references and CRFS protections.

You could test and see what happens?

Hugs,

Browser other questions tagged

You are not signed in. Login or sign up in order to post.