6

I have a pretty standard Entity with the correct imports:

/**
 * Budhaz\aMailerBundle\Entity\Instance
 *
 * @ORM\Table()
 * @ORM\Entity
 */
class Instance {
    use TimestampableEntity;

    /** @ORM\Id @ORM\GeneratedValue @ORM\Column(type="integer") */
    private $id;
...
}

But I would like to remove the createdAt (and updatedAt) from my form so the user don't and can't set them, so I remove it from the InstanceForm:

class InstanceType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('name')
            ->add('startAt')
            ->add('endAt')
            //->add('createdAt')
            //->add('updatedAt')
            ->add('campaign')
        ;
    }
...
}

But now I have this error:

SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'createdAt' cannot be null

createdAt and updatedAt should automaticaly be set by Doctrine, but it stays null, anyone know why?

2
  • Show please annotations for createdAt and updatedAt fields in Entity class Feb 19, 2013 at 11:38
  • 1
    I don't have them because it's a trait.
    – Dorian
    Feb 19, 2013 at 11:41

3 Answers 3

13

You have to set the values within the class manually. Then you can tell doctrine to set the new value before every update:

public function __construct() {
    $this->setCreatedAt(new \DateTime());
    $this->setUpdatedAt(new \DateTime());
}

/**
 * @ORM\PreUpdate
 */
public function setUpdatedAtValue() {
    $this->setUpdatedAt(new \DateTime());
}
4
  • 1
    I don't have to add the setter as I use a trait but I had to initilize the variables, thanks.
    – Dorian
    Feb 19, 2013 at 11:40
  • I overlooked that. You're right. In that case you only need to initialize the variables. Feb 19, 2013 at 11:43
  • @insertusernamehere but they did not mention that in the trait doc, it's weird!
    – Thamer
    Feb 6, 2020 at 16:40
  • There is a problem with this answer although it works well, if we take the case of Blameable would you inject the user object into the constructor to set it as you did ?
    – Lounis
    Jul 26, 2023 at 16:25
13

app/config/config.yml

stof_doctrine_extensions:
   orm:
      default:
          timestampable: true
2
5

You need to check if the bundle is installed. If not, run: composer require stof/doctrine-extensions-bundle

It should create file: app/config/packages/stof_doctrine_extensions.yaml with the content:

stof_doctrine_extensions:
    default_locale: en_US
    orm:
        default:
            timestampable: true

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.