0

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 Answers 2

3

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

Sign up to request clarification or add additional context in comments.

Comments

0

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'
                )
            ))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.