![](/img/trans.png)
[英]Symfony2: fos_user_bundle embedding registration form with entity
[英]Symfony2 fos_rest_bundle param converter not calling entity constructor
我正在開發API,並具有以下實體:
/**
* Solicitud de registro.
*
* @ORM\Table()
* @ORM\Entity(repositoryClass="DnD\RaHApiBundle\Repository\ApplicationRepository")
*/
class Application
{
public function __construct()
{
$pending = new Event("PENDING", "APPLICATION");
$this->status = new ArrayCollection($pending);
$this->ownsVehicle = false;
$this->resident = true;
$this->timestamp = new DateTime();
}
/**
* @var integer
*
* @ORM\Column(name="id", type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
* @Groups({"application_info"})
*/
private $id;
...
注意構造函數。 它使用其默認值設置我實體中的某些字段。 現在我的控制器的動作:
/**
* Crea una nueva solicitud de afiliacion
* @return array
*
* @Post("applications")
* @ParamConverter("application", converter="fos_rest.request_body")
*/
public function postAction(Application $application)
{
$this->applicationsRepo->save($application);
// It has no date, no status, no defaults!!!
$view = $this->view($application, 200);
$view->getSerializationContext()->setSerializeNull(true);
$view->getSerializationContext()->setGroups(array('application_info'));
return $this->viewHandler->handle($view);
}
$ application對象沒有設置默認值,這為什么呢? 如何使轉換器調用構造函數並設置所有默認值?
我遇到了同樣的問題。 如果您確定不會從請求正文中覆蓋默認值,則可以顯式調用構造函數。
$application->__construct();
就我而言,我只是想初始化所有ArrayCollection
屬性,以防止嘗試訪問它們時出錯,因此我不在乎覆蓋請求中的標量值。
我也發現
vendor/doctrine/instantiator/src/Doctrine/Instantiator/Instantiator.php
buildFactory方法是問題的根源。 如果您更改:
return $reflectionClass->newInstanceWithoutConstructor();
至
return $reflectionClass->newInstance();
參數轉換器將返回一個對象,該對象的構造函數已被調用。 但是,如果構造函數具有必需的參數,則此操作將失敗。 當然,您可以分派教義並更改它,但是這可能會過大:-)
我認為通過將JMS的默認對象構造函數切換到Doctrine,可以調用一個hte實體的構造函數:
services:
jms_serializer.object_constructor:
alias: jms_serializer.doctrine_object_constructor
public: false
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.