Search code examples
phpsymfony4easyadmin

PHP Symfony EasyAdmin - configure actions - cant find field choice


I dont know where i can find place to change field from list to checkbox. I want to change form in EasyAdmin, in my field i have:

<div class="form-group  field-entity">

and i want to change it to:

<div class="form-group  field-choice">

I looked for in source code but i cant find the place where is it. In easy_admin.yaml i have only label of my form and i don't have details of this settings :/

edit:

in templates/bundles/ i dont have directory like: EasyAdminBundle in src/Controller/EasyAdmin i have only CatalogListUserController.php - backend code

EDIT: in: /src/Controller/EasyAdmin/CatalogListUserController.php i have:

namespace App\Controller\EasyAdmin;
use EasyCorp\Bundle\EasyAdminBundle\Controller\EasyAdminController;
use EasyCorp\Bundle\EasyAdminBundle\Event\EasyAdminEvents;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Response;
use App\Entity\{Report, CatalogList, CatalogListUser};
use DateTime;
use Doctrine\ORM\EntityRepository;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;

class CatalogListUserController extends EasyAdminController
{
    // public function createNewFormBuilder($entity, $view)
    public function createEntityFormBuilder($entity, $view)
    {
        $id = $this->getUser()->getId();
        $em = $this->getDoctrine()->getManager();
        $conn = $em->getConnection();
        $sql = "SELECT id, `name` FROM `catalog_list` WHERE user_id = $id AND status = 1";
        $stmt = $conn->prepare($sql);
        $stmt->execute();
        $rows = $stmt->fetchAll();
        $choices = [];
        foreach($rows as $row) {
            $choices[$row['name']] = $row['id'];
        }
        
        $ids = [];
        if ($view === 'edit') {
            $selected = $entity->getUser()->getListUsers();
            foreach ($selected as $s){
                $ids[] = $s->getId();
            }
        }

        $formBuilder = parent::createEntityFormBuilder($entity, $view);
        
        // Listy - checkbox
        $formBuilder->add('catalogLists', ChoiceType::class, [
            'required' => true,
            'multiple' => true,
            'expanded' => true,
            'label' => 'Listy',
            'choices' => $choices, 
            'data' => $ids,          
        ]);

    // User - change list of users but we dont create user list here - and we cant set here list or checkbox
        $fields = $formBuilder->all();
        foreach ($fields as $fieldId => $field) {
            if ($fieldId == 'user') {
                $options = [
                    'class' => 'App\Entity\User',
                ];
                $options['query_builder'] = function (EntityRepository $er) {
                    $qb = $er->createQueryBuilder('e');
        
                    return $qb->where($qb->expr()->eq('e.company', ':company'))
                        ->setParameter('company', $this->getUser()->getCompany())
                        ->orderBy('e.firstname', 'DESC');
                };
                $formBuilder->add($fieldId, EntityType::class, $options);
            } 
        }
           

        return $formBuilder;
    }

    /**
     * The method that is executed when the user performs a 'new' action on an entity.
     *
     * @return Response|RedirectResponse
     */
    protected function newAction()
    {
        $this->dispatch(EasyAdminEvents::PRE_NEW);

        $entity = $this->executeDynamicMethod('createNew<EntityName>Entity');

        $easyadmin = $this->request->attributes->get('easyadmin');
        $easyadmin['item'] = $entity;
        $this->request->attributes->set('easyadmin', $easyadmin);

        $fields = $this->entity['new']['fields'];

        $newForm = $this->executeDynamicMethod('create<EntityName>NewForm', [$entity, $fields]);

        $newForm->handleRequest($this->request);
        if ($newForm->isSubmitted() && $newForm->isValid()) {
            foreach ($entity->catalogLists as $id) {
                // check if already exists
                $catalogList = $this->getDoctrine()->getRepository(CatalogList::class)->find($id);
                $catalogListUser = $this->getDoctrine()->getRepository(CatalogListUser::class)->findOneBy(['user' => $entity->getUser(), 'list' => $catalogList, 'status' => 1]);
                // add to database
                if (!$catalogListUser) {
                    $newEntity = clone $entity;
                    $newEntity->setList($catalogList);
                    $this->dispatch(EasyAdminEvents::PRE_PERSIST, ['entity' => $newEntity]);
                    $this->executeDynamicMethod('persist<EntityName>Entity', [$newEntity, $newForm]);
                    $this->dispatch(EasyAdminEvents::POST_PERSIST, ['entity' => $newEntity]); 
                }
            }

            return $this->redirectToReferrer();
        }

        $this->dispatch(EasyAdminEvents::POST_NEW, [
            'entity_fields' => $fields,
            'form' => $newForm,
            'entity' => $entity,
        ]);

        $parameters = [
            'form' => $newForm->createView(),
            'entity_fields' => $fields,
            'entity' => $entity,
        ];

        return $this->executeDynamicMethod('render<EntityName>Template', ['new', $this->entity['templates']['new'], $parameters]);
    }

    protected function createListQueryBuilder($entityClass, $sortDirection, $sortField = null, $dqlFilter = null)
    {

        $response =  parent::createListQueryBuilder('CatalogListUser, User', $sortDirection, $sortField, $dqlFilter); // TODO: Change the autogenerated stub

        $response->join('entity.user','user');
        $response->andWhere('user.company = :company')->andWhere('entity.status = 1')->setParameter('company', $this->getUser()->getCompany());

        return $response;
    }
}

and my form is: enter image description here so i want at Users change from list to checkbox. As you see in my code line:

foreach ($fields as $fieldId => $field) {

only change my content of this list but when i comment thos block i still have list here - so this list is generated in another place - i cant find it, this is problem :/

regards


Solution

  • Fields on Easyadmin are configured from the CRUD controller configureFields() method. If your crud controller is CatalogListUserController (if you have created it from console it is maybe located at src/Controller/Admin/CatalogListUserCrudController.php) you could do something like this:

    class CatalogListUserController extends AbstractCrudController
    {
        //...
    
        public function configureFields(string $pageName): iterable
        {
            return [
                // other fields...
                
                ChoiceField::new('your_field_name')
                    ->setChoices([
                        'Choice 1' => 'value1',
                        'Choice 2' => 'value2',
                        // ...
                    ])                
                // other fields...
            ];
        }
    

    Refer to this doc to configure fields and its behaviour: https://symfony.com/bundles/EasyAdminBundle/current/fields.html