Skip to content

[Form] add choice_filter option to ChoiceType #18334

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 7 additions & 4 deletions src/Symfony/Bridge/Doctrine/Form/Type/DoctrineType.php
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
use Symfony\Component\Form\ChoiceList\Factory\CachingFactoryDecorator;
use Symfony\Component\Form\ChoiceList\Factory\ChoiceListFactoryInterface;
use Symfony\Component\Form\ChoiceList\Factory\DefaultChoiceListFactory;
use Symfony\Component\Form\ChoiceList\Factory\FilteringFactoryDecorator;
use Symfony\Component\Form\ChoiceList\Factory\PropertyAccessDecorator;
use Symfony\Component\Form\Exception\RuntimeException;
use Symfony\Component\Form\FormBuilderInterface;
Expand Down Expand Up @@ -111,10 +112,12 @@ public function getQueryBuilderPartsForCachingHash($queryBuilder)
public function __construct(ManagerRegistry $registry, PropertyAccessorInterface $propertyAccessor = null, ChoiceListFactoryInterface $choiceListFactory = null)
{
$this->registry = $registry;
$this->choiceListFactory = $choiceListFactory ?: new CachingFactoryDecorator(
new PropertyAccessDecorator(
new DefaultChoiceListFactory(),
$propertyAccessor
$this->choiceListFactory = $choiceListFactory ?: new FilteringFactoryDecorator(
new CachingFactoryDecorator(
new PropertyAccessDecorator(
new DefaultChoiceListFactory(),
$propertyAccessor
)
)
);
}
Expand Down
6 changes: 5 additions & 1 deletion src/Symfony/Bundle/FrameworkBundle/Resources/config/form.xml
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,11 @@
<argument type="service" id="form.choice_list_factory.property_access"/>
</service>

<service id="form.choice_list_factory" alias="form.choice_list_factory.cached" public="false"/>
<service id="form.choice_list_factory.filtered" class="Symfony\Component\Form\ChoiceList\Factory\FilteringFactoryDecorator" public="false">
<argument type="service" id="form.choice_list_factory.cached"/>
</service>

<service id="form.choice_list_factory" alias="form.choice_list_factory.filtered" public="false"/>

<service id="form.type.form" class="Symfony\Component\Form\Extension\Core\Type\FormType">
<argument type="service" id="form.property_accessor" />
Expand Down
2 changes: 1 addition & 1 deletion src/Symfony/Bundle/FrameworkBundle/composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@
"symfony/dom-crawler": "~2.8|~3.0",
"symfony/polyfill-intl-icu": "~1.0",
"symfony/security": "~2.8|~3.0",
"symfony/form": "~2.8|~3.0",
"symfony/form": "~2.8|~3.1",
"symfony/expression-language": "~2.8|~3.0",
"symfony/process": "~2.8|~3.0",
"symfony/serializer": "~2.8|^3.0",
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
<?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 Symfony\Component\Form\ChoiceList\Factory;

use Symfony\Component\Form\ChoiceList\ChoiceListInterface;
use Symfony\Component\Form\ChoiceList\Loader\ChoiceLoaderInterface;

/**
* Creates filtered {@link ChoiceListInterface} instances.
*
* @author Jules Pietri <jules@heahprod.com>
*/
interface FilteredChoiceListFactoryInterface extends ChoiceListFactoryInterface
{
/**
* Creates a filtered choice list for the given choices.
*
* The choices should be passed in the values of the choices array.
*
* The filter callable gets passed each choice and its resolved value
* and should return true to keep the choice and false or null otherwise.
*
* Optionally, a callable can be passed for generating the choice values.
* The callable receives the choice as only argument.
*
* @param array|\Traversable $choices The choices
* @param null|callable $value The callable generating the choice
* values
* @param callable $filter The filter
*
* @return ChoiceListInterface The filtered choice list
*/
public function createFilteredListFromChoices($choices, $value = null, callable $filter);

/**
* Creates a filtered choice list that is loaded with the given loader.
*
* The filter callable gets passed each choice and its resolved value
* and should return true to keep the choice and false or null otherwise.
*
* Optionally, a callable can be passed for generating the choice values.
* The callable receives the choice as only argument.
*
* @param ChoiceLoaderInterface $loader The choice loader
* @param null|callable $value The callable generating the choice
* values
* @param callable $filter The filter
*
* @return ChoiceListInterface The filtered choice list
*/
public function createFilteredListFromLoader(ChoiceLoaderInterface $loader, $value = null, callable $filter);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,138 @@
<?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 Symfony\Component\Form\ChoiceList\Factory;

use Symfony\Component\Form\ChoiceList\ChoiceListInterface;
use Symfony\Component\Form\ChoiceList\Loader\ChoiceLoaderInterface;

/**
* Filter the choices before passing them to the decorated factory.
*
* @author Jules Pietri <jules@heahprod.com>
*/
class FilteringFactoryDecorator implements FilteredChoiceListFactoryInterface
{
/**
* @var ChoiceListFactoryInterface
*/
private $decoratedFactory;

/**
* @var array[]
*/
private $choicesByValues = array();

/**
* Decorates the given factory.
*
* @param ChoiceListFactoryInterface $decoratedFactory The decorated factory
*/
public function __construct(ChoiceListFactoryInterface $decoratedFactory)
{
$this->decoratedFactory = $decoratedFactory;
}

/**
* Returns the decorated factory.
*
* @return ChoiceListFactoryInterface The decorated factory
*/
public function getDecoratedFactory()
{
return $this->decoratedFactory;
}

/**
* {@inheritdoc}
*/
public function createListFromChoices($choices, $value = null)
{
return $this->decoratedFactory->createListFromChoices($choices, $value);
}

/**
* {@inheritdoc}
*/
public function createListFromLoader(ChoiceLoaderInterface $loader, $value = null)
{
return $this->decoratedFactory->createListFromLoader($loader, $value);
}

/**
* {@inheritdoc}
*/
public function createFilteredListFromChoices($choices, $value = null, callable $filter)
{
// We need to apply the filter on a resolved choices array in case
// the same choices are filtered many times. The original choice list
// should be cached by the decorated factory
$choiceList = $this->decoratedFactory->createListFromChoices($choices, $value);

// The filtered choice list should be cached by the decorated factory
// if the same filter is applied on the same choices by values

return $this->decoratedFactory->createListFromChoices(self::filterChoices($choiceList->getChoices(), $filter));
}

/**
* {@inheritdoc}
*/
public function createFilteredListFromLoader(ChoiceLoaderInterface $loader, $value = null, callable $filter)
{
// Don't hash the filter since the original choices may have been loaded already
// with a different filter if any.
$hash = CachingFactoryDecorator::generateHash(array($loader, $value));
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm just not sure about the over caching here, but it seems that considering this decorator might not decorate the CachingFactoryDecorator, keeping the resolved choices to filter should be the right thing to do.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This caching is useless, as the decorated choice list already has caching

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.


if (!isset($this->choicesByValues[$hash])) {
// We need to load the choice list before filtering the choices
$choiceList = $this->decoratedFactory->createListFromLoader($loader, $value);

// Cache the choices by values, in case they are filtered many times,
// the original choice list should already have been cached by the
// previous call.
$this->choicesByValues[$hash] = $choiceList->getChoices();
}

// The filtered choice list should be cached by the decorated factory
// if the same filter is applied on the same choices by values

return $this->decoratedFactory->createListFromChoices(self::filterChoices($this->choicesByValues[$hash], $filter));
}

/**
* {@inheritdoc}
*/
public function createView(ChoiceListInterface $list, $preferredChoices = null, $label = null, $index = null, $groupBy = null, $attr = null)
{
$this->decoratedFactory->createView($list, $preferredChoices, $label, $index, $groupBy, $attr);
}

/**
* Filters the choices.
*
* @param array $choices The choices by values to filter
* @param callable $filter The filter
*
* @return array The filtered choices
*/
static private function filterChoices($choices, callable $filter)
{
foreach ($choices as $value => $choice) {
if (call_user_func($filter, $choice, $value)) {
continue;
}
unset($choices[$value]);
}

return $choices;
}
}
33 changes: 26 additions & 7 deletions src/Symfony/Component/Form/Extension/Core/Type/ChoiceType.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\ChoiceList\Factory\CachingFactoryDecorator;
use Symfony\Component\Form\ChoiceList\Factory\FilteredChoiceListFactoryInterface;
use Symfony\Component\Form\ChoiceList\Factory\FilteringFactoryDecorator;
use Symfony\Component\Form\ChoiceList\Factory\PropertyAccessDecorator;
use Symfony\Component\Form\ChoiceList\View\ChoiceGroupView;
use Symfony\Component\Form\ChoiceList\ChoiceListInterface;
Expand Down Expand Up @@ -45,9 +47,11 @@ class ChoiceType extends AbstractType

public function __construct(ChoiceListFactoryInterface $choiceListFactory = null)
{
$this->choiceListFactory = $choiceListFactory ?: new CachingFactoryDecorator(
new PropertyAccessDecorator(
new DefaultChoiceListFactory()
$this->choiceListFactory = $choiceListFactory ?: new FilteringFactoryDecorator(
new CachingFactoryDecorator(
new PropertyAccessDecorator(
new DefaultChoiceListFactory()
)
)
);
}
Expand Down Expand Up @@ -315,6 +319,7 @@ public function configureOptions(OptionsResolver $resolver)
'expanded' => false,
'choices' => array(),
'choices_as_values' => null, // deprecated since 3.1
'choice_filter' => null,
'choice_loader' => null,
'choice_label' => null,
'choice_name' => null,
Expand All @@ -339,6 +344,7 @@ public function configureOptions(OptionsResolver $resolver)

$resolver->setAllowedTypes('choices', array('null', 'array', '\Traversable'));
$resolver->setAllowedTypes('choice_translation_domain', array('null', 'bool', 'string'));
$resolver->setAllowedTypes('choice_filter', array('null', 'callable'));
$resolver->setAllowedTypes('choice_loader', array('null', 'Symfony\Component\Form\ChoiceList\Loader\ChoiceLoaderInterface'));
$resolver->setAllowedTypes('choice_label', array('null', 'bool', 'callable', 'string', 'Symfony\Component\PropertyAccess\PropertyPath'));
$resolver->setAllowedTypes('choice_name', array('null', 'callable', 'string', 'Symfony\Component\PropertyAccess\PropertyPath'));
Expand Down Expand Up @@ -414,15 +420,28 @@ private function addSubForm(FormBuilderInterface $builder, $name, ChoiceView $ch
private function createChoiceList(array $options)
{
if (null !== $options['choice_loader']) {
return $this->choiceListFactory->createListFromLoader(
$options['choice_loader'],
$options['choice_value']
);
if (is_callable($options['choice_filter']) && $this->choiceListFactory instanceof FilteredChoiceListFactoryInterface) {
return $this->choiceListFactory->createFilteredListFromLoader(
$options['choice_loader'],
$options['choice_value'],
$options['choice_filter']
);
}

return $this->choiceListFactory->createListFromLoader($options['choice_loader'], $options['choice_value']);
}

// Harden against NULL values (like in EntityType and ModelType)
$choices = null !== $options['choices'] ? $options['choices'] : array();

if (!empty($choices) && is_callable($options['choice_filter']) && $this->choiceListFactory instanceof FilteredChoiceListFactoryInterface) {
return $this->choiceListFactory->createFilteredListFromChoices(
$choices,
$options['choice_value'],
$options['choice_filter']
);
}

return $this->choiceListFactory->createListFromChoices($choices, $options['choice_value']);
}

Expand Down
Loading