form_placeholder.module in Form Placeholder 8
Same filename and directory in other branches
Use field label as placeholder for all elements in chosen form.
File
form_placeholder.moduleView source
<?php
/**
* @file
* Use field label as placeholder for all elements in chosen form.
*/
/**
* Implements hook_element_info_alter().
*/
function form_placeholder_element_info_alter(array &$types) {
foreach (array_keys($types) as $type) {
$allowed_types = [
'form',
'textarea',
'textfield',
'tel',
'email',
'url',
'number',
'password',
'password_confirm',
];
if (in_array($type, $allowed_types)) {
$types[$type]['#process'][] = 'form_placeholder_process_element';
}
}
}
/**
* Element process callback.
*
* @param array $element
* The render array element.
* @param \Drupal\Core\Form\FormStateInterface $form_state
* The FormStateInterface object for this form
*
* @return array
* The processed element.
*/
function form_placeholder_process_element($element, &$form_state) {
$form = $form_state
->getCompleteForm();
$form_placeholder = NULL;
if (isset($element['#form_placeholder'])) {
$form_placeholder = $element['#form_placeholder'];
}
elseif (isset($form['#form_placeholder'])) {
$form_placeholder = $form['#form_placeholder'];
}
if (!is_null($form_placeholder)) {
$action = $form_placeholder == TRUE ? 'include' : 'exclude';
if ($element['#type'] == 'form') {
$element['#attributes']['class'][] = 'form-placeholder-' . $action . '-children';
}
else {
$element['#attributes']['class'][] = 'form-placeholder-' . $action;
}
}
form_placeholder_attach($element);
return $element;
}
/**
* Adds placeholder to form element.
*
* @param array $element
* Form API element.
*/
function form_placeholder_attach(&$element) {
$config = \Drupal::config('form_placeholder.settings');
// Adding settings.
$whitechars = [
"\r\n",
"\r",
"\n",
];
$element['#attached']['drupalSettings']['form_placeholder'] = [
'include' => str_replace($whitechars, ',', $config
->get('included_selectors')),
'exclude' => str_replace($whitechars, ',', $config
->get('excluded_selectors')),
'required_indicator' => $config
->get('required_indicator'),
];
// Adding module JS file.
$element['#attached']['library'][] = 'form_placeholder/form_placeholder';
}
Functions
Name | Description |
---|---|
form_placeholder_attach | Adds placeholder to form element. |
form_placeholder_element_info_alter | Implements hook_element_info_alter(). |
form_placeholder_process_element | Element process callback. |