Fix awful Views Display machine names with '_1' suffix

Public

Site builder UX: Views will automatically add display with machine name 'block' instead of 'block_1', 'feed' instead 'feed_1' for new display of type Block (the same for other types).

Get raw version
php
  1. /**
  2.  * Implements hook_form_FORM_ID_alter().
  3.  *
  4.  * Add custom submit callback to Views "Add display" buttons.
  5.  */
  6. function MYMODULE_form_views_ui_edit_form_alter(&$form, &$form_state) {
  7. foreach ($form['displays']['top']['add_display'] as &$display_type) {
  8. // Keep views_ui_edit_form_submit_delay_destination() as last callback.
  9. $last_callback = array_pop($display_type['#submit']);
  10. $display_type['#submit'][] = 'MYMODULE_views_add_display_submit';
  11. $display_type['#submit'][] = $last_callback;
  12. }
  13. }
  14.  
  15. /**
  16.  * Views submit callback.
  17.  *
  18.  * Rename last added display from 'block_1' to just 'block', etc.
  19.  */
  20. function MYMODULE_views_add_display_submit($form, &$form_state) {
  21. $view = $form_state['view'];
  22.  
  23. // Type of new display.
  24. $parents = $form_state['triggering_element']['#parents'];
  25. $display_type = array_pop($parents);
  26. if (isset($view->display[$display_type])) {
  27. // Nice name already in use.
  28. return;
  29. }
  30.  
  31. // Change machine name for last added display.
  32. $display = array_pop($view->display);
  33. $display->id = $display_type;
  34. $view->display[$display_type] = $display;
  35. views_ui_cache_set($view);
  36.  
  37. // Redirect to the new display's edit page.
  38. $form_state['redirect'] = 'admin/structure/views/view/' . $view->name . '/edit/' . $display->id;
  39. }