ChainAccessor example

use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\PropertyAccess\PropertyAccess;
use Symfony\Component\PropertyAccess\PropertyAccessorInterface;
use Symfony\Contracts\Translation\TranslatableInterface;

class FormType extends BaseType
{
    private DataMapper $dataMapper;

    public function __construct(PropertyAccessorInterface $propertyAccessor = null)
    {
        $this->dataMapper = new DataMapper(new ChainAccessor([
            new CallbackAccessor(),
            new PropertyPathAccessor($propertyAccessor ?? PropertyAccess::createPropertyAccessor()),
        ]));
    }

    /** * @return void */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        parent::buildForm($builder$options);

        
/** * Maps arrays/objects to/from forms using data accessors. * * @author Bernhard Schussek <bschussek@gmail.com> */
class DataMapper implements DataMapperInterface
{
    private DataAccessorInterface $dataAccessor;

    public function __construct(DataAccessorInterface $dataAccessor = null)
    {
        $this->dataAccessor = $dataAccessor ?? new ChainAccessor([
            new CallbackAccessor(),
            new PropertyPathAccessor(),
        ]);
    }

    public function mapDataToForms(mixed $data, \Traversable $forms): void
    {
        $empty = null === $data || [] === $data;

        if (!$empty && !\is_array($data) && !\is_object($data)) {
            throw new UnexpectedTypeException($data, 'object, array or empty');
        }
Home | Imprint | This part of the site doesn't use cookies.