Extending Custom Field widget plugins

Last updated on
31 March 2025

While the module provides an extensive set of widgets out of the box, we provide the ability to extend them further to meet your specific needs.

How to extend a widget plugin

  1. Review the existing widgets in the module folder: /modules/contrib/custom_field/src/Plugin/CustomField/FieldWidget
  2. Create a CustomField/FieldWidget plugin directory in your module: /src/Plugin/CustomField/FieldWidget
  3. Copy one of the widgets from step #1 into this directory.
  4. Rename the file and class name accordingly.
  5. Open the file and modify the attributes.
    1. id - Change the id to a unique name (required). Prefixing with your module name is recommended.
    2. label - Change the label to a human friendly name that will differentiate it from other widgets in the UI.
    3. description - Provide a description (optional)
    4. category - Change the category (optional). It will default to 'General' if no category is provided.
    5. field_types - At least one field type is required. In most cases, you will want to maintain the original value from the plugin you're extending to prevent unexpected issues of incompatibility.
  6. Modify the existing methods in the class.
  7. Clear the cache.
  8. Edit the field widget settings for your custom field.
  9. You should now be able to select your new widget type for a field with a matching data type
  10. Here's an example of a class that extends the SelectWidget plugin:
     
    <?php
    
    namespace Drupal\my_module\Plugin\CustomField\FieldWidget;
    
    use Drupal\Core\StringTranslation\TranslatableMarkup;
    use Drupal\custom_field\Attribute\CustomFieldWidget;
    use Drupal\custom_field\Plugin\CustomField\FieldWidget\SelectWidget;
    
    /**
     * Plugin implementation of the 'my_module_custom_select' widget.
     */
    #[CustomFieldWidget(
      id: 'my_module_custom_select',
      label: new TranslatableMarkup('Select list (My module'),
      category: new TranslatableMarkup('Lists'),
      field_types: [
        'string',
        'integer',
        'float',
      ],
    )]
    class CustomSelectWidget extends SelectWidget {
      // My custom code.
    }
    

Help improve this page

Page status: No known problems

You can: