João Alves
João Alves

Reputation: 1941

Textarea field with data Transformer

I have a Form with a textarea field(where user adds domains names, each per line) and a Data Transformer that transforms from a string to an array:

$builder->add(
            $builder->create('domains', 'textarea', [
                'trim' => false,
                'constraints' => [
                    new Assert\NotBlank(),
                    new Assert\All([
                        'constraints' => [
                            new Assert\NotBlank(),
                            new Domain(),
                            new RegisterDomain(),
                        ]
                    ])
                ]
            ])->addModelTransformer(new ArrayToStringTransformer())
        );

ArrayToStringTransformer

public function transform($values)
    {
        if (empty($values)) {
            return '';
        }    
        return implode($this->delimiter, $values);        
    }


public function reverseTransform($string)
    {        
        if (!$string) {
            return [];
        }

        return array_filter(array_map('trim', explode($this->delimiter, $string))); 
    } 

Each domain should be on a new line. However, when i get the string value on the reverseTransform the value dont bring the new lines. I already setted the option trim as false on my field.

Any idea why this is happen?

My Delimiter is: '\n' but i already tried with '\r\n'.

Well it seems that the solution is use double quotes and not single. So, if i use "\r\n" everything works as expected.

Thanks.

Upvotes: 1

Views: 636

Answers (1)

ecc
ecc

Reputation: 1510

Newlines in input data can take two forms: \r or \n. Split your data using both of them.

return implode("\r\n", $values);

Upvotes: 1

Related Questions