0

I Have a Drupal 7 site with a node_presave function which works to enter a start date (date field) and number of days field (integer) which then populates the date field with the correct number of dates. ie Start date : 2018-02-05 Number of days : 3 Output in date field: 2018-02-05 2018-02-06 2018-02-07

Here is the code:

function node_presave($node) {
  if (in_array($node->type, array('boka_rum'))) {
    $date_field = $node->field_datum['und'][0];
    unset($node->field_datum['und']);
    $days = intval($node->field_antal_dagar['und'][0]['value']);
    for ($i = 0; $i < $days; $i++) {
      $node->field_datum['und'][] = $date_field;
      $date_field['value'] = $date_field['value2'] = date('Y-m-d 00:00:00',strtotime($date_field['value'] . "+1 days"));
    }
  }

}

I am trying to upgrade this to a Drupal 8 site but am missing something somewhere. Can anyone help with the correct syntax?

Drupal 8 code:

function entity_presave(Drupal\Core\Entity\EntityInterface $entity) {
  if (in_array($node->type, array('boka_rum'))) {
   $entity->field_datum = $date_field
    unset($entity->field_datum);
   $entity->field_antal_dagar = $dagar
    $days = intval($dagar);
    for ($i = 0; $i < $days; $i++) {
      $entity->field_datum = $date_field;
      $date_field['value'] = $date_field['value2'] = date('Y-m-d 00:00:00',strtotime($date_field['value'] . "+1 days"));
    }
  }

}

Thanks

0

The D7 function doesn't look like a hook, but in D8 there is a hook for this:

use Drupal\node\NodeInterface;

/**
 * Implements hook_ENTITY_TYPE_presave() for node entities.
 */
function mymodule_node_presave(NodeInterface $node) {
  if (in_array($node->getType(), array('boka_rum'))) {
    // ...
  }
}
  • Thanks for the code. Here is the updated version. It still isn't updating on the node after an update.php and cache clear. ` function node_presave(NodeInterface $node) { if (in_array($node->getType(), array('boka_rum'))) { $date_field = $node->field_datum['und'][0]; unset($node->field_datum['und']); $days = intval($node->field_antal_dagar['und'][0]['value']); for ($i = 0; $i < $days; $i++) { $node->field_datum['und'][] = $date_field; $date_field['value'] = $date_field['value2'] = date('Y-m-d // ... } } }` – James Feb 5 '18 at 10:49

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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