Search code examples
phpsymfonycontrollerdoctrineentitymanager

How can I store my data into the database with the entity manager?


This is the output of my variable $data:

array(7) { [0]=> array(2) { ["name"]=> string(14) "form[username]" ["value"]=> string(1) "1" } [1]=> array(2) { ["name"]=> string(11) "form[email]" ["value"]=> string(7) "1@12.sw" } [2]=> array(2) { ["name"]=> string(15) "form[is_active]" ["value"]=> string(1) "1" } [3]=> array(2) { ["name"]=> string(26) "form[plainPassword][first]" ["value"]=> string(0) "" } [4]=> array(2) { ["name"]=> string(27) "form[plainPassword][second]" ["value"]=> string(0) "" } [5]=> array(2) { ["name"]=> string(8) "form[id]" ["value"]=> string(1) "9" } [6]=> array(2) { ["name"]=> string(12) "form[_token]" ["value"]=> string(43) "MdSCKxGkdFs2HPUSoM2vGidSRUmPgzZC3pZaW2wK2Rk" } } 

I want to update now my data inside my database with the entity manager:

      $entityManager->persist($data);
      $entityManager = $data->getDoctrine()->getManager();
      $entityManager->flush();
      $response = new Response();
      $response->send();

But I get the error message:

EntityManager#persist() expects parameter 1 to be an entity object, NULL given.


Solution

  • You can create a new entity if your data does not contain one. Get the correct data out of the form values and put them in the set methods. A small example below.

    // Create new Entity
    $entity = new EntityNameHere
    $em = $this->getDoctrine()->getManager();
    
    // Use setter function from that Entity
    $entity->setName($data['name']);
    $entity->setPassword($data['password']); 
    
    $em->persist($entity);
    $em->flush();