2014-11-10 3 views
0

У меня есть событие Entity, у которого есть ключевые слова поля, которые являются Mapper One-to-Many для другого Entity EventKeywords. У меня также есть класс типа CreateEventFormType. Я создаю форму в моем контроллере, используя этот код:Symfony2 добавить настраиваемое поле для формирования builder

$event = new Event(); 
$form = $this->createForm(new CreateEventFormType(), $event); 

но также необходимо дополнительное поле для ввода ключевых слов, которые будут использоваться для создания объекта EventKeywords. Я пытался добавить, что к моему formBuilderInterface:

 ->add('keywords', 'text', [ 
       'constraints' =>[ 
        new Assert\NotBlank([ 
         'message' => "Renginio raktažodžiai negali būti tušti" 
        ]), 
        new Assert\Length([ 
         'min' => "2", 
         'max' => "255", 
         'minMessage' => "Renginio raktažodžiai negali būti trumpesni nei {{ limit }} simboliai", 
         'maxMessage' => "Renginio raktažodžiai negali būti ilgesni nei {{ limit }} simboliai" 
        ]) 
       ] 
      ]) 

, но затем я получаю ошибку

Neither the property "keywords" nor one of the methods "addKeyword()"/"removeKeyword()", "setKeywords()", "keywords()", "__set()" or "__call()" exist and have public access in class "Atotrukis\MainBundle\Entity\Event".

Полной Сущность и FormType код:

createEventFormType.php

<?php 
namespace Atotrukis\MainBundle\Form\Type; 

use Symfony\Component\Form\AbstractType; 
use Symfony\Component\Form\FormBuilderInterface; 
use Doctrine\ORM\EntityRepository; 
use Symfony\Component\Validator\Constraints as Assert; 
class CreateEventFormType extends AbstractType 
{ 
    public function buildForm(FormBuilderInterface $builder, array $options) 
    { 
     $builder 
      ->add('name', 'text', [ 
       'constraints' =>[ 
        new Assert\NotBlank([ 
         'message' => "Renginio pavadinimas negali būti tuščias" 
        ]), 
        new Assert\Length([ 
         'min' => "2", 
         'max' => "255", 
         'minMessage' => "Renginio pavadinimas negali būti trumpesnis nei {{ limit }} simboliai", 
         'maxMessage' => "Renginio pavadinimas negali būti ilgesnis nei {{ limit }} simboliai" 
        ]) 
       ] 
      ]) 
      ->add('description', 'textarea', [ 
       'constraints' =>[ 
        new Assert\NotBlank([ 
         'message' => "Renginio aprašymas negali būti tuščias" 
        ]), 
        new Assert\Length([ 
         'min' => "10", 
         'max' => "5000", 
         'minMessage' => "Renginio aprašymas negali būti trumpesnis nei {{ limit }} simbolių", 
         'maxMessage' => "Renginio aprašymas negali būti ilgesnis nei {{ limit }} simbolių" 
        ]) 
       ] 
      ]) 
      ->add('startDate', 'datetime', [ 
       'constraints' =>[ 
        new \Atotrukis\MainBundle\Validator\Constraints\FutureDateTime([ 
         'message' => "Pradžios laikas negali būti ankstesnis už dabartinį laiką." 
        ]) 
       ] 
      ]) 
      ->add('endDate', 'datetime', [ 
       'constraints' =>[ 
        new \Atotrukis\MainBundle\Validator\Constraints\FutureDateTime([ 
         'message' => "Pabaigos laikas negali būti ankstesnis už dabartinį laiką." 
        ]) 
       ] 
      ]) 
      ->add('keywords', 'text', [ 
       'constraints' =>[ 
        new Assert\NotBlank([ 
         'message' => "Renginio raktažodžiai negali būti tušti" 
        ]), 
        new Assert\Length([ 
         'min' => "2", 
         'max' => "255", 
         'minMessage' => "Renginio raktažodžiai negali būti trumpesni nei {{ limit }} simboliai", 
         'maxMessage' => "Renginio raktažodžiai negali būti ilgesni nei {{ limit }} simboliai" 
        ]) 
       ] 
      ]) 
      ->add('map', 'hidden') 
      ->add('city', 'entity', array(
       'class' => 'AtotrukisMainBundle:City', 
       'property' => 'name', 
       'constraints' =>[ 
        new Assert\NotBlank([ 
         'message' => "Privalote pasirinkti miestą" 
        ]) 
       ], 
       'empty_value' => 'Pasirinkite miestą', 
       'query_builder' => function(EntityRepository $er) { 
        return $er->createQueryBuilder('c') 
         ->addOrderBy('c.priority', 'ASC') 
         ->addOrderBy('c.name', 'ASC'); 
       }, 
      )); 
//   ->add('save', 'submit', array('label' => 'Sukurti')); 
    } 
    public function getName() 
    { 
     return 'createEventForm'; 
    } 

} 

Event.php

<?php 
namespace Atotrukis\MainBundle\Entity; 

use Doctrine\ORM\Mapping as ORM; 
use Symfony\Component\Validator\Constraints as Assert; 
use Atotrukis\MainBundle\Validator\Constraints as CustomAssert; 


/** 
* @ORM\Entity 
* @ORM\Table(name="events") 
* @CustomAssert\DateRange 
*/ 
class Event 
{ 
    /** 
    * @ORM\Column(type="integer") 
    * @ORM\Id 
    * @ORM\GeneratedValue(strategy="AUTO") 
    */ 
    protected $id; 
    /** 
    * @ORM\Column(type="string", length=255) 
    */ 
    protected $name; 

    /** 
    * @ORM\Column(type="text") 
    */ 
    protected $description; 

    /** 
    * @ORM\Column(type="datetime") 
    */ 
    protected $startDate; 

    /** 
    * @ORM\Column(type="datetime") 
    */ 
    protected $endDate; 

    /** 
    * @ORM\ManyToOne(targetEntity="User", inversedBy="events") 
    * @ORM\JoinColumn(name="createdBy", referencedColumnName="id") 
    */ 
    protected $createdBy; 

    /** 
    * @ORM\Column(type="datetime") 
    */ 
    protected $createdOn; 

    /** 
    * @ORM\Column(type="string", length=2083) 
    */ 
    protected $map; 


    /** 
    * @ORM\OneToMany(targetEntity="EventPhoto", mappedBy="eventId") 
    */ 
    protected $photos; 

    /** 
    * @ORM\OneToMany(targetEntity="UserAttending", mappedBy="eventId") 
    */ 
    protected $usersAttending; 

    /** 
    * @ORM\OneToMany(targetEntity="EventKeywords", mappedBy="eventId") 
    */ 
    protected $keywords; 

    /** 
    * @ORM\ManyToOne(targetEntity="City", inversedBy="eventId") 
    * @ORM\JoinColumn(name="city", referencedColumnName="id") 
    */ 
    protected $city; 


    public function __construct() 
    { 
     $this->createdOn = new \DateTime(); 
     $this->keywords = new ArrayCollection(); 
     //parent::__construct(); 
    } 

    /** 
    * Get id 
    * 
    * @return integer 
    */ 
    public function getId() 
    { 
     return $this->id; 
    } 

    /** 
    * Set name 
    * 
    * @param string $name 
    * @return Event 
    */ 
    public function setName($name) 
    { 
     $this->name = $name; 

     return $this; 
    } 

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

    /** 
    * Set description 
    * 
    * @param string $description 
    * @return Event 
    */ 
    public function setDescription($description) 
    { 
     $this->description = $description; 

     return $this; 
    } 

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

    /** 
    * Set startDate 
    * 
    * @param \DateTime $startDate 
    * @return Event 
    */ 
    public function setStartDate($startDate) 
    { 
     $this->startDate = $startDate; 

     return $this; 
    } 

    /** 
    * Get startDate 
    * 
    * @return \DateTime 
    */ 
    public function getStartDate() 
    { 
     return $this->startDate; 
    } 

    /** 
    * Set endDate 
    * 
    * @param \DateTime $endDate 
    * @return Event 
    */ 
    public function setEndDate($endDate) 
    { 
     $this->endDate = $endDate; 

     return $this; 
    } 

    /** 
    * Get endDate 
    * 
    * @return \DateTime 
    */ 
    public function getEndDate() 
    { 
     return $this->endDate; 
    } 

    /** 
    * Set createdBy 
    * 
    * @param integer $createdBy 
    * @return Event 
    */ 
    public function setCreatedBy($createdBy) 
    { 
     $this->createdBy = $createdBy; 

     return $this; 
    } 

    /** 
    * Get createdBy 
    * 
    * @return integer 
    */ 
    public function getCreatedBy() 
    { 
     return $this->createdBy; 
    } 

    /** 
    * Set createdOn 
    * 
    * @param \DateTime $createdOn 
    * @return Event 
    */ 
    public function setCreatedOn($createdOn) 
    { 
     $this->createdOn = $createdOn; 

     return $this; 
    } 

    /** 
    * Get createdOn 
    * 
    * @return \DateTime 
    */ 
    public function getCreatedOn() 
    { 
     return $this->createdOn; 
    } 

    /** 
    * Add photos 
    * 
    * @param \Atotrukis\MainBundle\Entity\EventPhoto $photos 
    * @return Event 
    */ 
    public function addPhoto(\Atotrukis\MainBundle\Entity\EventPhoto $photos) 
    { 
     $this->photos[] = $photos; 

     return $this; 
    } 

    /** 
    * Remove photos 
    * 
    * @param \Atotrukis\MainBundle\Entity\EventPhoto $photos 
    */ 
    public function removePhoto(\Atotrukis\MainBundle\Entity\EventPhoto $photos) 
    { 
     $this->photos->removeElement($photos); 
    } 

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

    /** 
    * Set map 
    * 
    * @param string $map 
    * @return Event 
    */ 
    public function setMap($map) 
    { 
     $this->map = $map; 

     return $this; 
    } 

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

    /** 
    * Set city 
    * 
    * @param \Atotrukis\MainBundle\Entity\City $city 
    * @return Event 
    */ 
    public function setCity(\Atotrukis\MainBundle\Entity\City $city = null) 
    { 
     $this->city = $city; 

     return $this; 
    } 

    /** 
    * Get city 
    * 
    * @return \Atotrukis\MainBundle\Entity\City 
    */ 
    public function getCity() 
    { 
     return $this->city; 
    } 

    /** 
    * Add usersAttending 
    * 
    * @param \Atotrukis\MainBundle\Entity\UserAttending $usersAttending 
    * @return Event 
    */ 
    public function addUsersAttending(\Atotrukis\MainBundle\Entity\UserAttending $usersAttending) 
    { 
     $this->usersAttending[] = $usersAttending; 

     return $this; 
    } 

    /** 
    * Remove usersAttending 
    * 
    * @param \Atotrukis\MainBundle\Entity\UserAttending $usersAttending 
    */ 
    public function removeUsersAttending(\Atotrukis\MainBundle\Entity\UserAttending $usersAttending) 
    { 
     $this->usersAttending->removeElement($usersAttending); 
    } 

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


    /** 
    * Add keywords 
    * 
    * @param \Atotrukis\MainBundle\Entity\EventKeywords $keywords 
    * @return Event 
    */ 
    public function addKeyword(\Atotrukis\MainBundle\Entity\EventKeywords $keywords) 
    { 
     $this->keywords[] = $keywords; 

     return $this; 
    } 

    /** 
    * Remove keywords 
    * 
    * @param \Atotrukis\MainBundle\Entity\EventKeywords $keywords 
    */ 
    public function removeKeyword(\Atotrukis\MainBundle\Entity\EventKeywords $keywords) 
    { 
     $this->keywords->removeElement($keywords); 
    } 

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

    /** 
    * Set keywords 
    * 
    * @param \Atotrukis\MainBundle\Entity\EventKeywords $keywords 
    * @return Event 
    */ 
    public function setKeywords(\Atotrukis\MainBundle\Entity\EventKeywords $keywords = null) 
    { 
     $this->keywords = $keywords; 

     return $this; 
    } 
} 

EventKeywords.php

<?php 
namespace Atotrukis\MainBundle\Entity; 

use Doctrine\ORM\Mapping as ORM; 

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

    /** 
    * @ORM\Column(type="string", length=255) 
    */ 
    protected $keyword; 

    /** 
    * @ORM\ManyToOne(targetEntity="Event", inversedBy="keywords") 
    * @ORM\JoinColumn(name="eventId", referencedColumnName="id") 
    */ 
    protected $eventId; 

    /** 
    * Get id 
    * 
    * @return integer 
    */ 
    public function getId() 
    { 
     return $this->id; 
    } 

    /** 
    * Set eventId 
    * 
    * @param \Atotrukis\MainBundle\Entity\Event $eventId 
    * @return UserAttending 
    */ 
    public function setEventId(\Atotrukis\MainBundle\Entity\Event $eventId = null) 
    { 
     $this->eventId = $eventId; 

     return $this; 
    } 

    /** 
    * Get eventId 
    * 
    * @return \Atotrukis\MainBundle\Entity\Event 
    */ 
    public function getEventId() 
    { 
     return $this->eventId; 
    } 

    /** 
    * Set keyword 
    * 
    * @param string $keyword 
    * @return EventKeywords 
    */ 
    public function setKeyword($keyword) 
    { 
     $this->keyword = $keyword; 

     return $this; 
    } 

    /** 
    * Get keyword 
    * 
    * @return string 
    */ 
    public function getKeyword() 
    { 
     return $this->keyword; 
    } 
} 
+0

где задатчик ключевых слов в событии? я не мог найти его .. – xurshid29

+0

также вы должны инициализировать коллекцию 'keywords' (в' __construct' с 'ArrayCollection') – xurshid29

+0

Я добавил установщик ключевых слов в объект Event. также попытался добавить '$ this-> keywords = new ArrayCollection();' в __construct, но теперь я получаю ошибку: 'Catchable Fatal Error: аргумент 1, переданный Atotrukis \ MainBundle \ Entity \ Event :: setKeywords(), должен быть экземпляр Atotrukis \ MainBundle \ Entity \ EventKeywords, строка, вызывается в /var/www/vendor/symfony/symfony/src/Symfony/Component/PropertyAccess/PropertyAccessor.php в строке 438 и определена в/var/www/src/Atotrukis/MainBundle/Entity/Event.php line 389' – Einius

ответ

0

То, что вы должны сделать, это:

->add('yourfield', 'choice', array(
      'label' => 'Your Field', 
      'required' => false, 
      'choices' => array(true => 'Yes', false => 'No'), 
      'empty_value' => false, 
      'mapped' => false     
     )) 

Обратите внимание на 'отображается' => ложным. Это означает, что это поле не имеет ничего общего с вашей сущностью (объектом). Он вообще не существует в вашем классе.
Сделав это, вы сможете добавить столько дополнительных полей, которые хотите.