In a module that I am working at, I want to have to possibility to choose avaible view modes from a select list, but for now I only know how to get the label ("Human") name, but I want the machine name, so how do I do that? My code for now looks like this:

 $available_view_modes = array();
  //entity_get_info feteches the info of avaible view modes
  $entity_info = entity_get_info();

  if (empty($available_view_modes)) {
    $entity_info = entity_get_info();
    foreach ($entity_info['node']['view modes'] as $key => $view_mode) {
      dpm($view_mode);
      $available_view_modes[] = $view_mode['label'];
    }
  }
  $form['view_mode'] = array(
    '#type' => 'select',
    '#description' => t("View modes."),
    '#options' => $available_view_modes,
    '#default_value' => !empty($conf['view_mode']) ? $conf['view_mode'] : '0',
);

Comments

misc’s picture

Not so nice looking code, but it works, if somebody have a better solution, which I am sure of, please share :-)

  //available_view_modes is the array to contain the avaible view modes, for now this is not content type aware, but should be
  $available_view_modes = array();
  //entity_get_info feteches the info of avaible view modes
  $entity_info = entity_get_info();

  if (empty($available_view_modes)) {
    $entity_info = entity_get_info();
  //get the machine names of the view modes
    $view_modes_machine_names[] = array_keys($entity_info['node']['view modes']);
// get the labels (human readable) of the view modes
    foreach ($entity_info['node']['view modes'] as $key => $view_mode) {
      $view_modes_labels[] = $view_mode[label];
    }
  }
  // combine the machine view mode name with the label, this could sure be done much better?
  $entities_to_display = array_combine($view_modes_machine_names[0], $view_modes_labels);
  //output the form
  $form['view_mode'] = array(
    '#type' => 'select',
    '#description' => t("View modes."),
    '#options' => $entities_to_display,
    '#default_value' => !empty($conf['view_mode']) ? $conf['view_mode'] : 'full',
);

// Mikke Schirén @ https://digitalist.se/

erald’s picture

I solved it a bit differently because I wanted to have only the modes which are defined with the node type.

   // get view modes available for the node type. These are only machine names.
    $view_mode_settings = field_view_mode_settings('node', $node->type);
   //available_view_modes is the array to contain the avaible view modes
   $available_view_modes = array();
  //entity_get_info fetches the info of avaible view modes
	if (empty($available_view_modes)) {
		$entity_info = entity_get_info();
		// get the labels (human readable) of the view modes
		foreach ($entity_info['node']['view modes'] as $key => $view_mode) {
			if ($view_mode_settings[$key]['custom_settings'] == 1){
				$view_modes[$key] = $view_mode['label'];
			}
		}
	}

Then just use $view_modes in your form element.

Hope this helps someone.