Programmatically change form widget type for a field

Public

</> CopyGet raw version
php
  1. /**
  2.  * Change form widget for a field.
  3.  *
  4.  * @param $entity_type
  5.  * Entity the field attached to.
  6.  * @param $bundle
  7.  * Bundle the field attached to.
  8.  * @param $field_name
  9.  * Field name.
  10.  * @param $widget_type_machine_name
  11.  * Machine name of the field widget
  12.  */
  13. function ejd_tests_change_form_widget($entity_type, $bundle, $field_name, $widget_type_machine_name) {
  14. // Retrieve the stored instance settings to merge with the incoming values.
  15. $instance = field_read_instance($entity_type, $field_name, $bundle);
  16.  
  17. // Set the right module information.
  18. $widget_type = field_info_widget_types($widget_type_machine_name);
  19. $widget_module = $widget_type['module'];
  20.  
  21. $instance['widget']['type'] = $widget_type_machine_name;
  22. $instance['widget']['module'] = $widget_module;
  23.  
  24. // Update field instance
  25. field_update_instance($instance);
  26. }