简体   繁体   中英

Sonata - Use the repository of an entity in admin

I am working on a Symfony project, using Sonata.

Context:

I got different entities:

  • Product ( ID , categories (relation) , characteristicValues (relation) )
  • Category ( ID , characteristics (relation) )
  • Characteristic ( ID , id_category (relation) , label ).
  • CharacteristicValue ( ID , id_product (relation) , id_characteristic (relation) , value )

Relations:

  • Product --OneToMany--> CharacteristicValue
  • Category -->OneToMany--> Characteristic
  • Characteristic -->OneToMany--> CharacteristicValue
  • Product --ManyToMany--> Category

Problem:

I need to get all characteristics of a the categories of a product (and their values if they're set) in the ProductAdmin, and show an input for each of them (like Characteristic1 : value1).

What I did:

I tried to call a function the CharacteristicValueRepository in the ProductAdmin , but the repository was not instantiated.

The code of ProductAdmin is really basic:

final class ProductAdmin extends AbstractAdmin
{
  protected function configureFormFields(FormMapper $formMapper)
  {

    $formMapper
    ->with('Product information', ['class' => 'col-md-6'])
        ->add('name', TextType::class, [
            'label' => 'Name of the product'
        ])
        ->add('categories', EntityType::class, [
            'class' => Category::class,
            'choice_label' => 'name',
            'multiple' => true,
            'label' => 'Categories of the product'
        ])
  ->end();

}

protected function configureDatagridFilters(DatagridMapper $datagridMapper)
{
    $datagridMapper->add('name');
    $datagridMapper->add('categories');
}

protected function configureListFields(ListMapper $listMapper)
{
    $listMapper->add('id');
    $listMapper->addIdentifier('name');
    $listMapper->addIdentifier('categories');
}
}

Notes:

I am using the last version of everything (Symfony, Sonata, ...)

If someone knows how to help me, I would be really grateful!

You need to configure custom form type for example ProductCharacteristicsType. While using Form Event listeners you could fetch all characteristics and form a proper collection. What you have here is EAV (Entity attribute value) model. It may cause confusion for Symfony, but it is manageable. On SonataAdmin you must use that custom type of yours.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM