2015-09-18 3 views
3

В приложении Symfony2 с помощью сверток Sonata администратора, у меня есть две сущности:sonata_type_collection поле работает только с существующими родителю объектов

  • CorporateAttributes
  • CorporateAttributesApi

Похожие в Учении например:

CorporateAttributes ← один-ко-многим → CorporateAttributesApi

My Sonata Админ-класс для CorporateAttributes содержит следующее:

в AppBundle/Администратор/CorporateAttributesAdmin.php

// Fields to be shown on create/edit forms 
protected function configureFormFields(FormMapper $formMapper) { 
    $formMapper 
     ->add('apis', 'sonata_type_collection', 
      ['required' => false, 'label' => 'API Clients'], 
      ['edit'=>'inline','inline'=>'table'] 
     ) 
    ; 
} 

Это добавляет " Добавить новую "в форму CorporateAttributes, где я могу добавлять и редактировать CorporateAttributesApi, связанные с объектом CorporateAttributes, для которого пользователь редактирует.

Однако это работает только для существующего объекта CorporateAttributes.

Если я пытаюсь добавить новый CorporateAttributes, нажав на кнопку «Add New» дает следующее сообщение об ошибке в консоли:

Failed to load resource: the server responded with a status of 500 (Internal Server Error) 
http://localhost/app_dev.php/admin/core/append-form-field-element?code=sonata.admin.corporateattributes&elementId=s55fc29157eeee_apis&uniqid=s55fc29157eeee 

Я подозреваю, что это что-то делать с тем фактом, что потребности CorporateAttributesApi идентификатор CorporateAttributes, который он ссылается, но я не уверен, как заставить его играть хорошо.

Вот другой соответствующий код:

в AppBundle/Администратор/CorporateAttributesApiAdmin.php:

// Fields to be shown on create/edit forms 
protected function configureFormFields(FormMapper $formMapper) { 
    $formMapper 
     ->add('corporate_attributes', null, ['required' => true]) 
     ->add('group_name', 'choice', [ 
      'choices' => ['a', 'b', 'c'], 
      'required' => false, 
     ]) 
    ; 
} 

И лица с doctrine2 аннотаций:

в AppBundle/Entity/CorporateAttributes.php :

namespace AppBundle\Entity; 
use Doctrine\ORM\Mapping as ORM; 

/** 
* CorporateAttributes 
* 
* 
* @ORM\Entity 
* @ORM\Table("drupal_wiredb_corporate_attributes") 
*/ 
class CorporateAttributes 
{ 
    /** 
    * @ORM\Id 
    * @ORM\Column(name="id", type="integer") 
    * @ORM\GeneratedValue(strategy="AUTO") 
    */ 
    protected $id; 

    /** 
    * @ORM\OneToMany(targetEntity="CorporateAttributesApi", mappedBy="corporate_attributes", cascade={"persist"}, orphanRemoval=true)) 
    */ 
    protected $apis; 

    public function getId() { 
     return $this->id; 
    } 

    /** 
    * Add apis 
    * 
    * @param \AppBundle\Entity\CorporateAttributesApi $apis 
    * @return CorporateAttributes 
    */ 
    public function addApi(\AppBundle\Entity\CorporateAttributesApi $api) 
    { 
     $this->apis[] = $api; 
     $api->setCorporateAttributes($this); 

     return $this; 
    } 

    /** 
    * Remove apis 
    * 
    * @param \AppBundle\Entity\CorporateAttributesApi $apis 
    */ 
    public function removeApi(\AppBundle\Entity\CorporateAttributesApi $api) 
    { 
     $this->apis->removeElement($api); 
     $api->setCorporateAttributes(null); 
    } 

    /** 
    * Get apis 
    * 
    * @return \Doctrine\Common\Collections\Collection 
    */ 
    public function getApis() 
    { 
     return $this->apis; 
    } 

    /** 
    * Constructor 
    */ 
    public function __construct() 
    { 
     $this->apis = new \Doctrine\Common\Collections\ArrayCollection(); 
    } 
} 

в AppBundle/Entities/Co rporateAttributesApi.php:

namespace AppBundle\Entity; 
use Doctrine\ORM\Mapping as ORM; 

/** 
* CorporateAttributesApi 
* 
* 
* @ORM\Entity 
* @ORM\Table("drupal_wiredb_corporate_attributes_api") 
*/ 
class CorporateAttributesApi 
{ 
    /** 
    * @ORM\Id 
    * @ORM\ManyToOne(targetEntity="CorporateAttributes", inversedBy="apis") 
    * @ORM\JoinColumn(name="attribute_id", referencedColumnName="id") 
    */ 
    protected $corporate_attributes; 

    /** 
    * @ORM\Id 
    * @ORM\Column(name="group_name", type="string", length=128, options={"default":""}) 
    */ 
    protected $group_name = ''; 

    public function __toString() { 
     if (empty($this->corporate_attributes) && empty($this->api_user)) { 
      return 'New Corporate Attributes - API User Join'; 
     } 
     else { 
      return (string)$this->corporate_attributes . ' | ' . (string)$this->api_user . ' | ' . $this->group_name; 
     } 
    } 

    /** 
    * Set group_name 
    * 
    * @param string $groupName 
    * @return CorporateAttributesApi 
    */ 
    public function setGroupName($groupName) 
    { 
     $this->group_name = $groupName; 

     return $this; 
    } 

    /** 
    * Get group_name 
    * 
    * @return string 
    */ 
    public function getGroupName() 
    { 
     return $this->group_name; 
    } 

    /** 
    * Set corporate_attributes 
    * 
    * @param \AppBundle\Entity\CorporateAttributes $corporateAttributes 
    * @return CorporateAttributesApi 
    */ 
    public function setCorporateAttributes(\AppBundle\Entity\CorporateAttributes $corporateAttributes) 
    { 
     $this->corporate_attributes = $corporateAttributes; 

     return $this; 
    } 

    /** 
    * Get corporate_attributes 
    * 
    * @return \AppBundle\Entity\CorporateAttributes 
    */ 
    public function getCorporateAttributes() 
    { 
     return $this->corporate_attributes; 
    } 
} 
+0

С этой ошибкой 500 на вкладке «Сеть» панели разработчиков вашего браузера отображается любой ответ html, например, сообщение об исключении исключения? – Vasily802

ответ

0

Я хотел бы попробовать изменить свой AppBundle/Admin/CorporateAttributesApiAdmin.php файл следующим образом:

// Fields to be shown on create/edit forms 
protected function configureFormFields(FormMapper $formMapper) { 
    $formMapper 
     ->add('corporate_attributes', null, ['required' => true]) 
     ->add('group_name', 'choice', [ 
      'choices' => ['a', 'b', 'c'], 
      'required' => false, 
     ]) 
    ; 

    // If this is sonata_type_collection inside CorporateAttributes form, 
    // then we don't need 'corporate_attributes' field as it would be the parent entity 
    if ($this->getRoot() instanceof \AppBundle\Admin\CorporateAttributesAdmin) { 
     $formMapper->remove('corporate_attributes'); 
    } 
} 

public function getNewInstance() 
{ 
    $object = parent::getNewInstance(); 

    // Here we specify the 'corporate_attributes' 
    if ($this->getRoot()->getSubject() instanceof \AppBundle\Entity\CorporateAttributes) { 
     $object->setCorporateAttributes($this->getRoot()->getSubject()); 
    } 

    return $object; 
} 

Вы также можете попробовать изменить AppBundle/Admin/CorporateAttributesAdmin.php установить by_reference = FALSE в определении поля формы:

// Fields to be shown on create/edit forms 
// AppBundle/Admin/CorporateAttributesAdmin.php 
protected function configureFormFields(FormMapper $formMapper) { 
    $formMapper 
     ->add('apis', 'sonata_type_collection', 
      ['required' => false, 'label' => 'API Clients', 'by_reference' => false], 
      ['edit'=>'inline','inline'=>'table'] 
     ) 
    ; 
} 

Вот документация для опции by_reference: http://symfony.com/doc/current/reference/forms/types/collection.html#by-reference

 Смежные вопросы

  • Нет связанных вопросов^_^