0

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.

3
  • See php.net/manual/en/…
    – Clive
    Jul 16, 2021 at 11:51
  • @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
    Jul 16, 2021 at 12:37
  • I realise I got by 'slashes' wrong in the comment above. They are correct in my code.
    – gmak
    Jul 16, 2021 at 12:43

1 Answer 1

0
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;

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.