0
votes

I have two entities with some properties:

  1. Category
    • category name
    • category description
  2. Subcategory
    • subcategory name
    • subcategory description
    • Category ID (ManyToOne relation)

There is a ManyToOne relation in the subcategory entity i.e. several subcategories can be connected to one category.

I would like to build a form with a dropdown listing all the subcategories, but I would like to display the name of category and subcategory, the list would look like so:

  • Category1 - Subcategory1
  • Category1 - Subcategory2
  • Category1 - Subcategory3
  • Category2 - Subcategory1
  • Category2 - Subcategory2
  • Category2 - Subcategory3
  • etc...

I'm thinking about creating a getter in the subcategory class that would return a concatenation of the category name and subcategory name, something like sprintf('%s - %s', $this->categoryName, $this->subcategoryName), but I can't see how I could access Category object properties using the subcategory class getter...

Any idea about the best practice to achieve this?

Thank you, JM

2

2 Answers

3
votes

I managed to do this by building the form like so:

        $builder
         ->add('subcategoryName', EntityType::class, array(
          'class'    => 'AppBundle:subcategory',
          'query_builder' => function(EntityRepository $er) {
            return $er->createQueryBuilder('u')
                ->addSelect('t')
                ->join('u.category', 't' )
                ->orderBy('t.category', 'ASC')
                ->addOrderBy('u.subcategory', 'ASC');
          },
          'choice_label' => function($subcategoryname){
            return $categoryname->getcategory()->getcategoryname() . " - " . $subcategoryname->getsubcategoryName();
          },
          'multiple' => false,
          'expanded' => false,
            ))

I was only strugling a bit with the choice_label option.

/JM

0
votes

You can use this method it is clear.when you have the IdCategory of Subcategory table, you access the fields Category table too

 ->add('idCategory', EntityType::class,array(
                'data'   =>  $options[0]['idCategory'],
                'class' => 'AppBundle:subcategory',
                'choice_label' => function (subcategory $subcategory) {
                    return $subcategory->getName() . '-' . $subcategory->getCategoryID()->getName().'-'.$subcategory->getCategoryID()->getDescription();
                },
                'attr' => array(
                    'label'    => 'Category ',
                    'class' => 'form-control'
                )
            ))