0

I have two content types, Brand and Sector. Brand have a sector field which is an Entity reference field.

I have views that display the list of Brands and it has a sector contextual filter which displayed as an input field where you have to input a node ID.

I was trying to make it a dropdown with sector titles for a user friendly experience but wasn't able to achieve this in views. So I decided to alter the views form but it seems like that it's not working the same as in D7.

What's the right way to alter the views field or is there a way to render a field as dropdown using views?

4
  • did you managed to make the field dropdown?
    – iamroald
    Commented Aug 20, 2016 at 8:46
  • Unfortunately I didn't, otherwise I'd post my answer here. Commented Aug 22, 2016 at 14:27
  • You can't exposed it as dropdown filter if its textfield, you have to alter the field type itself, to make it dropdown.
    – iamroald
    Commented Aug 22, 2016 at 14:55
  • In "Manage form display" section I've set the "Select list" widget. So when I edit the node, I see the dropdown. But in the view, I exposed this field as a "Single filter" and it's displayed as a text field. If is choose "Grouped filters", it does rendered as a dropdown but it's an empty list. Commented Aug 23, 2016 at 11:16

1 Answer 1

0

OK, I managed to achieve this by implementing hook_form_FORM_ID_alter() in my mytheme.theme file.

/**
 * Implements hook_form_FORM_ID_alter().
 */
function mytheme_form_views_exposed_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state) {
  if ($form['#id'] == 'my-views-exposed-form-id') {
    $query = db_select('node_field_data', 'n')
      ->fields('n', array('nid', 'title'))
      ->condition('type', 'sector')
      ->condition('status', 1)
      ->orderBy('title', 'ASC');
    $options = $query->execute()->fetchAllKeyed();

    // $form['sector'] is a type text, changing it to select.
    $form['sector'] = array(
      '#type' => 'select',
      '#options' => array('' => t('Filter by Sector')->render()) + $options
    );
  }
}

Hope it will help someone.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.