Form API

Entity Reference Selection

Entity Reference Selection

To 'alter' what shows in an entity reference selection

Reference https://drupal.stackexchange.com/questions/298105/can-i-create-non-default-entityreferenceselection

In src/Plugin/EntityReferenceSelection

<?php

namespace Drupal\YOUR_MODULE\Plugin\EntityReferenceSelection;

use Drupal\node\Plugin\EntityReferenceSelection\NodeSelection;

/**
 * Provides a query for a node entity reference selection.
 *
 * @EntityReferenceSelection(
 *   id = "YOUR_MODULE_REFERENCE_SELECTION_ID",
 *   label = @Translation("Filter nodes with a specific field value."),
 *   entity_types = {"node"},
 *   group = "YOUR_MODULE_REFERENCE_SELECTION_GROUP",
 *   weight = 1
 * )
 */
class YourModuleEntityReferenceSelection extends NodeSelection {
  /**
   * {@inheritdoc}
   */
  protected function buildEntityQuery($match = NULL, $match_operator = 'CONTAINS') {
    $query = parent::buildEntityQuery($match, $match_operator);
    $query->condition('field_featured', 1', '=');
    return $query;
  }
}

Admin configuration form with dependency injection

Admin configuration form with dependency injection

When adding a form using Form API, best practice is to use dependency injection when possible. Admin form classes typically 'extend ConfigFormBase'. If you want to add to it, it'll look like this.

 

<?php

namespace Drupal\my_module\Form;

use Drupal\Core\Config\Config;
use Drupal\Core\Form\ConfigFormBase;
use Drupal\Core\Config\ConfigFactoryInterface;
use Drupal\Core\Messenger\MessengerInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * Class myCustomAdminForm.
 *
 * @package Drupal\my_module\Form
 */
class myCustomAdminForm extends ConfigFormBase {
  
  /**
   * @var $configFactory
   */
  protected $configFactory;
  
  /**
   * @var Config $myConfig
   */
  protected $myConfig;

  /**
   * The Messenger service.
   *
   * @var \Drupal\Core\Messenger\MessengerInterface
   */
  protected $messenger;
  
  public function __construct(
    ConfigFactoryInterface $configFactory,
    MessengerInterface $messenger
  ) {
      parent::__construct($configFactory);
      $this->myConfig = $this->config('my_config.settings.my_settings');
      $this->messenger = $messenger;
  }
  
  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static(
      $container->get('config.factory'),
      $container->get('messenger')
    );
  }
  
    /**
   * {@inheritdoc}
   */
  protected function getEditableConfigNames() {
    return [
      'my_config.settings.my_settings',
    ];
  }
  
  /**
   * This needs to return a string that is the unique ID of your form. Namespace the form ID based on your module's name.
   */
  public function getFormId() {
    return 'my_module_admin_form';
  }
  
  /**
   * This returns a Form API array that defines each of the elements your form is composed of.
   */
  public function buildForm(array $form, FormStateInterface $form_state) {
  
  	$form['text_input'] = [
  		'#type' => 'textfield',
  		'#description' => t('Enter data into this field'),
  		'#default_value' => $this->myConfig->get('my_config_values')
  	]
  	
  	return parent::buildForm($form, $form_state);
  
  }
	
  /**
   * Validate the form
   */  
  public function validateForm(array &$form, FormStateInterface $form_state) {
  	$values = $form_state->getValues();
  	if(empty($values['text_input']) {
  		$form_state->setErrorByName('text_input', t('You must enter data into this field.'));
  	}

  }
  
  /**
   * Submit the form
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
  	$values = $form_state->getValues();
  	
  	$this->myConfig->set('my_config_values', $values['text_input']);
  	
  	$this->myConfig->save();
  	
  	$this->messenger->addStatus('Your value has been saved.');
  	
  	parent::submitForm($form, $form_state);
  }

}

Creating select form using Taxonomy and Form API

Creating select form using Taxonomy and Form API

Often times when using the Drupal Form API creating custom forms, you'll need to get a select list of Taxonomy terms as options. These snippets will help you look up terms in a vocabulary and put them in your options array.

Drupal 8

// Create empty options array
$options = array();

// Taxonomy vocabulary machine name
$taxonomy = 'tax_machine_name';

// Get all the taxonomy terms from the vocabulary
$tax_items = \Drupal::entityTypeManager()->getStorage('taxonomy_term')->loadTree($taxonomy);

// Inject into the options array
foreach($tax_items as $tax_item) {
  $options[$tax_item->tid] = $tax_item->name;
}

// Create a select form element
$form['taxonomy_options'] = array(
    '#type' => 'select',
    '#options' => $options,
    '#required' => TRUE,
);


Drupal 7

// Create empty options array
$options = array();

// Taxonomy vocabulary machine name
$taxonomy = 'tax_machine_name';

// Get all the taxonomy terms from the vocabulary
$vocab = taxonomy_vocabulary_machine_name_load('tax_machine_name')->vid;
$tax_items = taxonomy_get_tree($vocab);

// Inject into the options array
foreach($tax_items as $tax_item) {
  $options[$tax_item->tid] = $tax_item->name;
}

// Create a select form element
$form['taxonomy_options'] = array(
    '#type' => 'select',
    '#options' => $options,
    '#required' => TRUE,
);