Not exprexted behaviour on symfony datatransformer

Viewed 13

I created a datatransformer to store dates on unixtime on the database but show it as datetime on the form

this is the transformer

class IntegerToTimestampTransformer implements DataTransformerInterface
{

    public function transform($timestamp)
    {
        /**
         * This if sentenceis because when eidt $timestamp is a timestamp(unix)
         * but when create is a  DateTime ¿¿???
         */
        if($timestamp instanceof  \DateTime){
            return  $timestamp;
        }
        return (new \DateTime())->setTimestamp($timestamp);
    }

    public function reverseTransform($datetime)
    {
        if ($datetime === null) {
            return $datetime;
        }
        return $datetime->getTimestamp();
    }
}

this is the entity

/**
 * Popup
 *
 * @ORM\Table(name="popup")
 * @ORM\Entity(repositoryClass="AppBundle\Repository\PopUpRepository")
 */
class Popup
{

    /**
     * @var int
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @var string
     *
     * @Gedmo\Translatable()
     * @ORM\Column(name="title", type="string", length=255)
     */
    private $title;

    /**
     * @var string
     *
     * @Gedmo\Translatable()
     * @ORM\Column(name="description", type="text")
     */
    private $description;

    /**
     * @var int
     *
     * @ORM\Column(name="activation_date", type="integer", nullable=true)
     */
    private $activationDate;

    /**
     * @var int
     *
     * @ORM\Column(name="deactivation_date", type="integer", nullable=true)
     */
    private $deactivationDate;

    /**
     * @var boolean
     *
     * @ORM\Column(name="active", type="boolean")
     */
    private $active;

    /**
     * @var Collection
     *
     * @ORM\ManyToMany(targetEntity="AppBundle\Entity\Role")
     * @ORM\JoinTable(name="popup_role", joinColumns={@ORM\JoinColumn(name="popup_id", referencedColumnName="id")},
     *     inverseJoinColumns={@ORM\JoinColumn(name="role_id", referencedColumnName="id")})
     */
    private $roles;

    public function  __construct()
    {
        $this->roles = new ArrayCollection();
    }

    /**
     * @return int
     */
    public function getId(): int
    {
        return $this->id;
    }

    /**
     * @param int $id
     */
    public function setId(int $id): void
    {
        $this->id = $id;
    }

    /**
     * @return string
     */
    public function getTitle():? string
    {
        return $this->title;
    }

    /**
     * @param string $title
     */
    public function setTitle(string $title): void
    {
        $this->title = $title;
    }

    /**
     * @return string
     */
    public function getDescription(): ?string
    {
        return $this->description;
    }

    /**
     * @param string $description
     */
    public function setDescription(string $description): void
    {
        $this->description = $description;
    }

    /**
     * @return int
     */
    public function getActivationDate(): ?int
    {
        return $this->activationDate;
    }

    /**
     * @param int $activationDate
     */
    public function setActivationDate(int $activationDate): void
    {
        $this->activationDate = $activationDate;
    }

    /**
     * @return int
     */
    public function getDeactivationDate(): ?int
    {
        return $this->deactivationDate;
    }

    /**
     * @param int $deactivationDate
     */
    public function setDeactivationDate(int $deactivationDate): void
    {
        $this->deactivationDate = $deactivationDate;
    }


    /**
     * @return bool
     */
    public function isActive(): ?bool
    {
        return $this->active;
    }

    /**
     * @param bool $active
     */
    public function setActive(bool $active): void
    {
        $this->active = $active;
    }

    /**
     * Add role
     *
     * @param Role $role
     *
     * @return Role
     */
    public function addRole(Role $role)
    {
        $this->roles[] = $role;

        return $this;
    }

    /**
     * Remove role
     *
     * @param Role $role
     */
    public function removeRole(Role $role)
    {
        $this->roles->removeElement($role);
    }

    /**
     * Get role
     *
     * @return Collection
     */
    public function getRoles()
    {
        return $this->roles;
    }

}

and the formtype

class PopupType extends AbstractType
{
    private $tranformer;

    public function __construct(IntegerToTimestampTransformer $tranformer){
        $this->tranformer = $tranformer;
    }

    /**
     * {@inheritdoc}
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $date_array = [
            'label_attr' => [
                'class' => 'font-weight-bold'
            ],
            'required' => false
        ];
        if(!$options['edit']){
            $date_array['data'] = new \DateTime();
        }

        $builder
            ->add('title', TextType::class, [
                'label_attr' => [
                    'class' => 'font-weight-bold'
                ],
            ])
            ->add('description', TextareaType::class, [
                'label_attr' => [
                    'class' => 'font-weight-bold'
                ],
                'required' => false
            ])
            ->add('activation_date', DateTimeType::class, $date_array)
            ->add('deactivation_date', DateTimeType::class,$date_array)
            ->add('active', CheckboxType::class, [
                'label_attr' => [
                    'class' => 'font-weight-bold'
                ],
                'required' => false
            ])
            ->add('roles', EntityType::class, [
                'class' => Role::class,
                'expanded' => true,
                'multiple' => true,
                'required' => true,
                'label_attr' => [
                    'class' => 'font-weight-bold'
                ],
            ])
        ;

        $builder->get('activation_date')->addModelTransformer($this->tranformer);
        $builder->get('deactivation_date')->addModelTransformer($this->tranformer);
    }

    /**
     * {@inheritdoc}
     */
    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => Popup::class,
            'edit' => false
        ));
    }

    /**
     * {@inheritdoc}
     */
    public function getBlockPrefix()
    {
        return 'appbundle_popup';
    }
}

I debugged and I checked that in the transform function when I try to create on the crud the parameter passed to transform is a Datetime the there is no need to transformate the data but when I try to edit the parameter passed to transform is a unixtime integer the the transformation is needed, I don't understant that behaviour.

0 Answers
Related