1

I have an "Question" entity, and I need to updates its 'key' field (of string type):

My code isn't working:

  $storage = \Drupal::entityManager()->getStorage('question');
  $query = $storage->getQuery();
  $query
          ->condition('key', $key);

  $entity = $query->execute();


 $entity -> set ('key', 'new_value');
 $entity->save();

It returns the error Fatal error: Call to a member function set() on a non-object

2

The QueryInterface::execute() method returns either an integer or an array, not an object. It is a good idea to check api.drupal.org (if you don't use an IDE), or let your IDE do the work for you with intellisense.

It probably would be easier to use loadByProperties, which loads the entities for you. However it is definitely useful to get the query object, but you need to call loadMultiple.

$entities = \Drupal::entityTypeManager()
  ->getStorage('question')
  ->loadByProperties(['key' => $key]);

if (!empty($entities)) {
  $entity = reset($entities);
  $entity->set('key', 'new_value');
  $entity->save();
}

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.