samedi 16 mai 2015

Can I set a field value in an Entity by providing the field name?

I am writing a bundle that is supposed to be used with different user-defined entities. I would like this bundle to be able to access a user-provided field in that entity.

Is there a method that looks like $entity->set('field', 'value')? Do I have to do it from scratch using reflection?

What I came up to already:

In the controller:

public function editAction(Request $request) {
  $content = $request->request->get('content'); // Example: "John Doe"
  $entity = $request->request->get('entity'); // Example: "SomeBundle:SomeEntity"
  $field = $request->request->get('field'); // Example: "name"
  $id = $request->request->get('id'); // Example: "42"

  $em = $this->getDoctrine()->getManager();
  $element = $em->getRepository($entity)->find($id); // Entity with id 42

  // How can I write this line?:
  $element->set($field, $content); //Alias for $element->setName($content);
  // ...
}





Aucun commentaire:

Enregistrer un commentaire