Do you want to know how to Drupal?

Let's Drupal

Form API

How to set a custom redirection after form submission Drupal 9?

To redirect a user after form submit to a custom URL. We need to implement custom submit function.

use Drupal\Core\Form\FormStateInterface;

/** 
 * Implements hook_form_FORM_ID_alter().
 */
function mydoule_form_YOUR_FORM_ID_alter(&$form, FormStateInterface $form_state, $form_id) {
  // add custom function as submit handler.
  $form['#submit'][] = '_mymodule_custom_submit_handler';

  // Sometime forms doesn't into account '#submit' parameter. So, we have to set custom handler to the specific button of the form
  $form['actions']['submit']['#submit'][] = '_mymodule_custom_submit_handler';
}

/**
 * Custom submit handler for your form form.
 */
function _mymodule_custom_submit_handler($form, FormStateInterface $form_state) {
  // Set a custom redirect.
  $form_state->setRedirect('custom.route');
}

You will need to replace module name and put into install file of your module and also don't forget to replace form id.


How to alter options for dropdown (select input) in Drupal

Sometimes we need to alter or restrict some options for dropdown of entity reference field. One of the solution to use views and provide views entity reference widget, but in some cases the logic would be too complex and we will have to implement custom plugins for views. The second solution could be just replace options for dropdown widget. For this we need implement "hook_field_widget_form_alter"

/**
 * Implements hook_field_widget_form_alter().
 */
function your_module_field_widget_form_alter(
   if (!empty($field_definition) && $field_definition->getName() == 'fut_collection') {
    $element['#options'] = _your_module_get_input_options();
  }
}

/**
 * Gets group collection options.
 */
function _your_module_get_input_options() {
   $options = [];
   // here your custom logic to get ids.
   $items = Term::loadMultiple($ids);
   if ($items ) {
      // a default empty value.
      $options['_none'] = t('- None -');
      foreach ($items as $item) {
        $options[$item->id()] = $item->getName();
      }
   }

   return $options;
}

Keep in mind that you have to use the entity ids of entity type for your entity reference field. Also, if you want to provide the default value without any value, you should use this code:

$options['_none'] = t('- None -');

and not like

$options[''] = t('- None -');

In other case you can face some unexpected bugs