0

I'm trying to get the content of all instances of certain fields based on their names. I've got a list of fields (which are in nodes/paragraphs and blocks) of which I want to extract the values from.

For example field_call_to_action_link. I need values of all the instances of this field.

Each field has it's own database table, like: node__field_name, paragraph__fieldname, block_content__fieldname.

I get the field names like this ($configFieldTypes is an array of types I want):

foreach ($configFieldTypes as $fieldType) {
  $fieldNamesFiltered[] = $this->entityFieldManager->getFieldMapByFieldType($fieldType);
}

Then I filter based on the name starting with 'field_' and make an array with the fieldname as key and the bundles associated with each field:

  private function recursiveKeys($fields, &$fieldNames) {
    foreach ($fields as $key => $field) {
      if ($key === 'parent_field_name'){
        continue;
      }
      if (FALSE !== strpos($key, 'field_')) {
        $fieldNames[$key] = [$field][0]['bundles'];
      }
      if (is_array($field)) {
        $this->recursiveKeys($field, $fieldNames);
      }
    }
  }

The endresult is an array like this:

  ["field_call_to_action_link"]=>
  array(1) {
    ["call_to_action_button"]=>
    string(21) "call_to_action_button"
  }
  ["field_image_gallery_link"]=>
  array(1) {
    ["image_gallery"]=>
    string(13) "image_gallery"
  }

Now I need to know if field_call_to_action_link is a node, block, or paragraph.

How can I determine which database table to query?

Drupal 8.8.x

1

If i understand correctly you have field_call_to_action_link in node, paragraph, block entities. And you would like to get values from this field from all entities which contain this field.

I would use EntityQuery and condition to check if field exists in given Entity.

$query = \Drupal::entityQuery('node')
->condition('status', 1)
->condition('field_call_to_action_link', 'NULL', 'IS NOT NULL')
->execute();

this should give you all published nodes which contain field_call_to_action_link. You can obtain 'block' Entity the same way only change 'node' to 'block'.


Useful links:

| improve this answer | |
  • 1
    Isn't entityQuery deprecated and we should use entityTypeQuery instead? – leymannx Feb 22 at 23:42
  • Yes you’re right. Thanks. You should use EntityTypeManager to build query. – Patrick Star Feb 23 at 8:55
  • Ah no, for non-OOP code, \Drupal::entityQuery() is not deprecated and can still be used. For services, forms or controllers it's $this->entityTypeManager->getStorage('node')->getQuery() or $this->nodeStorage->getQuery(). – leymannx Feb 23 at 9:20

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.