2015-02-25 8 views
28

mam tego podmiotu zdefiniowane:Symfony2 połów Fatal Error: Przedmiot klasie nie może być zamieniony na ciąg

<?php 

namespace Apw\BlackbullBundle\Entity; 

use Doctrine\Common\Collections\ArrayCollection; 
use Doctrine\ORM\Mapping as ORM; 

/** 
* Categories 
* 
* @ORM\Table() 
* @ORM\Entity(repositoryClass="Apw\BlackbullBundle\Entity\CategoriesRepository") 
*/ 
class Categories 
{ 
/** 
* @var integer 
* 
* @ORM\Column(name="id", type="integer") 
* @ORM\Id 
* @ORM\GeneratedValue(strategy="AUTO") 
*/ 
private $id; 

/** 
* @var string 
* 
* @ORM\Column(name="categories_image", type="string", length=64, nullable = true) 
*/ 
private $categoriesImage; 

/** 
* @var integer 
* 
* @ORM\Column(name="parent_id", type="integer", nullable = true, options={"default":0}) 
*/ 
private $parentId; 

/** 
* @var integer 
* 
* @ORM\Column(name="sort_order", type="integer", nullable = true, options={"default":0}) 
*/ 
private $sortOrder; 

/** 
* @var \DateTime 
* 
* @ORM\Column(name="date_added", type="datetime", nullable = true) 
*/ 
private $dateAdded; 

/** 
* @var \DateTime 
* 
* @ORM\Column(name="last_modified", type="datetime", nullable = true) 
*/ 
private $lastModified; 

/** 
* @var boolean 
* 
* @ORM\Column(name="categories_status", type="boolean", nullable = true, options={"default" = 1}) 
*/ 
private $categoriesStatus; 

/** 
* @ORM\OneToMany(targetEntity="CategoriesDescription", mappedBy="category", cascade={"persist", "remove"}) 
*/ 
private $categoryDescription; 

/** 
* @ORM\ManyToMany(targetEntity="Products", mappedBy="categories") 
**/ 
private $products; 

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

/** 
* Set categoriesImage 
* 
* @param string $categoriesImage 
* @return Categories 
*/ 
public function setCategoriesImage($categoriesImage) 
{ 
    $this->categoriesImage = $categoriesImage; 

    return $this; 
} 

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

/** 
* Set parentId 
* 
* @param integer $parentId 
* @return Categories 
*/ 
public function setParentId($parentId) 
{ 
    $this->parentId = $parentId; 

    return $this; 
} 

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

/** 
* Set sortOrder 
* 
* @param string $sortOrder 
* @return Categories 
*/ 
public function setSortOrder($sortOrder) 
{ 
    $this->sortOrder = $sortOrder; 

    return $this; 
} 

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

/** 
* Set dateAdded 
* 
* @param \DateTime $dateAdded 
* @return Categories 
*/ 
public function setDateAdded($dateAdded) 
{ 
    $this->dateAdded = $dateAdded; 

    return $this; 
} 

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

/** 
* Set lastModified 
* 
* @param \DateTime $lastModified 
* @return Categories 
*/ 
public function setLastModified($lastModified) 
{ 
    $this->lastModified = $lastModified; 

    return $this; 
} 

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

/** 
* Constructor 
*/ 
public function __construct() 
{ 
    $this->categoryDescription = new ArrayCollection(); 
    $this->products = new ArrayCollection(); 
} 

/** 
* Add categoryDescription 
* 
* @param \Apw\BlackbullBundle\Entity\CategoriesDescription $categoryDescription 
* @return Categories 
*/ 
public function addCategoryDescription(\Apw\BlackbullBundle\Entity\CategoriesDescription $categoryDescription) 
{ 
    $this->categoryDescription[] = $categoryDescription; 

    return $this; 
} 

/** 
* Remove categoryDescription 
* 
* @param \Apw\BlackbullBundle\Entity\CategoriesDescription $categoryDescription 
*/ 
public function removeCategoryDescription(\Apw\BlackbullBundle\Entity\CategoriesDescription $categoryDescription) 
{ 
    $this->categoryDescription->removeElement($categoryDescription); 
} 

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

/** 
* Add products 
* 
* @param \Apw\BlackbullBundle\Entity\Products $products 
* @return Categories 
*/ 
public function addProduct(\Apw\BlackbullBundle\Entity\Products $products) 
{ 
    $this->products[] = $products; 

    return $this; 
} 

/** 
* Remove products 
* 
* @param \Apw\BlackbullBundle\Entity\Products $products 
*/ 
public function removeProduct(\Apw\BlackbullBundle\Entity\Products $products) 
{ 
    $this->products->removeElement($products); 
} 

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

/** 
* Set categoriesStatus 
* 
* @param boolean $categoriesStatus 
* @return Categories 
*/ 
public function setCategoriesStatus($categoriesStatus) 
{ 
    $this->categoriesStatus = $categoriesStatus; 

    return $this; 
} 

/** 
* Get categoriesStatus 
* 
* @return boolean 
*/ 
public function getCategoriesStatus() 
{ 
    return $this->categoriesStatus; 
} 
} 

Wtedy mam tę metodę w moim kontroler składania formularza Rękojeść:

<?php 

namespace Apw\BlackbullBundle\Controller; 


use Apw\BlackbullBundle\Entity\Categories; 
use Apw\BlackbullBundle\Entity\CategoriesDescription; 
use Apw\BlackbullBundle\Form\CategoriesType; 
use Symfony\Bundle\FrameworkBundle\Controller\Controller; 
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route; 
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template; 
use Symfony\Component\HttpFoundation\JsonResponse; 
use Symfony\Component\HttpFoundation\Request; 
use Symfony\Component\Form\Extension\Core\ChoiceList\ChoiceList; 
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Security; 


class CategoriesController extends Controller 
{ 
    /** 
* @Security("has_role('ROLE_ADMIN')") 
* @Route("/createCategory") 
* @Template() 
*/ 

public function createCategoryAction(Request $request){ 

    $category = new Categories(); 
    $categoryDesc = new CategoriesDescription(); 
    $category->addCategoryDescription($categoryDesc); 
    $categoryDesc->setCategory($category); 

    $form = $this->createForm(new CategoriesType(), $category); 
    $form->handleRequest($request); 

    if($form->isValid()){ 
     //exit(\Doctrine\Common\Util\Debug::dump($category)); 
     $em = $this->getDoctrine()->getManager(); 

     $em->persist($category); 
     $em->persist($categoryDesc); 
     $em->flush(); 

     return $this->redirect($this->generateUrl('apw_blackbull_categories_showcategories')); 
    } 

    return array(
     'form' => $form->createView() 
    ); 
} 

} 

I w końcu to jest mój CategoryType.php:

<?php 

namespace Apw\BlackbullBundle\Form; 

use Doctrine\ORM\EntityRepository; 
use Symfony\Component\Form\AbstractType; 
use Symfony\Component\Form\FormBuilderInterface; 
use Symfony\Component\OptionsResolver\OptionsResolverInterface; 

class CategoriesType extends AbstractType 
{ 
    /** 
    * @param FormBuilderInterface $builder 
    * @param array $options 
    */ 
    public function buildForm(FormBuilderInterface $builder, array $options) 
    { 
     $builder 
      ->add('categoryDescription', 'collection', 
       array(
        'type' => new CategoriesDescriptionType(), 
        'allow_add' => true, 
        'options' => array('data_class' => 'Apw\BlackbullBundle\Entity\CategoriesDescription'), 
        'by_reference' => false, 
       )) 
      ->add('categoriesImage', null, array('label'=>'Foto:')) 
      ->add('categoriesStatus', null, array('label'=>'Stato:')) 
      ->add('parentId', 'entity', array(//provare a mettere una querybuiler 
              'class'  => 'ApwBlackbullBundle:CategoriesDescription', 
              'property' => 'categoriesName', 
              'empty_value' => 'Scegliere una categoria', 
              'required' => false, 
              'label'  => 'Crea in:')) 
      ->add('salva','submit') 
      ->add('azzera','reset') 
     ; 
    } 

    /** 
    * @param OptionsResolverInterface $resolver 
    */ 
    public function setDefaultOptions(OptionsResolverInterface $resolver) 
    { 
     $resolver->setDefaults(array(
      'data_class' => 'Apw\BlackbullBundle\Entity\Categories', 
     )); 
    } 

    /** 
    * @return string 
    */ 
    public function getName() 
    { 
     return 'categories'; 
    } 
} 

Kiedy próbuję zapisać dane, pojawia się ten błąd:

An exception occurred while executing 'INSERT INTO Categories (categories_image, parent_id, sort_order, date_added, last_modified, categories_status) VALUES (?, ?, ?, ?, ?, ?)' with params ["as", {}, null, null, null, 1]:

Catchable Fatal Error: Object of class Apw\BlackbullBundle\Entity\CategoriesDescription could not be converted to string

Co robię źle?

Odpowiedz

1

więc rozwiązać ten problem przez uzyskać wartość względnej rodzica w metodzie $form->isValid()

public function createCategoryAction(Request $request){ 

     $category = new Categories(); 
     $categoryDesc = new CategoriesDescription(); 
     $category->addCategoryDescription($categoryDesc); 
     $categoryDesc->setCategory($category); 

     $form = $this->createForm(new CategoriesType(), $category); 
     $form->handleRequest($request); 

     if($form->isValid()){ 
     //exit(\Doctrine\Common\Util\Debug::dump($parentCategory->getId())); 
      $em = $this->getDoctrine()->getManager(); 
      if(!$category->getParentId()){ 
       $category->setParentId(0); 
      }else{ 
      // get parent id value from input choice 
      $parent = $category->getParentId(); 
      $parentCategory = $parent->getCategory(); 
      // end 
       $category->setParentId($parentCategory->getId()); 
      } 
      $em->persist($category); 
      $em->persist($categoryDesc); 
      $em->flush(); 

      return $this->redirect($this->generateUrl('apw_blackbull_categories_showcategories')); 
     } 

     return array(
      'form' => $form->createView() 
     ); 
    } 

dzięki!

+0

Jak do tego doszło? Mam podobny problem z kontrolerem i zagnieżdżony jeden do wielu relacji, i jest uszkodzony, gdy są pewne wiersze w tabeli (działa dobrze, gdy db jest pusta). Zgaduję więc, że mój problem jest podobny do twojego (naprawia się go, tworząc '__toString', ale to jest dla mnie hackowanie). Wiedząc, w jaki sposób otrzymałeś to rozwiązanie, pomóż mi rozwiązać mój problem! –

67

Musisz wdrożyć metodę __toString() w swoim Apw\BlackbullBundle\Entity\CategoriesDescription.

Można zrobić:

public function __toString() { 
    return $this->name; 
} 
+0

Witam CoachNono próbowałem Twojego kodu, a wartość parentId jest abject: object (stdClass) # 620 (10) {["__CLASS __"] => ciąg (37) "Apw \ BlackbullBundle \ Entity \ Categories" [" id "] => NULL [" categoriesImage "] => ciąg (6)" hp.jpg "[" parentId "] => obiekt (stdClass) # 765 (5) {[" __CLASS __ "] => ciąg (48) "Apw \ BlackbullBundle \ Entity \ CategoriesDescription" ["id"] => int (36) ["categoriesName"] => string (17) "Komputer osobisty" ["category"] => string (52) "Proxy \ __ CG__ \ Apw \ BlackbullBundle \ Entity \ Categories "[" języki "] => NULL} [" sortOrder "] => NULL [" dateAdded "] => NULL [" lastModified "] => NULL [" categoriesStat ... – Falar

+0

this pracował dla mnie, jednak kiedy edytuję formularz, w którym wszystkie dane są wstępnie wypełnione, menu rozwijane domyślnie nie pokazuje zapisanej opcji - jak to zrobić? – Baig

+0

Zwykle powinno się opublikować nowe pytanie i połączyć je tutaj a ja wezmę kibel k na to – CoachNono

0

Można również użyć nieruchomości akcesor do formularza:

->add('categoryDescription', 'collection', 
      array(
       'type'   => new CategoriesDescriptionType(), 
       'allow_add' => true, 
       'options'  => array('data_class' => 'Apw\BlackbullBundle\Entity\CategoriesDescription'), 
       'by_reference' => false, 

      )) 

I dodać 'property' => 'name' w CategoriesDescriptionType.

Przy okazji odpowiedź @CoachNono też jest OK.

+0

Witam Smashou Wypróbowałem twój kod i błąd jest: Opcja "właściwość" nie istnieje w typie wejściowym kolekcji. – Falar

+0

Moja bad, właściwość musi być w twoich kategoriach Types TypeType – Smashou

+0

jeśli zastosuję metodę __toString() nie przypisuje wartości jej parentId – Falar

3

Dla Symfony 3.x

Zgodnie z Symfony docs v3.x należy użyć choice_label właściwości można określić nazwę pola jednostka ma być używany tutaj.

->add('categoryDescription', 'collection', 
     array(
      'type'   => new CategoriesDescriptionType(), 
      'allow_add' => true, 
      'options'  => array('data_class' => 'Apw\BlackbullBundle\Entity\CategoriesDescription'), 
      'choice_label' => 'name', 
      'by_reference' => false, 

     )) 
1

Mam ten sam błąd, ale manipulowane go trochę dodając:

public function __toString() { 
return (string) $this->name; } 

jestem sur byłem coraz zerowy zamiast wartości strun. (Pracowałem z projektem sonata).

Powiązane problemy