1

Hi Every one I am trying to create new field collection item programmatically but code is not working. I want to create a number of field collection items but no Luck. My code is following.

use Drupal\Core\Field\FieldItemListInterface;
use Drupal\field_collection\Entity\FieldCollectionItem;

function mymodule_form_alter(&$form, FormStateInterface $form_state, $form_id) { 
if($form_id == 'my_form'){

for($i = 0; $i < 2; $i++) {

$new_experience_item = FieldCollectionItem::create(['field_name' => 'field_collection_name']);

      }


    }

}

My first Question-> Can we run this code in the hook_form_alter? If yes, Then why my code is not working perfectly?

0

Paragraphs or Field Collection doesn't matter for your code. You need to add the newly created items to a field.

For example if the field collection field is in a node:

$node->field_collection_name[] = $new_item;

Not in a form alter hook, but in an entity create hook. See the linked question.

  • Let me tell you my case. I have a field in profile named Experience and the field is field collection and unlimited.When the user apply to a job so I want to copy all the experience from the user profile. For this purpose I made a new field collection field and on the job page I load all the experience and want to create new field collection items to store that experience data. – Fawad Ali Jun 11 at 6:33
  • for reference you can see this drupal.stackexchange.com/questions/268421/… – Fawad Ali Jun 11 at 6:35
  • Then do this in a controller, see drupal.stackexchange.com/questions/236871/… – 4k4 Jun 11 at 6:41
  • I want this for field collection item ... Sorry I am very new to Drupal 8 module development – Fawad Ali Jun 11 at 6:45
  • Use the code from your link and put it in a controller like in my link. – 4k4 Jun 11 at 6:48

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.