Search code examples
symfonysonata-adminsymfony-sonatasonata-user-bundle

Sonata Admin Bundle: for create new, how can I have user already selected?


I have two (2) Admins, UserAdmin and CarAdmin. From the list view of UserAdmin, I want to have a custom action that redirects to CarAdmin create view with the user already selected.

So far I have managed to create a custom action with its controller. My challenge is to redirect to CarAdmin create/new form passing some parameters for data persistence.

Any points of reference will be much appreciated. Thanks


Solution

  • Sonata Admin allows to resolve such task pretty easy, no need to make a custom action. One of the solutions could be:

    • Define a custom template for one column in UserAdmin list view, render a special button(link) in it. A link should lead to CarAdmin create action with some get parameter.
    • In CarAdmin in method getNewInstance() check that if there is a special get parameter - set user with that ID. This step can also be done in methods getFormFields(), prePersist(), etc.

    Some code samples:

    In UserAdmin

    protected function configureListFields(ListMapper $listMapper)
    {
        $listMapper
            ->add('actions', 'string', array(
                'template' => 'your_template_name.html.twig',
                'mapped' => false,
                )
           );
    }
    

    In your_template_name.html.twig

    <a href="{{ path('route_of_the_car_admin_create', {user: object.id}) }}">Create Car for this user</a>
    

    In CarAdmin

    public function getNewInstance()
    {
        $car= parent::getNewInstance();
    
        $userId = $this->getRequest()->query->get('user');
        if ($userId) {
            $em = $this->modelManager->getEntityManager(User::class);
            $user = $em->getRepository(User::class)->find($id);
            $car->setUser($user);
        }
        return $car;
    }