Overriding FormType In symfony - 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

Related

Validations Groups doesn't working with forms

I'm trying to setup groups validation on my symfony project.
When I update an entity, I only need to validate some fields. When I create an entity, I only need to validate some other fields.
Service:
$form = $this->formFactory->createNamed('form', FormType::class, $entity, ['validation_groups' => ['update']]);
Form:
class FormType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('user', EntityType::class, [
'class' => User::class,
'validation_groups' => ['create']
])
->add('number', EntityType::class, [
'class' => Numbers::class,
'validation_groups' => ['create', 'update']
])
->add('phone', TextType::class, [
'validation_groups' => ['create', 'update']
])
;
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults([
'data_class' => Phones::class,
'allow_extra_fields' => true,
'validation_groups' => ['create', 'update'],
'cascade_validation' => true,
]);
}
}
But, when I submit my form, the "user" field still validated.
{"form":{"user":748,"number":"9.2","phone":"0x xx xx xx xx"}}
{"id":957,"error":"Expected argument of type \"App\\Entity\\User\", \"null\" given at property path \"user\"."}
You don't need to specifify validation_groups on fields.
Groups passed into form options are applied to all fields by default.
# Service 1
// Only 'create' group will be validated
$this->formFactory->createNamed('form', FormType::class, $entity, ['validation_groups' => ['create']]);
# Service 2
// Only 'create' and 'update' group will be validated
$this->formFactory->createNamed('form', FormType::class, $entity, ['validation_groups' => ['create', 'update']]);
# Form
class FormType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('user', EntityType::class, [
'class' => User::class,
// 'validation_groups' => ['create']
])
->add('number', EntityType::class, [
'class' => Numbers::class,
// 'validation_groups' => ['create', 'update']
])
->add('phone', TextType::class, [
// 'validation_groups' => ['create', 'update']
])
;
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults([
'data_class' => Phones::class,
'allow_extra_fields' => true,
// 'validation_groups' => ['create', 'update'],
'cascade_validation' => true,
]);
}
}
However, this doesn't seem like form validation error (violation).
Expected argument of type \"App\\Entity\\User\", \"null\" given at property path \"user\" means, that value passed into 'user' field is null (not set).
You should omit 'user' field when it form is used for 'creation'.
Solution 1:
// add option
$resolver->setDefaults([
'data_class' => Phones::class,
// ...
'addUserField' => null,
]);
// in service pass this option
$this->formFactory->createNamed('form', FormType::class, $entity, [
'validation_groups' => ['create'],
'addUserField' => true
]);
// use condition in form to add field only if option is passed with true value
if($options['addUserField'] === true) {
$builder->add('user', EntityType::class, [class' => User::class]);
}
$builder
->add('number'/** ... */)
->add('phone'/** ... */)
;
Solution 2:
Create 2 form types FormTypeCreate and FormTypeUpdate. Skip 'user' field in FormTypeUpdate. You could also extend FormTypeCreate from FormTypeUpdate.
class FormTypeUpdate extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('number', EntityType::class, [
'class' => Numbers::class,
])
->add('phone', TextType::class)
;
}
//...
}
//
class FormTypeCreate extends FormTypeUpdate
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('user', EntityType::class, [
'class' => User::class,
])
parent::buildForm($builder, $options); // adds 'number' and 'phone' fields
}
//...
}

Symfony: Collection and subform required option & validator not working

I have a Form which embeds a collectionType.
The Collection type uses two subforms.
When I set required option to fields belonging to CollectionType form or Subforms, it does not work: neither red * nor form validation errors...
I have a Form which embeds a collectionType.
The Collection type uses two subforms.
When I set required option to fields belonging to CollectionType form or Subforms, it does not work: neither red * nor form validation errors...
What did I miss ?
Classe:
class: App\Entity\Classe
label: 'Classes'
form:
fields:
- { property: 'classe', label: 'Classe Name'}
- { property: 'maxextcuth', label: 'Max ext. Cu', type: 'entity'}
- { property: 'maxintcuth', label: 'Max int. Cu', type: 'entity'}
- { property: 'enabled', label: 'Enabled'}
- { type: 'section', label: 'Price rules', icon: 'euro' }
- property: 'classePrices'
label: false
type: 'collection'
type_options:
entry_type: App\Form\Type\ClassePriceType
allow_delete: true
allow_add: true
by_reference: false
prototype: true
block_prefix: 'price_collection'
class ClassePriceType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('priceform', PriceformType::class, [
'data_class' => ClassePrice::class,
'block_prefix' => 'mainprice_block'
]);
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults([
'data_class' => ClassePrice::class,
'attr' => array(
'class' => 'fullwidth'
)
]);
}
}
class PriceformType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('pricecover', ChoiceType::class, [
'label' => 'Price type',
'placeholder' => 'Select a price option',
'choices' => [ 'Global' => '1' ,'Step' => '2'],
'required' => true
])
->add('rangesubform', RangesubformType::class, [
'data_class' => ClassePrice::class,
'block_prefix' => 'range_block'
])
->add('pricesubform', PricesubformType::class, [
'data_class' => ClassePrice::class,
'block_prefix' => 'price_block'
]);
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults([
'inherit_data' => true
]);
}
}
class RangesubformType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('rangetype', EntityType::class, [
'class' => Ptur::class,
'label' => 'Step type',
'choice_translation_domain'=> true,
'required' => true
])
->add('rangeformat', EntityType::class, [
'class' => Format::class,
'label' => 'Format',
'required' => true
])
->add('rangemin', IntegerType::class, [
'label' => 'Range min',
'required' => true
]);
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults([
'inherit_data' => true,
'attr' => array(
'class' => 'form-horizontal'
)
]);
}
}

Expected argument of type "string", "null" given at property path

Actually when I try to edit the form by sending empty fields, the above error comes on ,
My UserType class looks like:
class UserType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('firstName', null, [
'label' => 'Prénom'
])
->add('lastName', null, [
'label' => 'Nom'
])
->add('email', EmailType::class, [
'label' => 'Adresse e-mail'
])
->add('password', PasswordType::class, [
'label' => 'Mot de passe'
])
;
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults([
'data_class' => User::class,
]);
}
}
This problem can be resolved by adding 'empty_data' param in the builder add function:
So the new UserType classe becomes:
class UserType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('firstName', null, [
'label' => 'Prénom',
**'empty_data' => ''**
])
->add('lastName', null, [
'label' => 'Nom',
**'empty_data' => ''**
])
->add('email', EmailType::class, [
'label' => 'Adresse e-mail',
**'empty_data' => ''**
])
->add('password', PasswordType::class, [
'label' => 'Mot de passe',
**'empty_data' => ''**
])
;
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults([
'data_class' => User::class,
]);
}
}
Instead of #Mustapha GHLISSI answer, you can set your field to accept null values:
<?php
class User
{
public ?string $firstName;
// your other fields
}
The public ?string $firstName will accept string and null values for the field firstName.
Before PHP 8.0 its maybe:
public function setFirstName(string $firstName = null): self
{
$this->firstName = $firstName;
return $this;
}

Symfony FOS User Bundle registration form overriding error

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

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 }

Resources