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);
// ...
}
You can use the Property Accessor component which will allow you to do just this. You simply provide your object, the field name and the value to set it to and the component will handle the rest (pubic properties, _set or setters).
You have to implement this method in your entity. E.g. :
Or you can set your properties as public and do: