Symfony validate email without assert - php

I have made a simple Symfony form with only an email field. This form is used to send a document to a user. The form is not linked to any entity. Therefore the formtype looks like this:
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('email', 'email', array(
'mapped' => false
))
->add('save', 'submit');
}
So the email field is not mapped and this works fine.
Now I want to validate the email address like I do with other forms where I have the following asserts:
#Assert\Email(message = "email.not_valid", checkMX = true)
As this formtype has no entity I'm wondering how I can add the checkMX to the email field?

https://symfony.com/doc/current/form/without_class.html#form-option-constraints
use Symfony\Component\Validator\Constraints\Email;
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('email', 'email', array(
'mapped' => false,
'constraints' => array(
new Email(array('checkMX' => true)),
),
))
->add('save', 'submit');
}
EDIT checkMx -> checkMX

Related

How to set choice field values in Symfony2?

Whats the best way to set a collection of key/values pairs (obtained from MySQL) as a choice field 'choices' inside a controller?
I think about something similar to :
$form = $this->createForm(new AddNews(), $news);
$newsList = $this->getDoctrine()
->getRepository('BakaMainBundle:News')->getAllNews();
$titlesList = ...($newsList); // some fuction that extract title=>id
// array from news object collection
$form->get('newsList')->setData($titlesList);
where the AddNews() form looks like :
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add(...)
->add(...)
->add('accept' , 'submit')
->add('newsList', 'choice', array
(
'mapped' => false,
'required' => true
));
}
Perhaps something like below (assuming Symfony >= 2.7). See docs for field options:
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add(...)
->add(...)
->add('accept' , 'submit')
->add('newsList', 'entity', array
(
'class' => ''BakaMainBundle:News'',
'choice_label' => 'title',
'mapped' => false,
'required' => true
));
}
You could get your "news" directly from your formType file, using your repository, like that:
private function getNews(){
$newsList = $this->getDoctrine()
->getRepository('BakaMainBundle:News')->getAllNews();
$titlesList = ...($newsList); // some fuction that extract title=>id
// array from news object collection
}
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add(...)
->add(...)
->add('accept' , 'submit')
->add('newsList', 'choice', array
(
'mapped' => false,
'required' => true,
'choices' => $this->getNews()
));
}

Symfony2 form entity preferred_choices set selected values

I'm having dificulties trying to set on my form the selected values on the preferred choices.
I have a class calendar that can have multiple taxes:
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('name')
->add('possibledigits')
->add('notes')
->add('autogenerateyear', 'checkbox', array('required' => false))
->add('calendartaxes', null, array(
'required' => false,
'multiple' => true,
'expanded' => true
))
;
}
The relation is many to many:
/**
* #ORM\ManyToMany(targetEntity="CalendarTax", indexBy="name", inversedBy="calendarios")
* #ORM\JoinTable(name="contable_schedule_taxes_relation")
*/
private $calendartaxes;
What I was going to do is to try to get the entity of the form and try to get the selected taxes. But I don't know if that is the correct way to do it.
Is there a more elegant way to do it?
I'm using symfony 2.3.
Regards.
I am assuming you have a relationship set up betwween Calendarios and CalendarTax
so before you create the form ... do
$calendarios = new CalendarIOS();
$calendartax = $this->getDoctrine()->getManager()->getRepository('NamBundle:CalendarTax')->find($calendar_tax_id);
$calendarios->addCalendarTax($calendartax);
now when you send the entity over to the formbuilder...you will have that perticular calendartax checked... :)
Finally I use the preferred_choices of the choice.
public function buildForm(FormBuilderInterface $builder, array $options)
{
$calendario = $builder->getData();
$taxesId = array();
foreach($calendario->getCalendartaxes() as $tax){
$taxesId[] = $tax;
}
$builder
->add('name')
->add('possibledigits')
->add('notes')
->add('autogenerateyear', 'checkbox', array('required' => false))
->add('calendartaxes', null, array(
'required' => false,
'multiple' => true,
'expanded' => true,
'preferred_choices' => $taxesId,
))
;
}
Making one more query and getting the calendar of the form builder.
The comment given by #Hakim was the one that put me on the right path.
Thanks!

Symfony2 "The option Required does not exist"

I have created a FormType class called BookType. The method for generating the form is:
/**
* #param FormBuilderInterface $builder
* #param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('name', 'text', array('required'=>$this->searchForm))
->add('author', 'text', array('required'=>$this->searchForm))
->add('genre', 'text', array('required'=>$this->searchForm));
if(!$this->searchForm) {
$builder
->add('picture', 'text', array('required' => false));
}
$builder
->add('description', 'text', array('required'=>$this->searchForm))
->add('submit', 'submit', array('required'=>$this->searchForm))
;
}
However, whenever I try to access this with the following code:
$book = new Book();
$form = $this->createForm(
new BookType(true),
$book,
[
'action'=> $request->getUri()
]
);
I am seeing the following error message:
The option "required" does not exist. Known options are: "attr", "auto_initialize", "block_name", "disabled", "label", "translation_domain", "validation_groups".
As far as I am aware from the various tutorials I have read, this should be a completely valid parameter. Am I wrong here?
I think error is occurring here:
->add('submit', 'submit', array('required'=>$this->searchForm));
Since 'submit' field does not have 'required' option.

Multiple (oneToMany) Entities form generation with symfony2 and file upload

I'm on a problem related to a Symfony2 application which i'm building. The problem concerns an article (News) linked to one or many pictures (Illustration). It seems pretty simple. But i'm stacking on the controller which should persist the News, the Illustration and uploading the picture file.
My News form type:
namespace Fcbg\NewsBundle\Form\Type;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
class NewsType extends AbstractType
{
public function buildForm( FormBuilderInterface $builder, array $options )
{
$builder
->add('date', 'date')
->add('titre', 'text')
->add('contenu', 'textarea')
->add('publication', 'checkbox', array('required' => false))
->add('type', 'entity', array( 'class' => 'FcbgNewsBundle:Illustration', 'property' => 'value', 'multiple' => true ));
}
public function getName()
{
return 'News';
}
}
My picture(s) form type:
namespace Fcbg\NewsBundle\Form\Type;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
class IllustrationType extends AbstractType
{
public function buildForm( FormBuilderInterface $builder, array $options )
{
$builder
->add('file', 'file');
}
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'Fcbg\NewsBundle\Entity\Illustration',
'cascade_validation' => true,
));
}
public function getName()
{
return 'News';
}
}
My controller action:
public function addAction()
{
//link works properly I think
$news = new News();
$illustration = new Illustration();
$illustration->setNews($news);
$news->addIllustration($illustration);
$form = $this->createForm(new NewsType(), $news);
$request = $this->get('request');
if ($request->getMethod() == 'POST') {
$form->bind($request);
if ($form->isValid()) {
$doctrine = $this->getDoctrine();
$newsManager = $doctrine->getManager();
$newsManager->persist($news);
$newsManager->persist($illustration);
$newsManager->flush();
return $this->redirect(...);
}
}
return $this->render('base.html.twig',
array(
'content' => 'FcbgNewsBundle:Default:formulaireNews.html.twig',
'form' => $form->createView(),
'name' => "add a news"
)
);
}
The error i get on the execution:
Entities passed to the choice field must be managed. Maybe persist them in the entity manager?
The problem here is that my entity gets a method called "getIllustrations()" which returns logically an arrey of Illustration. So i'm not able to understand this error/question. I assume that my "illustration should be a file field and not a choice field...
Any idea about how i can go further? thx a lot!
I think the problem is that you are using the 'entity' form field here:
->add('type', 'entity', array( 'class' => 'FcbgNewsBundle:Illustration', 'property' => 'value', 'multiple' => true ));
and this type of form field acts as a choice and it's used to work with elements created in the database. You can see this in http://symfony.com/doc/current/reference/forms/types/entity.html
A possible solution could be use the "prototype" like here http://symfony.com/doc/current/cookbook/form/form_collections.html#cookbook-form-collections-new-prototype
where you could have:
public function buildForm( FormBuilderInterface $builder, array $options )
{
$builder
->add('date', 'date')
->add('titre', 'text')
->add('contenu', 'textarea')
->add('publication', 'checkbox', array('required' => false))
->add('type', 'collection', array(
'type' => new IllustrationType(),
'allow_add' => true,
));
}
I hope that this be useful for you.
Kind regards.
So, the code which I was talking about:
public function buildForm( FormBuilderInterface $builder, array $options )
{
$builder
->add('date', 'date')
->add('titre', 'text')
->add('contenu', 'textarea')
->add('publication', 'checkbox', array('required' => false))
->add('illustrations', 'collection', array(
'type' => new IllustrationType(),
'allow_add' => true
));
}

Symfony2: The option "widget" does not exist

I'm trying to build a form using symfony2, but I keep getting the error message 'The option "widget" does not exist ' whenever I add the widget option to specify a form field type.
I'm following the example given on the documentation there http://symfony.com/doc/current/book/forms.html
here is my code that does not work.
class UserType extends AbstractType
{
public function buildForm(FormBuilder $builder, array $options)
{
$builder
->add('Name')
->add('Login')
->add('Password')//, 'text', array('widget' => 'password'))
->add('ConfirmPassword')//, 'text', array('widget' => 'password', 'label' =>'Confirm Password'))
->add('Email', 'text', array('widget' => 'email'))
->add('ConfirmEmail')//,'text', array('widget' => 'email', 'label' =>'Confirm Email'))
//...
}
Anyone knows why ?
Thanks
I believe, the correct way to do what you want to achieve is the following:
->add('Name', 'text')
->add('Login', 'text')
->add('Password', 'password')
->add('ConfirmPassword', 'password', array('label' =>'Confirm Password'))
->add('Email', 'email')
->add('ConfirmEmail', 'email')
The first argument of add method is field's name (it has to be unique within form). The second is type and it is responsible for the form taken by widget while rendering. The list of built-in types here. The third argument is array of options. Each type has it's own set of possible options. Indeed, some of types have the widget option. For example date type has such option. But password and email types don't have such option.

Categories