我可以通过提供字段名称在实体中设置字段值吗? [英] Can I set a field value in an Entity by providing the field name?

查看:67
本文介绍了我可以通过提供字段名称在实体中设置字段值吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在写一个应该与不同的用户定义实体一起使用的包。我希望该捆绑包能够访问该实体中用户提供的字段。

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.

有没有一种方法类似于 $ entity- > set('field','value')?我必须使用反射从头开始吗?

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

我已经想到的事情:

在控制器中:

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


推荐答案

您可以使用属性访问器组件,该组件将允许你要做的就是这个。您只需提供对象,字段名称和将其设置为的值,然后组件将处理其余的(公共属性,_set或setters)。

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');
}

这篇关于我可以通过提供字段名称在实体中设置字段值吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆