Can I set a field value in an Entity by providing

2019-08-09 11:23发布

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);
  // ...
}

2条回答
聊天终结者
2楼-- · 2019-08-09 11:34

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).

use Symfony\Component\PropertyAccess\PropertyAccess;

// ...

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

$accessor = PropertyAccess::createPropertyAccessor();

if ($accessor->isWritable($element, 'fieldName')) {
    $accessor->setValue($element, 'fieldName', $value);
} else {
    throw new \Exception('fieldName is not writable');
}
查看更多
你好瞎i
3楼-- · 2019-08-09 11:37

You have to implement this method in your entity. E.g. :

class YourEntity
{
   public function set($field, $value)
   {
      $this->{'set'.$field}($value);
   }
}

Or you can set your properties as public and do:

$element->$field = $content;
查看更多
登录 后发表回答