Novice

Create a block programatically in Drupal 8

​​block_example.PNG

Basic creation of a block in Drupal 8. As seen in the image on the left, a predefined library structure is needed to create a block plugin.

The annotations plugin is used to handle the block id, subject and admin label from within the comment block. The annotation class is found at core/lib/Drupal/Component/Annotation/Plugin.php.

Reinstall Drupal 8

Reinstalling a Drupal 8 site can't be bruteforced as in Drupal 7 where dropping all tables in the database is enough to reinstall a site.

One of the reasons why just dropping tables in the database isn't enough is that the config directory (e.g. sites/default/files/config_somehashkey) needs to be deleted.

Check if taxonomy term exists and save the term if it doesn't

A dynamic query can be used to check if a taxonomy term exists.

Query conditions are the taxonomy term name and the vocabulary.

Create a form


/**
 * Implements hook_form().
 */
function MY_CUSTOM_FORM_form($node, &$form_state) {
  $form = array();
   
  $form['CUSTOM_FIELD'] = array(
    '#type' => 'textfield',
    '#label' => 'MY_LABEL',
  );
   
  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Submit')
  )
   
  return $form;
}
 
/**
 * MY_CUSTOM_FORM validation handler.
 */
function MY_CUSTOM_FORM_form_validate($node, &$form_state) {
   
}
 
/**
 * MY_CUSTOM_FORM submit handler.
 */
function MY_CUSTOM_FORM_form_submit($node, &$form_state) {
   
}

Load all nodes by type


  $nids = db_select('node', 'n')
  ->fields('n', array('nid'))
  ->condition('n.type', 'NODE_TYPE')
  ->execute()->fetchCol();
  
  $nodes = node_load_multiple($nids);


 

Create and update database fields by using hook_update_N

Db_add_field() can be used in hook_update_N() to add fields to a database table. Always remember to add the field to hook_schema() to allow entities to properly read the table. Also, this is needed to properly install the module in other projects or to reinstall the module in the current project, mostly in the development fase. 

Bulk create menu lnks


$items = array(
    array(
      'link_path' => '<front>',
      'link_title' => 'TITLE',
      'menu_name' => 'footer-menu',
    ),
    array(
      'link_path' => '<front>',
      'link_title' => 'TITLE',
      'menu_name' => 'footer-menu',
    ),
    array(
      'link_path' => '<front>',
      'link_title' => 'TITLE',
      'menu_name' => 'footer-menu',
    ),
    array(
      'link_path' => '<front>',
      'link_title' => 'TITLE',
      'menu_name' => 'footer-menu',
  );
 

Performance - using the bootstrap timer functions

Use timer_start(), timer_read() and timer_stop() to measure code performance

These practical and easy to use performance measuring functions can be found in the bootstrap.inc file, provided by Drupal core. The same timer can be started and stopped multiple times, the measured intervals will be accumulated.

Pages

Subscribe to RSS - Novice