Score:0

How to copy fields from an entity to another for same type entities?

in flag
Lia

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 = [
  'id',
  'uuid',
  'vid',
];

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

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.

Score:0
in flag
Lia

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
cn flag
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.
4uk4 avatar
cn flag
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 https://drupal.stackexchange.com/questions/278500/get-the-custom-fields-created-for-user-entity-in-drupal8
mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.