Once a page is saved I want to put the current time (I know I can do it by the form, but I need to do it programmatically). My code:

function mymodule_node_presave(EntityInterface $entity) {
    $node_type = $entity->bundle();
    if ($node_type === 'page') {
            $date = date('Y-m-d 00:00:00', time());
            $entity->field_mydate->value = $date;
            $entity->body = $date;

It changes the body correctly but not the date field. I tried all those, none works. I can't understand where is the problem.

  • You don’t have a variable named $node_type defined, so the condition never passes.
    – Clive
    Commented Oct 19, 2017 at 16:59
  • :P I cleaned the code for the question and I removed too much. I edited it. The condition enters correctly, in fact as I said the body value is correctly set to the date 2017-10-19 00:00:00 Commented Oct 19, 2017 at 22:23
  • You could just create a field of type changed and this would automatically be set for you.
    – Felix Eve
    Commented Oct 19, 2017 at 23:08
  • Yes, thank you for the suggestion. I could also set the current time by default. As I stated I need to change it programmatically. I want to set a date programmatically, any date, not necessarily the current time, I put that code to have a starting excerpt. My question is, why the date value set in this case is not working? Commented Oct 19, 2017 at 23:31

1 Answer 1


Solved the issue. In my case, after debugging the value, I guessed the right code could be:

$date = date('Y-m-d\T00:00:00', time());

And it is. I'm not sure what the date format depends on. For sure it doesn't depends on the form display format since in the I'm using the Italian one (d/m/Y).

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.