user10800263
user10800263

Reputation:

How can I replace a method into a variable inside a foreach loop?

This is fieldsData:

{#1292 ▼
  +"167d580ee0": 1
  +"20fc1f0271": 2
  +"585687a0fb": 3
}

my Controller:

 foreach ($fieldsData as $uuid => $fieldId) {

  $fieldsEntity = $this->getDoctrine()->getRepository($en)->findOneBy(['id' => $fieldId]);
  $name = $fieldsEntity->getName();

  $entity = new $EntityName();

  $entity->setName("test");
  $entity->setAge("test");
  $entity->setJob("test");

 }

 $this->em->persist($entity);
 $this->em->flush();

This works well so far. But I want to replace the method with a variable like this:

 foreach ($fieldsData as $uuid => $fieldId) {

   $fieldsEntity = $this->getDoctrine()->getRepository($en)->findOneBy(['id' => $fieldId]);
   $name = $fieldsEntity->getName();

   $entity = new $EntityName();
   $func = 'set' . $name;
   $entity->$func("test");

 }

 $this->em->persist($entity);
 $this->em->flush();

But I get the error message now:

SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'name' cannot be null

I do not unterstand, because when I dump $name I get the output:

name
age
job

Upvotes: 0

Views: 46

Answers (2)

Cid
Cid

Reputation: 15247

You are creating a new $entity on each iteration.

You said when you dump $name you get this output :

name
age
job

This means, the last iteration will result this :

foreach ($fieldsData as $uuid => $fieldId) {

   $fieldsEntity = $this->getDoctrine()->getRepository($en)->findOneBy(['id' => $fieldId]);
   $name = $fieldsEntity->getName();

   $entity = new $EntityName();
   $func = 'set' . 'job';
   $entity->$func("test");

 }

 $this->em->persist($entity); // you didn't set name in $entity, but only job.
 $this->em->flush();

Move $entity = new $EntityName(); before the foreach

Upvotes: 1

Pavol Velky
Pavol Velky

Reputation: 810

Use property accessor for this job:

use Symfony\Component\PropertyAccess\PropertyAccess;

$propertyAccessor = PropertyAccess::createPropertyAccessor();
$propertyAccessor->setValue($entity, $name, 'test');

More info: https://symfony.com/doc/current/components/property_access.html#usage

Upvotes: 0

Related Questions