Score:0

Use hook_entity_presave to convert multiple lines in a field to separate values in a multi-value field?

cn flag

I have a field defined as 'long text' that allows infinite number of values. The difficulty is that users are entering everything in one iteration of the field. So, I need to get the value they have entered, explode it and create separate multi-value field entries. But... my approach isn't working:

function builder2020_entity_presave(EntityInterface $entity){
  switch ($entity->bundle()) {
    case 'ec_topics':
      $count = count($entity->field_ec_subtopics);//check if the user has only used one field
      if ($count == 1){ //user has put everything in one field value
        $values = array(explode('\n',$entity->field_ec_subtopics->value)); create array from the field value
          $entity->field_subtopics->value = $values; //feed the array to the field
      }
      $entity->field_sub_topic_count->value = $count; //set the number of ec_topics
      break;

I 'think' I'm close, but I can't seem to figure out where I'm falling down.

cn flag
See https://www.php.net/manual/en/language.types.string.php#language.types.string.syntax.single
gmak avatar
cn flag
@Clive I can see what you are suggesting, that '\n' is not going to be found in the explode() statement, and that I should use "\n". However, when I do that I'm still not getting the result that I expects. It seems like the explode() is not working, in any case.
gmak avatar
cn flag
I realise I got by 'slashes' wrong in the comment above. They are correct in my code.
Score:0
cn flag
case 'ec_topics':
      $count = count($entity->field_ec_subtopics);
      if ($count == 1){
        $values = $entity->field_ec_subtopics->getValue();
        $content = $values[0]['value'];
        $items = explode(PHP_EOL,$content);
        $count = count($items);
        $entity->field_ec_subtopics = $items;
      }
      $entity->field_sub_topic_count->value = $count;
      break;
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.