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();
          ->condition('key', $key);

  $entity = $query->execute();

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

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

1 Answer 1


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()
  ->loadByProperties(['key' => $key]);

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

Your Answer

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

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