I have a paragraph bundle with several fields, on of them being drop-down list.

How would I go about populating this dropdown list via code, programmaticaly?

I don't really know where to begin with this...

  • When do you want to fill it? on creating paragraph? and on which bases you want to fill it? – Ziftman Dec 19 '17 at 1:29

Check out hook_options_list() to dynamically populate available options.

|improve this answer|||||

Ok, here's what I figured out:

Use hook_field_widget_form_alter()

My case:

function my_module_field_widget_form_alter(&$element, &$form_state, $context) {

  // Check if element is paragraph type, belongs to a specific paragraphs
  // bundle and contains a specific field.
  if (empty($element['#entity']) || $element['#entity_type'] !== 'paragraphs_item' ||
    $element['#bundle'] !== 'content_block' || $element['#field_name'] !== 'field_dropdown_text_single') {

  // Get entity metadata
  $form_field_wrapper = entity_metadata_wrapper('paragraphs_item', $element['#entity']);

  // Set default value. If there is already a set value use that,
  // else set to '_none'
  $default_value = $form_field_wrapper->field_dropdown_text_single->value();
  $element['#default_value'] = !empty($default_value) ? $default_value : '_none';

  // Code to get your custom select options goes here

  // Inject custom options into paragraph's dropdown selector.
  $element['#options'] = $my_options;
|improve this answer|||||

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.