Created
March 22, 2012 23:53
-
-
Save jmikola/2165584 to your computer and use it in GitHub Desktop.
Temp work-around for BC break in Symfony2 Form component's default option processing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace Acme\MainBundle\Form\Type; | |
use Acme\MainBundle\Form\Util; | |
use Symfony\Component\Form\AbstractType; | |
use Symfony\Component\Form\FormBuilder; | |
class ExampleFormType extends AbstractType | |
{ | |
public function buildForm(FormBuilder $builder, array $options) | |
{ | |
$builder | |
->add('foo') | |
->add('bar') | |
; | |
} | |
public function getName() | |
{ | |
return 'example'; | |
} | |
public function getDefaultOptions(array $options) | |
{ | |
return Util::addEmptyDataOption(array( | |
'data_class' => 'Acme\MainBundle\Model\Example', | |
), $options); | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace Acme\MainBundle\Form; | |
use Symfony\Component\Form\FormInterface; | |
class Util | |
{ | |
/** | |
* Adds a default value for the "empty_data" option if none exists. | |
* | |
* This is similar to what was done by FieldType before a BC break in the | |
* Form component. | |
* | |
* @see https://github.com/symfony/symfony/issues/3354 | |
* @param array $defaultOptions | |
* @param array $options | |
* @return array | |
*/ | |
public static function addEmptyDataOption(array $defaultOptions, array $options) | |
{ | |
if (isset($defaultOptions['empty_data'])) { | |
return $defaultOptions; | |
} | |
$class = isset($options['data_class']) ? $options['data_class'] : isset($defaultOptions['data_class']) ? $defaultOptions['data_class']: null; | |
// If no data class is set explicitly and an object is passed as data, | |
// use the class of that object as data class | |
if (!$class) { | |
$data = isset($options['data']) ? $options['data'] : isset($defaultOptions['data']) ? $defaultOptions['data']: null; | |
if (is_object($data)) { | |
$defaultOptions['data_class'] = $class = get_class($data); | |
} | |
} | |
if ($class) { | |
$defaultOptions['empty_data'] = function (FormInterface $form) use ($class) { | |
if ($form->isEmpty() && !$form->isRequired()) { | |
return null; | |
} | |
return new $class(); | |
}; | |
} | |
return $defaultOptions; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment