I try to update automatically entity title after form is sent. I tried that in form_alter, but everybody guided me to use entity presave. I cannot manage to save the updated title however (please see comments below in the code).

function discount_entity_presave(Drupal\Core\Entity\EntityInterface $entity) {
  if (!empty($entity->toArray()['product_id'][0]['target_id'])) {
    $title = $entity->toArray()['title'][0]['value'];
    $product_id = (int)$entity->toArray()['product_id'][0]['target_id'];
    $product = \Drupal::entityTypeManager()->getStorage('commerce_product')->load($product_id);
    $events_dates = $product->get('event_date')->getValue();
    $count = count($events_dates);
    if (empty($events_dates[$count-1])){
      $count = $count - 1;
    if ($count > 0) {
      $start_date = date("j/n/y", strtotime($events_dates[0]['value']));
      $end_date = date("j/n/y", strtotime($events_dates[$count-1]['end_value']));
      if ($count == 1) {
        $count_suffix = "zjazd";
      } else if ($count == 2 || $count == 3) {
        $count_suffix = "zjazdy";
      } else {
        $count_suffix = "zjazdów";
      $date = $start_date.' - '.$end_date.' ('.$count.' '.$count_suffix.')';

    /* if I kint($title.$date) here it gives me a proper value, so only the code below doesn't work */

    /* this code below doesn't update the title regardless if there is $entity->save() later on or not */
    /* I tried these 3 options below, none of them updates the title */
    $entity->title->value = $title.$date;
    $entity->set('title', $title.$date);
    /* When I do kint($entity->toArray()); here I can see the updated title, however it doesn't save it later do database */

    /* this line below causes endless loop, when it is commented it also doesn't save the title */
  • 6
    Just remove $entity->save().
    – MrD
    Dec 18, 2020 at 9:11
  • Thanks, but like I wrote above - it doesn't cause endless loop when I remove it, but title's value is not saved after submitting the form, I mean it still has the old value.
    – rukya
    Dec 18, 2020 at 13:14
  • 3
    You cannot call $entity->save() on the entity passed to hook_entity_presave(). You must remove that line. Additionally, as you note, you appear to be setting the title correctly. My best guess is there's some code somewhere else that runs after this that changes the title.
    – sonfd
    Dec 18, 2020 at 13:52


Your Answer

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

Browse other questions tagged or ask your own question.