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;
}