Suggested Topics Flashcards

1
Q

[Security] SQL : Example

A

db_query(“INSERT INTO {video_files} (fid, status, dimensions) VALUES (%d, %d, ‘%s’)”, $video[‘fid’], VIDEO_RENDERING_PENDING, $video[‘dimensions’]);

%d for integer values and %s for string values. You can also use %f for a floating point value, %b for binary data and %% just to insert a percent symbol

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

3 aspects of hook_initi()

A

Cached page doesn’t run this hook
When this hook is called, all modules are already loaded in memory
It happens after bootstrap mode

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

3 aspects of hook_boot()

A

Even cached page executes this hook
This hook is called before modules or most include files are loaded into memory.
It happens while Drupal is still in bootstrap mode.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

[CSS] CSS selector precedence.

A

Precedence is evaluated according to these rules:
Inline CSS takes precedence over any other CSS (outdated form of styling, typically still used in email templating).
More specific selectors take precedence over less specific ones.
ID selectors take precedence over class selectors.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

[jQuery] Drupal specific jQuery code sample what will execute only once for each page.

A
$('#some_element', context).once('mybehavior', function () {
  // Code here will only be applied to $('#some_element')
  // a single time.
});
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

[Library] Including the jQuery library in a page.

A

Include the jQuery library in a page
Use a preprocess function to attach like
[‘#attached’][‘#library’][] = ‘mytheme/mylibraryname’;

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

[Git] Squashing multiple git commits into one commit while rebasing.

A

git rebase -i master

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

[Git] Committing all changes made inside a directory.

A

git add .

git commit -m “Commit message.”

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

[PHP] Abstract class.

A

PHP 5 introduces abstract classes and methods. Classes defined as abstract may not be instantiated, and any class that contains at least one abstract method must also be abstract. Methods defined as abstract simply declare the method’s signature - they cannot define the implementation.

abstract class AbstractClass
{
class ConcreteClass1 extends AbstractClass
{
class ConcreteClass2 extends AbstractClass
{

$class1 = new ConcreteClass1;
$class1->printOut();
echo $class1->prefixValue(‘FOO_’) .”\n”;

$class2 = new ConcreteClass2;
$class2->printOut();
echo $class2->prefixValue(‘FOO_’) .”\n”;

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

[Theming] hook_preprocess_hook()

A

Twig renders everything automatically so there is no need to call drupal_render() or theme() within a preprocess function. Instead, render arrays should be passed to the template since this allows for much more customization than an already-rendered HTML string.

// Drupal 8 - passing a render array to the template.
$variables['table'] = [
  '#theme' => 'table',
  '#header' => $header,
  '#rows' => $rows,
];
// Before, unnecessary call to drupal_render().
$variables['teaser'] = drupal_render($node_teaser);
// After, with drupal_render() removed.
$variables['teaser'] = $node_teaser;
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

[Theming] Difference between hook_preprocess_html() and template_preprocess_page(&$variables)

A

mytheme_preprocess_page(&$vars) {
$vars[‘variable’] = ‘string’; // $variable will be available in page.tpl.php
}

mytheme_preprocess_html(&$vars) {
$vars[‘variable’] = ‘string’; // $variable will be available in html.tpl.php
}

mytheme_preprocess_custom_theme_function(&$vars) {
$vars[‘variable’] = ‘string’; // $variable will be available in the template you specified in mymodule_theme() (custom-theme-template.tpl.php)
}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

[Theming] Theme template suggestion

A

You enable Twig Debugging in sites/default/services.yml.

parameters:

twig. config:
debug: true

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

[Coding standard] What goes between “namespace” and “use” statements

A

Empty line between “namespace” and “use” statements

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

[API] Custom code that is going to execute after node insert

A
use Drupal\node\Entity\Node;
/**
 * Implements hook_ENTITY_TYPE_insert().
 */
function mymodule_node_insert(Node $node) {
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

[API] Custom code that is going to execute after node delete

A

hook_ENTITY_TYPE_delete

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

[API] Watchdog logging

A
hook_watchdog() is gone. For a module to implement a logger, it has to register a service tagged as logger. eg
services:

logger.mylog:
class: Drupal\mylog\Logger\MyLog
tags:
- { name: logger }

This class must implement \Psr\Log\LoggerInterface. like this:

namespace Drupal\mylog\Logger;

use Drupal\Core\Logger\RfcLoggerTrait;
use Psr\Log\LoggerInterface;

class MyLog implements LoggerInterface {
  use RfcLoggerTrait;
  /**
   * {@inheritdoc}
   */
  public function log($level, $message, array $context = array()) {
    // Do stuff
  }

}

D8 - procedural

// Logs a notice
\Drupal::logger(‘my_module’)->notice($message);
// Logs an error
\Drupal::logger(‘my_module’)->error($message);

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

[API] Block annotation

A

Creating a custom block defined by your module involves the following steps:

Create a block plugin using annotations
Extend the Drupal\Core\Block\BlockBase class.
Implement the methods from the Drupal\Core\Block\BlockPluginInterface interface needed for your use case.

namespace Drupal\fax\Plugin\Block;

use Drupal\Core\Block\BlockBase;

/**
 * Provides a 'Fax' block.
 *
 * @Block(
 *   id = "fax_block",
 *   admin_label = @Translation("Fax block"),
 * )
 */
class FaxBlock extends BlockBase {
  // Override BlockPluginInterface methods here.
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q

[API] Retrieving settings using the configuration API

A

Reading configuration
Configuration is read using the get() method. This can be used in several ways. To read a piece of configuration, just provide its key.

$config = \Drupal::config(‘system.maintenance’);
$message = $config->get(‘message’);
Calls to \Drupal::config() can also be chained.

$message = \Drupal::config(‘system.maintenance’)->get(‘message’);
To read nested configuration, separate the keys with the ‘.’ character.

$enabled = \Drupal::config(‘system.performance’)->get(‘cache.page.enabled’);
You can read configuration at any level, if there is configuration nested underneath your level, it will be returned as an array.

$page_cache = \Drupal::config(‘system.performance’)->get(‘cache.page’);
This would return an array with two keys - ‘enabled’ and ‘max_age’.

To return all the data in a config object, just call get() with no arguments.

Also, you can return all configuration keys available on the system or just those keys starting with a particular substring ($prefix).

$keys = \Drupal::service(‘config.factory’)->listAll($prefix = “”);

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
19
Q

[Tests] Choosing the right base class

A

Drupal 8 comes with various automated testing options to choose from. Most of those are part of core testing framework.

  1. Unit tests
  2. Kernel tests
  3. Functional tests

It is also possible to use external framework like behat with scenarios in gherkin syntax. Read more about different types of testing in core here.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
20
Q

[Security] SQL injection

A

db_query(“INSERT INTO {video_files} (fid, status, dimensions) VALUES (%d, %d, ‘%s’)”, $video[‘fid’], VIDEO_RENDERING_PENDING, $video[‘dimensions’]);

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
21
Q

[Caching] Cache context and cache tag (hard)

A

The service ID is standardized. It always begins with cache_context., followed by the parents of the cache context, finally followed by the name of the cache context. So, for example: cache_context (mandatory prefix) + route (parents) + book_navigation (this cache context’s name):

cache_context.route.book_navigation:
class: Drupal\book\Cache\BookNavigationCacheContext
arguments: [‘@request_stack’]
tags:
- { name: cache.context }
This defines the route.book_navigation cache context.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
22
Q

[Caching] Dynamic page caching

A

Drupal 8 provides the Dynamic Page Cache module that is recommended for websites of all sizes. It caches pages minus the personalized parts, and is therefore useful for all users (both anonymous & authenticated).

Disabling while developing
In example.settings.local.php, this section can be found:

/**
* Disable Dynamic Page Cache.
*
* Note: you should test with Dynamic Page Cache enabled, to ensure the correct
* cacheability metadata is present (and hence the expected behavior). However,
* in the early stages of development, you may want to disable it.
*/
# $settings[‘cache’][‘bins’][‘dynamic_page_cache’] = ‘cache.backend.null’;
Uncomment the commented-out line to disable the dynamic page cache. But please do pay attention to the comment!

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
23
Q

[Views] Contextual parameters

A

Contextual Filters in Drupal 8 are similar to the Drupal 7 with advance feature and more dynamic compared to normal filter. A Contextual Filter provides more convenient way to fetch the data either from variables sent programmatically or URL.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
24
Q

Configuration update for an existing module

A

If your module is making a data model change related to configuration, then you need to properly update your data model. The four steps are:

Update your configuration schema YML file so that it reflects your new data model. This will make sure that people that install your module after you made the change will get the correct schema. See the Configuration Schema documentation for details on that.
Make sure any configuration items provided by your module in the config/install and config/optional directories have been updated, so that people installing your module will get correct configuration.
Write a hook_update_N() function. This will update configuration items for existing users of your module who already had it installed before you made the change so that they can continue to function. This is described below.
Write tests to ensure the code in your hook_update_N() correctly modifies the configuration. This will make sure that people who have an older version of your module installed can successfully update to the new version. See https://www.drupal.org/docs/8/api/update-api/writing-automated-update-tests-for-drupal-8 for details.

/**
* Add fruit to the default configuration for example.module.
*/
function example_update_8001() {
$config_factory = \Drupal::configFactory();
$config = $config_factory->getEditable(‘example.configuration’);
$config->set(‘fruit’, [‘apple’, ‘banana’, ‘mango’]);
$config->save(TRUE);
}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
25
Q

Multilingual blocks and menus

A

To translate custom block/menu content try the follwing:

Install and enable your desired languages in Admin > Config > Regional and Language > Languages
Enable the content translation module
Go to Admin > Config > Regional and language > Content language and translation
Select under Custom language settings the option ‘Custom block’
Select all options in the newly added page section ‘Custom block’
Go to Structure > Block lay-out > Custom block library
Select in the column ‘operations’ the option ‘translate’
You should get a page ‘Translations of [block-name]’ with the currently enabled languages
Click add in the column ‘operations’ to create a translation of the block

for views:

1) Go to Structure > View (domain.com/admin/structure/views)
2) Select the view you want to create and instead of clicking edit, click the arrow for the the dropdown menu and click “translate”.
3) Add translations for each language.
4) When you are adding each language, make sure you add the menu item translation in the subsettings below view title: DISPLAYS > PAGE DISPLAY SETTINGS > PAGE DISPLAY OPTIONS.
5) Click SAVE TRANSLATION.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
26
Q

Setting up entity specific commenting

A

Commenting is a field

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
27
Q

Structure of a *.info.yml file

A

name: Hello World Module
description: Creates a page showing “Hello World”.
package: Custom

type: module
core: 8.x

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
28
Q

Structure of a *.routing.yml file (book example)

A

book.routing.yml

Each route is defined by a machine name, in the form of module_name.route_name.
#
book.render:
# The path always starts with a leading forward-slash.
path: ‘/book’
# Defines the default properties of a route.
defaults:
# For page callbacks that return a render array use _controller.
_controller: ‘\Drupal\book\Controller\BookController::bookRender’
# Require a permission to access this route.
requirements:
_permission: ‘access content’

book.export:
# This path takes dynamic arguments, which are enclosed in { }.
path: ‘/book/export/{type}/{node}’
defaults:
# Because this route does not return HTML, use _controller.
_controller: ‘\Drupal\book\Controller\BookController::bookExport’
requirements:
_permission: ‘access printer-friendly version’
# Ensure user has access to view the node passed in.
_entity_access: ‘node.view’
options:
# Enable the admin theme for this route.
_admin_route: TRUE

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
29
Q

hook_theme()

A
Step #1: Define hook_theme in .module file
Create a [module].module file if it doesn't already exist, and add code that defines each of your twig templates. The key of each item in the array is what you will need to call the template later. Do not use dashes in the file name.

function test_twig_theme($existing, $type, $theme, $path) {
return [
‘my_template’ => [
‘variables’ => [‘test_var’ => NULL],
],
];
}

Step #2: Call the Template
In the place where you are returning your render array (whether from a controller method that is called from your router yml file, or wherever), make a call to your twig template. Below is an example from a testing module that is called from the routing yml file in the module. (need more info on this part)

/**

  • @file
  • Contains \Drupal\test_twig\Controller\TestTwigController.
  • /

namespace Drupal\test_twig\Controller;

use Drupal\Core\Controller\ControllerBase;

class TestTwigController extends ControllerBase {
  public function content() {
return [
  '#theme' => 'my_template',
  '#test_var' => $this->t('Test Value'),
];

}
}

Step #3: Create Twig Template
In your module, inside of the templates folder, create your twig template. The name of the file has to match what you put into hook_theme() (replace underscores with dashes). In this case, the file name would be my-template.html.twig.
Here is the file I used to test:

<p>Test twig template!</p>

<p>test_var: {{ test_var }}</p>

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
30
Q

passing variables by reference

A

Sometimes it’s useful to pass arguments by reference, so that changes made by actions also apply to the arguments of the calling code later on. To make this possible, rules supports passing arguments to rules in a array.

So the example

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
31
Q

The difference between dynamic queries and static queries

A

for static:

$select = db_query(‘SELECT field1, field2 FROM {table_one} t1 INNER JOIN {table_two} t2 ON t1.id = t2.id INNER JOIN {table_three} t3 ON t3.tbl_three_id = pcl.tbl_three_id’);
for dynamic:

$select = db_select(‘table_one’, ‘t1’);
$select->join(‘table_two’, ‘t2’, ‘t2.id = t1.id’);
$select->join(‘table_three’, ‘t3’, ‘t3.tbl_three_id = t2.tbl_three_id’);
$select = $select->fields(‘t1’, array(‘field1’, ‘field2’));
$select = $select->execute();

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
32
Q

static queries

A

for static:

$select = db_query(‘SELECT field1, field2 FROM {table_one} t1 INNER JOIN {table_two} t2 ON t1.id = t2.id INNER JOIN {table_three} t3 ON t3.tbl_three_id = pcl.tbl_three_id’);
for dynamic:

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
33
Q

Drupal Behaviours work

A

Behaviors:
Drupal’s official JavaScript documentation suggests that modules should implement JavaScript by attaching logic to Drupal.behaviors. Here is an example taken from that page:

Drupal.behaviors.exampleModule = {
  attach: function (context, settings) {
    $('.example', context).click(function () {
      $(this).next('ul').toggle('show');
    });
  }
};

Drupal core will call attached behaviors when the DOM (the object representation of the HTML) is fully loaded, passing in two arguments:

context: which contains the DOM.
settings: which contains all the settings injected server side.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
34
Q

Search Index - View Modes

A

Content bundle option in the view modes

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
35
Q

Multi-site folder structure

A
    • sites
      • site1
          • modules
            • custom
            • contrib
          • themes
            • custom
            • contrib
          • files
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
36
Q

t() method

A

Firstly, t() translates text at runtime if you have more than one language enabled. Depending on which placeholder you use, it runs different sanitization functions.

$good = t(‘Read about the t() function <a>here</a>’, array(‘@api’ => ‘https://api.drupal.org’));

$username . “‘s “ . t(‘Homepage.’);

t(‘Homepage de @user.’, array(‘@username’ => ‘Bob’));

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
37
Q

2 on menu translation

A

If you go to /admin/config/regional/content-language and choose “Custom Menu Link”

38
Q

designation pages to particular languages

A

Content type configuration provides dropdown for type specific language

39
Q

Twig submitted

A

<p>{{ submitted }}</p>

40
Q

Twig submitted by/on

A

<p>Submitted by {{ author }} on {{ date }}</p>

41
Q

Twit Submitted + translation

A
<p class="submitted">
{% trans %}
  Submitted by {{ author.username }} on {{ node.created }}
{% endtrans %}
</p>
42
Q

Twig - adjust a variable, and then

A

{% set date = node.created|format_date(‘medium’) %}
{% trans %}
Node was created on {{ date }}.
{% endtrans %}

43
Q

Plural translations

A

{% set count = comments|length %}
{% trans %}
{{ count }} comment was deleted successfully.
{% plural count %}
{{ count }} comments were deleted successfully.
{% endtrans %}

44
Q

Placeholder Equivalents - code

A
{% set string = '&amp;"<>' %}
<div>
  {% trans %}
    Escaped: {{ string }}
  {% endtrans %}
</div>
<div>
  {% trans %}
    Pass-through: {{ string|passthrough }}
  {% endtrans %}
</div>
<div>
  {% trans %}
    Placeholder: {{ string|placeholder }}
  {% endtrans %}
</div>
45
Q

Placeholder Equivalents - @ ! %

A

By default, all Twig variables detected in the {% trans %} tag are sent with the @ prefix so they can escaped safely. If the value of that variable needs to be passed through (!) or used as a placeholder (%), modify the variable with these following Twig filters |passthrough and |placeholder:

function MYMODULE_form_alter(&amp;$form, &amp;$form_state, $form_id) {
  if ($form_id == 'some_form') {
    $form['some_element']['#attributes']['placeholder'] = t('Placeholder text');
  }
}
46
Q

Language Options

A

{% trans with {‘context’: ‘Long month name’, ‘langcode’: ‘fr’} %}
January
{% endtrans %}

47
Q

(too broad) How to override templates and write preprocess functions, including how to figure out the possible names for templates based on the specificity you want, and which template names take priority when overriding. You should also know how to change the possible name suggestions for a template.

A

Learn

48
Q

How to create a base theme, including understanding the differences in the included core themes: Stable, Class, Stark, and Bartik.

A
Bartik (our trusty default theme)
Classy (new!)
Seven (still the admin theme for D8)
Stable (what’s this?)
Stark (basically the same as in D7)
The interesting two that you’ll notice are Classy and Stable. These don’t show up on our ‘Appearance’ page like the other themes (this is because they are set to be ‘hidden’ in their .info.yml file). Instead, they’re meant to be used as base themes when you build a custom theme.

In fact the ‘stable’ theme is the de facto base theme for Drupal 8. Even if you don’t tell Drupal you want to use it as the base theme, it will be used automatically.

The ‘classy’ theme is the base theme to use if you want to start with a version of Drupal core with more classes. For example, if you want to have body classes available that indicate whether the current user is logged in, whether the current page is the front page, and what the current language of the site is, then classy is the theme for you. If your theme name is mytheme, you’d add the following in mytheme.info.yml:

49
Q

How to create URL routes in a routing.yml file that point to controller and form classes.

A

example.content:
path: ‘/example’
defaults:
_controller: ‘\Drupal\example\Controller\ExampleController::content’
custom_arg: 12
requirements:
_permission: ‘access content’

50
Q

Javascript and jQuery:
Review the jQuery Api docs for examples of jQuery methods. For example: .filter, $( document ).ready() and some other methods.

A

jQuery methods

.filter() - Reduces the set of matched elements. Takes a selector or a function as an argument.

51
Q

Content Types and fields:

A

The base configuration of a content type defines the default behaviour and properties of the content type.

52
Q

How to start a site with a new default language

A

Selectable option in the install process

53
Q

Web Services:

A

Web services are now included as a part of Drupal core. After enabling the RESTful web services you can expose entities and other resources as RESTful web API.

54
Q

CSS file structure

A
base (f)
 - elements (body, h1, ul etc)
component (f)
 - block
 - field
layout (wrapper, container)
55
Q

Twig: Print Variable:

A

{{ Say Something }}

56
Q

Twig: For conditions and extending other twig files

A

{% Do Something %}

57
Q

Twig: Add comments

A

{# Comments #}

58
Q

Base Class

A

name();
$obj->price();
?>

59
Q

Abstract Class

A

Abstract Classes:

An abstract class is a class that contains at least one abstract method. The abstract method is function declaration without anybody and it has the only name of the method and its parameters.
There can be any number of methods in the class and we have to declare the class as abstract only when there is an abstract method

Example for Abstract class

';
    }
    public  function getPrice() {
      return 720000 . '<br>';
    }
}
class Santro extends Cars {
    public function getCompanyName() {
        return "Hyundai" . '<br>';
    }
    public function getPrice() {
        return 300000 . '<br>';
    }
}
$car = new Baleno();
$car1 = new Santro();
echo $car->getCompanyName();
echo $car->getPrice();
echo $car1->getCompanyName();
echo $car1->getPrice();
60
Q

Interface

A

INTERFACES:

An interface is a description of the actions that an object can do.
Interface is written in the same way as the class the declaration with interface keyword.
Rules of Interfaces:
All methods declared in an interface must be public; this is the nature of an interface.
All methods in the interface must be implemented within a class; failure to do so will result in a fatal error.
The class implementing the interface must use the exact same method signatures as are defined in the interface
Interfaces can be extended like classes using the extends operator.
Example for the interface class
x = $x;
    }
    public function description() {
        echo 'Describing' . $this->x . tree;
  }
}
$Mango = new Mangoes();
$Mango->setProperty(mango);
$Mango->description();
61
Q

Query Debugging - Analyse queries

A

$query = $this->entity_query->get(‘node’);
$query->condition(‘status’, NODE_PUBLISHED);
$query->addTag(‘debug’);
$query->execute();

62
Q

Add this - form mode manager

A

https://www.drupal.org/docs/8/modules/form-mode-manager/tutorials

63
Q

Demonstrate ability to build RESTful web application using core Web Services capabilities

A

Build RESTful web application using core Web Services capabilities
https://drupalize.me/blog/201402/your-first-restful-view-drupal-8
REST (Representational state transfer)
Using views (GET only):
Create a view with a display as ‘REST export’
Give it a path
Select a format: JSON (default), HAL, and XML
Display fields or entities. If entities it’ll display entire serialized node object
Change row styles for different labels

64
Q

core.entity_view_mode.node.full.yml

A

uuid: 15dc7aa9-13fd-4412-9c06-06d09f915d08
langcode: en
status: false
dependencies:
module:
- node
id: node.full
label: ‘Full content’
targetEntityType: node
cache: true

65
Q

targetEntityType

A

The main property to take note of is the “targetEntityType” property. Each display mode (view mode or form mode) is associated with one, and only one, type of Content Entity. By convention there are labels that get used for multiple display modes. For instance, Drupal Core’s standard profile uses the word “Full” in the labels of view modes for the content entity types of node, custom blocks and comments.

66
Q

View modes and view displays

A

Administered in aggregate at: /admin/structure/display-modes/view
Enabled per bundle under “Custom display settings” at urls like: /admin/structure/types/manage/page/display (where ‘page’ is a bundle of the node entity)
Configured per view mode per bundle at urls like: /admin/structure/types/manage/page/display/teaser (where ‘page’ is a bundle of the node entity and ‘teaser’ is a view mode)

like teasers, full, etc

67
Q

“RSS” and “Teaser”

A

view modes for bundles

The association between an entity type bundle and view mode is called a View Display. @see EntityViewDisplayInterface

68
Q

Form Mode

A

Administered in aggregate at: /admin/structure/display-modes/form

Enabled per bundle at urls like: /admin/structure/types/manage/page/form-display (where ‘page’ is a bundle of the node entity)

Configured per form mode per bundle at URLs like: /admin/structure/types/manage/page/form-display/simple (where ‘page’ is a bundle of the node entity and ‘simple’ is a form mode).

69
Q

Like view modes, form modes are:

A

Form modes are a way to create different field configurations with the same content entity bundle. Form modes allow for multiple sets of field widget orderings and customizations, just as view modes allow for different orderings and customization of field formatters.

70
Q

In addition to form modes, form operations allow for:

A

Form operations allow for defining which classes should be used for forms like a node delete form. The class used to delete a node is different from the class used to edit a node. Operations are defined in an entity’s

71
Q

example that will map 2 custom form operations, as well as the “default” form mode

A

/**

  • @ContentEntityType(
  • id = “myentity”,
  • handlers = {
  • “form” = {
  • “default” = “Drupal\myentity\Form\MyEntityForm”,
  • “add” = “Drupal\myentity\Form\MyEntityForm”,
  • “edit” = “Drupal\myentity\Form\MyEntityForm”,
  • “delete” = “Drupal\myentity\Form\MyEntityDeleteForm”,
  • },
  • },
  • )
  • /
72
Q

To display a form with a custom form mode, use _entity_form in your route. For example, to display the custom “edit” form of the MyEntity, use this route:

A

entity.myentity.edit_form:
path: ‘/myentity/{myentity}/edit’
defaults:
_entity_form: myentity.edit
_title: ‘Edit MyEntity’
requirements:
_permission: ‘edit myentity entities’

73
Q

Lots of Drupal users/developers ask how to have only a few fields display on the Registration but the rest display on the user profile and user edit pages. Display Mode to the rescue.

A

Click Add Field from /admin/config/people/accounts/fields
Next screen select a field type, List(Text)
Give it a Label, Subscription List
Click Save and continue
Fill out the Allowed values list for example
1|News
2|Important Announcements
3|Offers, Discounts, Specials
4|Partner Messages
Click Save
Make it a Required field
Select All four items as default, click save.
Next Click the Manage form Display tab (/admin/config/people/accounts/form-display)
At the bottom of the field list is “Custom Display Settings”, cilck it
There’s a Register form mode already made for the Registration page. Enable it. Click Save.
(If you had more User display forms you’ll see them here.)
Now you’ll have a second tab menu labeled Default and Register. This is where the magic happens.
Disable the Subscription List field using drag and drop. Click save.
Next go to the Manage Display tab to make sure that the Subscription List field is enabled.

74
Q

DrupalSettings

A

drupalSettings
Pass server side values to javascript via the core/drupalSettings asset library. Through a hook like hook_page_attachments_alter() you can add:
$page[‘attached’][drupalSettings’][‘mydynamicvalue’] = ‘value’;

75
Q

1.4 Demonstrate knowledge of Responsive Design concepts
A front-end specialist should have an understanding of the principles of responsive design. Drupal 8 uses a responsive “Mobile First” approach out of the box.

What are responsive design and mobile first concepts
Responsive design scales with breakpoints and adaptive has distinct layouts. Mobile first is you design the mobile layout first and build upon that with breakpoints.

How to apply responsive design in your stylesheets and themes
Include [theme].breakpoints.yml - labels and media queries go in here

For responsive images
/admin/config/media/responsive-image-style
enable the Responsive Images module (requires breakpoint module enabled by default)
Config > responsive image mapping: and select image styles for each breakpoint
Apply the mapping structure > content types > [type] > manage display and choose responsive image mapping for an image

A

1.4 Demonstrate knowledge of Responsive Design concepts
A front-end specialist should have an understanding of the principles of responsive design. Drupal 8 uses a responsive “Mobile First” approach out of the box.

What are responsive design and mobile first concepts
Responsive design scales with breakpoints and adaptive has distinct layouts. Mobile first is you design the mobile layout first and build upon that with breakpoints.

How to apply responsive design in your stylesheets and themes
Include [theme].breakpoints.yml - labels and media queries go in here

For responsive images
/admin/config/media/responsive-image-style
enable the Responsive Images module (requires breakpoint module enabled by default)
Config > responsive image mapping: and select image styles for each breakpoint
Apply the mapping structure > content types > [type] > manage display and choose responsive image mapping for an image

76
Q

Understand the use of media queries in a responsive site

A

Understand the use of media queries in a responsive site
width - the width of the viewport
device-width - the width of the output device
Making page responsive
Include meta data

this will account for devices like iPhone 4 which have 2px per 1 css px.
Target a media type or comma-delimited types
@media screen { … }
options: print, screen, speach
Target media features
@media (max-width: 12450px) { … }
Use and to combine
@media (min-width: 30em) and (orientation: landscape) { … }
Use commas to represent or states
@media (min-height: 680px), screen and (orientation: portrait) { … }
Also you can use not and only

77
Q

Demonstrate ability to define and use custom regions in a theme

A

Demonstrate ability to define and use custom regions in a theme
Resources:
https://www.drupal.org/docs/8/theming-drupal-8/adding-regions-to-a-theme
https://api.drupal.org/api/drupal/core%21themes%21classy%21templates%21layout%21page.html.twig/8.1.x

Define a custom region
Add to your .info file THEMENAME.info.yml:
regions:
header: ‘Header’

includes the theme name and base theme, regions (as soon as you define this, however, it overrides the core regions so make sure to add them) etc.

Print region in proper template
In page.html.twig:
{{ page.header }}

Create conditional display logic to print regions
{% if page.sidebar_first %}

{{ page.sidebar_first }}

{% endif %}

78
Q

Demonstrate ability to work with Theme Configuration

A

Demonstrate ability to work with Theme Configuration
Administrative settings related to theme configuration
admin/appearance/settings/themeName
Page element display: use pictures in posts/comments, verification status in comments, shortcut icon
Logo image: use logo supplied by theme (uncheck to upload)
Favicon: use favicon supplied by theme uncheck to upload

Ability to create his/her own theme settings using custom code.
Set default value in config/install/THEME.settings.yml

Use hook function in THEMENAME.theme or theme-settings.php file:
THEMENAME_form_system_theme_settings_alter(&$form, $form_state)

Get the settings in your php file or use a preprocess function to get it in your twig file:
$foo_example = theme_get_setting(‘foo_example’);

Setup
Install and set theme as default/admin under: admin/appearance after creating the following:
themename.info.yml: includes the theme name and base theme, regions (as soon as you define this, however, it overrides the core regions so make sure to add them) etc.
themename.theme: preprocess functions & theme hook suggestions
templates/.twig: presentation logic in templates directory
themename.libraries: css & js libraries - add all css/js via asset libraries
themename.breakpoints: responsive design breakpoints
config/
.yml: for config like image styles

Know required items in theme .info:
name (required) - human readable name
type (required) - module, theme, or profile
description (optional)
package (optional)
core (required) - version of Drupal compatible with 8.x
php (optional)
version (optional)
libraries (optional)
libraries-override (optional)
base theme (recommended) 
- stable is default, recommended classy or stable
- stable is bare and doesn’t have extra classes for styling with the exception of the toolbar etc.
hidden (optional)
engine (optional)
screenshot (optional)
regions (optional)
regions_hidden (optional)
features (optional)
stylesheets-remove (deprecated)
ckeditor_stylesheets (optional)
79
Q

Drupal javascript coding standards

A

Drupal javascript coding standards
Constants: UPPER_UNDERSCORED
Constructors: UpperCamelCased (Constructors are functions that are designed to be used with the new prefix)
Multi-word variables and functions: lowerCamelCased
Function names SHOULD begin with the name of the module or theme declaring the function, so as to avoid name collisions - Drupal.behaviors.tableDrag
Control structures on new lines; use else if (php standard is elseif)
To avoid type coercion confusion use strict comparison operators: (=== or !==)

80
Q

Demonstrate knowledge of working with Breakpoints in a theme

A

Demonstrate knowledge of working with Breakpoints in a theme
Define and use a common set of breakpoints that can be used throughout a site
Add to your THEME.breakpoints.yml:
yourtheme.narrow:
label: narrow
mediaQuery: ‘all and (min-width: 560px) and (max-width: 850px)’
weight: 1
multipliers:
- 1x

Multiplier:
2x is iPhone retina - ratio between the physical pixel size of the active device and the device-independent pixel size

You can also use groups:
yourtheme.group1.narrow:

Add the breakpoint defined in your module to the breakpoint group defined in yourtheme:
yourmodule.yourtheme.group2.superwide

CSS media queries + Constructing media queries that can target a wide variety of devices
[See section 1.4]

81
Q

Demonstrate knowledge of working with Breakpoints in a theme

A

Demonstrate knowledge of working with Breakpoints in a theme
Define and use a common set of breakpoints that can be used throughout a site
Add to your THEME.breakpoints.yml:
yourtheme.narrow:
label: narrow
mediaQuery: ‘all and (min-width: 560px) and (max-width: 850px)’
weight: 1
multipliers:
- 1x

Multiplier:
2x is iPhone retina - ratio between the physical pixel size of the active device and the device-independent pixel size

You can also use groups:
yourtheme.group1.narrow:

Add the breakpoint defined in your module to the breakpoint group defined in yourtheme:
yourmodule.yourtheme.group2.superwide

CSS media queries + Constructing media queries that can target a wide variety of devices
[See section 1.4]

82
Q

Demonstrate knowledge of working with Breakpoints in a theme

A

Demonstrate knowledge of working with Breakpoints in a theme
Define and use a common set of breakpoints that can be used throughout a site
Add to your THEME.breakpoints.yml:
yourtheme.narrow:
label: narrow
mediaQuery: ‘all and (min-width: 560px) and (max-width: 850px)’
weight: 1
multipliers:
- 1x

Multiplier:
2x is iPhone retina - ratio between the physical pixel size of the active device and the device-independent pixel size

You can also use groups:
yourtheme.group1.narrow:

Add the breakpoint defined in your module to the breakpoint group defined in yourtheme:
yourmodule.yourtheme.group2.superwide

CSS media queries + Constructing media queries that can target a wide variety of devices
[See section 1.4]

83
Q

Demonstrate ability to build a sub-theme from a base theme

A

Demonstrate ability to build a sub-theme from a base theme
Pros and cons of a wide variety of core and contributed base themes.
. . .

How to choose the appropriate base theme for a project
Set in your theme’s *.info.yml file (ex. ‘base theme: classy’)
“classy” if you want markup with BEM/SMACSS convention
“stable” (the default if a base theme isn’t defined) for a minimal amount of css
“stark” for absolute minimal

Sub-theme utilizes the assets of the base theme
base theme: classy

Sub-theme overrides the assets of the base theme
libraries-override - define your library overrides
regions - list theme regions

Sub-theme extends the assets of the base theme
libraries-extend - are specified by extending a library with any number of other libraries.

84
Q

Templates and Pre-process Functions

A

Templates and Pre-process Functions
3.1 Demonstrate ability to use Twig syntax

Twig basic syntax
D8 snippets: https://github.com/jenter/twig-snippets

Twig node.pub > today|week(-1)???

Comment:
{# Comment #}

Print something:
{{ variable_name }}

Translate using t or trans filter:
This filter should be used for any interface strings manually placed in the template that will appear for users. Not for user provided content. Strings that are contained within a variable can be considered already translated (this happens when the variable is set) and should be output directly.

http://getlevelten.com/blog/mark-carver/drupal-8-twig-templates-and-translations
{{ ‘Hello, World’|t }}
{{ ‘Hello @acorn’|t({ ‘@acorn’: myarray.acorn }) }}

{% trans %}
Submitted by {{ author.username }} on {{ node.created }}
{% endtrans %}

Placeholders:
@variable - most use-cases, special chars converted to html entities
%variable - text html escaped and wrapped with <em> tags
:variable - when substituting an href to escape dangerous protocols</em>

If and for tags (note: in a for loop you have access to the loop variable like loop.length, loop.last and loop.first):
{% for delta, product in products %}
{{ delta }}: {{ product }}
{% endfor %}

Pass filters with a pipe and can be chained:
{{ product|upper|reverse }}

Get the count of products via a filter:
{% if products|length == 0 %}

Convert a valid string to time value to a date format or apply to a variable.
{{ ‘tomorrow noon’|date(‘D M jS ga’) }}

Variable dump:
{{ dump() }}

Data from an array or object, use period operator:
{{ products.0 }}
{{ product_page.title }}
For objects, behind scenes twig checks to see if there is a public ‘title’ property, if not checks for a public getTitle() method.

Using the [] syntax:
{{ products[0] }}
…but use it really when you need to pass a variable as a key.
{{ products[myvaraskey] }}

Template inheritance:
{% extends ‘layout.twig’ %}
The above template would contain {% block body %}{% endblock %} and in the template that inherits you’d swap out that block by:
{% block body %} your content… {% endblock %}
If the parent has content you want to supplement, make sure to include the parent content inside your overridden block with:
{{ parent() }}

Include template:
{% include(’_file.twig’) %}

You can pass variables to the include:
{{ include(‘_file.twig’, { ‘myVar’: ‘test content’ }) }}

Setting a variable:
{% set myVar = “this is a value” %}

“Tests” in Twig can be used in conditionals along with operators
Examples: set, defined, odd, same as, etc.)
Tests like divisibleby() can take an argument.

Ternary operators:
{% backgroundColor is defined ? backgroundColor : “light-blue” %}

Default rather than above ternary:
{{ backgroundColor|default(‘light-blue’) }}

Macros
Create a reusable macro:
{% macro myMacro(arg1, arg2) %}
  {{ arg 1 }}
{% endmacro %}
Use it in same file with _self or in an included external file.
{{ _self.myMacro(‘item 1’, ‘item 2’) }}

Drupal Twig functions
These are PHP callables that Twig can invoke. Functions registered with TwigExtension::getFunctions() which return twig filter objects can be used in twig template.

Some examples:
url($name, $parameters, $options) - absolute url, given route and params
path($name, $parameters, $options) - relative url given route name and params
attach_library($library)

Use of general functions and filters as well as Drupal specific ones.
[see above]

Variable handling
[see above]

Control structure
[see above]
</em>

85
Q

Demonstrate ability to build and customize core templates for managing markup

A

Demonstrate ability to build and customize core templates for managing markup
A front-end specialist should have knowledge of how to use, name, and create the templates to output the desired markup for the project.
Template order and naming conventions
Template inheritance and extension
HTML and Twig markup combinations to accomplish the theming task

Hook naming convention
The first “hook” should be replaced with the name of your theme or module.

The second “HOOK” should be replaced with the base name of the template that you’re suggesting alternatives:
hook_preprocess_html() - is for the html.html.twig template
hook_preprocess_page() - is for the page.html.twig template

Theme hook suggestions:
For more fine-grained control (state and context)
node–{NODE.NID}.html.twig – node-123.html.twig
node–{NODE.TYPE}.html.twig – node–blog_post.html.twig
Node.html.twig

86
Q

Unit tests

A

Unit tests
Tests on functions, methods, classes.

Base class to extend: UnitTestCase

Pros Cons
Verify individual parts
Quickly find problems in code
Fast execution
No system setup for the test run Rewrite on every refactoring
Complicated mocking
No guarantee that the whole system actually works

87
Q

Kernel tests

A

Kernel tests
Kernel tests are integration tests that test on components. You can install modules.

Base class to extend: KernelTestBase or EntityKernelTestBase

Pros Cons
Verify that components actually work together
Somewhat easy to locate bugs Slower execution
System setup required
No guarantee that end user features actually work

88
Q

Browser & Javascript tests

A

Browser & Javascript tests
This type of testing is often called System or Functional testing because it tests on the complete system. Drupal 8 ships with two types: BrowserTestBase and JavascriptTestBase. Use JavascriptTestBase when you need to test how the system works for a user with Javascript enabled.

Tutorials: BrowserTestBase and JavascriptTestBase

Drupal 8 also has legacy support for Simpletest’s WebTestBase.

Pros Cons
Verify that the system works as experienced by the user
Verify that the system works when code is refactored Very slow execution
Heavy system setup
Hard to locate origins of bugs
Prone to random test fails
Hard to change

113
Q

Drupal 8 provides a better way to: handle template suggestions, add custom suggestions, or define a specific template suggestion for an element.

Create theme hook suggestions with one of the following methods in theme or module:
hook_theme_suggestions_HOOK(array $variables)
HOOK is the least-specific version of the hook being called (ex. node not node__article)
hook_theme_suggestions_HOOK_alter(array &$suggestions, array $variables)
For altering existing lists of suggestions. Provide alternative theme function or template name suggestions and reorder or remove suggestions
hook_theme_suggestions_alter(array &$suggestions, array $variables, $hook)
invoked for all theme hooks, if you are targeting a specific theme hook it’s best to use the above …HOOK_alter()

array(
‘node__custom_suggestion’, // node–custom-suggestion.html.twig
‘node__teaser’ // node–teaser.html.twig
‘node’ // node.html.twig
),
);

Preprocess theme variables:
Variables are provided to templates via preprocess functions. Preprocess function should always return render arrays.

hook_preprocess()
This hook allows modules to preprocess theme variables for theme templates. It is called for all theme hooks implemented as templates, but not for theme hooks implemented as functions. Avoid it if you can or keep logic simple since it can potentially be called hundreds of times on a single page.

Instead, use hook_preprocess_HOOK() for a specific theme hook. For example:
function mymodule_preprocess(&amp;$variables, $hook) {
  if ($hook == 'node') {
    // do what you gotta do.
  }
}
template_preprocess_HOOK(&amp;$variables)
Should be implemented by the module that registers the theme hook, to set up default variables.

Development Config
In your *.settings.php file:
Disable the Render API Caching (this caching happens first):
$settings[‘cache’][‘bins’][‘render’] = ‘cache.backend.null’;
Disable the CSS and JavaScript aggregation features:
$config[‘system.performance’][‘css’][‘preprocess’] = FALSE;
$config[‘system.performance’][‘js’][‘preprocess’] = FALSE;

In your *.services.yml file:
# Enable Twig debugging.
parameters:
 twig.config:
   debug: true
   auto_reload: true
   cache: false
Inspecting variables
Use dump() or kint()by enabling kint module.
A

Drupal 8 provides a better way to: handle template suggestions, add custom suggestions, or define a specific template suggestion for an element.

Create theme hook suggestions with one of the following methods in theme or module:
hook_theme_suggestions_HOOK(array $variables)
HOOK is the least-specific version of the hook being called (ex. node not node__article)
hook_theme_suggestions_HOOK_alter(array &$suggestions, array $variables)
For altering existing lists of suggestions. Provide alternative theme function or template name suggestions and reorder or remove suggestions
hook_theme_suggestions_alter(array &$suggestions, array $variables, $hook)
invoked for all theme hooks, if you are targeting a specific theme hook it’s best to use the above …HOOK_alter()

array(
‘node__custom_suggestion’, // node–custom-suggestion.html.twig
‘node__teaser’ // node–teaser.html.twig
‘node’ // node.html.twig
),
);

Preprocess theme variables:
Variables are provided to templates via preprocess functions. Preprocess function should always return render arrays.

hook_preprocess()
This hook allows modules to preprocess theme variables for theme templates. It is called for all theme hooks implemented as templates, but not for theme hooks implemented as functions. Avoid it if you can or keep logic simple since it can potentially be called hundreds of times on a single page.

Instead, use hook_preprocess_HOOK() for a specific theme hook. For example:
function mymodule_preprocess(&amp;$variables, $hook) {
  if ($hook == 'node') {
    // do what you gotta do.
  }
}
template_preprocess_HOOK(&amp;$variables)
Should be implemented by the module that registers the theme hook, to set up default variables.

Development Config
In your *.settings.php file:
Disable the Render API Caching (this caching happens first):
$settings[‘cache’][‘bins’][‘render’] = ‘cache.backend.null’;
Disable the CSS and JavaScript aggregation features:
$config[‘system.performance’][‘css’][‘preprocess’] = FALSE;
$config[‘system.performance’][‘js’][‘preprocess’] = FALSE;

In your *.services.yml file:
# Enable Twig debugging.
parameters:
 twig.config:
   debug: true
   auto_reload: true
   cache: false
Inspecting variables
Use dump() or kint()by enabling kint module.
114
Q

Demonstrate ability to write template pre-process functions for overriding custom output

A

A front end specialist should be able to use pre-process functions to override, improve, or get extra data needed for templates.
Correct use, specificity, and hierarchy of pre-process functions
How to obtain information from the Database, or objects and entities from Drupal and know the correct way of passing this information to your template
How to use the new and improved library management to have a better management of JS libraries and stylesheets
Be aware of the changes to the theme API and the improvements to previous versions of Drupal

115
Q

Detach behaviors

A

Detach behaviors
Will be called when content is removed from the DOM.
Drupal.behaviors.fileAutoUpload = {
attach: function (context) {

},
detach: function (context, setting, trigger) {
if (trigger === ‘unload’) {
$(context).find(‘input[type=”file”]’)
.removeOnce(‘auto-file-upload’).off(‘.autoFileUpload’);
}
}
};