I have one paragraph type of Product. and I have to add one field to paragraph product programmatically, how can I achive this.

function my_module_field_widget_paragraphs_form_alter(&$element, FormStateInterface &$form_state, $context){
  if ($element['#paragraph_type'] == 'products') {

<!-- add field here -->


and other answer I found is

use Drupal\paragraphs\Entity\Paragraph;

  $paragraph = Paragraph::load($paragraph_id);
  $paragraph->field_image[] = [
    'target_id' => $fid,
    'alt' => $alt,
    'title' => $title,

But in which function or preprocess I need to add above code?

  • 1
    Normally you go to the UI edit a paragraph type, add fields, save, export config, done. What are you trying to do here? And why don't you use the UI and export config as usual?
    – leymannx
    Commented Dec 4, 2019 at 9:28
  • @leymannx I need to create one dropdown field in paragraph and options of that dropdown will be come from config file.
    – mintra
    Commented Dec 4, 2019 at 9:30
  • Then add the field from the UI and define an allowed values callback in a custom module.
    – leymannx
    Commented Dec 4, 2019 at 9:32
  • @leymannx can you share link
    – mintra
    Commented Dec 4, 2019 at 9:33
  • 2
    check this out flocondetoile.fr/blog/…
    – berramou
    Commented Dec 4, 2019 at 10:02

1 Answer 1


We cannot create a field to existing paragraph type using hook_field_widget_paragraphs_form_alter(), because it will not create the field. So the best way to add a custom field is using hook_entity_base_field_info()

In my case I need to create a text field in all my existing paragraph types and into the new paragraph which will be created in future so I used below code.

function hook_entity_base_field_info(EntityTypeInterface $entity_type) {
  if ($entity_type->id() === 'paragraph') {
    $fields['field_parent_section_class'] = BaseFieldDefinition::create('string')
      ->setLabel(t('Parent section class'))
      ->setDescription(t('Class for the parent section element( Add more than one class separated by space )'))
      ->setDisplayConfigurable('form', array(
        'settings' => array (
        'display_label' => TRUE
      ->setDisplayConfigurable('view', TRUE)
        'default_value' => '',
        'max_length' => 255,
        'persist_with_no_fields' => TRUE
    return $fields;

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.