I have 2 entities of the same type & bundle but used in 2 different cases (linked differently to different entities). Upon publishing the second entity, I want to get the new data and put it into the 'main' entity since all logic is built based on the main entity and interacts with other sorts of things.

What I have so far:

 $fields_to_exclude = [

foreach ($second_entity->getFields() ?: [] as $name => $field) {
  if (!in_array($name, $fields_to_exclude)) {
    $main_entity->set($name, $field->getValue());

There are around 120 fields and I need to exclude only 5-10. My problem is that I want to get only fields created in the interface such as 'field_country_name', 'field_category' etc. The function above returns all entity fields (such as ID, UID, etc.) and there are too many to take into consideration. Is there any way to get only the 'custom created fields' ? I could not find anything in the Drupal API.

1 Answer 1


Apparently you can just check if the field name contains the word 'field' since it is specific to only 'created from the interface' fields.

strpos($name, 'field') !== FALSE
  • 1
    This is a reasonable solution, but note that it is possible to edit the field machine name in the interface and remove field_ from it, so your solution does not guarantee that all UI-created fields will be found. Dec 21, 2021 at 15:17
  • 2
    Yes, the default node content types have for example body and comment which are UI configurable but don't have the prefix. It might be a better idea to check whether $field->getFieldDefinition() is an instance of \Drupal\field\FieldConfigInterface. See drupal.stackexchange.com/questions/278500/…
    – 4uk4
    Dec 21, 2021 at 16:17

Your Answer

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

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