I created a custom form type and a transformer that goes with it.
Data in my database is saved in 1 Text field. “<EN>English text</EN><FR>Frenc text</FR>“
So I created a formtype that added separate text for each input and the transformer is suposed to put the right value in between the tags inside the input.
the problem is I echoed the value that should be passed in the transform function but it’s empty and I can’t figure out why.
here is my multilang type
class MultiLangType extends AbstractType
{
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
'type' => 'text',
'compound' => 'true'
));
}
public function buildForm(FormBuilderInterface $builder, array $options)
{
$langs = array('EN', 'FR', 'DE');
$transformer = new StringToMultiTransformer($langs);
$builder->prependClientTransformer($transformer);
//$builder->addModelTransformer(new StringToMultiTransformer($langs));
foreach($langs as $l)
{
$builder->add($l, 'text', $options);
}
}
public function getParent()
{
return 'field';
}
public function getName()
{
return 'multilang';
}
}
and now my transformer
class StringToMultiTransformer implements DataTransformerInterface
{
private $langs;
public function __construct(array $langs)
{
$this->langs = $langs;
}
public function transform($value)
{
// var_dump($value); exit;
$result = array();
foreach ($this->langs as $l) {
$ret = preg_match("/<$l>(.*?)<\/$l>/", $value);
$result[$l] = $ret[1];
}
return $result;
}
public function reverseTransform($array)
{
if (!is_array($array)) {
throw new UnexpectedTypeException($array, 'array');
}
$result = "";
$emptyKeys = array();
foreach ($this->langs as $l) {
$val = $array[$l];
$result .= "<$l>$val</$l>";
}
return $result;
}
Thanks in advance for any suggestion
Your transformer is called multiple times. So, I think you should use early return by checking if the passed $value is null.
Add at the top of your
transform()method logic,You should also do the same within your
reverseTransform()method to avoid taking into account empty and null values.