0

I have 2 custom content entities created with Drupal Console (drupal generate:entity:content): 'person' and 'member'.
They are linked (1 member <-> n persons) by a field named 'member_id' in 'person'.
If a person is set with 'iscontact' = true, the other persons related to the same member should have 'iscontact' = false.

In the PersonForm.php, I have this code.

public function save(array $form, FormStateInterface $form_state) {
  $entity = $this->entity;

  if ($entity->get('iscontact')) {

    $member_id = $entity->get('member_id')->getString();
    $iId = $entity->get('id')->getString();
    $database = \Drupal::database();
    $query = $database->select('person', 'ap');
    $query->fields('ap', ['id', 'member_id'])
      ->condition('id', $iId, '<>')
      ->condition('member_id', $member_id, '=');
    $results = $query->execute();

    foreach ($results as $key=>$result) {
      $numberofrowsaffected = $database->update('person')
        ->fields(['iscontact' => 0,])
        ->condition('id', $result->id)
        ->execute();
    }
  }

  $status = parent::save($form, $form_state);

  switch ($status) {
    case SAVED_NEW:
      drupal_set_message($this->t('La personne « %label » a été ajoutée.', [
        '%label' => $entity->label(),
      ]));
      break;
    default:
      drupal_set_message($this->t('La personne « %label » a été modifiée.', [
        '%label' => $entity->label(),
      ]));
  }
  $form_state->setRedirect('entity.person.canonical', ['person' => $entity->id()]);
}

When I execute this, the table 'person' in the database is correctly updated, but in the page the previous person is still seen as having 'iscontact' = 1.
It's incorrect until I clear the cache. What am I doing wrong?

  • Not using the entity API, specifically the storage handler to load and save entities. – 4k4 Nov 29 '18 at 19:55
2

I replaced

foreach ($results as $key=>$result) {
  $numberofrowsaffected = $database->update('person')
    ->fields(['iscontact' => 0,])
    ->condition('id', $result->id)
    ->execute();
}

by

  $storage = \Drupal::entityTypeManager()->getStorage('person');
  foreach ($results as $key=>$result) {
    $person = $storage->load($result->id);
    $person->iscontact = 0;
    $person->save();

And it works!

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

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