Symfony FOS User Bundle registration form overriding error - symfony

I am trying to override fos user bundle registration form, but the doc examples doesnt work for me
my services.yml
services:
app.form.registration:
class: AppBundle\Form\RegistrationFormType
tags:
- { name: form.type, alias: app_user_registration }
app.locale_listener:
class: AppBundle\EventListener\LocaleListener
arguments: ["%kernel.default_locale%"]
tags:
- { name: kernel.event_subscriber }
route
register:
pattern: /register
defaults: { _controller: AppBundle:Registration:register }
registration controller
namespace AppBundle\Controller;
use Symfony\Component\HttpFoundation\RedirectResponse;
use FOS\UserBundle\Controller\RegistrationController as BaseController;
use Symfony\Component\HttpFoundation\Request;
use FOS\UserBundle\FOSUserEvents;
use FOS\UserBundle\Event\GetResponseUserEvent;
class RegistrationController extends BaseController
{
public function registerAction(Request $request)
{
$form = $this->container->get('app.registration.form');
$formHandler = $this->container->get('fos_user.registration.form.handler');
$confirmationEnabled = $this->container->getParameter('fos_user.registration.confirmation.enabled');
$process = $formHandler->process($confirmationEnabled);
if ($process) {
$user = $form->getData();
/*****************************************************
* Add new functionality (e.g. log the registration) *
*****************************************************/
$this->container->get('logger')->info(
sprintf('New user registration: %s', $user)
);
if ($confirmationEnabled) {
$this->container->get('session')->set('fos_user_send_confirmation_email/email', $user->getEmail());
$route = 'fos_user_registration_check_email';
} else {
$this->authenticateUser($user);
$route = 'fos_user_registration_confirmed';
}
$this->setFlash('fos_user_success', 'registration.flash.user_created');
$url = $this->container->get('router')->generate($route);
return new RedirectResponse($url);
}
return $this->render('blog/register.html.twig', array(
'form' => $form->createView(),
));
}
}
registration form type
namespace AppBundle\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use FOS\UserBundle\Form\Type\RegistrationFormType as BaseController;
class RegistrationFormType extends BaseController
{
/**
* #param string $class The User class name
*/
public function __construct($class)
{
parent::__construct($class);
}
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('username', null, array('label' => 'form.username', 'translation_domain' => 'FOSUserBundle'))
->add('plainPassword', 'repeated', array(
'type' => 'password',
'options' => array('translation_domain' => 'FOSUserBundle'),
'first_options' => array('label' => 'form.password'),
'second_options' => array('label' => 'form.password_confirmation'),
'invalid_message' => 'fos_user.password.mismatch',
))
->add('email', 'email', array('label' => 'form.email', 'translation_domain' => 'FOSUserBundle'))
->add('phone', null, array('label' => 'form.phone', 'translation_domain' => 'FOSUserBundle'))
->add('gender', null, array(
'choices' => array(
'morning' => 'Morning',
'afternoon' => 'Afternoon',
'evening' => 'Evening',
)
))
->add('about', null, array('label' => 'form.about', 'type' => 'textarea', 'translation_domain' => 'FOSUserBundle'))
;
}
}
On /register page im getting error - You have requested a non-existent service "app.registration.form".
What is the right solution to override default register form to my custom?
Thank you

Related

Overriding FormType In symfony

i have a problem how to overriding a FormType in my app in symfony2
my class is
class ContactType extends AbstractType {
public function buildForm(FormBuilderInterface $builder, array $options) {
$builder
->add('firstName', 'text', array('label' => 'mremi_contact.form.first_name'))
->add('lastName', 'text', array('label' => 'mremi_contact.form.last_name'))
->add('email', 'email', array('label' => 'mremi_contact.form.email'));
if ($subjects = $this->subjectProvider->getSubjects()) {
$builder
->add('subject', 'choice', array(
'choices' => $subjects,
'label' => 'mremi_contact.form.subject',
));
} else {
$builder->add('subject', 'text', array('label' => 'mremi_contact.form.subject'));
}
$builder->add('message', 'textarea', array('label' => 'mremi_contact.form.message'));
if ($this->captchaType) {
$builder->add('captcha', $this->captchaType, array(
'label' => 'mremi_contact.form.captcha',
'mapped' => false,
));
}
$builder->add('save', 'submit', array('label' => 'mremi_contact.form_submit'));
}
public function getParent() {
return 'mremi_contact';
}
public function getName() {
return 'mremi_contact_contact_custom';
}
}
my services are : mybundle\ressources\config\services.yml
services:
mremi_contact.custom_contact.form.type:
class: Common\ContactBundle\Form\Type\ContactType
tags:
- { name: form.type, alias: mremi_contact_contact_custom }
and i declared it in my app/config
# Mremi ContactBundle
mremi_contact:
form:
type: mremi_contact_contact_custom
name: contact_form
validation_groups: [Default]
subject_provider: mremi_contact.subject_provider.noop
captcha_type: ewz_recaptcha
email:
mailer: mremi_contact.mailer.twig_swift
from: []
to:
- { address: thamer.nasri#gmail.com }
template: MremiContactBundle:Contact:email.txt.twig
the error is
Could not load type "mremi_contact_contact_custom"
plz help me thank you

Issue to override Subscription Form FOSUser Bundle

I'm trying to override the Subscription Form of FOSUser bundle in a Symfony2 Project but I get this error :
Warning: Missing argument 1 for Utilisateurs\UtilisateursBundle\Form\Type\RegistrationFormType::__construct(), called in C:\wamp\www\biblishare\app\cache\dev\appDevDebugProjectContainer.php on line 3730 and defined
I search for the same issue but can't resolve it...
Here are my codes :
-app/config/config.yml
fos_user:
db_driver: orm
firewall_name: main
user_class: Utilisateurs\UtilisateursBundle\Entity\Utilisateurs
from_email:
address: contact#biblishare.com
sender_name: contact#biblishare.com
registration:
form:
type: utilisateurs_utilisateurs_registration
-.../UtilisateursBundle/Resources/config/services.yml
services:
utilisateurs_utilisateurs.listener.authentication_success_handler:
class: %utilisateurs_utilisateurs.listener.authentication_success_handler.class%
public: false
arguments: ['#router', '#doctrine.orm.entity_manager', '#security.context']
utilisateurs_utilisateurs.registration.form.type:
class: Utilisateurs\UtilisateursBundle\Form\Type\RegistrationFormType
tags:
- { name: form.type, alias: utilisateurs_utilisateurs_registration }
and my form:
<?php
namespace Utilisateurs\UtilisateursBundle\Form\Type;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
class RegistrationFormType extends AbstractType
{
private $class;
/**
* #param string $class The User class name
*/
public function __construct($class)
{
$this->class = $class;
}
public function buildForm(FormBuilderInterface $builder, array $options)
{
// add your custom field
$builder
->add('first_name', null, array('label' => 'Prénom :', 'translation_domain' => 'FOSUserBundle'))
->add('family_name', null, array('label' => 'Nom :', 'translation_domain' => 'FOSUserBundle'))
->add('email', 'email', array('label' => 'form.email', 'translation_domain' => 'FOSUserBundle'))
->add('plainPassword', 'repeated', array(
'type' => 'password',
'options' => array('translation_domain' => 'FOSUserBundle'),
'first_options' => array('label' => 'form.password'),
'second_options' => array('label' => 'form.password_confirmation'),
'invalid_message' => 'fos_user.password.mismatch',
))
;
}
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
'data_class' => $this->class,
'intention' => 'registration',
));
}
public function getName()
{
return 'utilisateurs_utilisateurs_registration';
}
}
Thank you for your help, I tried to erase the cache but it doesn't work...
You need to add the user class as an argument to your service definition so that it will be called in the __construct method.
utilisateurs_utilisateurs.registration.form.type:
class: Utilisateurs\UtilisateursBundle\Form\Type\RegistrationFormType
arguments:
- %fos_user.model.user.class%
tags:
- { name: form.type, alias: utilisateurs_utilisateurs_registration }

Add roles field to FOSUserBundle group form

When activating group( base on its documentation) in FOSUserBundle, the group roles are not embedded on edit and update form!I already override GroupFormType and GroupController but I can't pass roles from controller to form class.
my question is how can I add roles to form to let administrator change or assign role to groups?
Solving my problem by adding the role field to override GroupController
public function editAction(Request $request, $groupName)
{
...
/** #var $formFactory \FOS\UserBundle\Form\Factory\FactoryInterface */
$formFactory = $this->get('fos_user.group.form.factory');
$form = $formFactory->createForm();
$form->add('roles', 'choice', array(
'choices' => $this->getExistingRoles(),
'data' => $group->getRoles(),
'label' => 'Roles',
'expanded' => true,
'multiple' => true,
'mapped' => true,
));
...
}
public function getExistingRoles()
{
$roleHierarchy = $this->container->getParameter('security.role_hierarchy.roles');
$roles = array_keys($roleHierarchy);
foreach ($roles as $role) {
$theRoles[$role] = $role;
}
return $theRoles;
}
For my part I decided to inerite the GroupFormType class. Here is inherited class :
namespace UserBundle\Form;
use FOS\UserBundle\Form\Type\GroupFormType;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\Form\FormBuilderInterface;
class GroupType extends AbstractType
{
/**
* {#inheritdoc}
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$permissions = array(
'Utilisateur' => 'ROLE_USER',
'Administrateur' => 'ROLE_ADMIN'
);
$builder
->add('name', null, array('label' => 'form.group_name', 'translation_domain' => 'FOSUserBundle'))
->add('role', ChoiceType::class, array(
'label' => 'Rôle',
'choices' => $permissions,
'multiple' => true,
'expanded' => true
))
;
}
public function getParent()
{
return GroupFormType::class;
}
}
Don't forget to precise your new class in the config.yml
fos_user:
group:
form:
type: UserBundle\Form\GroupType

Symfony2 + SonataAdminBundle: Error on updating User's roles (many-to-many)

Entities:
User:
class User implements AdvancedUserInterface, \Serializable
{
...
/**
* #ORM\ManyToMany(targetEntity="Role", inversedBy="users")
* #ORM\JoinTable(name="users_roles")
*
*/
private $roles;
...
}
Role:
class Role implements RoleInterface
{
...
/**
* #ORM\ManyToMany(targetEntity="User", mappedBy="roles")
*/
private $users;
public function __construct()
{
$this->users = new ArrayCollection();
}
public function __toString()
{
return $this->getName();
}
...
}
Admin classes:
UsersAdmin:
<?php
namespace Lan\ConsoleBundle\Admin;
use Sonata\AdminBundle\Admin\Admin;
use Sonata\AdminBundle\Form\FormMapper;
use Sonata\AdminBundle\Datagrid\DatagridMapper;
use Sonata\AdminBundle\Datagrid\ListMapper;
use Sonata\AdminBundle\Show\ShowMapper;
use Knp\Menu\ItemInterface as MenuItemInterface;
class UsersAdmin extends Admin
{
protected function configureShowField(ShowMapper $showMapper)
{
$showMapper
->add('id', null, array('label' => 'ID'))
->add('username', null, array('label' => 'Name'))
->add('password', null, array('label' => 'Password'))
->add('email', null, array('label' => 'Mail'))
->add('is_active', null, array('label' => 'Active', 'required' => false))
->add('roles');
}
protected function configureFormFields(FormMapper $formMapper)
{
$formMapper
->with('General')
->add('username', null, array('label' => 'Name'))
->add('password', null, array('label' => 'Password'))
->add('email', null, array('label' => 'Mail'))
->add('is_active', 'checkbox', array('label' => 'Active', 'required' => false))
->end()
->with('Roles')
->add('roles', 'sonata_type_model',array('expanded' => true, 'compound' => true, 'multiple' => true))
->end();
}
}
RolesAdmin:
<?php
namespace Lan\ConsoleBundle\Admin;
use Sonata\AdminBundle\Admin\Admin;
use Sonata\AdminBundle\Form\FormMapper;
use Sonata\AdminBundle\Datagrid\DatagridMapper;
use Sonata\AdminBundle\Datagrid\ListMapper;
use Sonata\AdminBundle\Show\ShowMapper;
use Knp\Menu\ItemInterface as MenuItemInterface;
class RolesAdmin extends Admin
{
protected function configureFormFields(FormMapper $formMapper)
{
$formMapper
->add('name', null, array('label' => 'Заголовок'))
->add('role', null, array('label' => 'Роль'));
}
}
Screenshot:
http://img577.imageshack.us/img577/3565/jyte.png
After updating User i get this error message:
FatalErrorException: Error: Call to a member function add() on a
non-object in
\vendor\sonata-project\doctrine-orm-admin-bundle\Sonata\DoctrineORMAdminBundle\Model\ModelManager.php line 560
I think this error occurs because the object instead of 'Role' value is passed to the function Role-> __toString (). How can I solve this problem?
Try something arround this code:
protected function configureFormFields(FormMapper $formMapper)
{
$formMapper
->add('name', null, array('label' => 'Заголовок'))
->add('Product' , 'entity' , array(
'class' => 'LanConsoleBundle:Role' ,
'property' => 'name' ,
'expanded' => true ,
'multiple' => true , ))
}

stuck on symfony2 for contact form

I have problem with a contact form in symfony2 here is the code what i've done and what error do i get
<?php
// src/Aleksandar/IntelMarketingBundle/Resources/views/ContactType.php
namespace Aleksandar\IntelMarketingBundle\Resources\views;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
use Symfony\Component\Validator\Constraints\Email;
use Symfony\Component\Validator\Constraints\Length;
use Symfony\Component\Validator\Constraints\NotBlank;
use Symfony\Component\Validator\Constraints\Collection;
class ContactType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('name', 'text', array(
'attr' => array(
'placeholder' => 'What\'s your name?',
'pattern' => '.{2,}' //minlength
)
))
->add('email', 'email', array(
'attr' => array(
'placeholder' => 'So I can get back to you.'
)
))
->add('subject', 'text', array(
'attr' => array(
'placeholder' => 'The subject of your message.',
'pattern' => '.{3,}' //minlength
)
))
->add('message', 'textarea', array(
'attr' => array(
'cols' => 20,
'rows' => 2,
'placeholder' => 'And your message to me...'
)
));
}
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$collectionConstraint = new Collection(array(
'name' => array(
new NotBlank(array('message' => 'Name should not be blank.')),
new Length(array('min' => 2))
),
'email' => array(
new NotBlank(array('message' => 'Email should not be blank.')),
new Email(array('message' => 'Invalid email address.'))
),
'subject' => array(
new NotBlank(array('message' => 'Subject should not be blank.')),
new Length(array('min' => 3))
),
'message' => array(
new NotBlank(array('message' => 'Message should not be blank.')),
new Length(array('min' => 5))
)
));
$resolver->setDefaults(array(
'constraints' => $collectionConstraint
));
}
public function getName()
{
return 'contact';
}
}
?>
This is the code for the contact form which will be rendered in the view
no here is the code from my controller
<?php
namespace Aleksandar\IntelMarketingBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
class DefaultController extends Controller
{
/**
* #Route("/contact", _name="contact")
* #Template()
*/
public function contactAction()
{
$form = $this->createForm(new ContactType());
if ($request->isMethod('POST')) {
$form->bind($request);
if ($form->isValid()) {
$message = \Swift_Message::newInstance()
->setSubject($form->get('subject')->getData())
->setFrom($form->get('email')->getData())
->setTo('info#intelmarketing.es')
->setBody(
$this->renderView(
'AleksandarIntelMarketingBundle::contact.html.php',
array(
'ip' => $request->getClientIp(),
'name' => $form->get('name')->getData(),
'message' => $form->get('message')->getData()
)
)
);
$this->get('mailer')->send($message);
$request->getSession()->getFlashBag()->add('success', 'Your email has been sent! Thanks!');
return $this->redirect($this->generateUrl('contact'));
}
}
return array(
'form' => $form->createView()
);
}
}
and here is the rooting
aleksandar_intel_marketing_contactpage:
pattern: /contact
defaults: { _controller: AleksandarIntelMarketingBundle:Default:contact }
now when i try to open the page its says the fallowing:
"[Semantical Error] The annotation "#Route" in method
Aleksandar\IntelMarketingBundle\Controller\DefaultController::contactAction()
was never imported. Did you maybe forget to add a "use" statement for
this annotation? 500 Internal Server Error - AnnotationException "
If any one knows what might be the problem please let me know
As the error message states, you are missing a use statement on top of your controller file.
Simply add:
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
on top of your class DefaultController.
You can then replace your routing with:
aleksandar_intel_marketing:
resource: "#AleksandarIntelMarketingBundle/Controller/DefaultController.php"
type: annotation
This way, you are using the #Route annotation instead of the default yml way to declare your routes.
http://symfony.com/doc/current/bundles/SensioFrameworkExtraBundle/annotations/routing.html

Resources