0

I can load a ViewExecutable and create a new Display programmatically:

$view = Views::getView('existing_view');
$display = $view->newDisplay('page', 'New page', 'page_2');

But how can I update the settings for the new display programmatically?

The display is an instance of \Drupal\views\Plugin\views\display\Page but I can't see any way of saving options to it.

The setOption method exists, but how can persist the options to storage?

3

Answering my own question: The settings are not made on the display, but on the handler.

$view = Views::getView('existing_view');
$display = $view->newDisplay('page', 'New page', 'page_2');

// ViewExecutable::setHandlerOption($display_id, $type, $id, $option, $value)
$view->setHandlerOption('page_2', 'argument', 'nid', 'admin_label', 'Foo');
$view->save();

Options and values correspond to the values in a View YAML config file, under display_options.

Important is that you find out the correct $type argument.

I had a look at the array keys returned from ViewExecutable::getHandlers.

  • "field"
  • "argument"
  • "sort"
  • "filter"
  • "relationship"
  • "header"
  • "footer"
  • "empty"
| improve this answer | |
  • 1
    Yes, but most times it's easier to update the settings in $view->storage directly (this is the config entity of the view), see for example api.drupal.org/api/drupal/… – 4k4 Feb 12 '18 at 12:52
  • Was just looking at that: it's the only way to update the path, AFAICS. The interface seems a bit lacking – there's no "setter" method. You get the array by reference, change it, and call save. – Tim Feb 12 '18 at 13:13
  • Having the display settings in an array is IMHO much easier, and the example shows that even the Views module is using this method. – 4k4 Feb 12 '18 at 13:16
  • Not saying it doesn't work. Accessing a public property to update an entity just feels unusual. – Tim Feb 12 '18 at 13:18
  • Good point, but in Views there are a lot of things not fully object-oriented yet. – 4k4 Feb 12 '18 at 13:30

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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