symfony2 erreur fatale saisissable: L'objet de la classe n'a pas pu être converti en chaîne

j'ai cette Entité définie:

<?php

namespace ApwBlackbullBundleEntity;

use DoctrineCommonCollectionsArrayCollection;
use DoctrineORMMapping as ORM;

/**
* Categories
*
* @ORMTable()
*    @ORMEntity(repositoryClass="ApwBlackbullBundleEntityCategoriesRepository")
*/
class Categories
{
/**
 * @var integer
 *
 * @ORMColumn(name="id", type="integer")
 * @ORMId
 * @ORMGeneratedValue(strategy="AUTO")
 */
private $id;

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

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

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

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

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

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

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

/**
 * @ORMManyToMany(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 ApwBlackbullBundleEntityCategoriesDescription $categoryDescription
 * @return Categories
 */
public function addCategoryDescription(ApwBlackbullBundleEntityCategoriesDescription $categoryDescription)
{
    $this->categoryDescription[] = $categoryDescription;

    return $this;
}

/**
 * Remove categoryDescription
 *
 * @param ApwBlackbullBundleEntityCategoriesDescription $categoryDescription
 */
public function removeCategoryDescription(ApwBlackbullBundleEntityCategoriesDescription $categoryDescription)
{
    $this->categoryDescription->removeElement($categoryDescription);
}

/**
 * Get categoryDescription
 *
 * @return DoctrineCommonCollectionsCollection
 */
public function getCategoryDescription()
{
    return $this->categoryDescription;
}

/**
 * Add products
 *
 * @param ApwBlackbullBundleEntityProducts $products
 * @return Categories
 */
public function addProduct(ApwBlackbullBundleEntityProducts $products)
{
    $this->products[] = $products;

    return $this;
}

/**
 * Remove products
 *
 * @param ApwBlackbullBundleEntityProducts $products
 */
public function removeProduct(ApwBlackbullBundleEntityProducts $products)
{
    $this->products->removeElement($products);
}

/**
 * Get products
 *
 * @return DoctrineCommonCollectionsCollection
 */
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;
}
}

Puis-je avoir cette méthode dans mon contrôleur pour gérer l'envoi du formulaire:

<?php

namespace ApwBlackbullBundleController;


use ApwBlackbullBundleEntityCategories;
use ApwBlackbullBundleEntityCategoriesDescription;
use ApwBlackbullBundleFormCategoriesType;
use SymfonyBundleFrameworkBundleControllerController;
use SensioBundleFrameworkExtraBundleConfigurationRoute;
use SensioBundleFrameworkExtraBundleConfigurationTemplate;
use SymfonyComponentHttpFoundationJsonResponse;
use SymfonyComponentHttpFoundationRequest;
use SymfonyComponentFormExtensionCoreChoiceListChoiceList;
use SensioBundleFrameworkExtraBundleConfigurationSecurity;


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(DoctrineCommonUtilDebug::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()
    );
}

}

et enfin voici mon CategoryType.php:

<?php

namespace ApwBlackbullBundleForm;

use DoctrineORMEntityRepository;
use SymfonyComponentFormAbstractType;
use SymfonyComponentFormFormBuilderInterface;
use SymfonyComponentOptionsResolverOptionsResolverInterface;

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' => 'ApwBlackbullBundleEntityCategoriesDescription'),
                    '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' => 'ApwBlackbullBundleEntityCategories',
        ));
    }

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

Quand j'essaie d'enregistrer les données, j'obtiens cette erreur:

une exception s'est produite lors de l'exécution ' insérer dans les catégories (categories_image, parent_id, sort_order, date_added, last_modified, categories_status) valeurs (?, ?, ?, ?, ?, ?) avec des params ["comme", {}, null, null, null, 1]:

erreur fatale relevable: objet de la classe ApwBlackbullBundleEntityCategoriesDescription n'a pas pu être converti en chaîne

Qu'est-ce que je fais de mal?

29
demandé sur Falar 2015-02-25 05:27:25

5 réponses

vous devez implémenter le __toString() dans votre Apw\BlackbullBundle\Entity\CategoriesDescription.

Tu pourrais faire:

public function __toString() {
    return $this->name;
}
82
répondu CoachNono 2015-02-25 03:35:57

Pour Symfony 3.x

Selon Symfony docs v3.x vous devez utiliser choice_label propriété pour spécifier l'entité nom du champ à utiliser ici.

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

        ))
5
répondu Giovani 2017-08-29 17:48:02

j'ai eu la même erreur mais je l'ai légèrement modifiée en ajoutant:

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

je suis sur que j'obtenais null au lieu d'une valeur de chaîne. (Je travaillais avec sonata-project).

3
répondu Oussama Keddar 2017-11-24 15:06:08

alors j'ai résolu le problème en obtenant la valeur de parent relatif dans la méthode $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()
        );
    }

merci!

1
répondu Falar 2016-04-04 08:40:53

Vous pouvez également utiliser le propriété accesseur dans votre formulaire:

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

            ))

'property' => 'name' dans votre CategoriesDescriptionType.

0
répondu Smashou 2015-02-25 13:58:28