Symfony - Unique entity in CollectionType field? - symfony

I have a formBuilder that contains a collectionType. I would like to be able to put a constraint on the email field to be sure that when the user validates, there is not the same email address several times in the form
I've :
RegistrationCollectionType.php
$builder
->add('utilisateurs', CollectionType::class, [
'entry_type' => RegistrationType::class,
'entry_options' => [
'label' => false,
'entreprise' => $entreprise,
],
'allow_add' => true,
'allow_delete' => true,
'delete_empty' => true,
'by_reference' => true,
'prototype' => true,
'label' => false,
'attr' => [
'class' => 'my-selector',
'label' => false,
],
'by_reference' => false,
])
;
With his class :
RegistrationCollection.php
class RegistrationCollection
{
private $utilisateurs = [];
public function getUtilisateurs(): ?array
{
return $this->utilisateurs;
}
public function setUtilisateurs(?array $utilisateurs): self
{
$this->utilisateurs = $utilisateurs;
return $this;
}
}
And in my RegistrationType.php which is associated with my User entity, I've :
RegistrationType.php
->add('email', EmailType::class, [
'attr' => [
'placeholder' => "Adresse email"
],
])
Now if I valid, I've :
SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicata du
champ 'ahahs#mail.fr' pour la clef 'UNIQ_8D93D649E7927C74'

I kept the idea of a custom constraint, but which would not apply only to emails but to any field that we want Unique:
#App\Validator\Constraints\UniqueProperty.php
<?php
namespace App\Validator\Constraints;
use Symfony\Component\Validator\Constraint;
/**
* #Annotation
*/
class UniqueProperty extends Constraint
{
public $message = 'This collection should contain only elements with uniqe value.';
public $propertyPath;
public function validatedBy()
{
return UniquePropertyValidator::class;
}
}
and
#App\Validator\Constraints\UniquePropertyValidator.php
<?php
namespace App\Validator\Constraints;
use Symfony\Component\PropertyAccess\PropertyAccess;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;
use Symfony\Component\Validator\Exception\UnexpectedTypeException;
use Symfony\Component\Validator\Exception\UnexpectedValueException;
class UniquePropertyValidator extends ConstraintValidator
{
/**
* #var \Symfony\Component\PropertyAccess\PropertyAccessor
*/
private $propertyAccessor;
public function __construct()
{
$this->propertyAccessor = PropertyAccess::createPropertyAccessor();
}
/**
* #param mixed $value
* #param Constraint $constraint
* #throws \Exception
*/
public function validate($value, Constraint $constraint)
{
if (!$constraint instanceof UniqueProperty) {
throw new UnexpectedTypeException($constraint, UniqueProperty::class);
}
if (null === $value) {
return;
}
if (!\is_array($value) && !$value instanceof \IteratorAggregate) {
throw new UnexpectedValueException($value, 'array|IteratorAggregate');
}
if ($constraint->propertyPath === null) {
throw new \Exception('Option propertyPath can not be null');
}
$propertyValues = [];
foreach ($value as $key => $element) {
$propertyValue = $this->propertyAccessor->getValue($element, $constraint->propertyPath);
if (in_array($propertyValue, $propertyValues, true)) {
$message = sprintf("%s (%s)", $constraint->message, $propertyValue);
$this->context->buildViolation($message)
// ->atPath(sprintf('[%s]', $key))
->atPath(sprintf('[%s][%s]', $key, $constraint->propertyPath))
->addViolation();
}
$propertyValues[] = $propertyValue;
}
}
}
and
class RegistrationCollection
{
/**
* #App\UniqueProperty(
* message = "Adresse mail déjà utilisée",
* propertyPath = "email"
* )
*
*/
private $utilisateurs = [];
It works very well, except that I can't target the child field for the error. Systematically, the error will go to the parent entity, and therefore the error will be put all over it.
I tried in the validator to redirect to the fields of the child entity concerned, but nothing to do, the error continues to put everything above..
In my FormType I tried to disable error_bubbling but same thing
->add('utilisateurs', CollectionType::class, [
'entry_type' => RegistrationType::class,
'entry_options' => [
'label' => false,
'entreprise' => $entreprise,
],
'allow_add' => true,
'allow_delete' => true,
'delete_empty' => true,
'by_reference' => true,
'prototype' => true,
'label' => false,
'attr' => [
'class' => 'my-selector',
'label' => false,
],
'by_reference' => false,
'error_bubbling' => false,
])
;

You can create custom validation constraint
class UniqueEmailValidator extends ConstraintValidator
{
public function validate($value, Constraint $constraint)
{
if (!$constraint instanceof UniqueEmail) {
throw new UnexpectedTypeException($constraint, UniqueEmail::class);
}
if (!\is_array($value) && !$value instanceof \IteratorAggregate) {
throw new UnexpectedValueException($value, 'array|IteratorAggregate');
}
$emails = [];
foreach ($value as $element) {
if (\in_array($element->getEmail(), $emails, true)) {
$this->context->buildViolation($constraint->message)
->addViolation();
return;
}
$emails[] = $element->getEmail();
}
}
}
and add to your property a validation annotation
class RegistrationCollection
{
/**
* #AppAssert\UniqueEmailValidator
*/
private $utilisateurs = [];
public function getUtilisateurs(): ?array
{
return $this->utilisateurs;
}
public function setUtilisateurs(?array $utilisateurs): self
{
$this->utilisateurs = $utilisateurs;
return $this;
}
}

Related

Symfony 5 - DataTransformer with Form Validation Constraint

I build a FormType in Symfony5 and make use of DataTransformer on 2 fields :
compagnie_princ
compagnie_sec.
DataTransformer basically takes an object ID and renders It to a label.
DataTransformer works fine, when Form is initially rendered on browser, see below capture:
Problem is after validation callbacks are executed, If an error occured, It fails to transform my Id back to a text value.
Code samples (most important parts) :
AccordCommercialFormType.php
public function buildForm(FormBuilderInterface $builder, array $options): void
{
$builder
->add('compagnie_princ', TextType::class,
[
'label' => 'forms.parameter.accord.compagnie_princ',
]
)
->add('compagnie_sec', TextType::class,
[
'label' => 'forms.parameter.accord.compagnie_sec',
]
);
/** ... **/
$builder>addEventListener(
FormEvents::PRE_SET_DATA,
[$this, 'onPreSetData']
)
->addEventListener(
FormEvents::PRE_SUBMIT,
[$this, 'onPreSubmit']
);
$builder->get('compagnie_princ')->addModelTransformer($this->transformer);
$builder->get('compagnie_sec')->addModelTransformer($this->transformer);
}
Events are captured on preSubmit to fetch ID, because fields 'compagnie_princ' and 'compagnie_sec' are autocompleted with AJAX, populating hidden inputs. My guess is something is going wrong on that part.
public function onPreSetData(FormEvent $event): void
{
$form = $event->getForm();
$form->add('compagnie_princ_id', HiddenType::class,
['mapped' => false,
'attr' => ['class' => 'hidden-field'],
'data' => $event->getData()->getCompagniePrinc() ? $event->getData()->getCompagniePrinc()->getId() : null
]
);
$form->add('compagnie_sec_id', HiddenType::class,
['mapped' => false,
'attr' => ['class' => 'hidden-field'],
'data' => $event->getData()->getCompagnieSec() ? $event->getData()->getCompagnieSec()->getId() : null,
]
);
}
public function onPreSubmit(FormEvent $event): void
{
$data = $event->getData();
$data['compagnie_princ'] = (int)$data['compagnie_princ_id'];
$data['compagnie_sec'] = (int)$data['compagnie_sec_id'];
$event->setData($data);
}
CompagnieToIdTransformer.php
class CompagnieToIdTransformer implements DataTransformerInterface
{
public function __construct(private EntityManagerInterface $em){
}
public function transform($compagnie)
{
if (null === $compagnie) {
return '';
}
return $compagnie->getCodeIata();
}
public function reverseTransform($compagnieId):?Compagnie
{
if (!$compagnieId) {
return null;
}
$compagnie = $this->em
->getRepository(Compagnie::class)
->find($compagnieId)
;
if (null === $compagnie) {
throw new TransformationFailedException(sprintf(
'A company with number "%s" does not exist!',
$compagnieId
));
}
return $compagnie;
}
}

Sonata ModelAutocompleteType result affected by getFilterParameters

I have this form field of a type ModelAutocompleteType that is supposed to show the result filtered by the "search" datagrid field of related admin:
class OperationAdmin extends AbstractAdmin
{
// ...
protected function configureFormFields(FormMapper $formMapper)
{
$formMapper
->add('business', ModelAutocompleteType::class, [
'label' => 'Business',
'property' => 'search'
]);
}
// ...
}
In this related "business" admin I have few filters defined as:
class BusinessAdmin extends AbstractAdmin
{
// ...
protected function configureDatagridFilters(DatagridMapper $datagridMapper)
{
$datagridMapper
->add('search', CallbackFilter::class, [
'label' => 'Search',
'show_filter' => true,
'advanced_filter' => false,
'callback' => function($qb, $alias, $field, $value) {
if (!$value['value']) return;
// ...
return true;
}
])
->add('state', ChoiceFilter::class, [
'label' => 'State',
'show_filter' => true,
'advanced_filter' => false,
'field_options' => ['choices' => Business::STATES],
'field_type' => 'choice'
]);
}
// ...
}
Now, if I set the default "state" datagrid field value using getFilterParameters to filter business list by state on initial page load:
public function getFilterParameters()
{
$this->datagridValues = array_merge([
'state' => ['type' => '', 'value' => 'active']
], $this->datagridValues);
return parent::getFilterParameters();
}
The related ModelAutocompleteType form field's result will also be filtered by "state" field even tho it's property is set to search.
How do I apply default filter values JUST to list view and nothing else? And why ModelAutocompleteType result depends on other datagrid fields even tho property is set to one?
In the end I left getFilterParameters method in to filter list by default, which is what I wanted:
public function getFilterParameters()
{
$this->datagridValues = array_merge([
'state' => ['type' => '', 'value' => 'active']
], $this->datagridValues);
return parent::getFilterParameters();
}
Unfortunatelly, that was also affecting ModelAutocompleteFilter and ModelAutocompleteType results, filtering them by 'active' state too, which I did not want.
To solve that I had to pass a callback property to ModelAutocompleteType field, to reset datagrid state value:
class OperationAdmin extends AbstractAdmin
{
// ...
protected function configureFormFields(FormMapper $formMapper)
{
$formMapper
->add('business', ModelAutocompleteType::class, [
'label' => 'Business',
'property' => 'search',
'callback' => [$this, 'filterAllBusinessesCallback']
]);
}
public function filterAllBusinessesCallback(AdminInterface $admin, $property, $value)
{
$datagrid = $admin->getDatagrid();
$datagrid->setValue($property, null, $value);
$datagrid->setValue('state', null, null);
}
// ...
}

Symfony2 Cannot instantiate interface Doctrine\Common\Collections\Collection

Symfony version 2.8
I have a problem when I try to add new Collection(); in construct function of User Entity.
public function __construct()
{
$this->sectors = new Collection();
parent::__construct();
}
Sector has many to many relationship
/**
* #ORM\ManyToMany(targetEntity="UserBundle\Entity\Sectors", fetch="EAGER")
* #ORM\JoinTable(
* joinColumns={#ORM\JoinColumn(onDelete="CASCADE")},
* inverseJoinColumns={#ORM\JoinColumn(onDelete="CASCADE")}
* )
*/
public $sectors;
and getter/setter methods are
/**
* Add sector
*
* #param UserBundle\Entity\Sectors $sector
*
* #return User
*/
public function addSector(UserBundle\Entity\Sectors $sector)
{
$this->sectors[] = $sector;
return $this;
}
/**
* Remove sector
*
* #param UserBundle\Entity\Sectors $sector
*/
public function removeSector(UserBundle\Entity\Sectors $sector)
{
$this->sectors->removeElement($sector);
}
/**
* Get sectors
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getSectors()
{
return $this->sectors;
}
When in a FormType I do:
$builder
->add('sectors', EntityType::class, array(
'class' => 'UserBundle\Entity\Sectors',
'placeholder' => 'Select Sector ...',
'label' => 'Sector',
'required' => false,
'attr' => ['placeholder' => 'Select Sector ...', 'data-jcf' => '{"wrapNative": false, "wrapNativeOnMobile": false, "useCustomScroll": true, "multipleCompactStyle": true}'],
'multiple' => true,
'expanded' => false,
'query_builder' => function(EntityRepository $er) {
return $er->createQueryBuilder('u')
->orderBy('u.name', 'ASC');
},
));
$formModify = function (FormInterface $form, \Doctrine\Common\Collections\ArrayCollection $sector, $factory) {
$output = [];
foreach($sector as $sec) {
$output[] = $sec->id;
}
$formOption = array(
'class' => 'UserBundle\Entity\UserAccreditation',
'multiple' => true,
'auto_initialize' => false,
'required' => false,
'expanded' => true,
'choice_attr' => function ($output) {
return ['class' => 'attr_checkbox'];
},
'query_builder' => function(EntityRepository $ertt) use ($output) {
$qb = $ertt->createQueryBuilder('g');
$qb->select(array('g'));
$qb->where('g.sector IN (:sector_id)');
$qb->setParameters( array('sector_id' => $output) );
$qb->orderBy('g.name', 'ASC');
return $qb;
},
);
$form->add($factory->createNamed('accreditationdata', EntityType::class, null, $formOption));
};
$builder->addEventListener(FormEvents::PRE_SET_DATA,function (FormEvent $event) use ($formModify,$factory) {
$data = $event->getData();
$form = $event->getForm();
if ($data != null) {
//print_r(get_object_vars($data->getSectors()));
$formModify($event->getForm(), $data->getSectors(),$factory);
}
}
);
$factory = $builder->getFormFactory();
$builder->get('sectors')->addEventListener(FormEvents::POST_SUBMIT,function (FormEvent $event) use ($formModify,$factory) {
$sector = $event->getForm()->getData();
//print_r($sector);
$formModify($event->getForm()->getParent(), $sector,$factory);
}
);
I get following error:
Fatal error: Cannot instantiate interface Doctrine\Common\Collections\Collection
Earlier I am using ArrayCollection instead of Collection, I have to do this because I am getting error
Type error: Argument 2 passed to UserBundle\Form\Type\ProfileAboutMeFormType::UserBundle\Form\Type{closure}() must be an instance of Doctrine\Common\Collections\ArrayCollection, instance of Doctrine\ORM\PersistentCollection given,
and by searching on google I found this solution on github link
https://github.com/doctrine/orm/issues/5946
but still I am facing the problem. can anyone tell me What goes wrong here ?

How to apply InputFilter validators to fieldset elements in ZF3

I had a form that had two fields. An InputFilter with validators was applied to it. It was working fine. Then I moved the fields to a fieldset and added the fieldset to the form. Now the assignment validators to the fields is not present. The validator objects isValid method is not triggered at all. So how to apply the InputFilter validators to fields in a fieldset? Here you are the classes:
Text class Validator
namespace Application\Validator;
use Zend\Validator\StringLength;
use Zend\Validator\ValidatorInterface;
class Text implements ValidatorInterface
{
protected $stringLength;
protected $messages = [];
public function __construct()
{
$this->stringLengthValidator = new StringLength();
}
public function isValid($value, $context = null)
{
if (empty($context['url'])) {
if (empty($value)) return false;
$this->stringLengthValidator->setMin(3);
$this->stringLengthValidator->setMax(5000);
if ($this->stringLengthValidator->isValid($value)) {
return true;
}
$this->messages = $this->stringLengthValidator->getMessages();
return false;
}
if (!empty($value)) return false;
return true;
}
public function getMessages()
{
return $this->messages;
}
}
Test class InputFilter
namespace Application\Filter;
use Application\Fieldset\Test as Fieldset;
use Application\Validator\Text;
use Application\Validator\Url;
use Zend\InputFilter\InputFilter;
class Test extends InputFilter
{
public function init()
{
$this->add([
'name' => Fieldset::TEXT,
'required' => false,
'allow_empty' => true,
'continue_if_empty' => true,
'validators' => [
['name' => Text::class],
],
]);
$this->add([
'name' => Fieldset::URL,
'required' => false,
'allow_empty' => true,
'continue_if_empty' => true,
'validators' => [
['name' => Url::class],
],
]);
}
}
Test class Fieldset
namespace Application\Fieldset;
use Zend\Form\Fieldset;
class Test extends Fieldset
{
const TEXT = 'text';
const URL = 'url';
public function init()
{
$this->add([
'name' => self::TEXT,
'type' => 'textarea',
'attributes' => [
'id' => 'text',
'class' => 'form-control',
'placeholder' => 'Type text here',
'rows' => '6',
],
'options' => [
'label' => self::TEXT,
],
]);
$this->add([
'name' => self::URL,
'type' => 'text',
'attributes' => [
'id' => 'url',
'class' => 'form-control',
'placeholder' => 'Type url here',
],
'options' => [
'label' => self::URL,
],
]);
}
}
Test class Form
namespace Application\Form;
use Application\Fieldset\Test as TestFieldset;
use Zend\Form\Form;
class Test extends Form
{
public function init()
{
$this->add([
'name' => 'test',
'type' => TestFieldset::class,
'options' => [
'use_as_base_fieldset' => true,
],
]);
$this->add([
'name' => 'submit',
'attributes' => [
'type' => 'submit',
'value' => 'Send',
],
]);
}
}
TestController class
namespace Application\Controller;
use Application\Form\Test as Form;
use Zend\Debug\Debug;
use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;
class TestController extends AbstractActionController
{
private $form;
public function __construct(Form $form)
{
$this->form = $form;
}
public function indexAction()
{
if ($this->getRequest()->isPost()) {
$this->form->setData($this->getRequest()->getPost());
Debug::dump($this->getRequest()->getPost());
if ($this->form->isValid()) {
Debug::dump($this->form->getData());
die();
}
}
return new ViewModel(['form' => $this->form]);
}
}
TestControllerFactory class
namespace Application\Factory;
use Application\Controller\TestController;
use Application\Form\Test;
use Interop\Container\ContainerInterface;
use Zend\ServiceManager\Factory\FactoryInterface;
class TestControllerFactory implements FactoryInterface
{
public function __invoke(ContainerInterface $container, $requestedName, array $options = null)
{
$form = $container->get('FormElementManager')->get(Test::class);
return new TestController($form);
}
}
Test class
namespace Application\Factory;
use Application\Filter\Test as Filter;
use Application\Entity\Form as Entity;
use Application\Form\Test as Form;
use Interop\Container\ContainerInterface;
use Zend\Hydrator\ClassMethods;
use Zend\ServiceManager\Factory\FactoryInterface;
class Test implements FactoryInterface
{
public function __invoke(ContainerInterface $container, $requestedName, array $options = null)
{
return (new Form())
->setHydrator($container
->get('HydratorManager')
->get(ClassMethods::class))
->setObject(new Entity())
->setInputFilter($container->get('InputFilterManager')->get(Filter::class));
}
}
Test Fieldset
namespace Application\Factory;
use Application\Entity\Fieldset as Entity;
use Application\Fieldset\Test as Fieldset;
use Interop\Container\ContainerInterface;
use Zend\Hydrator\ClassMethods;
use Zend\ServiceManager\Factory\FactoryInterface;
class TestFieldset implements FactoryInterface
{
public function __invoke(ContainerInterface $container, $requestedName, array $options = null)
{
return (new Fieldset())
->setHydrator($container->get('HydratorManager')->get(ClassMethods::class))
->setObject(new Entity());
}
}
UPDATE
I updated the fieldset class accordingly to #Nukeface advise by adding setInputFilter(). But it did not worked. It even had not executed InpuFilter class init method. Perhaps I did in wrong:
<?php
namespace Application\Fieldset;
use Application\Filter\Test as Filter;
use Zend\Form\Fieldset;
use Zend\InputFilter\InputFilterAwareTrait;
class Test extends Fieldset
{
use InputFilterAwareTrait;
const TEXT = 'text';
const URL = 'url';
public function init()
{
$this->add([
'name' => self::TEXT,
'type' => 'textarea',
'attributes' => [
'id' => 'text',
'class' => 'form-control',
'placeholder' => 'Type text here',
'rows' => '6',
],
'options' => [
'label' => self::TEXT,
],
]);
$this->add([
'name' => self::URL,
'type' => 'text',
'attributes' => [
'id' => 'url',
'class' => 'form-control',
'placeholder' => 'Type url here',
],
'options' => [
'label' => self::URL,
],
]);
$this->setInputFilter(new Filter());
}
}
Tried an answer before and ran out of chars (30k limit), so created a repo instead. The repo contains abstraction of the answer below, which is a working example.
Your question shows you having the right idea, just not yet the implementation. It also contains a few mistakes, such as setting a FQCN for a Fieldset name. Hopefully the below can have you up and running.
As a use case, we'll have a basic Address form. Relationships for Country, Timezones and other things I'll leave out of the scope. For more in depth and nesting of Fieldsets (also with Collections) I'll refer you to my repo.
General setup
First create the basic setup. Create the Entity and configuration.
Basic Entity
namespace Demo\Entity;
class Address
{
protected $id; // int - primary key - unique - auto increment
protected $street; // string - max length 255 - not null
protected $number; // int - max length 11 - not null
protected $city; // string - max length 255 - null
// getters/setters/annotation/et cetera
}
To handle this in a generic and re-usable way, we're going to need:
AddressForm (general container)
AddressFormFieldset (form needs to be validated)
AddressFieldset (contains the entity inputs)
AddressFieldsetInputFilter (must validate the data entered)
AddressController (to handle CRUD actions)
Factory classes for all of the above
a form partial
Configuration
To tie these together in Zend Framework, these need to be registered in the config. With clear naming, you can already add these. If you're using something like PhpStorm as your IDE, you might want to leave this till last, as the use statements can be generated for you.
As this is an explanation, I'm showing you now. Add this to your module's config:
// use statements here
return [
'controllers' => [
'factories' => [
AddressController::class => AddressControllerFactory::class,
],
],
'form_elements' => [ // <-- note: both Form and Fieldset classes count as Form elements
'factories' => [
AddressForm::class => AddressFormFactory::class,
AddressFieldset::class => AddressFieldsetFactory::class,
],
],
'input_filters' => [ // <-- note: input filter classes only!
'factories' => [
AddressFormInputFilter::class => AddressFormInputFilterFactory::class,
AddressFieldsetInputFilter::class => AddressFieldsetInputFilterFactory::class,
],
],
'view_manager' => [
'template_map' => [
'addressFormPartial' => __DIR__ . '/../view/partials/address-form.phtml',
],
];
Fieldset
First we create the Fieldset (and Factory) class. This is because this contains the actual object we're going to handle.
AddressFieldset
// other use statements for Elements
use Zend\Form\Fieldset;
class AddressFieldset extends Fieldset
{
public function init()
{
parent::init(); // called due to inheritance
$this->add([
'name' => 'id',
'type' => Hidden::class,
]);
$this->add([
'name' => 'street',
'required' => true,
'type' => Text::class,
'options' => [
'label' => 'Name',
],
'attributes' => [
'minlength' => 1,
'maxlength' => 255,
],
]);
$this->add([
'name' => 'number',
'required' => true,
'type' => Number::class,
'options' => [
'label' => 'Number',
],
'attributes' => [
'step' => 1,
'min' => 0,
],
]);
$this->add([
'name' => 'city',
'required' => false,
'type' => Text::class,
'options' => [
'label' => 'Name',
],
'attributes' => [
'minlength' => 1,
'maxlength' => 255,
],
]);
}
}
AddressFieldsetFactory
// other use statements
use Zend\ServiceManager\Factory\FactoryInterface;
class AddressFieldsetFactory implements FactoryInterface
{
public function __invoke(ContainerInterface $container, $requestedName, array $options = null)
{
$this->setEntityManager($container->get(EntityManager::class));
/** #var AddressFieldset $fieldset */
$fieldset = new AddressFieldset($this->getEntityManager(), 'address');
$fieldset->setHydrator(
new DoctrineObject($this->getEntityManager())
);
$fieldset->setObject(new Address());
return $fieldset;
}
}
InputFilter
Above we created the Fieldset. That allows for the generation of the Fieldset for in a Form. At the same time, Zend Framework also has defaults already set per type of input (e.g. 'type' => Text::class). However, if we want to validate it to our own, more strict, standards, we need to override the defaults. For this we need an InputFilter class.
AddressFieldsetInputFilter
// other use statements
use Zend\InputFilter\InputFilter;
class AddressFieldsetInputFilter extends InputFilter
{
public function init()
{
parent::init(); // called due to inheritance
$this->add([
'name' => 'id',
'required' => true,
'filters' => [
['name' => ToInt::class],
],
'validators' => [
['name' => IsInt::class],
],
]);
$this->add([
'name' => 'street',
'required' => true,
'filters' => [
['name' => StringTrim::class], // remove whitespace before & after string
['name' => StripTags::class], // remove unwanted tags
[ // if received is empty string, set to 'null'
'name' => ToNull::class,
'options' => [
'type' => ToNull::TYPE_STRING, // also supports other types
],
],
],
'validators' => [
[
'name' => StringLength::class, // set min/max string length
'options' => [
'min' => 1,
'max' => 255,
],
],
],
]);
$this->add([
'name' => 'number',
'required' => true,
'filters' => [
['name' => ToInt::class], // received from HTML form always string, have it cast to integer
[
'name' => ToNull::class, // if received is empty string, set to 'null'
'options' => [
'type' => ToNull::TYPE_INTEGER,
],
],
],
'validators' => [
['name' => IsInt::class], // check if actually integer
],
]);
$this->add([
'name' => 'city',
'required' => false, // <-- not required
'filters' => [
['name' => StringTrim::class], // remove whitespace before & after string
['name' => StripTags::class], // remove unwanted tags
[ // if received is empty string, set to 'null'
'name' => ToNull::class,
'options' => [
'type' => ToNull::TYPE_STRING, // also supports other types
],
],
],
'validators' => [
[
'name' => StringLength::class, // set min/max string length
'options' => [
'min' => 1,
'max' => 255,
],
],
],
]);
}
}
AddressFieldsetInputFilterFactory
// other use statements
use Zend\ServiceManager\Factory\FactoryInterface;
class AddressFieldsetInputFilterFactory implements FactoryInterface
{
public function __invoke(ContainerInterface $container, $requestedName, array $options = null)
{
// Nothing else required in this example. So it's as plain as can be.
return new AddressFieldsetInputFilter();
}
}
Form & Validation
So. Above we created the Fieldset, it's InputFilter and 2 required Factory classes. This already allows us to do a great deal, such as:
use the InputFilter in stand-alone setting to dynamically validate an object
re-use Fieldset + InputFilter combination in other Fieldset and InputFilter classes for nesting
Form
use Zend\Form\Form;
use Zend\InputFilter\InputFilterAwareInterface;
// other use statements
class AddressForm extends Form implements InputFilterAwareInterface
{
public function init()
{
//Call parent initializer. Check in parent what it does.
parent::init();
$this->add([
'type' => Csrf::class,
'name' => 'csrf',
'options' => [
'csrf_options' => [
'timeout' => 86400, // day
],
],
]);
$this->add([
'name' => 'address',
'type' => AddressFieldset::class,
'options' => [
'use_as_base_fieldset' => true,
],
]);
$this->add([
'name' => 'submit',
'type' => Submit::class,
'attributes' => [
'value' => 'Save',
],
]);
}
}
Form Factory
use Zend\ServiceManager\Factory\FactoryInterface;
// other use statements
class AddressFormFactory implements FactoryInterface
{
public function __invoke(ContainerInterface $container, $requestedName, array $options = null)
{
/** #var AbstractForm $form */
$form = new AddressForm('address', $this->options);
$form->setInputFilter(
$container->get('InputFilterManager')->get(ContactFormInputFilter::class);
);
return $form;
}
}
Making it all come together
I'll show just the AddressController#addAction
AddressController
use Zend\Mvc\Controller\AbstractActionController;
// other use statements
class AddressController extends AbstractActionController
{
protected $addressForm; // + getter/setter
protected $entityManager; // + getter/setter
public function __construct(
EntityManager $entityManager,
AddressForm $form
) {
$this->entityManager = $entityManager;
$this->addressForm = $form;
}
// Add your own: index, view, edit and delete functions
public function addAction () {
/** #var AddressForm $form */
$form = $this->getAddressForm();
/** #var Request $request */
$request = $this->getRequest();
if ($request->isPost()) {
$form->setData($request->getPost());
if ($form->isValid()) {
$entity = $form->getObject();
$this->getEntityManager()->persist($entity);
try {
$this->getEntityManager()->flush();
} catch (\Exception $e) {
$this->flashMessenger()->addErrorMessage($message);
return [
'form' => $form,
'validationMessages' => $form->getMessages() ?: '',
];
}
$this->flashMessenger()->addSuccessMessage(
'Successfully created object.'
);
return $this->redirect()->route($route, ['param' => 'routeParamValue']);
}
$this->flashMessenger()->addWarningMessage(
'Your form contains errors. Please correct them and try again.'
);
}
return [
'form' => $form,
'validationMessages' => $form->getMessages() ?: '',
];
}
}
AddressControllerFactory
class AddressControllerFactory implements FactoryInterface
{
public function __invoke(ContainerInterface $container, $requestedName, array $options = null)
{
/** #var AddressController $controller */
$controller = new AddressController(
$container->get(EntityManager::class),
$container->get('FormElementManager')->get(AddressForm::class);
);
return $controller;
}
}
Display in addressFormPartial
$this->headTitle('Add address');
$form->prepare();
echo $this->form()->openTag($form);
echo $this->formRow($form->get('csrf'));
echo $this->formRow($form->get('address')->get('id'));
echo $this->formRow($form->get('address')->get('street'));
echo $this->formRow($form->get('address')->get('number'));
echo $this->formRow($form->get('address')->get('city'));
echo $this->formRow($form->get('submit'));
echo $this->form()->closeTag($form);
To use this partial, say in a add.phtml view, use:
<?= $this->partial('addressFormPartial', ['form' => $form]) ?>
This bit of code will work with the demonstrated addAction in the Controller code above.
Hope you found this helpful ;-) If you have any questions left, don't hesitate to ask.
Just use the InputFilterProviderInterface class to your fieldset. This implements the getInputFilterSpecification method to your fieldset, which executes the input filters mentioned in this method.
class MyFieldset extends Fieldset implements InputFilterProviderInterface
{
public function init()
{
$this->add([
'name' => 'textfield',
'type' => Text::class,
'attributes' => [
...
],
'options' => [
...
]
]);
}
public function getInputFilterSpecification()
{
return [
'textfield' => [
'required' => true,
'filters' => [
...
],
'validators' => [
[
'name' => YourTextValidator::class,
'options' => [
...
],
],
],
],
];
}
}
AS long as you add this fieldset in your form the bound filters and validators will be executed on the isValid method call of your form.

Symfony2 ManyToMany multiple field form collection

Is there a way to save correctly in a relationship ManyToMany field entities in a form that is "multiple" and is part of a collection?
I looked everywhere but could not find a shred of example to make me understand how to do!
I cannot find the solution for this!
class Anagrafica
{
/**
* #ORM\ManyToMany(targetEntity="SubCategories", inversedBy="anagrafiche", cascade={"persist", "remove"})
* #ORM\JoinTable(name="AnCat")
**/
private $subCategories;
//..
public function __construct()
{
$this->subCategories = new \Doctrine\Common\Collections\ArrayCollection();
//..
}
/**
* Add subCategories
*
* #param \My\BusinessBundle\Entity\SubCategories $subCategories
* #return Anagrafica
*/
public function addSubCategory(\My\BusinessBundle\Entity\SubCategories $subCategories)
{
foreach ($subCategories as $subCategory) {
$subCategory->addAnagrafiche($this);
}
$this->subCategories = $subCategories;
}
*******
class SubCategories
{
/**
* #ORM\ManyToMany(targetEntity="Anagrafica", mappedBy="subCategories")
*/
private $anagrafiche;
public function __construct()
{
$this->anagrafiche = new \Doctrine\Common\Collections\ArrayCollection();
}
/**
* Add anagrafiche
*
* #param \My\BusinessBundle\Entity\Anagrafica $anagrafiche
* #return SubCategories
*/
public function addAnagrafiche(\My\BusinessBundle\Entity\Anagrafica $anagrafiche)
{
if (!$this->anagrafiche->contains($anagrafiche)) {
$this->anagrafiche->add($anagrafiche);
}
}
******
AnagraficaType:
//..
->add('subCategories', 'collection', array('type' => new SubCategoriesType(),
'allow_add' => true,
'allow_delete' => true,
'prototype' => true,
'prototype_name' => '__categ__',
'by_reference' => false
))
*******
SubCategoriesType:
->add('subCategory', 'entity', array(
'class' => 'CoffeeBusinessBundle:SubCategories',
'property' => 'subCategory',
'label' => 'Sotto Categorie',
'multiple' => true
))
Partially solved
If I enter the field collection directly and do these changes:
AnagraficaType:
->add('subCategories', 'collection', array(
'type' => 'entity',
'allow_add' => true,
'allow_delete' => true,
'prototype' => true,
'prototype_name' => '__categ__',
'by_reference' => false,
'options' => array(
'label' => 'Sotto Categorie',
'multiple' => true,
'class' => 'MyBusinessBundle:SubCategories',
'property' => 'subCategory'
)
))
Anagrafica entity:
public function addSubCategory(ArrayCollection $subCategories)
{
foreach ($subCategories as $subCategory) {
$subCategory->addAnagrafiche($this);
//var_dump($subCategory);
}
$this->subCategories = $subCategories;
}
Partially get the desired result, but if I add a field in the form subcategories (by collection) saves only the last field entered.
I did a var_dump ArrayCollection object received and in fact inside there are only data from the last field entered.
Any idea?

Resources