Symfony2 form collections limit - forms

I have a Course entity, which has many CourseSessions. CourseSession can be active or passed.
How can I render only active CourseSessions and save relations with the passed CourseSessions on the Course edit page?
Now I render all CourseSessions but when CourseSession counts more than 50, the page renders very slow.
Can anyone help me?
UPDATE 1:
class CourseType {
$builder->add('sessions', 'collection', array(
'label' => false,
'type' => new CourseSessionType(), // <- here I want to pass only active Sessions
'allow_add' => true,
'allow_delete' => true,
'prototype' => true,
'prototype_name' => '__name__'
))
}
class CourseSessionType {
// multiple CourseSession fields
}
// Course edit page
<div id="courseSessions" data-prototype="{{macros.course_session_prototype(form.sessions, 'Remove Session', true)|escape }}">
{% do form.sessions.setRendered %}
{% for widget in form.sessions.children %}
{{ macros.course_session_prototype(widget, 'Remove Session', false) }}
{% endfor %}
</div>
UPDATE 2:
How can I map my 'type' => new CourseSessionType() with getActiveCourseSessions() and setActiveCourseSessions()? I think it will help me.

try to set the name of the field accordingly to the method to map using active_course_sessions or shorter if you name your methods Course::getActiveSessions() and Course::setActiveSessions() it could be done like this :
class CourseType {
$builder->add('active_sessions', 'collection', array(
'label' => false,
'type' => new CourseSessionType(),
'allow_add' => true,
'allow_delete' => true,
'prototype' => true,
'prototype_name' => '__name__'
));
}

I'm glat to tell you that I found the solution!
I added in my Course entity a $showOnlyActiveSessions property and changed getSessions() method
class Course
{
/**
* Show only active sessions flag
* #var bool
*/
private $showOnlyActiveSessions = false;
// other properties
/**
* Get course sessions
* #return CourseSession []
*/
public function getSessions()
{
$sessions = $this->sessions;
if ($this->getShowOnlyActiveSessions()) {
return array_filter($sessions->toArray(), function($session) {
return !$session->isPast();
});
}
return $this->sessions;
}
/**
* #return bool
*/
public function getShowOnlyActiveSessions()
{
return $this->showOnlyActiveSessions;
}
/**
* #param bool $boolValue
*/
public function setShowOnlyActiveSessions($boolValue)
{
$this->showOnlyActiveSessions = $boolValue;
}
}
and now, when I need to get only active sessions i do the following in my controller:
public function editAction(Request $request, Course $course)
{
$course->setShowOnlyActiveSessions(true);
$editForm = $this->createEditForm($course);
$editForm->handleRequest($request);
if ($editForm->isValid()) {
// handle and persist form
}
return $this->redirectToRoute('course_list');
}
I hope it'll be helpful for somebody.

Related

Prestashop 1.7 renderform by admincontroller error

for my module i need to generate a form with helper. I found nothing with my error on the web so... I post again something...
Here my AdminYoutubeHomeController
<?php
class AdminYoutubeHomeController extends ModuleAdminController
{
public function __construct()
{
$this->bootstrap = true;
$this->display = 'view';
parent::__construct();
$this->meta_title = $this->l('Youtube');
if (!$this->module->active) {
Tools::redirectAdmin($this->context->link->getAdminLink('AdminHome'));
}
}
public function renderView()
{
/**
* If values have been submitted in the form, process.
*/
if (((bool)Tools::isSubmit('submitYoutubeHomeModule')) == true) {
$this->postProcess();
}
$this->context->smarty->assign([
'youtube_dir', _PS_MODULE_DIR_.'youtubehome',
'youtube_embeded' => "https://www.youtube.com/embed/",
'youtubeLink' => Configuration::get('YOUTUBEHOME_LINK_VIDEO')
]);
return $this->context->smarty->fetch(_PS_MODULE_DIR_.'youtubehome/views/templates/admin/youtubehome.tpl').$this->renderForm();
}
/**
* Create the form that will be displayed in the configuration of your module.
*/
public function renderForm()
{
$helper = new HelperForm();
$helper->show_toolbar = false;
$helper->table = $this->table;
$helper->module = $this;
$helper->name_controller = $this->module->name;
$helper->default_form_language = $this->context->language->id;
$helper->allow_employee_form_lang = Configuration::get('PS_BO_ALLOW_EMPLOYEE_FORM_LANG', 0);
$helper->identifier = $this->identifier;
$helper->submit_action = 'submitYoutubeHomeModule';
$helper->currentIndex = $this->context->link->getAdminLink('AdminModules', false)
.'&configure='.$this->module->name.'&tab_module='.$this->module->tab.'&module_name='.$this->module->name;
$helper->token = Tools::getAdminTokenLite('AdminModules');
$helper->tpl_vars = array(
'fields_value' => $this->getConfigFormValues(), /* Add values for your inputs */
'languages' => $this->context->controller->getLanguages(),
'id_language' => $this->context->language->id,
);
return $helper->generateForm(array($this->getConfigForm()));
}
/**
* Create the structure of your form.
*/
public function getConfigForm()
{
return array(
'form' => array(
'legend' => array(
'title' => $this->l('Settings'),
'icon' => 'icon-cogs',
),
'input' => array(
array(
'col' => 3,
'type' => 'text',
'prefix' => '<i class="icon icon-youtube-play"></i>',
'desc' => $this->l('Enter your youtube end link'),
'name' => 'YOUTUBEHOME_LINK_VIDEO',
'label' => $this->l('Link'),
),
),
'submit' => array(
'title' => $this->l('Save'),
),
),
);
}
/**
* Set values for the inputs.
*/
public function getConfigFormValues()
{
return array(
'YOUTUBEHOME_LINK_VIDEO' => Configuration::get('YOUTUBEHOME_LINK_VIDEO'),
);
}
/**
* Save form data.
*/
public function postProcess()
{
$form_values = $this->getConfigFormValues();
foreach (array_keys($form_values) as $key) {
Configuration::updateValue($key, Tools::getValue($key));
}
}
}
And here the error
My tpl file is in modules/youtubehome/views/templates/admin/youtubehome.tpl
I don't want to override the default form. Do you think i have doing something wrong ?
EDIT POST
Here it's the error with ps_version
try with :
$this->setTemplate('module:youtubehome/views/templates/admin/youtubehome.tpl');
Regards

Symfony2 Form Splitting in sub forms with css helper

I have large form, i need to split it in multiple form when on mobile view.
Desktop = 1 large form
Mobile = 2-3 smaller form, when i valid the 1 form, then new page 2 form, and so on..
I would like to do it in responsive way NOT sub-domaine like (http://mobile/blah.com)
PS: I want to avoid third party bundle !!
Advice, recommandation, direction anything than can help me
My controller:
public function ownerRegisterAction(Request $request)
{
$em = $this->getDoctrine()->getManager();
$owner = new Owner();
$form = $this->createCreateForm($owner);
$form->handleRequest($request);
if($form->isSubmitted() && $form->isValid())
{
$password = $this->get('security.password_encoder')
->encodePassword($owner->getOwner(), $owner->getOwner()->getPassword());
$owner->getOwner()->setPassword($password);
$owner->getOwner()->setStatus('owner');
$owner->getOwner()->setIsValid(0);
$em->persist($owner);
$em->flush();
// Login users after registration
$this->get('apx_auth_after_register')->authenticateUser($tenant->getTenant());
$response = $this->forward('PagesBundle:SearchOwner:search', ['owner' => $owner]);
return $response;
}
return $this->render('::form/owner-register.html.twig', array(
'form' => $form->createView()
));
}
My Form Type :
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('corporate', CorporateType::class, ['expanded' => true, 'multiple' => false, 'label' => false])
//->add('postcode', NumberType::class,['label' => false])
->add('type', TypeType::class, ['expanded' => true, 'multiple' => false,'label' => false])
->add('room', NbRoomType::class,['expanded' => true, 'multiple' => false,'label' => false])
->add('rent', NumberType::class,['label' => false])
->add('area', NumberType::class,['label' => false])
->add('images', CollectionType::class, [
'entry_type' => ImagesFlatType::class,
'allow_add' => true,
'required' => false,
'allow_delete' => true,
'label' => false,
])
->add('fee', NumberType::class, ['label' => false, 'required' => false])
// to be defined in list by city
->add('transport', TextType::class,['label' => false, 'required' => false])
->add('furnished', FurnishedType::class, ['expanded' => true, 'multiple' => false,'label' => false])
->add('vip', LesVipType::class, ['expanded' => true, 'multiple' => true,'label' => false])
->add('feature', FeatureType::class, ['expanded' => true, 'multiple' => true,'label' => false])
->add('description', TextareaType::class,['label' => false, 'required' => false])
// City ajax call to be fix
->add('location', EntityType::class, ['label' => false,
'class' => 'PagesBundle:City',
'choice_label' => 'zone']);
Thanks all
Nico
Well, I don't think it is a hard task. Actually it's seems somewhat obvious (at least for me though).
You could to use something like TabView or Accordion-like view. All of this can be achieved by using pure CSS (and maybe Javascript).
As you can see it is not related to Symfony at all. By using CSS + Media-queries I'm sure you can get done the desired UI.
Without mobile subdomain and with css help only
When you use FormBuilder::add() you create an instance of FormType which can be :
the entire form,
a field,
a sub form.
So they all behave the same way.
Then you can easily split your FormType in 3 SubFormTypes :
namespace AppBundle\Form;
/*
* When forms get heavy, it becomes handy to use aliases
* on import use statements since it eases the reading in code
* and reduces the list of imports.
*/
use Type as AppType;
use Symfony\Bridge\Doctrine\Form\Type as OrmType;
use Symfony\Component\Form\Extension\Core\Type as CoreType;
// An abstract class which all sub form will extend.
abstract class AbstractSubFormType extends AbstractType
{
/*
* We need to add a submit button on the sub form
* which will be only visible on mobile screens.
*
* Then to get help of css class :
* use ".submit-sub_owner { display: 'none'; }" for desktop screens,
* and ".submit-sub_owner { display: 'block'; }" for mobile screens.
*
* Plus we need dynamic hiding of next sub forms from controller :
* use ".sub_owner-next { display: 'none'; }" for mobile screens.
*/
public function buildForm(FormBuilderInterface $builder, array $options = array())
{
$builder->add('submit', CoreType\SubmitType::class,
'attr' => array(
// Needed to target sub owner controller.
'formaction' => $options['sub_action'],
// Hides sub owners submit button on big screens.
'class' => 'submit_sub_owner',
)
));
}
public function configureOptions(OptionsResolver $resolver)
{
$subNextNormalizer = function (Options $options, $subNext) {
$hideNextSubOwners = isset($options['sub_next']) && $subNext;
// Sets "attr" option of this sub owner type.
$options['attr']['class'] = $hideNextSubOwners ? 'sub_owner-next' : '';
}
// Allows custom options.
$resolver->setDefaults(array('sub_action' => '', 'sub_next' => false));
// Hides sub owners exept the first stage from main controller.
$resolver->setNormalizer('sub_next', $subNextNormalizer);
}
}
// Stage 1
class SubOwnerOne extends AppType\AbstractSubFormType
{
public function buildForm(FormBuilderInterface $builder, array $options = array())
{
// Arbitrary cut of your example
$builder
->add('corporate', AppType\CorporateType::class)
->add('type', AppType\TypeType::class)
->add('room', AppType\NbRoomType::class);
// Call parent to optionnaly add sumbit button
parent::builForm($builder, $options);
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(array('expanded' => true, 'multiple' => false));
}
public function getName()
{
return 'sub_owner_1';
}
}
// Stage 2
// note that this one is tricky because there is an image that may be a file.
class SubOwnerTwo extends AppType\AbstractSubFormType
{
public function buildForm(FormBuilderInterface $builder, array $options = array())
{
// Arbitrary cut of your example
$builder
//->add('postcode')
->add('area')
->add('rent')
->add('images', CoreType\CollectionType::class, array(
'entry_type' => AppType\ImagesFlatType::class,
'allow_add' => true,
'allow_delete' => true,
'required' => false,
));
// Call parent to optionnaly add sumbit button
parent::builForm($builder, $options);
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefault('data_class', CoreType\NumberType::class);
}
public function getName()
{
return 'sub_owner_2';
}
}
// Last stage
class SubOwnerThree extends AppType\AbstractSubFormType
{
public function buildForm(FormBuilderInterface $builder, array $options = array())
{
// Arbitrary cut of your example
$builder
->add('fee', CoreType\NumberType::class, array('required' => false))
// to be defined in list by city
->add('transport', CoreType\TextType::class, array('required' => false))
->add('furnished', AppType\FurnishedType::class) // define options in class
->add('vip', AppType\LesVipType::class) // when belongs to AppType
->add('feature', AppType\FeatureType::class) // ...
->add('description', CoreType\TextareaType::class, array('required' => false))
// City ajax call to be fix
->add('location', OrmType\EntityType::class, array(
'class' => 'PagesBundle:City',
'choice_label' => 'zone',
));
// Call parent to optionnaly add sumbit button
parent::builForm($builder, $options);
}
public function getName()
{
return 'sub_owner_3';
}
}
One FormType to wrap them all :
class OwnerType extends AbstractType
{
public function createForm(FormBuilderInterface $builder, array $options = array())
{
$sub = isset($option['sub_action']) ? $options['sub_action'] : false;
$next = isset($option['sub_next']) ? $options['sub_next'] : false;
$builder
->add('stage_one', AppType\SubOwnerOne::class, array(
'sub_action' => $sub, // get form action from controllers.
))
->add('stage_two', AppType\SubOwnerTwo::class, array(
'sub_action' => $sub,
'sub_next' => $next, // hide sub owners from main controller on mobile screens.
))
->add('final', AppType\SubFormTypeThree::class, array(
'sub_action' => $sub,
'sub_next' => $next,
))
->add('submit', CoreType\SubmitType::class, array(
'attr' => array(
// Allows using ".submit-owner { display: 'none'; }" for mobile screens.
'class' => 'submit-owner',
),
));
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(array(
'label' => false,
// Allows custom options
'sub_action' => '',
'sub_next' => false,
));
}
// ...
}
Controllers :
// Holds two controllers, one for owner type and another for sub owner types.
class OwnerController extends \Symfony\Bundle\FrameworkBundle\Controller\Controller
{
/*
* Main controller.
*
* This handles initial request
* and renders a view with a form view of OwnerType
*/
public function ownerRegisterAction(Request $request)
{
$owner = new Owner();
// Customizes options
$form = $this->createFormBuilder($owner, array(
// Uses route name of the other controller
'sub_action' => $this->generateUrl('handle_sub_owners'),
// Hides next stages
'sub_next' => true,
))->getForm();
$form->handleRequest($request);
if($form->isSubmitted && $form->isValid()) {
$password = $this->get('security.password_encoder')
->encodePassword($owner->getOwner(), $owner->getOwner()->getPassword());
$owner->getOwner()->setPassword($password);
$owner->getOwner()->setStatus('owner');
$owner->getOwner()->setIsValid(0);
$em = $this->getDoctrine()->getManager();
$em->persist($owner);
$em->flush();
// Login users after registration
$this->get('apx_auth_after_register')->authenticateUser($tenant->getTenant());
// Forwards quiting registration process
return $this->forward('PagesBundle:SearchOwner:search', array('owner' => $owner));
}
// This view should use css rules from above comments
return $this->render('::form/owner-register.html.twig', array(
'form' => $form->createView(),
));
}
/**
* Secondary controller handles sub forms
* and renders one form view among the sub forms.
*
* #Route('/_sub_owners', name="handle_sub_owners")
*/
public function handleSubOwnersAction(Request $request)
{
// Customize sub form action
$action = array('sub_action' => $this->generateUrl('handle_sub_owners'));
// Option "sub_next" will default to false.
$form = $this->createForm(AppType\OwnerType::class, new Owner(), $action);
$form->handleRequest($request);
$subOwner1 = $form->get('stage_one');
$subOwner2 = $form->get('stage_two');
$finalOwner = $form->get('final');
// Last stage is done, reforwards to the main controller.
if ($finalOwner->isSubmitted() && $finalOwner->isValid()) {
// Submits $data to new OwnerType as $form has been submitted by "handleRequest()" call
$owner = $this->createForm(AppType\OwnerType::class, new Owner());
$owner->get('stage_one')->submit(json_decode($finalOwner->get('j_stage_one')->getData()));
$owner->get('stage_two')->submit(json_decode($finalOwner->get('j_stage_two')->getData()));
$owner->get('final')->submit($finalOwner->getData());
// Form in main controller will handle the request again,
// so we need to pass normalized data.
return $this->forward('App:Owner:ownerRegister', array(), $owner->getNormData())
}
// Stage 2 is done
if ($subOwner2->isSubmitted() && $subOwner2->isValid()) {
// Gets back json of stage 1
$finalOwner->add('j_stage_one', 'hidden', array(
// Unmaps this hidden field as it won't match any property of Owner
'mapped' => false,
'data' => $subOwner1->get('j_stage_1')->getData(),
));
// Saves json of stage 2
$finalOwner->add('j_stage_two', 'hidden', array(
'mapped' => false,
'data' => json_encode($subOwner2->getData(), true),
));
// Renders final stage
return $this->render('::form/owner-register.html.twig', array(
'form' => $finalOwner->createView(),
));
}
// Stage 1 is done
if ($subOwner1->isSubmitted() && $subOwner1->isValid()) {
// Save json of $subOwner1
$subOwner2->add('j_stage_one', 'hidden', array(
'mapped' => false,
'data' => json_encode($subOwner1->getData(), true),
));
// Render stage 2
return $this->render('::form/owner-register.html.twig', array(
'form' => $subOwner2->createView(),
));
}
// Else renders stage 1
return $this->render('::form/owner-register.html.twig', array(
'form' => $subOwner1->createView(),
));
}
}
View
{# ::form/owner-register.html.twig #}
...
<style type="text/css">
/* #media mobile screens */
.sub_owner-next, .submit-owner { display: 'none'; }
.submit-sub_owner { display: 'block'; }
/* #media desktop screens */
.submit-sub_owner { display: 'none'; }
</style>
...
{{ form_start(form) }}
{% form sub_form in form %}
{{ form_start(sub_form) }}
{{ form_widget(sub_form) }}
{{ form_end(sub_form) }}
{% endear %}
{{ form_end(form) }}
...
Alternative use Mobile Detection
There are many php libraries to detect mobile browsers.
For example https://github.com/serbanghita/Mobile-Detect
which provides a bundle for symfony :
https://github.com/suncat2000/MobileDetectBundle
So you can even use a helper in a previous implementation :
$mobileDetector = $this->get('mobile_detect.mobile_detector');
$mobileDetector->isMobile();
$mobileDetector->isTablet()
If you want to split form using responsive way, you should format form output in your view (e.g. TWIG file). Place form parts in separate containers and then use CSS media queries and JS. Good luck!
I did something a few years back in which a passed a 'step' var into the formType which I incremented after each post.
I used an if statement in the formType to build the form depending on the step value.

symfony2 form create new type combining collection and entity

With symfony 2, I am willing to create a new field type combining the behaviour of the entity field type and the one of the collection field type:
- if the user selects an existing entity, the collection of new entity is null
- if the user creates a new entity, the first field is not required
Do ou have any idea as how to proceed? Can I reuse existing symfony types? Where do I put the logic (if old, collection is not required, if new, entity is not required) ?
Thansk a lot
I finally got it ! Wow, this was not that easy.
So basically, adding a new entry to a select with javascript when the form type is an entity type triggers a Symfony\Component\Form\Exception\TransformationFailedException.
This exception comes from the getChoicesForValues method called on a ChoiceListInterface in the reverseTransform method of the ChoicesToValuesTransformer. This DataTransformer is used in the ChoiceType so to overcome this, I had to build a new type extending the ChoiceType and replacing just a tiny part of it.
The steps to make it work :
Create a new type :
<?php
namespace AppBundle\Form\Type;
use AppBundle\Form\DataTransformer\ChoicesToValuesTransformer;
use Doctrine\Common\Persistence\ObjectManager;
use Doctrine\ORM\EntityManager;
use Symfony\Bridge\Doctrine\Form\ChoiceList\ORMQueryBuilderLoader;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\Form\FormBuilderInterface;
use Doctrine\Common\Persistence\ManagerRegistry;
use Symfony\Component\Form\Exception\RuntimeException;
use Symfony\Bridge\Doctrine\Form\ChoiceList\EntityChoiceList;
use Symfony\Bridge\Doctrine\Form\EventListener\MergeDoctrineCollectionListener;
use Symfony\Bridge\Doctrine\Form\DataTransformer\CollectionToArrayTransformer;
use Symfony\Component\OptionsResolver\Options;
use Symfony\Component\PropertyAccess\PropertyAccess;
use Symfony\Component\PropertyAccess\PropertyAccessorInterface;
use Symfony\Component\Form\Extension\Core\View\ChoiceView;
use Symfony\Component\Form\Exception\LogicException;
use Symfony\Component\Form\Extension\Core\EventListener\FixRadioInputListener;
use Symfony\Component\Form\Extension\Core\EventListener\FixCheckboxInputListener;
use Symfony\Component\Form\Extension\Core\EventListener\MergeCollectionListener;
use Symfony\Component\Form\Extension\Core\DataTransformer\ChoiceToValueTransformer;
use Symfony\Component\Form\Extension\Core\DataTransformer\ChoiceToBooleanArrayTransformer;
use Symfony\Component\Form\Extension\Core\DataTransformer\ChoicesToBooleanArrayTransformer;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
class TagType extends ChoiceType
{
/**
* #var ManagerRegistry
*/
protected $registry;
/**
* #var array
*/
private $choiceListCache = array();
/**
* #var PropertyAccessorInterface
*/
private $propertyAccessor;
/**
* #var EntityManager
*/
private $entityManager;
public function __construct(EntityManager $entityManager, ManagerRegistry $registry, PropertyAccessorInterface $propertyAccessor = null)
{
$this->registry = $registry;
$this->propertyAccessor = $propertyAccessor ?: PropertyAccess::createPropertyAccessor();
$this->entityManager = $entityManager;
$this->propertyAccessor = $propertyAccessor;
}
public function buildForm(FormBuilderInterface $builder, array $options)
{
if (!$options['choice_list'] && !is_array($options['choices']) && !$options['choices'] instanceof \Traversable) {
throw new LogicException('Either the option "choices" or "choice_list" must be set.');
}
if ($options['expanded']) {
// Initialize all choices before doing the index check below.
// This helps in cases where index checks are optimized for non
// initialized choice lists. For example, when using an SQL driver,
// the index check would read in one SQL query and the initialization
// requires another SQL query. When the initialization is done first,
// one SQL query is sufficient.
$preferredViews = $options['choice_list']->getPreferredViews();
$remainingViews = $options['choice_list']->getRemainingViews();
// Check if the choices already contain the empty value
// Only add the empty value option if this is not the case
if (null !== $options['placeholder'] && 0 === count($options['choice_list']->getChoicesForValues(array('')))) {
$placeholderView = new ChoiceView(null, '', $options['placeholder']);
// "placeholder" is a reserved index
$this->addSubForms($builder, array('placeholder' => $placeholderView), $options);
}
$this->addSubForms($builder, $preferredViews, $options);
$this->addSubForms($builder, $remainingViews, $options);
if ($options['multiple']) {
$builder->addViewTransformer(new ChoicesToBooleanArrayTransformer($options['choice_list']));
$builder->addEventSubscriber(new FixCheckboxInputListener($options['choice_list']), 10);
} else {
$builder->addViewTransformer(new ChoiceToBooleanArrayTransformer($options['choice_list'], $builder->has('placeholder')));
$builder->addEventSubscriber(new FixRadioInputListener($options['choice_list'], $builder->has('placeholder')), 10);
}
} else {
if ($options['multiple']) {
$builder->addViewTransformer(new ChoicesToValuesTransformer($options['choice_list']));
} else {
$builder->addViewTransformer(new ChoiceToValueTransformer($options['choice_list']));
}
}
if ($options['multiple'] && $options['by_reference']) {
// Make sure the collection created during the client->norm
// transformation is merged back into the original collection
$builder->addEventSubscriber(new MergeCollectionListener(true, true));
}
if ($options['multiple']) {
$builder
->addEventSubscriber(new MergeDoctrineCollectionListener())
->addViewTransformer(new CollectionToArrayTransformer(), true)
;
}
}
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$choiceListCache = & $this->choiceListCache;
$choiceList = function (Options $options) use (&$choiceListCache) {
// Harden against NULL values (like in EntityType and ModelType)
$choices = null !== $options['choices'] ? $options['choices'] : array();
// Reuse existing choice lists in order to increase performance
$hash = hash('sha256', serialize(array($choices, $options['preferred_choices'])));
if (!isset($choiceListCache[$hash])) {
$choiceListCache[$hash] = new SimpleChoiceList($choices, $options['preferred_choices']);
}
return $choiceListCache[$hash];
};
$emptyData = function (Options $options) {
if ($options['multiple'] || $options['expanded']) {
return array();
}
return '';
};
$emptyValue = function (Options $options) {
return $options['required'] ? null : '';
};
// for BC with the "empty_value" option
$placeholder = function (Options $options) {
return $options['empty_value'];
};
$placeholderNormalizer = function (Options $options, $placeholder) {
if ($options['multiple']) {
// never use an empty value for this case
return;
} elseif (false === $placeholder) {
// an empty value should be added but the user decided otherwise
return;
} elseif ($options['expanded'] && '' === $placeholder) {
// never use an empty label for radio buttons
return 'None';
}
// empty value has been set explicitly
return $placeholder;
};
$compound = function (Options $options) {
return $options['expanded'];
};
$resolver->setDefaults(array(
'multiple' => false,
'expanded' => false,
'choice_list' => $choiceList,
'choices' => array(),
'preferred_choices' => array(),
'empty_data' => $emptyData,
'empty_value' => $emptyValue, // deprecated
'placeholder' => $placeholder,
'error_bubbling' => false,
'compound' => $compound,
// The view data is always a string, even if the "data" option
// is manually set to an object.
// See https://github.com/symfony/symfony/pull/5582
'data_class' => null,
));
$resolver->setNormalizers(array(
'empty_value' => $placeholderNormalizer,
'placeholder' => $placeholderNormalizer,
));
$resolver->setAllowedTypes(array(
'choice_list' => array('null', 'Symfony\Component\Form\Extension\Core\ChoiceList\ChoiceListInterface'),
));
$choiceListCache = & $this->choiceListCache;
$registry = $this->registry;
$propertyAccessor = $this->propertyAccessor;
$type = $this;
$loader = function (Options $options) use ($type) {
if (null !== $options['query_builder']) {
return $type->getLoader($options['em'], $options['query_builder'], $options['class']);
}
};
$choiceList = function (Options $options) use (&$choiceListCache, $propertyAccessor) {
// Support for closures
$propertyHash = is_object($options['property'])
? spl_object_hash($options['property'])
: $options['property'];
$choiceHashes = $options['choices'];
// Support for recursive arrays
if (is_array($choiceHashes)) {
// A second parameter ($key) is passed, so we cannot use
// spl_object_hash() directly (which strictly requires
// one parameter)
array_walk_recursive($choiceHashes, function (&$value) {
$value = spl_object_hash($value);
});
} elseif ($choiceHashes instanceof \Traversable) {
$hashes = array();
foreach ($choiceHashes as $value) {
$hashes[] = spl_object_hash($value);
}
$choiceHashes = $hashes;
}
$preferredChoiceHashes = $options['preferred_choices'];
if (is_array($preferredChoiceHashes)) {
array_walk_recursive($preferredChoiceHashes, function (&$value) {
$value = spl_object_hash($value);
});
}
// Support for custom loaders (with query builders)
$loaderHash = is_object($options['loader'])
? spl_object_hash($options['loader'])
: $options['loader'];
// Support for closures
$groupByHash = is_object($options['group_by'])
? spl_object_hash($options['group_by'])
: $options['group_by'];
$hash = hash('sha256', json_encode(array(
spl_object_hash($options['em']),
$options['class'],
$propertyHash,
$loaderHash,
$choiceHashes,
$preferredChoiceHashes,
$groupByHash,
)));
if (!isset($choiceListCache[$hash])) {
$choiceListCache[$hash] = new EntityChoiceList(
$options['em'],
$options['class'],
$options['property'],
$options['loader'],
$options['choices'],
$options['preferred_choices'],
$options['group_by'],
$propertyAccessor
);
}
return $choiceListCache[$hash];
};
$emNormalizer = function (Options $options, $em) use ($registry) {
/* #var ManagerRegistry $registry */
if (null !== $em) {
if ($em instanceof ObjectManager) {
return $em;
}
return $registry->getManager($em);
}
$em = $registry->getManagerForClass($options['class']);
if (null === $em) {
throw new RuntimeException(sprintf(
'Class "%s" seems not to be a managed Doctrine entity. '.
'Did you forget to map it?',
$options['class']
));
}
return $em;
};
$resolver->setDefaults(array(
'em' => null,
'property' => null,
'query_builder' => null,
'loader' => $loader,
'choices' => null,
'choice_list' => $choiceList,
'group_by' => null,
));
$resolver->setRequired(array('class'));
$resolver->setNormalizers(array(
'em' => $emNormalizer,
));
$resolver->setAllowedTypes(array(
'em' => array('null', 'string', 'Doctrine\Common\Persistence\ObjectManager'),
'loader' => array('null', 'Symfony\Bridge\Doctrine\Form\ChoiceList\EntityLoaderInterface'),
));
}
/**
* #return string
*/
public function getName()
{
return 'fmu_tag';
}
/**
* Return the default loader object.
*
* #param ObjectManager $manager
* #param mixed $queryBuilder
* #param string $class
*
* #return ORMQueryBuilderLoader
*/
public function getLoader(ObjectManager $manager, $queryBuilder, $class)
{
return new ORMQueryBuilderLoader(
$queryBuilder,
$manager,
$class
);
}
/**
* Adds the sub fields for an expanded choice field.
*
* #param FormBuilderInterface $builder The form builder.
* #param array $choiceViews The choice view objects.
* #param array $options The build options.
*/
private function addSubForms(FormBuilderInterface $builder, array $choiceViews, array $options)
{
foreach ($choiceViews as $i => $choiceView) {
if (is_array($choiceView)) {
// Flatten groups
$this->addSubForms($builder, $choiceView, $options);
} else {
$choiceOpts = array(
'value' => $choiceView->value,
'label' => $choiceView->label,
'translation_domain' => $options['translation_domain'],
'block_name' => 'entry',
);
if ($options['multiple']) {
$choiceType = 'checkbox';
// The user can check 0 or more checkboxes. If required
// is true, he is required to check all of them.
$choiceOpts['required'] = false;
} else {
$choiceType = 'radio';
}
$builder->add($i, $choiceType, $choiceOpts);
}
}
}
}
Register the type in your services :
tag.type:
class: %tag.type.class%
arguments: [#doctrine.orm.entity_manager, #doctrine ,#property_accessor]
tags:
- { name: form.type, alias: fmu_tag }
Create a new view for the type copying the choice one :
{#app/Resources/views/Form/fmu_tag.html.twig#}
{% block fmu_tag_widget %}
{% if expanded %}
{{- block('choice_widget_expanded') -}}
{% else %}
{{- block('choice_widget_collapsed') -}}
{% endif %}
{% endblock %}
Register the view in your twig config.yml :
# Twig Configuration
twig:
form:
resources:
- 'Form/fmu_tag.html.twig'
Create a new ChoiceToValueDataTransformer replace the default class used in the choiceType
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien#symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace AppBundle\Form\DataTransformer;
use AppBundle\Entity\Core\Tag;
use Symfony\Component\Form\Exception\TransformationFailedException;
use Symfony\Component\Form\DataTransformerInterface;
use Symfony\Component\Form\Extension\Core\ChoiceList\ChoiceListInterface;
/**
* #author Bernhard Schussek <bschussek#gmail.com>
*/
class ChoicesToValuesTransformer implements DataTransformerInterface
{
private $choiceList;
/**
* Constructor.
*
* #param ChoiceListInterface $choiceList
*/
public function __construct(ChoiceListInterface $choiceList)
{
$this->choiceList = $choiceList;
}
/**
* #param array $array
*
* #return array
*
* #throws TransformationFailedException If the given value is not an array.
*/
public function transform($array)
{
if (null === $array) {
return array();
}
if (!is_array($array)) {
throw new TransformationFailedException('Expected an array.');
}
return $this->choiceList->getValuesForChoices($array);
}
/**
* #param array $array
*
* #return array
*
* #throws TransformationFailedException If the given value is not an array
* or if no matching choice could be
* found for some given value.
*/
public function reverseTransform($array)
{
if (null === $array) {
return array();
}
if (!is_array($array)) {
throw new TransformationFailedException('Expected an array.');
}
$choices = $this->choiceList->getChoicesForValues($array);
if (count($choices) !== count($array)) {
$missingChoices = array_diff($array, $this->choiceList->getValues());
$choices = array_merge($choices, $this->transformMissingChoicesToEntities($missingChoices));
}
return $choices;
}
public function transformMissingChoicesToEntities(Array $missingChoices)
{
$newChoices = array_map(function($choice){
return new Tag($choice);
}, $missingChoices);
return $newChoices;
}
}
Loot at the last method of this file : transformMissingChoicesToEntities
This is where, when missing, I have created a new entity. So if you want to use all this, you need to adapt the new Tag($choice) ie. replace it by a new entity of your own.
So the form to which you add a collection now uses your new type:
$builder
->add('tags', 'fmu_tag', array(
'by_reference' => false,
'required' => false,
'class' => 'AppBundle\Entity\Core\Tag',
'multiple' => true,
'label'=>'Tags',
));
In order to create new choices, I am using the select2 control.
Add the file in your javascripts : http://select2.github.io
Add the following code in your view :
<script>
$(function() {
$('#appbundle_marketplace_product_ingredient_tags').select2({
closeOnSelect: false,
multiple: true,
placeholder: 'Tapez quelques lettres',
tags: true,
tokenSeparators: [',', ' ']
});
});
</script>
That's all, you're good to select existing entities or create new ones from a new entry generated by the select2.
You shouldn't really need a brand new form type for this behavior (although you can certainly create one if you want).
Check out Symfony dynamic form modification which has an example of modifying form fields depending on if an entity is 'new' or not. You can start with that as a base and modify to your needs.
If you already know what you want as you're creating the form from your Controller, then you could instead pass options flagging what you would like to display. For example, from your Controller:
$form = $this->createForm(
new MyType(),
$entity,
array('show_my_entity_collection' => false)
);
Then in your form type:
public function buildForm(FormBuilderInterface $builder, array $options)
{
if ($options['show_my_entity_collection'])
{
$builder->add('entity', 'entity', array(
'class' => 'MyBundle:MyEntity',
'required' => false,
'query_builder' => function(MyEntityRepository $repository) {
return $repository->findAll();
},
));
}
// rest of form builder here
}
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'MyBundle\Entity\MyEntity',
'show_my_entity_collection' => true,
));
}
If you need to create a new field type, with new template you can check here how to do this:
http://symfony.com/doc/current/cookbook/form/create_custom_field_type.html

Symfony2: EventSubscriber yields Date error

I've added an EventSubscriber to a form class so that a single template can be used for both add and edit of an entity. Before adding the subscriber, a form would not throw an error for either add or edit. After adding the subscriber, the following error occurs on editing when the conditions for adding the dateAdded field are met:
Expected argument of type "\DateTime", "array" given
Otherwise, the EventSubscriber appears to perform as expected.
Subscriber
class AddV2FieldsSubscriber implements EventSubscriberInterface {
private $factory;
public function __construct(FormFactoryInterface $factory) {
$this->factory = $factory;
}
public static function getSubscribedEvents() {
return array(FormEvents::PRE_SET_DATA => 'preSetData');
}
public function preSetData(DataEvent $event) {
$data = $event->getData();
$form = $event->getForm();
if (null === $data) {
return;
}
// check if the client object is v1
if (!$data->getId() || $data->getDateAdded()) {
$date = new \DateTime();
$form->add($this->factory->createNamed('dateAdded', 'date', $date, array(
'widget' => 'single_text',
'format' => 'MM/dd/yyyy',
'pattern' => '{{ year }}-{{ month }}-{{ day }}',
'years' => range(Date('Y'), Date('Y') - 5),
'required' => false,
'data' => date_create(),))
);
$form->add($this->factory->createNamed('dob', 'dob_age')
);
$form->add($this->factory->createNamed('sex', 'choice', array(
'choices' => array('Male' => 'Male', 'Female' => 'Female'),
'empty_value' => "Select a gender",
'required' => false))
);
}
}
}
The dateAdded field in its Entity:
/**
* #var \DateTime $dateAdded
*
* #ORM\Column(name="date_added", type="date", nullable=true)
*/
private $dateAdded;
Template snippet
{% if form.dateAdded is defined %}
{% include 'ManaClientBundle:Client:v2.html.twig' %}
{% endif %}
Again, the answer is to pay attention to the third parameter of the createNamed() function. In this case, I had to modify
$form->add($this->factory->createNamed('sex', 'choice', array(...
to read
$form->add($this->factory->createNamed('sex', 'choice', null, array(...

Symfony2: How to add form constraint for a field in bind PRE_SET_DATA depending on the data

I have a form in Symfony 2 with basically two fields:
public function buildForm(FormBuilderInterface $builder, array $options) {
$builder->add('contactType', 'select', array( 'choices' => $contactTypes ))
->add('value', 'text');
}
Then I added an EventSubscriber that listens to the FormEvents::PRE_SET_DATA event. What I actually want to do, is to change the way of validation depending on the value of contactType (numeric values from 1 to 4, which stand for email, mobile, fixed line and fax).
I followed this tutorial http://symfony.com/doc/current/cookbook/form/dynamic_form_generation.html
but I can't figure out, how to add a constraint to the value field.
Can anyone help me? Thanks a lot in advance.
Instead of adding validation constraints dynamically in event subscriber (not sure if this is even possible), you can set groups to field's validation constraints and determine validation groups based on submitted data.
A function to create the form from the controller :
<?php
// ...
class DefaultController extends Controller
{
/**
*
* #param \Clicproxy\DeltadocCabBundle\Entity\Mark $mark
* #param \Clicproxy\DeltadocCabBundle\Entity\Tag $tag
* #return Form
*/
private function createTagForm(Mark $mark, Tag $tag)
{
$form = $this->createForm(new TagType(), $tag, array(
'action' => $this->generateUrl('tag_new', array('slug' => $this->slugify($mark->getName()))),
'method' => 'POST',
));
foreach ($mark->getFields() as $field)
{
$form->add($this->slugify($field->getName()), $field->getFormType(), $field->getOptions());
}
$form->add('submit', 'submit', array('label' => 'crud.default.save'));
return $form;
}
// ...
The code in the entity (type, constraints, ...) :
<?php
// ...
/**
* Field
*
* #ORM\Table()
* #ORM\Entity
* #UniqueEntity({"name", "mark"})
*/
class Field
{
// ...
/**
*
* #return array
*/
public function getOptions()
{
$options = array('label' => $this->getName(), 'mapped' => FALSE);
$options['required'] = $this->getType() != 'checkbox';
if ('date' == $this->getType())
{
$options['attr']['class'] = 'datepicker'; // 'input-group date datepicker';
$options['attr']['data-date-format'] = 'dd/mm/yyyy';
$options['attr']['data-date-autoclose'] = true;
}
if ('choice' == $this->getType())
{
$choices = array();
foreach ($this->getChoices() as $choice)
{
$choices[$choice->getValue()] = $choice->getName();
}
asort($choices);
$options['choices'] = $choices;
}
$options['constraints'] = $this->getValidationConstraint();
return $options;
}
public function getValidationConstraint ()
{
$validation_constraint = array();
if ('number' == $this->getType()) {
if (0 < $this->getMaximum()) {
$validation_constraint[] = new LessThanOrEqual (array(
'message' => 'entity.field.number.lessthanorequal', // {{ compared_value }}
'value' => $this->getMaximum()
));
}
if (0 < $this->getMinimum()) {
$validation_constraint[] = new GreaterThanOrEqual(array(
'message' => 'entity.field.number.greaterthanorequal', // {{ compared_value }}
'value' => $this->getMinimum()
));
}
} elseif ('text' == $this->getType ()) {
if (0 < $this->getMaximum()) {
$validation_constraint[] = new Length(array(
'min' => $this->getMinimum() > 0 ? $this->getMinimum() : 0,
'max' => $this->getMaximum() > 0 ? $this->getMaximum() : 0,
'minMessage' => 'entity.field.text.minMessage', // {{ limit }}
'maxMessage' => 'entity.field.text.maxMessage',
'exactMessage' => 'entity.field.text.exactMessage',
));
}
} elseif ('date' == $this->getType()) {
}
return $validation_constraint;
}
// ...
All this code work actually.
With this you have a solution to generate a form on the fly with constraints.