Reputation: 293
How do I pass a variable to all controllers in my project?
Let's say I have one Entity called User that relates to Company, and Company relates to Products, Customers and others entities.
When the User enters the app, he will choose in a dropdown which Company he will use (because he can have more than 1 company).
Right now I am injecting TokenStorageInterface and doing this in my controllers
$user = $tokenStorage->getToken()->getUser();
and
$form->add('company', EntityType::class, [
'class' => Company::class,
'choice_label' => 'name',
'choice_value' => 'id',
'label' => 'Company:',
'choices' => $user->getCompanies()
]);
but the problem is that I am repeating this code in every form and in every controller, and I have a lot. Also, I dont want to have a dropdown with the Companies in every form, I would like to save the company_id automatic based on his choice when he entered the app, so all CRUD operations would be saved with this company_id in the FK. And if the User want to change the Company, he just go to a fixed dropdown in the navbar (for example), and change it, changing the ID in this global variable.
How can I achieve this?
Upvotes: 1
Views: 536
Reputation: 531
You can use https://symfony.com/doc/4.0/templating/embedding_controllers.html in your template.
The best way is to create own service that provides necessary logic. Then load this service into the controller and embed this action in template.
Upvotes: 1