I have an application which only admin can create users and I use FOSUserBundle.
I can create user but I've got some problems when I want to login the created user.
They can't login.
I use the default login from FOSUserBundle and it works with users created from command line.
What I missed to do?
This is my createAction from my UserController:
public function createAction(Request $request)
{
$user = new User();
$form = $this->createForm(new UserType(), $user);
if ($request->getMethod() == 'POST') {
$form->handleRequest($request);
if ($form->isValid()) {
$em = $this->getDoctrine()->getManager();
$em->persist($user);
$em->flush();
}
$this->get('session')->getFlashBag()->add('success', 'The user has been added!');
return $this->redirect($this->generateUrl('crm_users'));
}
return $this->render('LanCrmBundle:User:create.html.twig', array(
'form' => $form->createView(),
));
}
This is my buildForm:
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('username')
->add('email')
->add('enabled')
->add('password')
->add('roles', 'choice', array('choices' => array('ROLE_USER' => 'User', 'ROLE_ADMIN' => 'Admin'),'multiple' => true));
}
You are not encrypting the password while creating the user.
Change the code inside form valid success to,
if ($form->isValid()) {
$em = $this->getDoctrine()->getManager();
$userManager = $this->container->get('fos_user.user_manager');
$user->setPlainPassword($user->getPassword());
$userManager->updatePassword($user);
$em->persist($user);
$em->flush();
}
Maybe your default enabled value is false.
Try to set it directly :
if ($form->isValid()) {
$em = $this->getDoctrine()->getManager();
$user->setEnabled(true);
$em->persist($user);
$em->flush();
}
Or put it in your default value in entity class.
Related
Is there any way to refresh User session? I have my controller with change locale form, once it submitted i want to refresh that session with new set locale. I already tried to use session migrate() ,but unsuccessfully.
Any ideas?
Part of my controller
/**
* #route("/changeLocale", name="changeLocale")
*/
public function changeLocale(Request $request, Session $session)
{
$form = $this->createFormBuilder(null)
->add('locale', ChoiceType::class, [
'choices' => [
'Français' => 'fr_FR',
'Czech' => 'cs_CZ',
'English(US)' => 'en_US'
]
])
->add('save', SubmitType::class)
->getForm()
;
$form->handleRequest($request);
if ($form->isSubmitted()) {
$em = $this->getDoctrine()->getManager();
$locale = $form->getData()['locale'];
$user = $this->getUser();
$user->setLocale($locale);
$em->persist($user);
$em->flush();
$session->migrate();
}
return $this->render('admin/dashboard/locale.html.twig', [
'form' => $form->createView()
]);
}
That's the wrong way.
When you authenticate, you save the locale of your user entity in the session. Right? If you have a LocaleSubscriber that saves the locale in your session, recreating your session won't work. The locale is only saved in the session at authentication.
If you change the locale, you just need to update the session.
if ($form->isSubmitted()) {
$em = $this->getDoctrine()->getManager();
$locale = $form->getData()['locale'];
$user = $this->getUser();
$user->setLocale($locale);
$em->persist($user);
$em->flush();
// Update the session
$request->getSession()->set('_locale', $locale);
}
This is my code. I want to set default value from database in the form. I want to set value in form which i create in this method.
public function updateBlogAction(Request $request, $id)
{
$em = $this->getDoctrine()->getManager();
$data = $em->getRepository('AppBundle:Blog\Post')->find($id);
$blogs = new Post();
$form = $this->createFormBuilder($blogs)
->add('title', TextType::class, array('attr'=>array( 'class'=>'form-control','placeholder'=>'Blog title')))
->add('description', TextareaType::class, array('attr'=>array('class'=>'form-control','placeholder'=>'Blog description')))
->add('submit',SubmitType::class, array('label'=>'Add Blog', 'attr'=> array('class'=>'btn btn-primary pull-right')))
->getForm();
$form->handleRequest($request);
if( $form->isSubmitted() && $form->isValid() ){
$data->setTitle($blogs);
$em->flush();
return $this->redirectToRoute('blog');
}
return $this->render('blog/update_blog.html.twig', array(
'form' => $form->createView()
));
}
It is as easy as
$em = $this->getDoctrine()->getManager();
$blogs= $em->getRepository('AppBundle:Blog\Post')->find($id);
$form = $this->createFormBuilder($blogs)
/* ... */
I have a form that I am building using the FormBuilder:
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('rosters', 'entity', array(
'class' => 'ReliefAppsPlatformBundle:Roster',
'property' => 'display',
'query_builder' => function(RosterRepository $r) use ($user) {
return $r->createQueryBuilder('r')
->leftJoin('r.members', 'm')
->addSelect('m')
->where('(m.rights = :adminRight or m.rights = :managerRight) and m.user = :user')
->setParameter('adminRight', RosterMember::ADMIN_LEVEL)
->setParameter('managerRight', RosterMember::MANAGER_LEVEL)
->setParameter('user', $user);
},
'required' => true,
'expanded' => true,
'multiple' => true
))
->add('save', 'submit')
;
}
As you can see I my QueryBuilder I use $user (the current user) as a parameter.
My controler looks like that:
public function createAction(Request $request, Event $event)
{
$alert = new RosterEvent;
$alert->setEvent($event);
$user = $this->getUser();
$form = $this->createForm(new RosterEventType(), $alert, $user);
$form->handleRequest($request);
if ($form->isValid()) { ....
My issue is that I need to pass the $user to the formbiulder. But I get "Catchable Fatal Error: Argument 3 passed to Symfony\Bundle\FrameworkBundle\Controller\Controller::createForm() must be of the type array, object given,..."
I know the problem is how I pass $user from the controller to the formbuilder. But I have no clue how to do that.
Any ideas?
As mentioned in the documentation, the third parameter ($options = array()) of method createForm need an array and not a object.
This line is wrong
$form = $this->createForm(new RosterEventType(), $alert, $user);
The $options parameter can be used for example like this
$form = $this->createForm(new TaskType(), $task, array(
'action' => $this->generateUrl('target_route'),
'method' => 'GET',
));
If you want pass a parameter to the form, you can try something like this
Controller
$form = $this->createForm(new RosterEventType($user), $alert);
Form
protected $user;
public function __construct (User $user)
{
$this->user = $user;
}
Hope it will help.
The third parameter of createForm is expecting an array of options so use this when creating the form:
$form = $this->createForm(new RosterEventType(), $alert, array('user'=>$user));
Then you will need to get your RosterEventType to allow the 'user' option to be provided. You can do this by overriding the setDefaultOptions function of your AbstractType and provided a default value for the option. For example you can add the following to your RosterEventType class:
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
'user' => false,
));
}
If you do this then you can access the user object in your buildForm function using $options['user'].
i'm trying to add my data into my database , i was trying to not use a formbuilder, inside that i put all my form into the controller,
but when i submit the button i did't got an error but i can't find my data in the database.
here is my code any one have an idea please.
public function AjoutAction()
{
$classe=new Classes();
$formBuilder = $this->get('form.factory')->createBuilder('form', $classe);
$formBuilder
->add('NomClasse', 'text')
->add('save', 'submit')
;
$form = $formBuilder->getForm();
if ($form->isValid()) {
$em = $this->getDoctrine()->getManager();
$em->persist($classe);
$em->flush();
} return $this->render('MyAppSchoolBundle:Classe:ajout.html.twig',array(
'form' => $form->createView(),
));
}
my twig file is here :
<h3>Formulaire d'annonce</h3>
{{ form(form) }}
thank you for your help
You need to change it to something like this:
public function AjoutAction(Request $request)
{
$classe=new Classes();
$formBuilder = $this->get('form.factory')->createBuilder('form', $classe);
$formBuilder
->add('NomClasse', 'text')
->add('save', 'submit')
;
$form = $formBuilder->getForm();
if ($form->handleRequest($request)->isValid()) {
$objToPersist = $form->getData();
$em = $this->getDoctrine()->getManager();
$em->persist($objToPersist);
$em->flush();
}
return $this->render('MyAppSchoolBundle:Classe:ajout.html.twig',array(
'form' => $form->createView(),
));
}
I want to update the data in two conditions:
When user enters all the fields in form (Name, email, password)
When user does not enter password (I have to update only name & email).
I have the Following formHandler Method.
public function process(UserInterface $user)
{
$this->form->setData($user);
if ('POST' === $this->request->getMethod()) {
$password = trim($this->request->get('fos_user_profile_form')['password']) ;
// Checked where password is empty
// But when I remove the password field, it doesn't update anything.
if(empty($password))
{
$this->form->remove('password');
}
$this->form->bind($this->request);
if ($this->form->isValid()) {
$this->onSuccess($user);
return true;
}
// Reloads the user to reset its username. This is needed when the
// username or password have been changed to avoid issues with the
// security layer.
$this->userManager->reloadUser($user);
}
An easy solution to your problem is to disable the mapping of the password field and copy its value to your model manually unless it is empty. Sample code:
$form = $this->createFormBuilder()
->add('name', 'text')
->add('email', 'repeated', array('type' => 'email'))
->add('password', 'repeated', array('type' => 'password', 'mapped' => false))
// ...
->getForm();
// Symfony 2.3+
$form->handleRequest($request);
// Symfony < 2.3
if ('POST' === $request->getMethod()) {
$form->bind($request);
}
// all versions
if ($form->isValid()) {
$user = $form->getData();
if (null !== $form->get('password')->getData()) {
$user->setPassword($form->get('password')->getData());
}
// persist $user
}
You can also add this logic to your form type if you prefer to keep your controllers clean:
$builder->addEventListener(FormEvents::POST_SUBMIT, function (FormInterface $form) {
$form = $event->getForm();
$user = $form->getData();
if (null !== $form->get('password')->getData()) {
$user->setPassword($form->get('password')->getData());
}
});
Easier way:
/my/Entity/User
public function setPassword($password)
{
if ($password) {
$this->password = $password;
}
}
So, any form using User with password will act as expected :)