0
votes

I am trying to learn Symfony2 and currently : Entity Relationships/Associations (Joining to Related Records) . I have a problem I can not get correct

Notice: Undefined index: roles 500 Internal Server Error - ContextErrorException

This is the my code:

*Class Role:

class Roles
{
    /**
     * @var integer
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;


    /**
     * @var string
     *
     * @ORM\Column(name="nom_roles", type="string", length=225, nullable=false)
     *@Assert\NotBlank(message="le champ nom du role est obligatoire")
     *
     */
    Private $name_role;

    /**
     * @var ArrayCollection $groups
     *
     * @ORM\OneToMany(targetEntity="Groups", mappedBy="roles", cascade={"persist","merge"})
     *@Assert\Valid()
     */
    protected $groups;  
    /**
     * @var ArrayCollection Permissions $permision
     *
     * @ORM\ManyToMany(targetEntity="Permissions", inversedBy="roleGroup", cascade={"persist", "merge"})
     * @ORM\JoinTable(name="roles_permissions",
     *   joinColumns={@ORM\JoinColumn(name="id_rolesGR", referencedColumnName="id")},
     *   inverseJoinColumns={@ORM\JoinColumn(name="id_permGR", referencedColumnName="id_per")}
     * )
     * @Assert\Valid()
     */
    protected $permissions_role;

    /**
     * Roles constructor.
     */
    public function __construct()
    {
        $this->groups = new ArrayCollection();
        $this->permissions_role = new ArrayCollection();
    }

-class permissions:

class Permissions {

/**
 * @var integer
 *
 * @ORM\Column(name="id_per", type="integer")
 * @ORM\Id
 * @ORM\GeneratedValue(strategy="AUTO")
 */
private $id;

/**
 * @var string
 * @ORM\Column(name="nom_permisions", length=255, nullable=true)
 * @Assert\NotBlank(message="le choix des permissions sont obligatoire")
 */
private $name_permissions;


/**
 * @var ArrayCollection Roles $roleGroup
 *
 * Inverse Side
 *
 * @ORM\ManyToMany(targetEntity="Roles", mappedBy="permissions", cascade={"persist", "merge"})
 *@Assert\Valid()
 */
protected $roleGroup;

-Class Groups:

class Groups
{

/**
 * @var integer
 *
 * @ORM\Column(name="id_groupes", type="integer")
 * @ORM\Id
 * @ORM\GeneratedValue(strategy="AUTO")
 * 
 */
private $id;
/**
 * @var string
 *
 *-- contrainte sur le chmap
 *
 * @Assert\NotBlank(message="le champ nom du groupe est obligatoire")
 *
 * @Assert\Type(
 *     type="string",
 *     message="la valeur {{ value }} n'est pas valide {{ type }}.
 *     Elle est de type chaine des cractéres"
 * )
 *
 * @Assert\Length(
 *     min=5,
 *     max= 50,
 *     minMessage="votre nom du groupe doit comprendre au moins {{ limit }} caractéres",
 *     maxMessage="votre nom du groupe doit comprendre au maximun {{ limit }} caractéres"
 * )
 *
 * @ORM\Column(name="nom_groupe", type="string", length=225, nullable=false)
 *@Assert\NotBlank(message="le champ nom du groupe est obligatoire")
 *
 *
 */
 Private $name_groups;

/**
 * @var DateTime()
 *
 * @ORM\Column(name="date_creation", type="datetime",nullable=false)
 *
 *@Assert\DateTime()
 */
 private $date_create;

/**
 * @ORM\OneToOne(targetEntity="Images", cascade={"persist", "merge", "remove"})
 * @ORM\JoinColumn(name="image_id", referencedColumnName="id_images")
 * @Assert\Valid()
 */
protected $image;
/**
 * @var Roles $role
 *
 * @ORM\ManyToOne(targetEntity="Roles", inversedBy="groups", cascade={"persist", "merge"})
 * @ORM\JoinColumns({
 *  @ORM\JoinColumn(name="role_id", referencedColumnName="id", nullable=false)
 * })
 * @Assert\Valid()
 */
protected $role;

-here is my controller

class GroupsController extends Controller

{ public function indexAction()
    {
    $em = $this->getDoctrine()->getManager();

    $entities = $em->getRepository('GroupsBundle:Groups')->findAll();

    return $this->render('GroupsBundle:Groups:index.html.twig', array(
        'entities' => $entities,
    ));
}
/**
 * Creates a new Groups entity.
 *
 */
public function createAction(Request $request)
{
    $entity = new Groups();
    $form = $this->createCreateForm($entity);
    $form->handleRequest($request);

    if ($form->isValid()) {
        $em = $this->getDoctrine()->getManager();
        $em->persist($entity);
        $em->flush();

        return $this->redirect($this->generateUrl('groups_show', array('id' => $entity->getId())));
    }

    return $this->render('GroupsBundle:Groups:new.html.twig', array(
        'entity' => $entity,
        'form'   => $form->createView(),
    ));
}

/**
 * Creates a form to create a Groups entity.
 *
 * @param Groups $entity The entity
 *
 * @return \Symfony\Component\Form\Form The form
 */
private function createCreateForm(Groups $entity)
{
    $form = $this->createForm(new GroupsType(), $entity, array(
        'action' => $this->generateUrl('groups_create'),
        'method' => 'POST',
    ));

    $form->add('submit', 'submit', array('label' => 'Create'));

    return $form;
}

/**
 * Displays a form to create a new Groups entity.
 *
 */
public function newAction()
{
    $entity = new Groups();
    $form   = $this->createCreateForm($entity);

    return $this->render('GroupsBundle:Groups:new.html.twig', array(
        'entity' => $entity,
        'form'   => $form->createView(),
    ));
}

/**
 * Finds and displays a Groups entity.
 *
 */
public function showAction($id)
{
    $em = $this->getDoctrine()->getManager();

    $entity = $em->getRepository('GroupsBundle:Groups')->find($id);

    if (!$entity) {
        throw $this->createNotFoundException('Unable to find Groups entity.');
    }

    $deleteForm = $this->createDeleteForm($id);

    return $this->render('GroupsBundle:Groups:show.html.twig', array(
        'entity'      => $entity,
        'delete_form' => $deleteForm->createView(),
    ));
}

/**
 * Displays a form to edit an existing Groups entity.
 *
 */
public function editAction($id)
{
    $em = $this->getDoctrine()->getManager();

    $entity = $em->getRepository('GroupsBundle:Groups')->find($id);

    if (!$entity) {
        throw $this->createNotFoundException('Unable to find Groups entity.');
    }

    $editForm = $this->createEditForm($entity);
    $deleteForm = $this->createDeleteForm($id);

    return $this->render('GroupsBundle:Groups:edit.html.twig', array(
        'entity'      => $entity,
        'edit_form'   => $editForm->createView(),
        'delete_form' => $deleteForm->createView(),
    ));
}

/**
* Creates a form to edit a Groups entity.
*
* @param Groups $entity The entity
*
* @return \Symfony\Component\Form\Form The form
*/
private function createEditForm(Groups $entity)
{
    $form = $this->createForm(new GroupsType(), $entity, array(
        'action' => $this->generateUrl('groups_update', array('id' => $entity->getId())),
        'method' => 'PUT',
    ));

    $form->add('submit', 'submit', array('label' => 'Update'));

    return $form;
}
/**
 * Edits an existing Groups entity.
 *
 */
public function updateAction(Request $request, $id)
{
    $em = $this->getDoctrine()->getManager();

    $entity = $em->getRepository('GroupsBundle:Groups')->find($id);

    if (!$entity) {
        throw $this->createNotFoundException('Unable to find Groups entity.');
    }

    $deleteForm = $this->createDeleteForm($id);
    $editForm = $this->createEditForm($entity);
    $editForm->handleRequest($request);

    if ($editForm->isValid()) {
        $em->flush();

        return $this->redirect($this->generateUrl('groups_edit', array('id' => $id)));
    }

    return $this->render('GroupsBundle:Groups:edit.html.twig', array(
        'entity'      => $entity,
        'edit_form'   => $editForm->createView(),
        'delete_form' => $deleteForm->createView(),
    ));
}
/**
 * Deletes a Groups entity.
 *
 */
public function deleteAction(Request $request, $id)
{
    $form = $this->createDeleteForm($id);
    $form->handleRequest($request);

    if ($form->isValid()) {
        $em = $this->getDoctrine()->getManager();
        $entity = $em->getRepository('GroupsBundle:Groups')->find($id);

        if (!$entity) {
            throw $this->createNotFoundException('Unable to find Groups entity.');
        }

        $em->remove($entity);
        $em->flush();
    }

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

/**
 * Creates a form to delete a Groups entity by id.
 *
 * @param mixed $id The entity id
 *
 * @return \Symfony\Component\Form\Form The form
 */
private function createDeleteForm($id)
{
    return $this->createFormBuilder()
        ->setAction($this->generateUrl('groups_delete', array('id' => $id)))
        ->setMethod('DELETE')
        ->add('submit', 'submit', array('label' => 'Delete'))
        ->getForm()
    ;
}

}

the problem:

Catchable Fatal Error: Argument 1 passed to Doctrine\Common\Collections\ArrayCollection::__construct() must be of the type array, object given, called in /home/cros/Desktop/Project_Console/vendor/doctrine/orm/lib/Doctrine/ORM/UnitOfWork.php on line 555 and defined 500 Internal Server Error - ContextErrorException

*Stack Trace:

in vendor/doctrine/collections/lib/Doctrine/Common/Collections/ArrayCollection.php at line 48 -

 /*
 * @param array $elements
 */
public function __construct(array $elements = array())
{
    $this->elements = $elements;
}

at ErrorHandler ->handleError ('4096', 'Argument 1 passed to Doctrine\Common\Collections\ArrayCollection::__construct() must be of the type array, object given, called in /home/cros/Desktop/Project_Console/vendor/doctrine/orm/lib/Doctrine/ORM/UnitOfWork.php on line 555 and defined', '/home/Cros/Desktop/Project_Console/vendor/doctrine/collections/lib/Doctrine/Common/Collections/ArrayCollection.php',

My GroupsType and RolesType:

  class GroupsType extends AbstractType
    {
        /**
         * @param FormBuilderInterface $builder
         * @param array $options
         */
        public function buildForm(FormBuilderInterface $builder, array $options)
        {
            $builder
                ->add('image',new ImagesType())
                ->add('name_groups', 'text',array('required' => true, 'attr' => array('placeholder' => 'Nom du groupe')))
                ->add('role', new RolesType())
            ;
        }
    }

//My RolesType:
class RolesType extends AbstractType
    {  
public function buildForm(FormBuilderInterface $builder, array $options)
        {

            $builder
               ->add('groups', 'entity',array(
                                                'class' => 'GroupsBundle:Roles',
                                                'choice_label' => 'name_role',
                                                /*'query_builder' => function(EntityRepository $er)
                                                {
                                                 return $er->createQueryBuilder('r')
                                                 ->orderBy('r.id', 'ASC');
                                                },*/
                                                 'required' => true,
                                                 'placeholder' => 'Choisir le role du votre groupe'
                                             )
               )

               ->add('permissions_role','entity',array(
                       'class' => 'GroupsBundle:Permissions',
                       'multiple' => true,
                       'expanded' => true,
                       'query_builder' => function(EntityRepository $er) {
                           return $er->createQueryBuilder('u')
                               ->orderBy('u.id', 'ASC');
                       },
                       'required' => true
                   )
                   )
                // ->add('permissions_role','number')

            ;

Thank you

1
When does this error occcured ? It seems that you trying to access to a non-existant array key. Can you show us the context of this error ? (a controller maybe ?).Ugo T.
the problem appears when I completed all fields (name, role, permissions) to create the group. (I changed the subject) may be the problem here -> mappedBy="roles" !!Cros
A stack trace would be quite useful here, otherwise it's almost a guessing gamekix

1 Answers

1
votes

It's quite hard to dig through all the code you've supplied here, but I'll try to help.

As I see, the $groups property in your Roles class is annotated with OneToMany having mappedBy set to "roles".

/**
 * @var ArrayCollection $groups
 *
 * @ORM\OneToMany(targetEntity="Groups", mappedBy="roles", cascade={"persist","merge"})
 * @Assert\Valid()
 */
protected $groups;

The target entity of the relation is Groups, and as far as I see from your listings, this entity does not have a roles property, it has role instead:

/**
 * @var Roles $role
 *
 * @ORM\ManyToOne(targetEntity="Roles", inversedBy="groups", cascade={"persist", "merge"})
 * @ORM\JoinColumns({
 *  @ORM\JoinColumn(name="role_id", referencedColumnName="id", nullable=false)
 * })
 * @Assert\Valid()
 */
protected $role;

You should try renaming this property to roles instead.