How to programmatically import a block to existing view?
-
27-02-2021 - |
Question
I need to programmatically import a block to existing view with its settings.
I know how to export the whole view and import it programmatically. But I don't want to export whole view and then import whole view. In my view there is 25 blocks, so it gives me 4000 lines of code to import. I can copy export code only of my new block. But how to import only this part of code to the existing view? Is that possible? I can't find any solutions.
Solution
The indicated "block" you point out in the UI, is internally called a "display". Displays are stored inside the view object in the display
property (e.g. $view->display
).
If you look at the views export code you should see the pattern of exported blocks (e.g. /* Display: Block 1 */
, /* Display: Block 2 */
, etc.) that's rendered by the views::export()
method.
For each block (i.e. display) you should see the $handler = $view->new_display(...)
followed by many $handler->display...
lines that add the relevant fields/filters for that display.
To programmatically import a single display you would do something like the following:
$view = views_get_view('my_existing_view');
// @TODO: Add my new display handler code
$view->save();