Lets say I have a Car Entity. Other than typical Car properties I have updatedBy attribute
In sonata I created a CRUD admin page using AppBundle\Admin\CarAdmin.php
Inside the class CarAdmin I have the required methods like configureListFields, configureFormFields, etc...
I'm guessing I need to add updatedBy using the method prePersist($object) but I'm facing that $this->getUser() is not available
The question is, how can I get the logged in user to populate updateBy attribute?
You can get logged user using $this->getConfigurationPool()->getContainer()->get('security.context')->getToken()->getUser(). In your case you need to do something like this:
public function setUpdatedByAttribute($car)
{
$user = $this->getConfigurationPool()->getContainer()->get('security.context')->getToken()->getUser();
$car->setUpdatedBy($user);
}
public function prePersist($car)
{
$this->setUpdatedByAttribute($car);
}
public function preUpdate($car)
{
$this->setUpdatedByAttribute($car);
}
Related
I've used the maker bundle to create a standard login form. When the user has successfully logged in it calls function onAuthenticationSuccess to redirect to the new page.
public function onAuthenticationSuccess(Request $request, TokenInterface $token, $providerKey)
{
return new RedirectResponse($this->urlGenerator->generate('app_homepage'));
}
However, I would like to redirect to different pages depending on what role the user has. I would like to do something like:
if ($this->security->isGranted('ROLE_STANDARD_USER')) {
return new RedirectResponse($this->urlGenerator->generate('app_homepage'));
}
if ($this->security->isGranted('ROLE_SYS_ADMIN')) {
return new RedirectResponse($this->urlGenerator->generate('app_ADMINpage'));
}
But the error I'm getting is Undefined property: App\Security\LoginFormAuthenticator::$security
Many thanks in advance for the help.
I didn't have much to go by, but it seems that the default implementation of the LoginFormAuthenticator does not request the AuthorizationChecker.
You can fix this by injecting an AuthorizationChecker into your class using the constructor. Example of how dependency injection works
Seeing as you have used the maker bundle, it is safe to assume you have autowiring turned on for your services, meaning that the Symfony kernel will automagically do all the rest of the work
i create an entity "Products".
in this entity, i get the price like
public function getPrice()
{
return $this->price;
}
Indeed, i would like to add in this method a session variable for convert currency like this :
public function getPrix()
{
$devise = $this->session->get('CurencyToConvert');
$json = json_decode(file_get_contents('http://api.fixer.io/latest?symbols='.$devise));
$rates = $json->rates->CHF;
return $this->prix * $rates;
}
but i think this is the wrong solution.
i don't know how to do to get an automatic conversion when i get the price!!
do I create a service for my checkout and a twig filter for my views?
thank you
The Products class is a POPO (Playing Old PHP Object) it's really required to keep it simple which means this class must have only attributes like price and getters and setters for those attributes,
You can create a service to handle Currency conversion, and you can also inject it into a twig filter so you gonna have one piece of code implementing this functionality
I am using Symfony version 2.7.6. I have created an entity named EmployeeBasicInfo having fields
firstname
lastname
identificationCode etc
I have created a callback function for validating Identification code in EmployeeBasicInfo entity itself which looks like
/**
* #Assert\Callback(groups={"edit_myinfo"})
*/
public function validateIdentificationCode(ExecutionContextInterface $context)
{
if ($this->getEmployeeFirstName() == 'fakename') {
$context->buildViolation('This name sounds totally fake!')
->atPath('employeeFirstName')
->addViolation();
}
}
and this callback function works properly
Actually I want such a callback functionality which checks identidfication code against database. I have added $em = $this->getDoctrine()->getManager(); inside the callback function and the error is like Attempted to call an undefined method named "getDoctrine" of class "XXX\EmployeeBundle\Entity\EmployeeBasicInfo".. Please advise me the effective way
Do not inject the EntityManager in your Entity. One basic concept of the DataMapper-Pattern is, that your entity does not have to know about your data source and its connectors.
I'd suggest to write a custom validation constraint, in which you inject the dependencies you need.
EntityManager, Repository to query, etc. Whatever service suits you.
Have a look at how to create custom constraint validators with dependencies
I would suggest you use a service to do this
class EmployeeUtility($connection)
{
public function __construct($conn) { $this->connection = $v; }
public function validateIdentificationCode($emloyeeId, $validationCode)
{
// Your code here
}
}
In your controller, you inject the service:
$employeeUtility = $this->get('employee.utility');
$employeeUtility->validateIdentificationCode(1,'GF38883dkDdW3373d');
Alternatively, add the code in a repository class.
According to the Sonata source code, the last node in the breadcrumb is rendered this way:
# standard_layout.html.twig #
<li class="active"><span>{{ menu.label }}</span></li>
In my setup, when opening a given Admin subclass, the last node simply becomes a raw string according to the entity handled by the Admin:
Dashboard / Entity List / Acme\SomeBundle\Entity\Stuff:000000001d74ac0a00007ff2930a326f
How can I set the value of menu.label to get something more appropriate? I have tried, in my Admin subclass, to override the following:
protected function configureTabMenu(MenuItemInterface $menu, $action, AdminInterface $childAdmin = null) {
$this->configureSideMenu($menu, $action, $childAdmin);
}
protected function configureSideMenu(MenuItemInterface $menu, $action, AdminInterface $childAdmin = null) {
$menu->setLabel("Some nice label");
$menu->setName("Some nice name");
}
However, this does not change anything, even though I have verified that the methods above are called during runtime.
Finally found a good (and somewhat obvious) solution to this.
The Sonata Admin class uses an internal toString($object) method in order to get a label string for the entity it is handling. Thus, the key is to implement the __toString() method of the entity in question:
public function __toString() {
return "test";
}
The best way is to configure the $classnameLabel variable in the Admin Class :
class fooAdmin extends Admin
{
protected $classnameLabel = 'Custom Label';
}
But it have the same issue (weird name with entity path) doing it, even if it is working fine on all the others pages.
Apparently, the Sonata way of solving this is show here:
Quote:
While it’s very friendly of the SonataAdminBundle to notify the admin of a successful creation, the classname and some sort of hash aren’t really nice to read. This is the default string representation of an object in the SonataAdminBundle. You can change it by defining a toString() (note: no underscore prefix) method in the Admin class. This receives the object to transform to a string as the first parameter:
Source: https://sonata-project.org/bundles/admin/master/doc/getting_started/the_form_view.html#creating-a-blog-post
I am creating an application where visitors can upload some stuff (it will be for invited people only). At the end, if they are not logged in, they are asked to log in or create a user. If they create a new user, I only want to ask them to fill in their name and email.
a password will be generated, and a mail will be sent to the user with the links to change their password if they want to (only to make the procedure as low level as possible).
I can't seem to remove the password fields from the registration form. Can someone help me out. I create a custom form type, service and registered it. I also put custom templates in the app/Resource folder etc. Although my custom Form type AND the templates are being used, the password still appears ...
class RegistrationFormType extends BaseType {
public function buildForm(FormBuilderInterface $builder, array $options) {
parent::buildForm($builder, $options);
// add your custom field
$builder->add('username');
$builder->add('email');
}
public function getName() {
return 'val_user_registration';
}
}
You don't need to extend your parent form ... and you're better off not doing it in this case.
just create a Username/Email form and create the new User entity yourself in a custom registration method then persisting it into database ( don't forget to set the usernameCanonical property on your newly created User ).
FOSUserBundle calls several password-related things during the registration process which you don't need and can't easily circumvent in this case.
You can pass the entity ( with newly created password ) to the update method of FOSUserBundle's UserManager service after you have completed the password/email step then.