Drupal 8: Node create/edit form alter with example

Normally content are created and managing is done using node form in Drupal. There is node create form and edit form help create and manage contents in Drupal sites. the hook function hook_form_node_form_alter() will help to achieve altering node forms to alter.
The below is the example of altering node forms.

Syntax: 

use Drupal\Core\Form\FormStateInterface;
 
/**
 * Implements hook_form_FORM_ID_alter().
 */
function hook_form_node_form_alter(&$form, FormStateInterface $form_state) {
  .......
  .......
}

Example: 

/**
 * Implements hook_form_FORM_ID_alter().
 */
function uc_volume_pricing_form_node_form_alter(&$form, FormStateInterface $form_state) {
  $node = $form_state->getFormObject()->getEntity();
  $nodeBundle = $node->bundle();
  if (in_array($form['#form_id'], ['node_product_edit_form', 'node_product_form']) && uc_product_is_product($nodeBundle)) {
    $form['volume_pricing']['volume-set' . $count]['min'] = [
      '#type' => 'textfield',
      '#title' => 'Min Quantity',
      '#default_value' => 5,
    ];
    $form['volume_pricing']['volume-set' . $count]['price'] = [
      '#type' => 'textfield',
      '#title' => 'Price Each',
      '#default_value' => 10,
    ];
  }
}

 

Category: