Drupal 8 hook example: hook_form_alter - views-exposed-form alter example

This hook is used most often.

  1. **
  2. * Implements hook_form_alter().
  3. */
  4. function custom_module_form_alter(array &$form, FormStateInterface $form_state, $form_id) {
  5.  
  6. if ($form['#id'] == 'views-exposed-form-companies-page-1') {
  7.  
  8. // Views exposed form: Display select as checkbox on view exposed form
  9.  
  10. if ($form['field_opportunity_areas_target_id']['#type'] == 'select') {
  11. $form['field_opportunity_areas_target_id']['#type'] = 'checkboxes';
  12. }
  13. if ($form['field_stage_of_development01_target_id']['#type'] == 'select') {
  14. $form['field_stage_of_development01_target_id']['#type'] = 'checkboxes';
  15. }
  16. if ($form['field_new_technology_trends_target_id']['#type'] == 'select') {
  17. $form['field_new_technology_trends_target_id']['#type'] = 'checkboxes';
  18. }
  19. if ($form['field_client_journey_target_id']['#type'] == 'select') {
  20. $form['field_client_journey_target_id']['#type'] = 'checkboxes';
  21. }
  22.  
  23.  
  24. // Views exposed form: Add placeholder to input (keywords search) field
  25. $form['keys']['#weight'] = -20;
  26. $form['keys']['#attributes']['placeholder'] = 'Search';
  27.  
  28.  
  29. // Views exposed form: Default values and filter visibility based on user roles. user with "mas" can't see few filter and another filter has "1" as befault value, another users can see the filters and default value is "All"
  30.  
  31. $current_user = \Drupal::currentUser();
  32. $roles = $current_user->getRoles();
  33.  
  34. if (in_array('mas', $roles)) {
  35.  
  36. $form['field_do_you_want_to_opt_in_to_t']['#default_value'] = 1;
  37. $form['field_do_you_want_to_opt_in_to_t']['#value'] = 1;
  38.  
  39. $form['type']['#access'] = FALSE;
  40. $form['field_categories_target_id']['#access'] = FALSE;
  41.  
  42. } else {
  43. $form['field_do_you_want_to_opt_in_to_t']['#default_value'] = 'All';
  44. }
  45.  
  46. $form['field_do_you_want_to_opt_in_to_t']['#access'] = FALSE;
  47.  
  48. }
  49. }