[Drupal] How to Programmatically Uncheck 'Generate Automatic url Alias' Option for a Specific Node Editing form in Drupal 7?

| | 1 min read

In one of my works, I want to programmatically uncheck the checkbox option of 'Generate automatic URL alias' for a specific node editing form. For this, I have created the following form alter for the content type. I have added a custom after-build function for the necessary content type in the form alter.


/**
 * Implements hook_form_alter().
 */
function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
  if (isset($form['#node_edit_form']) && $form['#node_edit_form'] == TRUE && $form['type']['#value'] == 'MYCONTENTTYPE_MACHINENAME') {
    $form['#after_build'][] = 'MYMODULE_node_after_build';
  }
}

/**
 * Custom node form after build function.
 */
function MYMODULE_node_after_build($form, &$form_state) {
  // Unchecks the checkbox for Generate automatic URL alias, if path exists.
  if (isset($form['path']['pathauto']) && $form['path']['pid']['#value']) {
    $form['path']['pathauto']['#checked'] = FALSE;
  } 
  return $form;
}

Hope this tip helps for any of your specific node editing forms for handling the URL alias, if the path is already created without affecting other nodes and configurations.