2013-07-31 2 views
1

Я хотел бы создать форму с набором самонаблюдающего объекта.form symfony 2 много объектов самообслуживания

Мне нужна форма для создания нового продукта, в этой форме будет поле выбора (дочернее) с существующими продуктами.

У меня есть объект продукта, и этот объект включает дочернее поле (дочерний продукт тоже).

сущность продукта:

/** 
* @var integer 
* 
* @ORM\Column(name="id", type="bigint", length=20) 
* @ORM\Id 
* @ORM\GeneratedValue(strategy="AUTO") 
*/ 
protected $id; 

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

/** 
* @var string 
* 
* @ORM\Column(name="manufacturer_reference", type="string", length=255, nullable=true) 
*/ 
protected $manufacturer_reference; 

/** 
* @var string 
* 
* @ORM\Column(name="resume", type="text", nullable=true) 
*/ 
protected $resume; 

/** 
* @var boolean 
* 
* @ORM\Column(name="is_salable", type="boolean", options={"default" = 1}) 
*/ 
protected $is_salable = 1; 

/** 
* @var boolean 
* 
* @ORM\Column(name="is_active", type="boolean", options={"default" = 1}) 
*/ 
protected $is_active = 1; 

/** 
* @ORM\ManyToOne(targetEntity="\Hexanet\Common\CatalogBundle\Entity\ProductCategory") 
* @ORM\JoinColumn(name="product_category_id", referencedColumnName="id", nullable=true) 
*/ 
protected $product_category; 

/** 
* @ORM\ManyToOne(targetEntity="\Hexanet\Common\CatalogBundle\Entity\Manufacturer") 
* @ORM\JoinColumn(name="manufacturer_id", referencedColumnName="id", nullable=true) 
*/ 
protected $manufacturer; 

/** 
* @ORM\ManyToMany(targetEntity="\Hexanet\Common\CatalogBundle\Entity\Product", mappedBy="parents") 
*/ 
protected $children; 

/** 
* @ORM\ManyToMany(targetEntity="\Hexanet\Common\CatalogBundle\Entity\Product") 
* @ORM\JoinTable(name="product_to_product", 
*  joinColumns={@ORM\JoinColumn(name="child_product_id", referencedColumnName="id")}, 
*  inverseJoinColumns={@ORM\JoinColumn(name="parent_product_id", referencedColumnName="id")} 
*) 
*/ 
protected $parents; 

/** 
* @ORM\OneToMany(targetEntity="\Hexanet\Common\CatalogBundle\Entity\ProductPrice", mappedBy="product") 
*/ 
protected $product_prices; 

/** 
* @ORM\OneToMany(targetEntity="\Hexanet\Common\CatalogBundle\Entity\ProductPricePurchase", mappedBy="product") 
*/ 
protected $product_prices_purchase; 

/** 
* @ORM\OneToMany(targetEntity="\Hexanet\Common\CatalogBundle\Entity\ProductPriceCustom", mappedBy="product") 
*/ 
protected $product_prices_custom; 

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

/** 
* Set title 
* 
* @param string $title 
* @return Product 
*/ 
public function setTitle($title) 
{ 
    $this->title = $title; 

    return $this; 
} 

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

/** 
* Set product category 
* 
* @param \Hexanet\Common\CatalogBundle\Entity\ProductCategory $product_category 
* @return Product 
*/ 
public function setProductCategory(\Hexanet\Common\CatalogBundle\Entity\ProductCategory $product_category = null) 
{ 
    $this->product_category = $product_category; 

    return $this; 
} 

/** 
* Get product category 
* 
* @return \Hexanet\Common\CatalogBundle\Entity\ProductCategory 
*/ 
public function getProductCategory() 
{ 
    return $this->product_category; 
} 

/** 
* Set resume 
* 
* @param string $resume 
* @return Product 
*/ 
public function setResume($resume) 
{ 
    $this->resume = $resume; 

    return $this; 
} 

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

/** 
* Set manufacturer reference 
* 
* @param string $title 
* @return Product 
*/ 
public function setManufacturerReference($ref) 
{ 
    $this->manufacturer_reference = $ref; 

    return $this; 
} 

/** 
* Get manufacturer reference 
* 
* @return string 
*/ 
public function getManufacturerReference() 
{ 
    return $this->manufacturer_reference; 
} 

/** 
* Set is salable 
* 
* @param boolean $active 
* @return Product 
*/ 
public function setIsSalable($salable) 
{ 
    $this->is_salable = $salable; 

    return $this; 
} 

/** 
* Get is salable 
* 
* @return boolean 
*/ 
public function getIsSalable() 
{ 
    return $this->is_salable; 
} 

/** 
* Set is active 
* 
* @param boolean $active 
* @return Product 
*/ 
public function setIsActive($active) 
{ 
    $this->is_active = $active; 

    return $this; 
} 

/** 
* Get is active 
* 
* @return boolean 
*/ 
public function getIsActive() 
{ 
    return $this->is_active; 
} 

/** 
* Set manufacturer 
* 
* @param $manufacturer 
* @return Product 
*/ 
public function setManufacturer($manufacturer) 
{ 
    $this->manufacturer = $manufacturer; 

    return $this; 
} 

/** 
* Get manufacturer 
* 
*/ 
public function getManufacturer() 
{ 
    return $this->manufacturer; 
} 

/** 
* Constructor 
*/ 
public function __construct() 
{ 
    $this->parents = new \Doctrine\Common\Collections\ArrayCollection(); 
    $this->children = new \Doctrine\Common\Collections\ArrayCollection(); 
    $this->product_prices = new \Doctrine\Common\Collections\ArrayCollection(); 
    $this->product_prices_purchase = new \Doctrine\Common\Collections\ArrayCollection(); 
    $this->product_prices_custom = new \Doctrine\Common\Collections\ArrayCollection(); 
} 

/** 
* Add child 
* 
* @param \Hexanet\Common\CatalogBundle\Entity\Product $product 
* @return Product 
*/ 
public function addChild(\Hexanet\Common\CatalogBundle\Entity\Product $product) 
{ 
    die(var_dump($product)); 
    $this->children[] = $product; 

    return $this; 
} 

/** 
* Remove child 
* 
* @param \Hexanet\Common\CatalogBundle\Entity\Product $product 
*/ 
public function removeChild(\Hexanet\Common\CatalogBundle\Entity\Product $product) 
{ 
    $this->children->removeElement($product); 
} 

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

/** 
* Add parent 
* 
* @param \Hexanet\Common\CatalogBundle\Entity\Product $product 
* @return Product 
*/ 
public function addParent(\Hexanet\Common\CatalogBundle\Entity\Product $product) 
{ 
    $this->parents[] = $product; 

    return $this; 
} 

/** 
* Remove parent 
* 
* @param \Hexanet\Common\CatalogBundle\Entity\Product $price 
*/ 
public function removeParent(\Hexanet\Common\CatalogBundle\Entity\Product $product) 
{ 
    $this->parents->removeElement($product); 
} 

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

/** 
* Add product price 
* 
* @param \Hexanet\Common\CatalogBundle\Entity\ProductPrice $price 
* @return Product 
*/ 
public function addProductPrice(\Hexanet\Common\CatalogBundle\Entity\ProductPrice $price) 
{ 
    $this->product_prices[] = $price; 

    return $this; 
} 

/** 
* Remove product price 
* 
* @param \Hexanet\Common\CatalogBundle\Entity\ProductPrice $price 
*/ 
public function removeProductPrice(\Hexanet\Common\CatalogBundle\Entity\ProductPrice $price) 
{ 
    $this->product_prices->removeElement($price); 
} 

/** 
* Get product prices 
* 
* @return \Doctrine\Common\Collections\Collection 
*/ 
public function getProductPrices() 
{ 
    return $this->product_prices; 
} 

/** 
* Add product price purchase 
* 
* @param \Hexanet\Common\CatalogBundle\Entity\ProductPricePurchase $price 
* @return Product 
*/ 
public function addProductPricePurchase(\Hexanet\Common\CatalogBundle\Entity\ProductPricePurchase $price) 
{ 
    $this->product_prices_purchase[] = $price; 

    return $this; 
} 

/** 
* Remove product price purchase 
* 
* @param \Hexanet\Common\CatalogBundle\Entity\ProductPricePurchase $price 
*/ 
public function removeProductPricePurchase(\Hexanet\Common\CatalogBundle\Entity\ProductPricePurchase $price) 
{ 
    $this->product_prices_purchase->removeElement($price); 
} 

/** 
* Get product prices purchase 
* 
* @return \Doctrine\Common\Collections\Collection 
*/ 
public function getProductPricesPurchase() 
{ 
    return $this->product_prices_purchase; 
} 

/** 
* Add product price custom 
* 
* @param \Hexanet\Common\CatalogBundle\Entity\ProductPriceCustom $price 
* @return Product 
*/ 
public function addProductPriceCustom(\Hexanet\Common\CatalogBundle\Entity\ProductPriceCustom $price) 
{ 
    $this->product_prices_custom[] = $price; 

    return $this; 
} 

/** 
* Remove product price custom 
* 
* @param \Hexanet\Common\CatalogBundle\Entity\ProductPriceCustom $price 
*/ 
public function removeProductPriceCustom(\Hexanet\Common\CatalogBundle\Entity\ProductPriceCustom $price) 
{ 
    $this->product_prices_custom->removeElement($price); 
} 

/** 
* Get product prices custom 
* 
* @return \Doctrine\Common\Collections\Collection 
*/ 
public function getProductPricesCustom() 
{ 
    return $this->product_prices_custom; 
}} 

для формы у меня есть это:

class ProductType extends AbstractType{ 

public function buildForm(FormBuilderInterface $builder, array $options) 
{ 
    $builder 
     ->add('title') 
     ->add('manufacturer_reference') 
     ->add('resume') 
     ->add('product_category', 'entity', array(
     'class' => 'HexanetCatalogBundle:ProductCategory', 
     'property' => 'title', 
     )) 
     ->add('children', 'collection', array(
     'type' => new ProductChildrenType, 
     'allow_add' => true)); 
} 

public function setDefaultOptions(OptionsResolverInterface $resolver) 
{ 
    $resolver->setDefaults(array(
     'data_class' => 'Hexanet\Common\CatalogBundle\Entity\Product' 
    )); 
} 

public function getName() 
{ 
    return 'hexanet_common_catalogbundle_producttype'; 
}} 

Проблема есть, я не знаю, как создать ProductChildrenType строитель:

class ProductChildrenType extends AbstractType{ 
public function buildForm(FormBuilderInterface $builder, array $options) 
{ 
    $builder 
     ->add('product', 'entity', array(
     'class' => 'HexanetCatalogBundle:Product', 
     'property' => 'title', 
     )); 
} 

public function setDefaultOptions(OptionsResolverInterface $resolver) 
{ 
    $resolver->setDefaults(array(
     'data_class' => 'Hexanet\Common\CatalogBundle\Entity\Product' 
    )); 
} 

public function getName() 
{ 
    return 'hexanet_common_catalogbundle_productchildrentype'; 
}} 

-> add ('product', 'entity', ...) У меня есть ошибка:

Ни один из свойств «продукт» или метод «getProduct()» или метод «isProduct()» не существует в классе «Hexanet \ Common \ CatalogBundle \ Entity \ Product».

Thx для справки

+0

Я думаю, что ошибка явная: вы должны использовать 'product_category' вместо' product' в 'ProductChildrenType':' -> add ('product_category', ...) '. Надеюсь, что это полезно –

+0

Нет, я хочу, чтобы список продуктов не был выбран. Product_category находится в классе ProductType – nematite10

+0

Вы нашли решение для этого? У меня очень похожая сущность, и я застрял в той же точке. – jakabadambalazs

ответ

2

У меня есть подобный случай для магазина, так что я могу добавить дополнительные продукты в админке, так что я могу предложить их на кассе ... Моего партнера на работе и я решил эта проблема вчера, так что, если вас все еще интересует, вот мы идем .... Мы используем Symfony 2.6.x, я еще не тестировал ее на старых версиях Symfony.

->add('myExtras', 'collection', array(
      'type' => 'entity', 
      'options' => array(
       'class'  => 'StoreBundle:Productos', 
       'placeholder' => '-- Select an extra product --', 
       'property' => 'name', 
       'query_builder' => function (EntityRepository $er) use($options) { 
        return $er->createQueryBuilder('p') 
         ->where('p.asociable = :asociable') 
         ->andWhere('p.id != :selfid') 
         ->setParameters(array('adjuntable' => '1', 'selfid' => $options['selfid'])); 
       }, 
       'label' => 'Extra Product' 
      ), 
      'by_reference' => false, 
      'allow_add' => true, 
      'allow_delete' => true 
     )) 

вместо того, чтобы использовать коллекцию типа формы для «детей», мы использовали набор типа «лица», и мы использовали QueryBuilder контролировать условия, нам нужно, чтобы получить правильные варианты, чтобы показать ,

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

в сущности у меня есть коллекции myExtras (дети) и imExtraOf (родители), поэтому, когда я добавляю детей, я должен рассказать детям, что я получаю аналог -> addImExtraOf (я - ваша функция отца) ... t добавим продукт в наш дополнительный список. и для удаления, то же самое, мы вызываем сначала -> removeImExtraOf, если вы этого не сделаете, отношение не будет сохранено.

лица:

public function addMyExtra(Productos $extra) 
{ 
    $extra->addImExtraOf($this); 
    if(!$this->myExtras->contains($extra)) { 
     $this->myExtras[] = $extra; 
    } 


    return $this; 
} 

public function removeMyExtra(Productos $extra) 
{ 
    $extra->removeImExtraOf($this); 
    $this->myExtras->removeElement($extra); 
} 

отображение ОРМ (ут): (myExtras = дети, imExtraOf = родители)

надеюсь, что это поможет кому-то.

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