Thanks to visit codestin.com
Credit goes to github.com

Skip to content

[Form] Add option widget to ChoiceType #15053

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
wants to merge 1 commit into from
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
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,11 @@
{%- endblock textarea_widget -%}

{%- block choice_widget -%}
{% if expanded %}
{% if 'hidden' == widget %}
{{- block('hidden_widget') -}}
{% elseif 'text' == widget %}
{{- block('form_widget_simple') -}}
{% elseif expanded %}
{{- block('choice_widget_expanded') -}}
{% else %}
{{- block('choice_widget_collapsed') -}}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
<?php

/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Symfony\Component\Form\Extension\Core\DataTransformer;

use Symfony\Component\Form\DataTransformerInterface;
use Symfony\Component\Form\Exception\TransformationFailedException;

/**
* Converts an array of values to a string with multiple values separated by a delimiter.
*
* @author Bilal Amarni <[email protected]>
*/
class ValuesToStringTransformer implements DataTransformerInterface
{
/**
* @var string
*/
private $delimiter;

/**
* @var bool
*/
private $trim;

/**
* @param string $delimiter
* @param bool $trim
*/
public function __construct($delimiter, $trim)
{
$this->delimiter = $delimiter;
$this->trim = $trim;
}

/**
* @param array $array
*
* @return string
*
* @throws UnexpectedTypeException if the given value is not an array
*/
public function transform($array)
{
if (null === $array) {
return '';
}

if (!is_array($array)) {
throw new TransformationFailedException('Expected an array');
}

return implode($this->delimiter, $array);
}

/**
* @param string $string
*
* @return array
*
* @throws UnexpectedTypeException if the given value is not a string
*/
public function reverseTransform($string)
{
if (empty($string)) {
return array();
}

if (!is_string($string)) {
throw new TransformationFailedException('Expected a string');
}

$values = explode($this->delimiter, $string);

if ($this->trim) {
$values = array_map('trim', $values);
}

return $values;
}
}
41 changes: 36 additions & 5 deletions src/Symfony/Component/Form/Extension/Core/Type/ChoiceType.php
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@
use Symfony\Component\Form\Extension\Core\EventListener\MergeCollectionListener;
use Symfony\Component\Form\Extension\Core\DataTransformer\ChoiceToValueTransformer;
use Symfony\Component\Form\Extension\Core\DataTransformer\ChoicesToValuesTransformer;
use Symfony\Component\Form\Extension\Core\DataTransformer\ValuesToStringTransformer;
use Symfony\Component\OptionsResolver\Options;
use Symfony\Component\OptionsResolver\OptionsResolver;

Expand All @@ -54,7 +55,7 @@ public function __construct(ChoiceListFactoryInterface $choiceListFactory = null
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
if ($options['expanded']) {
if ($options['expanded'] && !in_array($options['widget'], array('text', 'hidden'))) {
$builder->setDataMapper($options['multiple']
? new CheckboxListMapper($options['choice_list'])
: new RadioListMapper($options['choice_list']));
Expand Down Expand Up @@ -140,10 +141,15 @@ public function buildForm(FormBuilderInterface $builder, array $options)
});
}
} elseif ($options['multiple']) {
// <select> tag with "multiple" option
// "select", "text" or "hidden" widget with "multiple" option
$builder->addViewTransformer(new ChoicesToValuesTransformer($options['choice_list']));

// for "text" / "hidden" widget, view data uses a delimiter
if (in_array($options['widget'], array('text', 'hidden'))) {
$builder->addViewTransformer(new ValuesToStringTransformer($options['delimiter'], $options['trim']));
}
} else {
// <select> tag without "multiple" option
// "select", "text" or "hidden" tag without "multiple" option
$builder->addViewTransformer(new ChoiceToValueTransformer($options['choice_list']));
}

Expand All @@ -170,15 +176,20 @@ public function buildView(FormView $view, FormInterface $form, array $options)
: $this->createChoiceListView($options['choice_list'], $options);

$view->vars = array_replace($view->vars, array(
'widget' => $options['widget'],
'multiple' => $options['multiple'],
'expanded' => $options['expanded'],
'expanded' => $options['expanded'], // BC
'preferred_choices' => $choiceListView->preferredChoices,
'choices' => $choiceListView->choices,
'separator' => '-------------------',
'placeholder' => null,
'choice_translation_domain' => $choiceTranslationDomain,
));

if (in_array($options['widget'], array('text', 'hidden'))) {
return;
}

// The decision, whether a choice is selected, is potentially done
// thousand of times during the rendering of a template. Provide a
// closure here that is optimized for the value of the form, to
Expand Down Expand Up @@ -218,6 +229,10 @@ public function buildView(FormView $view, FormInterface $form, array $options)
*/
public function finishView(FormView $view, FormInterface $form, array $options)
{
if (in_array($options['widget'], array('text', 'hidden'))) {
return;
}

if ($options['expanded']) {
// Radio buttons should have the same name as the parent
$childName = $view->vars['full_name'];
Expand Down Expand Up @@ -292,6 +307,18 @@ public function configureOptions(OptionsResolver $resolver)
return;
};

$multipleNormalizer = function (Options $options, $multiple) {
if (in_array($options['widget'], array('radio', 'checkbox'))) {
return 'checkbox' == $options['widget'];
}

return $multiple;
};

$expandedNomalizer = function (Options $options, $expanded) {
return in_array($options['widget'], array('radio', 'checkbox')) ?: $expanded;
};

$choiceListNormalizer = function (Options $options, $choiceList) use ($choiceListFactory) {
if ($choiceList) {
@trigger_error('The "choice_list" option is deprecated since version 2.7 and will be removed in 3.0. Use "choice_loader" instead.', E_USER_DEPRECATED);
Expand Down Expand Up @@ -364,8 +391,10 @@ public function configureOptions(OptionsResolver $resolver)
};

$resolver->setDefaults(array(
'widget' => null,
'multiple' => false,
'expanded' => false,
'delimiter' => ',',
'expanded' => false, // deprecated
Copy link
Member

Choose a reason for hiding this comment

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

missing deprecation trigger

'choice_list' => null, // deprecated
'choices' => array(),
'choices_as_values' => false,
Expand All @@ -388,6 +417,8 @@ public function configureOptions(OptionsResolver $resolver)
'choice_translation_domain' => true,
));

$resolver->setNormalizer('expanded', $expandedNomalizer);
$resolver->setNormalizer('multiple', $multipleNormalizer);
$resolver->setNormalizer('choices', $choicesNormalizer);
$resolver->setNormalizer('choice_list', $choiceListNormalizer);
$resolver->setNormalizer('placeholder', $placeholderNormalizer);
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
<?php

/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Symfony\Component\Form\Tests\Extension\Core\DataTransformer;

use Symfony\Component\Form\Extension\Core\DataTransformer\ValuesToStringTransformer;

class ValuesToStringTransformerTest extends \PHPUnit_Framework_TestCase
{
private $transformer;

protected function setUp()
{
$this->transformer = new ValuesToStringTransformer(',', true);
Copy link
Member

Choose a reason for hiding this comment

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

We should have tests for other delimiters too.

}

protected function tearDown()
{
$this->transformer = null;
}

public function testTransform()
{
$output = 'a,b,c';

$this->assertSame($output, $this->transformer->transform(array('a', 'b', 'c')));
}

public function testTransformNull()
{
$this->assertSame('', $this->transformer->transform(null));
}

/**
* @expectedException \Symfony\Component\Form\Exception\TransformationFailedException
*/
public function testReverseTransformRequiresAnArray()
{
$this->transformer->transform('a, b, c');
}

public function testReverseTransform()
{
$input = 'a, b ,c ';

$this->assertSame(array('a', 'b', 'c'), $this->transformer->reverseTransform($input));
}

public function testReverseTransformEmpty()
{
$input = '';

$this->assertSame(array(), $this->transformer->reverseTransform($input));
}

/**
* @expectedException \Symfony\Component\Form\Exception\TransformationFailedException
*/
public function testReverseTransformRequiresAString()
{
$this->transformer->reverseTransform(array('a', 'b', 'c'));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -1887,4 +1887,68 @@ public function testInitializeWithDefaultObjectChoice()
// Trigger data initialization
$form->getViewData();
}

/**
* @dataProvider simpleWidgetsProvider
*/
public function testSubmitChoicesWithSimpleWidgets($widget)
{
$form = $this->factory->create('Symfony\Component\Form\Extension\Core\Type\ChoiceType', null, array(
'widget' => $widget,
'multiple' => false,
'choices' => $this->choices,
'choices_as_values' => true,
));

$form->submit('b');

$this->assertEquals('b', $form->getData());
$this->assertEquals('b', $form->getViewData());
}

/**
* @dataProvider simpleWidgetsProvider
*/
public function testSubmitMultipleChoicesWithSimpleWidgets($widget)
{
$form = $this->factory->create('Symfony\Component\Form\Extension\Core\Type\ChoiceType', null, array(
'widget' => $widget,
'multiple' => true,
'choices' => $this->choices,
'choices_as_values' => true,
));

$form->submit('a,b');

$this->assertEquals(array('a', 'b'), $form->getData());
$this->assertEquals('a,b', $form->getViewData());
}

/**
* @dataProvider simpleWidgetsProvider
*/
public function testSubmitMultipleChoicesDelimiterAndTrimWithSimpleWidgets($widget)
{
$form = $this->factory->create('Symfony\Component\Form\Extension\Core\Type\ChoiceType', null, array(
'widget' => $widget,
'multiple' => true,
'delimiter' => '|',
'trim' => true,
'choices' => $this->choices,
'choices_as_values' => true,
));

$form->submit('a| b ');

$this->assertEquals(array('a', 'b'), $form->getData());
$this->assertEquals('a|b', $form->getViewData());
}

public function simpleWidgetsProvider()
{
return array(
array('text'),
array('hidden'),
);
}
}