Load CSS/Javascript in frontend conditionally if block is used

Assuming I have no unfinite scroll or anything else going on in my theme: Is there a way to enqueue my custom Gutenberg block styles and scripts so they are only (lazy) loaded in the frontend when the block is really used? Something like is_active_widget, just for blocks? If I enqueue them inside a enqueue_block_assets function they’re added to any site.

On github, I found this https://github.com/WordPress/gutenberg/issues/5445 , but it sounds like it’s more on bundling than conditional load, so I still hope they didn’t leave that optimization opportunity out – otherwise any other site will soon be junked with 20 additional scripts from numerous Gutenberg block plugins people install and only use once on a page (think of large image gallery block scripts for example).

Thanks & Regards!

Gutenberg InspectorControls is deprecated, how to add custom block settings?

How to add custom settings in the side panel that shows when a block is active? For example Paragraph block has “Text Settings” and “Custom Size” options, how can I add options to my custom block?

This tutorial: https://wordpress.org/gutenberg/handbook/designers-developers/developers/tutorials/block-tutorial/block-controls-toolbars-and-inspector/, says to use InspectorControls however that appears to be deprecated and does not work.

Here’s what I have so far:

( function( blocks, i18n, element ) {     var el = element.createElement;     var __ = i18n.__;     var ServerSideRender = window.wp.components.ServerSideRender;      blocks.registerBlockType( 'my-block/block', {         title: __( 'My Block', 'my-block' ),         icon: 'welcome-widgets-menus',         category: 'widgets',         attributes : {},         edit: function( props ) {             return [                 el( ServerSideRender, {                     block: "my-block/block",                     attributes:  props.attributes                 } )             ];         },         save: function() {             return null;         },     } ); }(     window.wp.blocks,     window.wp.i18n,     window.wp.element ) ); 

Thank you!

Print custom field in user edit form in block

Following code prints user edit form in block:

function notifikacie_custom_block_info() {  $  blocks['user_profile'] = array(    'info' => t('User profile edit'),    'cache' => DRUPAL_NO_CACHE,  );   return $  blocks; }  function notifikacie_custom_block_view($  delta = '') {   $  block = array();        global $  user;       module_load_include('inc', 'user', 'user.pages');       $  block['subject'] = t('Fill your profile');       $  block['content'] = drupal_get_form('user_profile_form', $  user);    return $  block; } 

But it does not print custom fields created in admin/config/people/accounts/fields. How do I print those custom fields?

Render Custom Menu Block from Menu Tree Array of Links Programmatically

Here’s what I have: A custom menu (side nav) that mimics the main/secondary menu tree which shows the entire subtree of the root menu item (Dine, Play, Stay) you’re under.

enter image description here

This sidenav can be shortened with a checkbox field in the content type. If checked, the sidenav shows the checked page as the root and all children, recursively, but omits any parents of the checked page. I’ve successfully created that menu and this all works on the checked pages.

enter image description here

This yields:

enter image description here

This is done by creating both menus, then adding a “hide” css class to one of them in the template_preprocess_page() function, depending on the checkbox of the current node.

MY ISSUE: The final thing I need it to do is when you are on a CHILD page of a parent with the shortened nav checked, I need it to still show that shortened nav. So on the example above, when on the Visitor FAQ page, it needs to show the shortened menu from Visitor Tips (with the current page bolded or whatever). So it needs to grab the field from the parent node, and if it is true, grab the shortened submenu array, which I’ve done, but I haven’t been able to render the menu tree array into html correctly.

Here’s the current code for grabbing the submenu (from the full menu), and it saves the menu array in $ alternateSecondaryMenu. I also tried saving in $ vars[‘secondary_nav’], which is the key Drupal uses for the rendered menu array, but I think the menu has already rendered by the time it calls preprocess_page(). I just can’t figure out how to render that menu tree. (The menu is 4 levels deep, level 0 being the root menu item, so this only happens on level 1 or level 2.)

In template.php:

function THEME_preprocess_page(&$  vars) {    // Follow active-trail and check if short/long menu is toggled   // ***********************************************************   if(!empty($  vars['secondary_nav'])) {      // Level 1     foreach($  vars['secondary_nav'] as &$  topmenuitem) { // for each top level item       if(!empty($  topmenuitem['#title'])) {          if(in_array('active-trail', $  topmenuitem['#attributes']['class'])) { // check if in active-trail (parent)            // load the node of the parent menu item           $  firstnid = str_replace('node/','',$  topmenuitem['#href']);           $  firstnode = node_load($  firstnid);            // check for shortened menu checkbox           if (array_key_exists('field_show_menu_as_parent',$  firstnode) && $  firstnode->field_show_menu_as_parent && $  firstnode->field_show_menu_as_parent['und'][0]['value']) {              dsm("1. YES, shortened menu.");              // Saving this submenu in these variables             $  vars['secondary_nav'] = $  topmenuitem; // this is the drupal-made array that shows the menu in question             $  alternateSecondaryMenu = $  topmenuitem; // just saving to some other variable, too.            } else {             dsm("1. NO shortened Menu for you!");           }            // Level 2 (same as level one)           foreach($  topmenuitem['#below'] as &$  secondmenuitem) {             if(!empty($  secondmenuitem['#title'])) {                             if(in_array('active-trail', $  secondmenuitem['#attributes']['class'])) {                 $  secondnid = str_replace('node/','',$  secondmenuitem['#href']);                 $  secondnode = node_load($  secondnid);                 if (array_key_exists('field_show_menu_as_parent',$  secondnode) && $  secondnode->field_show_menu_as_parent && $  secondnode->field_show_menu_as_parent['und'][0]['value']) {                   dsm("2. YES, shortened menu.");                                 $  vars['secondary_nav'] = $  secondmenuitem;                   $  alternateSecondaryMenu = $  secondmenuitem;                 } else {                   dsm("2. NO shortened menu for you!");                 }                              }             }           }                   }       }     }        }    dsm(drupal_render($  alternateSecondaryMenu));    // Only renders an <li> of the current node, not the <ul> or the children <li>, even though it has the whole menu tree.   dsm($  vars['secondary_nav']);    // doesn't render anything because this preprocess_page() is called after the elements of the page have already rendered, right? } 

I am using Panelizer to display and Menu Block to create the menu (only modules that ones that might be relevant).

Do I need to call the theme_menu_tree() and theme_menu_link() functions on this array again to render it, somehow? I wasn’t able to get render() or drupal_render() to work. Also tried doing this with menu_preprocessing/tree functions but was having difficulty getting the checkbox value in the nodes. Any ideas or help would be GREATLY appreciated.

Thanks!

Get defaultConfig block from repository

I have a several projects and want to share defaultConfig block in app gradle. Is it possible to get that from repository?

I published my project to artifactory.

api (group: 'com.cinemood', name: 'gradleconfiguration', version: '1.0.3', ext: 'aar') 

And want to use defaultConfig from it, not from app gradle.

defaultConfig {         versionCode versionMajor.toString()                 .concat(versionMinor.toString())                 .concat(versionBuild.toString()).toInteger()         versionName versionMajor.toString()                 .concat('.')                 .concat(versionMinor.toString())                 .concat('.')                 .concat(versionBuild.toString()     } 

How to get related product collection in block

I use this way to get collection

/**  * Prepare and return product collection  *  * @return \Magento\Catalog\Model\ResourceModel\Product\Collection  */ public function createCollection() {     /** @var $  collection \Magento\Catalog\Model\ResourceModel\Product\Collection */     $  myBlock = \Magento\Framework\App\ObjectManager::getInstance()->get('AntonStudio\StockUpdate\Block\RelatedProducts');      $  currentProduct = $  myBlock->getCurrentProduct();     $  relatedProducts = $  currentProduct->getRelatedProductCollection();     /**      * Prevent retrieval of duplicate records. This may occur when multiselect product attribute matches      * several allowed values from condition simultaneously      */     $  relatedProducts->distinct(true);      return $  relatedProducts; } 

and used it in template

<?php if ( $  exist = ( $  block->getProductCollection() && $  block->getProductCollection()->getSize() ) ): ?>     <?php     $  type = 'widget-product-grid';      $  mode = 'grid';      $  image = 'new_products_content_widget_grid';     $  items = $  block->getProductCollection()->getItems();      $  showWishlist = true;     $  showCompare  = true;     $  showCart     = true;     $  templateType = \Magento\Catalog\Block\Product\ReviewRendererInterface::DEFAULT_VIEW;     $  description  = false;      $  objectManager = \Magento\Framework\App\ObjectManager::getInstance();      $  _helper      = $  this->helper( 'Magento\Catalog\Helper\Output' );     $  _imagehelper = $  this->helper( 'Magento\Catalog\Helper\Image' );     ?>      <div class="block widget block-products-list <?= /* @noEscape */     $  mode ?>">         <?php if ( $  block->getTitle() ): ?>             <div class="block-title">                 <strong><?= $  block->escapeHtml( __( $  block->getTitle() ) ) ?></strong>             </div>         <?php endif ?>         <div class="block-content">             <?= /* @noEscape */             '<!-- ' . $  image . '-->' ?>             <div class="home-products-<?= /* @noEscape */             $  mode ?> <?= /* @noEscape */             $  mode ?>">                 <ol class="home-product-items <?= /* @noEscape */                 $  type ?>">                     <?php $  iterator = 1; ?>                     <?php foreach ( $  items as $  _item ): ?>                         <?php                         $  _product = $  objectManager->get( 'Magento\Catalog\Model\Product' )->load( $  _item->getId() );                         $  all_data = $  _product->getData();                          $  imageUrl = $  _imagehelper->init( $  _item, 'product_thumbnail_image' )->resize(300, 300)->getUrl();                         ?>                          <?= /* @noEscape */                     ( $  iterator ++ == 1 ) ? '<li class="product-item">' : '</li><li class="product-item">' ?>                          <div class="ProductListItem">                             <a href="<?= $  block->escapeUrl($  block->getProductUrl($  _item)) ?>" class="ProductListItem__imageWrap">                                 <img src="<?= $  imageUrl ?>"                                      class="ProductListItem__productImage">                             </a>                             <div class="ProductListItem__summaryWrap"> <!--                                <div class="ProductListItem__productSize">--><?//= isset($  all_data['tile_length_mm'])?$  all_data['tile_length_mm']:'' . ' * ' . isset($  all_data['tile_width_mm'])?$  all_data['tile_width_mm']:'' ?><!--</div>-->                                 <a href="<?= $  block->escapeUrl($  block->getProductUrl($  _item)) ?>" class="ProductListItem__productTitle">title<?= $  block->escapeHtml( $  _item->getName() ) ?></a>                             </div>                             <div class="ProductListItem__addToCartWrap">                                 <div class="ProductListItem__price">                                     <?= $  block->getProductPriceHtml( $  _item, $  type ) ?>/M2                                 </div>                                 <div class="ProductListItem__addToCartIcon">                                     <?php if ($  this->helper('Magento\Wishlist\Helper\Data')->isAllow() && $  showWishlist): ?>                                         <a href="#"                                            data-post='<?= /* @noEscape */ $  block->getAddToWishlistParams($  _item) ?>' class="action towishlist" data-action="add-to-wishlist" title="<?= $  block->escapeHtmlAttr(__('Add to Wish List')) ?>">                                             <span><?= $  block->escapeHtml(__('Add to Wish List')) ?></span>                                         </a>                                     <?php endif; ?>                                 </div>                             </div>                         </div>                         <?= ( $  iterator == count( $  items ) + 1 ) ? '</li>' : '' ?>                     <?php endforeach ?>                 </ol>             </div>             <?= $  block->getPagerHtml() ?>         </div>     </div> <?php endif; ?> 

But “$ block->escapeHtml( $ _item->getName() )” out put null

Module with block plugin not using custom template

I am struggling to get my custom module template to get use by by block plugin.

I have followed the solution given at: Twig Template for a Custom Block Plugin but continually get this error:

The website encountered an unexpected error. Please try again later. Twig_Error_Loader: Template “modules/custom/lrg_osm/templates/block–osmnhd.html.twig” is not defined in Twig_Loader_Chain->getCacheKey() (line 64 of themes/contrib/bootstrap/templates/block/block.html.twig). Drupal\Core\Template\TwigEnvironment–>getTemplateClass(“modules/custom/lrg_osm/templates/block–osmnhd.html.twig”) (Line: 424)

I have tried to also fiddle the name of the twig file in various ways to not avail.

My module file structure is shown below with relevant code if anyone is able to point out the error of my ways please:

File and folder structure

src/Plugin/Block/osmnhdblock.php

<?php declare(strict_types=1);  namespace Drupal\lrg_osm\Plugin\Block;  use Drupal\Core\Block\BlockBase; use Drupal\Core\Block\BlockPluginInterface;  /**  * Provides a 'OSM Block for Home development Landing page' block.  *  * @Block(  *   id = "osmnhdblock",  *   admin_label = @Translation("OSM New Homes Development (NHD) block"),  *   category = @Translation("LRG")  * )  */ class OsmNhdBlock extends BlockBase implements BlockPluginInterface {     /**      * {@inheritdoc}      *      */     public function build()     {         return array(             '#theme' => 'osmtheme',             '#jsonDataLocations' => 'nhd some data',             '#title' => 'nhd some title',         );          /*          '#attach' => [                 'css' => '/css/openstreetmap.css',                 'js' => '/js/openstreetmap.js',             ],          */     } } 

lrg_osm.module

<?php declare(strict_types=1);  function lrg_osm_theme($  existing, $  type, $  theme, $  path) {      return array('osmtheme' =>         array(             'variables' => array(                 'title' => null,                 'jsonDataLocations' => null             ),             'template' => 'block--osmnhd'         )     ); } 

templates/block–osmnhd.html.twig

{# /**  * @file  * Some description  */ #} <div class="col-md-12 block--osmnhdmap">     <h1>{{ title }}</h1>     <h2>{{ jsonDataLocations }}</h2> </div>