# Question
Title: Mail subject and body remain empty using mailManager
I have been fiddling with sending a mail in my custom module in Drupal 8. The mail gets sent but the subject and body are empty. It has been an issue for days and I can't get it to work. The code and var\_dump are below. I just can't find the issue. Maybe someone can!

Code in `hook_mail`:

```
<?php
/**
 * Implements hook_mail().
 */
function document_mail($key, $message, $params)
{
    $options = array(
        'langcode' => $message['langcode'],
    );
    switch ($key) {
       case 'send_file':
            $message['from'] = \Drupal::config('system.site')->get('mail');
            $message['subject'] = t('@title', array('@title' => $params['mail_title']), $options);
            $message['body'][] = $params['message'];
        break;
    }
}

```

Code to send mail:

```
    $mailManager = \Drupal::service('plugin.manager.mail');
    $module = 'document';
    $key = 'send_file';
    $to = 'info@example.com';
    $params['mail_title'] = 'a title';
    $params['message'] = 'a message';
    $langcode = \Drupal::currentUser()->getPreferredLangcode();
    $send = true;
    $result = $mailManager->mail($module, $key, $to, $langcode, $params, null, $send);
    var_dump($result);
    if ($result['result'] !== true) {
        drupal_set_message(t('There was a problem sending your message and it was not sent.'), 'error');
    } else {
        drupal_set_message(t('Your message has been sent.'));
    }

```

var\_dump of result from $result of mailManager

```
array(12) {
["id"]=> string(18) "document_send_file"
["module"]=> string(8) "document"
["key"]=> string(9) "send_file"
["to"]=> string(24) "info@example.com,"
["from"]=> string(22) "info@example.com"
["reply-to"]=> NULL
["langcode"]=> string(2) "en"
["params"]=> array(2)
{
    ["mail_title"]=> string(7) "a title"
    ["message"]=> string(9) "a message"
}
["send"]=> bool(true)
["subject"]=> object(Drupal\Core\StringTranslation\TranslatableMarkup)#410 (5)
{
    ["string":protected]=> string(6) "@title"
        ["translatedMarkup":protected]=> NULL
        ["options":protected]=> array(1)
        {
                ["langcode"]=> string(2) "en"
        }
        ["stringTranslation":protected]=> NULL
        ["arguments":protected]=> array(1)
        {
            ["@title"]=> string(7) "a title"
        }
    }
    ["body"]=> array(1)
    {
        [0]=> string(9) "a message"
    }
    ["headers"]=> array(7)
    {
        ["MIME-Version"]=> string(3) "1.0"
        ["Content-Type"]=> string(51) "text/plain; charset=UTF-8; format=flowed; delsp=yes"
        ["Content-Transfer-Encoding"]=> string(4) "8Bit"
        ["X-Mailer"]=> string(6) "Drupal"
        ["Return-Path"]=> string(22) "info@example.com"
        ["Sender"]=> string(22) "info@example.com"
        ["From"]=> string(44) "a string"
    }
    ["result"]=> bool(true)
}

```

# Answer
> 1 votes
I believe you forgot to pass `$message` by reference (`&`), so please double check the implementation of your `hook_mail` as per details below:

> `hook_mail($key, &$message, $params)`

Otherwise, any changes to `$message` won't take any effect.

# Answer
> -1 votes
Remove the empty array tag from body as below.

```
$message['body'] = $params['message'];

```

---
Tags: 8, hooks, emails
---


# Question
Title: How to display (automatically in a field) all media that references this node?
I have a content type, "Fruit". Using that content type I have created a "Bananas" node. It contains text and link fields that constitute "banana information".

I have media type, "Fruit Image", with a field, "FruitShown". Using that media type I have numerous images of bananas and other fruit.

On my Fruit pages, how can I display **automatically in a field** all images of bananas (i.e. All images of media type "Fruit Image" that have "bananas" in the "FruitShown" field)?

**CONTEXT:** I believe I am able to display the banana images in a **block** using a View with a contextual filter. However I prefer to display the images in a **field** so that I can wrap the images around a "banana information" CSS float, not just place them in a separate rectangular block (which leaves empty space in my theme).

**WHAT I TRIED:** I am able to display the banana images in a field by using an entity reference field with an entity reference view reference method, but when adding the "Bananas" node, the images must be selected manually one-by-one. I prefer all of them to display automatically.

# Answer
> 1 votes
Use the Views Reference Field module

When you've created your view, go to your node strcuture and create a field type using the module above. On node edit you then can select your banana view. This way your view is wrapped inside the same markup just like any other field of your node.

---
Tags: views, 8, entities, media
---


title: Flag : access, context, role

text:
# Question
Title: Flag : access, context, role
I have a site where members (with different roles) can post projects.

**My goal :** To show to "recruiters" (role) a view of all the users who have flagged their nodes. In other words, the flag accessibility / visibility is dependant of the author's role and node type.

**I need :**

1. to show a flag to every user if the author of the node has the role "recruiter"
2. to let the "recruiter" unflag a user from his view of applicants.

**I can't / I can:**

1. I cannot figure out how to control the visibility / accessibility of the flag based on the author's role. I've checked a few modules, but did not find anything relevent yet.
2. I'm ok with Views: I guess I could make a second flag only for "recruiters" (available in the view) and set a double condition : if user has flagged node AND if "recruiter" has flagged the user in the list, then remove user from the view. By doing this, the user would not be able to flag again the node (job post) if the 'recruiter" has (un)flagged the user.

**My hope :** to be able to combine available modules (no coding).

I guess a custom module could look for a boolean field (checkbox) only available to some roles and show (or not) the flag. But I'm no coder unfortunately.

Let's start with available modules : is there anything that I missed?

# Answer
> 1 votes
I have the impression that what you're asking for requires more then just (only) the Flag module. I.e. you should get it to work if you also use the Rules Link module.

If you're not familiar with Rules Link, then have a look at "How to show authorized users a link for relevant Views results using the Rules Link module?". The scenario explained in that question is about users that are "blocked" or "active", and which you could consider as a variation of what this question here is about, i.e.:

* think of "active" users as "*users who have flagged their nodes*" (as in your question).
* think of "blocked" users as "*unflag a user from his view of applicants*" (as in your question).

Of course, you don't want to block or activate users for your case. But instead you could use 2 separate flags:

* a 1st flag to be used by all the users, to indicate something like "I want to apply for this node" (adapt the label to whatever fits).
* a 2nd flag to be used by the recruiter to indicate something like "reject a user as an applicant".

Obviously, you could show to "recruiters" (role) a view of all the users who have flagged their nodes (with the "1st flag"). And using Rules Link you could improve that view to trigger some additional Rules magic to simply flag an applicant (with the "2nd flag").

**Note**: no custom coding needed, only 2 flags to be configured, and some rules magic (combined with Rules Link).

---
Tags: 7, flags
---


# Question
Title: Where can I find all form display options types for custom entity fields?
I created a custom entity with `drupal generate:entity:content`.

I am adding fields in the `baseFieldDefinitions` method of the entity class.

Below is what drupal console generates by default for the `name` field.

Where I can find a list of all possible `type` values for `->setDisplayOptions('form')`. For example, the field below uses `string_textfield`.

```
public static function baseFieldDefinitions(EntityTypeInterface $entity_type) {
    ...
    $fields['name'] = BaseFieldDefinition::create('string')
      ->setLabel(t('Name'))
      ->setDescription(t('The name of the entity.'))
      ->setSettings([
        'max_length' => 50,
        'text_processing' => 0,
      ])
      ->setDefaultValue('')
      ->setDisplayOptions('view', [
        'label' => 'above',
        'type' => 'string',
        'weight' => -4,
      ])
      ->setDisplayOptions('form', [
        'type' => 'string_textfield',
        'weight' => -4,
      ])
      ->setDisplayConfigurable('form', TRUE)
      ->setDisplayConfigurable('view', TRUE);

```

# Answer
> 9 votes
Those are field widget plugin IDs.

You can get all of those by querying the field widget plugin manager (service ID: `plugin.manager.field.widget`).

E.g. to get all the IDs in your entity class (once the service is injected):

```
$widget_types = $this->fieldWidgetPluginManager->getDefinitions();
$plugin_ids = array_keys($widget_types);

```

Same thing in procedural code in case someone wants it:

```
$widget_types = \Drupal::service('plugin.manager.field.widget')->getDefinitions();
$plugin_ids = array_keys($widget_types);

```

If your current context allows you to inject the widget plugin manager service rather than get it from `\Drupal`, all the better.

---
Tags: 8, entities
---


title: Change a field type using Migrate

text:
# Question
Title: Change a field type using Migrate
Can I migrate a Drupal 7 field from one field type to another using Migrate and `$this->systemOfRecord = Migration::DESTINATION;`?

I'm trying to move field\_phone which is an ordinary Field API text field into a mobile\_number field which is also a Field API field but provided by the Mobile number module.

uid is the only listed source field, and that makes sense because it's the only field selected in the query, but I don't see any examples that use JOINs to select data from fields attached to an entity.

How do I add field\_phone to the source?

```
public function __construct($arguments) {
  $this->sourceFields['field_phone'] = t('Phone');
  parent::__construct($arguments);

  $this->systemOfRecord = Migration::DESTINATION;

  $query = db_select('users', 'u')
    ->fields('u', array('uid'))
    ->condition('uid', 0, '>');
  $this->source = new MigrateSourceSQL($query);

  $this->destination = new MigrateDestinationUser(array());

  $this->map = new MigrateSQLMap($this->machineName,
    array('uid' => array(
      'type' => 'int',
      'unsigned' => TRUE,
      'default' => 0,
      'description' => "User's {users}.uid.",
    )),
    MigrateDestinationUser::getKeySchema()
  );
  $this->addFieldMapping('uid', 'uid');
  $this->addFieldMapping('field_phone_number', 'field_phone');
}

```

Additionally, If I can keep the same field machine name I rather do that then moving from field\_phone to field\_phone\_number, but it's not important.

# Answer
> 0 votes
This is hard for me to believe, but the results are telling. The source fields were never loaded, so they weren't available to the destination handler. I added the following `prepare()` function to my Migration class so that the values would be available. I don't see any examples that look like this, so I'm almost certain there's a better way.

```
function prepareRow($current_row) {
  if (parent::prepareRow($current_row) === FALSE) {
    return FALSE;
  }

  $phone = db_select("field_data_field_phone", "p")
    ->fields("p", array("field_phone_value"))
    ->condition("p.entity_type", "user")
    ->condition("p.entity_id", $current_row->uid)
    ->execute()
    ->fetchField();
  $current_row->field_phone = $phone;
}

```

---
Tags: migrations
---


# Question
Title: How to remove orphaned actions if you get not authorized access as uid1?
I get this error `1 orphaned actions (views_bulk_operations_archive_action) exist in the actions table. Remove orphaned actions`

But when I click `Remove orphaned actions` I get `You are not authorized to access this page.`.

And I'm logged in as UID1 user.

Can this be solved via drush?

# Answer
> 2 votes
Relative path `/admin/config/system/actions` shows a list of the actions available in the site.

If a site has orphaned actions, then relative path `/admin/config/system/actions/orphan` will provide the opportunity to remove them.

If you enter relative path `/admin/config/system/actions/orphan` and get redirected (automatically) to `/admin/config/system/actions/manage`, then that is an indication that there are no orphaned actions.

And if everything else fails, and you're willing to take the risk (+ a backup of your database first!), you might want to give it a try to edit the Drupal database using an SQL which looks like so:

```
delete from actions where aid = "views_bulk_operations_archive_action";

```

---
Tags: 7, drush
---


# Question
Title: how to theme content type based on context
I have an article content type with categories (term1,term2 etc) I want to be able to theme the node view with a different theme when specific category is picked on node edit

how can this be done ? any kind of solution is acceptable

NOTE: at this point https://www.drupal.org/project/page\_theme, https://www.drupal.org/project/themekey have not been ported to D8 :-( They would really be great solutions

# Answer
Here is a complete solution

1. Installing context module we can create a `context` which comprise of conditions which if they are met they do the specified reactions
2. Installing entity\_field\_condition will let as set the desired condition
3. Add `context` (lets name `alternative theme section`)
4. Add `Node Field (entity_field_condition)` and select category name and choose the specific value that corresponds to the desired category (tid since we are talking about term reference).
5. Add reaction `theme` and choose the theme that you want to be activated on above conditions

NOTES: At the time of writing this `entity_field_condition` needs a patch to work properly with entity reference (as is the case of category field). The patch can be found here

term condition was not working at the moment (buggy was not able to add the condition it was giving WSOD)

Alternatives would be to write my own custom condition or debug the `term condition` module or write my own theme negotiator
> 1 votes

---
Tags: 8, theming
---


# Question
Title: What date format is this? Or is it even a date?
I'm working with a Drupal 8.3.6 setup done by someone else and I have a date format that doesn't make sense to me. I'm interacting with it thru MySQL Workbench. The best I can tell, 1499287512 = Wed, 07/05/2017 - 23:02 and 1501079338 = Tue, 08/22/2017 - 06:25 BUT there's no guarantee of that. In any event, 1499287512 and 1501079338 appear to be in a date placeholder; numbers like it appear in users\_field\_data.fields, created, changed, access, login.

# Answer
Those are dates stored as Unix timestamps, which are essentially the number of seconds since midnight, January 1st, 1970 UTC (the epoch is 1970-01-01T00:00:00+00:00).

As far as Drupal is concerned, they are proper fields on those entities, either `TimestampItem`, `CreatedItem`, or `ChangedItem` fields.

Keep in mind that the timestamp always refers to that epoch and always is referenced to UTC; there is no real thing as a Unix timestamp in a local time zone. When working with them in Drupal it is always best to use `DrupalDateTime` objects, and use it methods for computation (which will inherit from `\DateTime`).
> 4 votes

---
Tags: datetime
---


# Question
Title: hook_entity_base_field_info() vs. creating a new entity
I need to create a fairly extensive user/account management section of a site.

I'm wondering whether to just extend the existing user entity, or whether I should create a completely new entity to house all the extra stuff I need...

Are there any pro's/con's I should bear in mind when making this decision?

# Answer
> 2 votes
There isn't a 'right' or 'wrong' method of this. It really depends on your business requirements.

Are the fields you are thinking you need related to the user object? If they are, then I would use the User object. However, that shouldn't involve extending it, you can just add fields to it.

Without more information it's hard to be more specific.

---
Tags: 8, users, entities
---


# Question
Title: How can I display a block on view page, excluding paginated/paged/pager output pages?
I'm trying to use Context to display a block on a view page path, e.g. /view, but exclude it from the paged output, e.g. /view?page=1. The path exclusion tools in Drupal 8 don't work with the query string (and no query string rules are available).

There's a Drupal 7 solution (hack?) for this posted on How can I show a block in a view page, excluding its paginated pages?

Any help to get something like this in Drupal 8 working would be appreciated.

The issue on Drupal.org is https://www.drupal.org/project/context/issues/2930896.

# Answer
> 0 votes
Thanks to Clive's post above, this can be accomplished with the early dev module Request Data Conditions:

https://drupal.org/project/request\_data\_conditions

---
Tags: blocks, paging
---


title: How to translate a header in drupal 7

text:
# Question
Title: How to translate a header in drupal 7
I have a drupal 7 site I inherited to manage. There is a view I can edit at /newsletters#overlay=admin/structure/views/view/newsletters/edit and it has a section titled "header" that I can't figure out how to enable for translations. The section below it,"content", is showing up properly translated on the front end.

The menu for Header looks like this:

Clicking Edit Global: Text area reveals this:

What do I have to do to translate this and display it properly?

# Answer
> 0 votes
The "global" header and "global" footer built in Drupal Views isn't treated as a separate translatable entity like a node is.

One recommended approach (that will also avoid giving content managers access to edit views) is to setup a single custom content type for view headers and footers and then with the Entity API module enabled, set/embed an entity reference to the specific node in the view header (and/or footer). A breakdown of steps for this approach is below:

1. Make sure your site has the Entity API module installed and enabled.
2. Create a custom content type (it can be just a body field and title. NOTE: the title will render in the embedded entity in the view, so you may want to utilize it for the view page title/H1 in lieu of the specific "title" field on the specific display of the view. Otherwise you can preprocess the node type to exclude the title or use css to hide it.
3. Enable internationalization/translations for the new content type.
4. Create a node for each specific view header or view footer where you need manageable/translatable content, noting the node ID upon save.
5. Export a backup of the views impacted.
6. Edit the desired views; be sure to be editing the specific "view display" that applies to your block or page. In the "Header" or "Footer" section of the view edit/config page (where you currently have a global textarea), click "ADD".
7. In the modal, make sure the selector in the top left corner is set to apply changes to "This Page"/"This Block"/etc and ***not*** "All Displays". Select Entity: Rendered Entity and click Apply (this display).
8. Input the node ID and choose the desired display mode (full node should suffice as outlined, unless you need a custom display mode setup on the node/content type).
9. Remove the Global Text object in the View Header or View Footer. After applying this change (and assuming you have no other custom objects in the view header or footer), you should only see the referenced entity in the View Header or View Footer section.
10. Save and test the page where the view appears.
11. If you decide to revert, import the backed up copy of the view as Admin1 to restore it.

---
Tags: i18n-l10n
---


# Question
Title: Get all content in all language using query
I tired to get the content from db using query with some conditions and I need to fetch content in all languages. I have tried two methods, only english language content were fetched, but it doesn't work for all other languages...

Method 1:

```
    $langcd = \Drupal::languageManager()->getCurrentLanguage()->getId();
    $query = \Drupal::entityQuery('node')
      ->condition('status', 1)
      ->condition('type', 'page');
      ->condition('langcode', $langcd);
    $nids = $query->execute();

```

Method 2:

```
    $db = \Drupal::database();
    $query = $db->select('node', 'n');
    $query->fields('n');
    $query->condition('type', "page", "=");
    $query->condition('langcode', $langcd);
    $result = $query->execute()->fetchCol();

```

Every time I am getting only the English version of that content, but other language for that particular content was available in db. Please somebody help me to get the content in all other languages.

# Answer
> 3 votes
Following code should work:

```
$langcd = \Drupal::languageManager()->getLanguages();
$langcd = array_keys($langcd);
$query = \Drupal::entityQuery('node')
        ->condition('status', 1)
        ->condition('type', 'page');
$query->condition('langcode', $langcd, 'IN');
$nids = $query->execute();

```

Get list of active languages first, then change condition for `langcode` to `IN`.

---
Tags: nodes, database
---


title: Webform display for specific roles

text:
# Question
Title: Webform display for specific roles
Suppose we have 20 webforms A user which has Admin role as well User1 role should only view its corresponding webform (eg: weform1 and webform2)rest webform should not display at(`admin/content`,`/admin/content/webform`) when he logged in as a user which is having **User1+Admin** role.

How to achieve this?

# Answer
> 0 votes
As per my knowledge you need to do little customization to achieve this.

1. Check the roles
2. Perform your require action(permission)

code to check logged in user has both roles?

```
global $user;
$roleA = 'administrator';
$roleB = 'user1';
$roleC = 'some other role';
$user_roles = array_values($user->roles);

    if (in_array($roleA, $user_roles) && in_array($roleC, $user_roles)) {
      // Do something.
    }
    elseif (in_array($roleA, $user_roles) && in_array($roleB, $user_roles)) {
      // Do something.
    }
    elseif (in_array($roleB, $user_roles) && in_array($roleC, $user_roles)) {
      // Do something.
    }

```

**Second option.**

You can look Rules module.

---
Tags: 7, webforms, users
---


title: role and permission

text:
# Question
Title: role and permission
I want to create a new role and give that to some permissions but not for drupal access, it for my website to access some of things in drupalwebsite. Like student/parent/teacher/alumni etc.is this possible?

# Answer
It looks like you should give it a try to use the Group module (available as of D7, and has a D8 version also). You'd enable the `gnode` submodule, and for each group type you would define the appropriate permissions (view, edit, delete, etc) for the various Content Types.

From the details included in your question, it seems that possibly you'd only need 1 group type, with as many groups for that group type as you like/need. Every group can have users, roles and permissions attached to it (refer to "What are the various roles supported by the Group module?" for more details about that).

***More info:*** What's the purpose of the Group module and how to get started with it?
> 0 votes

---
Tags: users
---


# Question
Title: Access a field from page.html.twig template
I would like to display an image above the page header.
The image is stored in a field (its name is “image”) related to a node (its type is “article”).
I can display {{content.field\_image}} using the node--article.html.twig template.
But as the

```
<h1 class="page-header">{{ title }}</h1>

```

lives in the page-title.html.twig template I can no longer access the image.

Can someone help me finding the right way to write a preprocess function?
I already used

```
function [my_theme]_preprocess_page(&$variables) {
  $site_config = \Drupal::config('system.site');
  $variables['site_name'] = $site_config->get('name');
  $variables['site_slogan'] = $site_config->get('slogan');
}

```

But I can't find a way to do the same again with my image

# Answer
The page title has its own preprocess hook. You may want to use hook\_preprocess\_HOOK() to add your image to the variables. As it is using the page-title.html.twig template, the theme registry HOOK is called 'page\_title'.

Following is an excerpt from a theme's page title preprocess function of a D8 theme that is adding the URI of an image with an image style applied along with the page title. Maybe you find it useful as inspiration for your use case:

```
use Drupal\image\Entity\ImageStyle;

/**
 * Implements hook_preprocess_HOOK() for page title images.
 */
function mytheme_preprocess_page_title(array &$variables) {
  $image = '';

  // Load the image entity from current route.
  if (
    !empty($node = \Drupal::routeMatch()->getParameter('node')) &&
    $node->getType() == 'page' &&
    $node->hasField('field_image') &&
    $image_entity = $node->field_image->entity
  ) {
    $style = ImageStyle::load('title_image');
    $image = ($style->buildUri($image_entity->getFileUri());
  }

  $variables['image'] = $image;
}

```
> 1 votes

# Answer
In your

> \[my\_theme\].theme

you can try:

```
function [my_theme]_preprocess_page(&$variables) {
 $nid= 1;
 $node= Drupal\node\Entity\Node::load($nid);
 $variables['page']['image']=file_create_url($node->field_image->entity->getFileUri());
}

```

In your template

> page.html.twig

you can try:

```
{{ page.image }}

```

EDIT

I did a test with the theme bartik.

I have a node of nid = 1 that has an image in field field\_image

I edited the `bartik.theme` file

I edited the file page.html.twig

and add the code:

```
<img src="{{ page.image }}">

```

delete all caches

If you refresh the page, you can see that the image is shown
> 0 votes

---
Tags: 8, theming
---


# Question
Title: Post method trow an Preflight not successful response
Im working with Drupal 8 and Angular.

I want to create a content from angular.

I have the Get method working.

The problem is with the Post method, **I don't know how to configure it.**

With the Rest Ui module, i have this configuration:

And in the services.yml file I have this one:

```
  cors.config:
    enabled: true
    # Specify allowed headers, like 'x-allowed-header'.
    allowedHeaders: []
    # Specify allowed request methods, specify ['*'] to allow all possible ones.
    allowedMethods: []
    # Configure requests allowed from specific origins.
    allowedOrigins: ['*']
    # Sets the Access-Control-Expose-Headers header.
    exposedHeaders: false
    # Sets the Access-Control-Max-Age header.
    maxAge: false
    # Sets the Access-Control-Allow-Credentials header.
    supportsCredentials: false

```

It works fine for the Get method, but for the POST, it gives me this error:

> XMLHttpRequest cannot load http://drupal.dd:8083/entity/node. Preflight response is not successful task.service.ts:92

The task.service.ts is from my Angular app.

**Questions:**

1) Is the problem from Drupal configuration or from angular? (if is from angular, i will move the post. )

2)Wich on is the correct way to configure Post Method in Drupal?

**Extra info from the method**

# Answer
> 1 votes
This is the right cors.config configuration:

```
 cors.config:
        enabled: true
        # Specify allowed headers, like 'x-allowed-header'.
        allowedHeaders: ['*']
        # Specify allowed request methods, specify ['*'] to allow all possible ones.
        allowedMethods: ['*']
        # Configure requests allowed from specific origins.
        allowedOrigins: ['*']

```

---
Tags: 8
---


# Question
Title: Access current node in an existing block
I am using Drupal Lightning and a bootstrap subtheme. I have a requirement to place a section of the node page template in another block region. So I need to access the nodes fields in that block, fields like the taxonomy, block, breadcrumbs. Example my node--page.html.twig template prints these fields:

```
{{ node.title.value }}
{{ content.field_text }}
{{ drupal_view('mysection', 'block_1') }}
{{ drupal_block('mytheme_breadcrumbs') }}

```

It also has an includes template

```
{% include '@mytheme/includes/section.html.twig' %}

```

I can print these fields fine in a node template

```
node--page.html.twig

```

But I need to print these fields outside of the node template and into a block. I tried to create a View block and set a contextual filter "Content ID from URL" Then placed the View block in a region and then in the region template I tried to access the node fields from my region template but could not. I can access the title and body fields. This is the template.

```
region--myregion.html.twig

```

I then tried Entity blocks. I created a new block of type Entity view (Content). I tried to access the node fields from my region template but could not.

```
block--entityviewcontent.html.twig

```

# Answer
## Enable debug

by going in `sites/default/` and copying the file `default.services.yml` to `services.yml` and modifying the following lines

```
cache: false
debug: true

```

## Turn browser comments on

make sure your browser has Comments enabled (some browsers have them disabled by default for example in chrome in inspector on the 3 dot menu click `settings` and `preferences` find `Show HTML comments`

## Find out which twig template is used

after that inspect the code in near the block that you want to override and you should see something similar to this

```
<!-- THEME DEBUG -->
<!-- THEME HOOK: 'block' -->
<!-- FILE NAME SUGGESTIONS:
   * block--block-name.html.twig
   * block--block-content--b436f9c6-34ae-4879-8b55-068015a999d3.html.twig
   * block--block-content--bundle-name.html.twig
   * block--block-content.html.twig
   * block--block-content.html.twig
   x block.html.twig
-->
<!-- BEGIN OUTPUT from 'themes/bootstrap/templates/block/block--system.html.twig' -->

```

you can get the twig block template from the location in comment `BEGIN OUTPUT`

## Use and modify template

Copy this twig file into your theme `templates` folder and rename to any name above. Modify the code and add something similar to the twig block template you just created

```
{% if nid %}
    nid:{{nid}} <br/>
    title:{{node_title}} <br/>
    body:{{body}}<br/>
    text:{{field_text}} <br/>
{% endif %}

```

## Expose node variable to block templates

Add into your THEMENAME.theme the following code or similar

```
function THEMENAME_preprocess_block(&$vars){
    $node = \Drupal::routeMatch()->getParameter('node');
    if ($node instanceof \Drupal\node\NodeInterface) {
      // You can get nid and anything else you need from the node object.
      $vars["nid"] = $node->id();
      $vars["node_title"] = $node->getTitle();
      $vars["body"] = $node->body->value;
      $vars["field_text"] = $node->field_text->value;

      //following did not work ?!
      //$vars["field_text"] = $node->get('field_text')->getValue();
      //$vars["field_text"] = $node->field_text->getValue();
    }
}

```

## Clear cache

with the above you are making the node fields available to block templates
> 10 votes

---
Tags: 8, theming, entities
---


title: Alter field value in a form

text:
# Question
Title: Alter field value in a form
I've created a module so users can insert a link.

When users will insert their link, i wish to add a suffix to the link.

For exemple : they will add a link \> "www.test.com"

I want to be able to add to the link once they hit save "http://"

So the link will be http://www.test.com

When i do :

```
$form['attributes']['href']['#prefix'] = 'prefix';

```

I get :

What's the best way to do it without using $form\['attributes'\]\['href'\]\['#default\_value'\]

Many thanks,

# Answer
> 3 votes
As you want the suffix to be added when the save button is added you need to add a custom submit handler. In the `hook_form_alter` do something like `$form['actions']['submit']['#submit'][] = 'mymodule_form_submit';` and in the submit function `mymodule_form_submit` save the value you want.

```
function mymodule_form_submit(&$form, FormStateInterface $form_state) {
  $entity = $form_state->getFormObject()->getEntity();
  // Get the value of your field
  $my_val = $entity->get('field_name')->getValue();
  // Set new value
  $entity->set('field_name', 'http://' . $my_val);
  //Save the entity
  $entity->save();
}

```

---
Tags: 8, forms
---


# Question
Title: Display values of custom fields created on media entity in a template file
I'm trying to display the values from the custom fields that have created on my `Media Entity` to my `page--media.html.twig` file. The fields that I'm trying to output are `Location` and `Photographer`

I tried using this code below, to make it work.

`{{ node.field_photographer.entity.value }}`

Also tried an alternative

`{{ content.field_photographer.entity.value }}`

# Answer
> 3 votes
Your question is more about how to handle Drupal templates and passed variables. I suggest you to use Devel and Devel Kint modules to be able to debug variables just in your template like this:

`{{ kint() }}` \- print all available variables

`{{ kint(your_var_name) }}` \- print particular variable

And don't forget to enable twig debug mode \- it will show you templates structure.

Once you have everything visible it becomes much easier to understand.

---
Tags: entities
---


# Question
Title: Avoid reattaching javascript when a form is rebuilt by ajax callback
I have a form that uses `['#attached']['js']` to attach a simple javascript file. A checkbox element of this same form uses `['#ajax']` to dynamically update some portions of the form. I'm finding that, when the form is rebuilt after the ajax callback, the javascript file is reattached multiple times, causing unintended behaviors.

Is there any way to avoid reattaching a javascript file to a form if that same javascript has been attached previously?

# Answer
> 4 votes
As Clive mentioned, the usual way to solve this is to use `once()` when attaching behaviors:

```
Drupal.behaviors.myBehavior = {
  attach: function (context, serverSettings) {
    $('elementSelector', context).once('myId', function () {
      // The code that will be executed only once.
    });
  }
};

```

Also, check the official docs on Managing JavaScript in Drupal 7.

---
Tags: 7, javascript, ajax
---


title: Disable off-site payment redirect

text:
# Question
Title: Disable off-site payment redirect
I am using Drupal Commerce Kickstart and since we are having only one payment method I would like to disable the extra step "Payment" in the checkout process which is reserved for "Off-site payment redirect".

I did not find a way to disable this directly in the UI at Checkout settings (`admin/commerce/config/checkout`) because this checkout pane seems to be locked.

So I digged in code and found line 309 to 315 in commerce\_payment.module `(profiles\commerce_kickstart\modules\contrib\commerce\modules\payment\commerce_payment.module).`

```
  $checkout_panes['commerce_payment_redirect'] = array(
'title' => t('Off-site payment redirect'),
'page' => 'payment',
'locked' => TRUE,
'file' => 'includes/commerce_payment.checkout_pane.inc',
'base' => 'commerce_payment_redirect_pane',
 );

```

If I completely remove these lines the payment step is gone. If I set the locked value to "FALSE" I can disable the pane at Checkout settings.

What is the cause that this step is locked and is it safe to disable this step this way?

# Answer
> 1 votes
You don't need to disable it, because it will automatically skip itself if the payment method does not require an off-site redirect.

# Answer
> 0 votes
Thanks for your help, I understand that the step will be skipped if not necessary.

But I don't like that this additional button "Payment" is shown in checkout process also this will never be needed (in my case). I am assuming that this may confuse some customer to be expecting one more step that is not needed and also customer might think he still has one step before finally sending the order although the order will be placed already when finishing the "Review" step.

I have already succeeded to disable this step by using hook\_commerce\_checkout\_pane\_info\_alter in a custom module and setting this pane to not be locked and then disabling the pane via checkout settings.

Just wanted to know if this is the way to go and if there are any caveats by disabling this pane.

# Answer
> 0 votes
We had slightly different needs in our website, and finaly took the following approach:

1. First we disabled the review page. so the process is: cart-\>checkout-\>payment-\>complete.
2. The payment is our custom payment method. With rules we added custom condition: check if the order balance is more than zero: then enable the payment method.
3. In the configuration of Payment checkout page(*admin/commerce/config/checkout/form/pane/commerce\_payment*) there is an option `Require a payment method at all times` we unchecked this box and chose the final option: `Display a message ... and trigger...`

Now for your case:

I think you should explore the options in the checkout settings and disable the panes you do not need. Next look at the various rules you currently have, specially the ones triggered by `Completing the checkout process` (we override the default to change the status to complete since we had digital products).

Keep in mind that most of the job is happening in the checkout router. (I think that any website in production should implement the hook\_commerce\_checkout\_router )

When talking about payments there is two functions in commerce\_payment module that responsible for the redirections and the process flow:

1. commerce\_payment\_redirect\_pane\_previous\_page
2. commerce\_payment\_redirect\_pane\_next\_page

So if payment is successful, we move forward (each page has `next_page` definition). and if not, move back. When hitting `complete` page, all the rules will fire.

Best of luck!

---
Tags: commerce
---


title: Basic functions not being seen

text:
# Question
Title: Basic functions not being seen
I am getting the following error when invoking "commerce\_cart\_order\_product\_line\_item\_delete()" in a custom module I'm writing.

> Fatal error: Call to undefined function commerce\_entity\_reference\_delete() in /Users/\[username\]/Documents/Sites/\[site\_name\]/profiles/commerce\_kickstart/modules/contrib/commerce/modules/cart/commerce\_cart.module on line 1268

The `commerce_entity_reference_delete()` function that Drupal claims it can't find resides in:

> /\[site\]/profiles/commerce\_kickstart/modules/contrib/commerce/commerce.module

Which, if I understand correctly is THE main commerce module that makes the whole shopping cart functionality work. So, my commerce module is enabled (because my shopping cart is working, and which is confirmed also on the Modules page), so why isn't commerce.module serving up the function above for me?

Aren't I allowed to call `commerce_cart_order_product_line_item_delete()` from a custom module?

# Answer
This function `commerce_cart_order_product_line_item_delete` is in `commerce_cart.module` in line **1259** tnen in line **1268** call `commerce_entity_reference_delete`, function should be in `commerce.module` file line **124**, check the function exist there. This is some strange if the function exist in `commerce.module` and return fatal error, I suggest first be sure that the function exist in code then clear cache and then try again. It is allowable call any function in any custom module and drupal not have restriction about this subject.
> 0 votes

# Answer
A custom module can call any function defined from another module, if these conditions are met.

1. If the function is defined in the module file, that module must be installed, enabled, and loaded
2. If the function is defined in a .inc file, the module must be installed, and the file containing the function must be first loaded with `module_load_include()`

To expand the first point, if you are calling that function in `hook_boot()`, it could be too early for that, since the other module could not be loaded, yet.

In your case, `commerce_entity_reference_delete()` is defined in the commerce.module file, so the only reason I can think for that error is that the other module is calling `commerce_entity_reference_delete()` too early, when the module is not yet loaded, or Drupal didn't even complete its bootstrap, which happens with external script trying to call Drupal functions.
It could also be that the line calling `commerce_entity_reference_delete()` is not put inside a function call, and in this case we are back to `commerce_entity_reference_delete()` being called before the module file containing it is loaded.
> 0 votes

# Answer
Sounds like the weight of your module is lighter than drupal\_commerce (not the best starting point, I would change the module name and "reinstalling" my custom module)

So if you trying to call function that declared in another module before all modules are loaded, it will throw the above exception.

Also please have a look at: `hook_module_implements_alter`
> 0 votes

---
Tags: 7, commerce
---


# Question
Title: Redirect after submitting custom entity form
I'm working with a custom entity and would like to programmatically set the redirect based on submitted values.

When I set the redirect path however, the user is redirected to the canonical path instead of the path I'm setting in the redirect.

In the file `mymodule/src/Form/MyEntityForm.php`, I'm doing something like this:

```
  public function submitForm(array &$form, FormStateInterface $form_state)
  {
    // Note: Same results with the order of the next 2 lines reversed.
    parent::submitForm($form, $form_state);
    $form_state->setRedirect('mymodule.overview', ['state' => 'CA']);
  }

```

So how would I set the destination of an entity form submission dynamically?

# Answer
> 1 votes
Probably you need to override EntityFormInterface::save():

> Form submission handler for the 'save' action.
>
> Normally this method should be overridden to provide specific messages to the user and redirect the form after the entity has been saved.

`submitForm()` is the first submit handler called and should not be used to override submit actions.

---
Tags: 8, entities
---


title: Millions of entities when logging

text:
# Question
Title: Millions of entities when logging
I know there is a lot written on Drupal and tables that have tens of thousands and even millions of records but everyone has a different solution and I want to bring up a specific case.

I am using the log module (https://www.drupal.org/project/log) for Drupal 7 to save detailed custom log messages about a process that I have created for an internal system running on a small ubuntu VM in the Azure cloud. My bundle for the log entity has three custom fields. At 1.5 Million records with 4 custom fields that is 6 Million Records and we are growing every time the process iterates.

As you can imagine the site is slowed down to a near stop when making queries against the log table.

I am thinking of writing a little module to put the entities into a table that is not part of Drupal or exporting the data into a CSV file.

Is there a better way?

Thanks, Josh

# Answer
> 0 votes
I was trying to archive entities rather than system log entities from the log module (drupal.org/project/log). I wrote a small module that on cron finds up to 25K log entities that are 30 days old and then saves them to a CSV file and deletes them. http://dropbucket.org/node/9182

I hope this helps someone else.

# Answer
> 0 votes
First thing I would look at is creating indices for your tables. Look at the queries you are making and see if you can't optimize them with an SQL index. E.g. if you are querying against node id and user id with joins, try creating three indices, one for nid, one for id, one for nid and id.

Having the right indices can make a long running query fly.

# Answer
> 0 votes
Regarding your general approach, you're on the right track- avoid logging to Drupal's watchdog table; avoid writing to even a custom table in Drupal. Write logs to file(s) instead. Additionally, you'll want to determine a retention plan and prune the logs on a regular basis.

As @darvanen commented, there are some modules available for Drupal 7, but they vary in stability/support. Here's a synopsis of what you'll find:

* File Logger (https://www.drupal.org/project/flog): has a stable release, but has not been updated in 5 years; supports logging of any php variable, a label, and dump of php stack at time of log entry; limited to logging to just one log file
* File logger action (https://www.drupal.org/sandbox/martin\_klima/2257705): sandbox module that extends above to allow support of writing a customizable message (with tokens) to the log file
* Write Logs In File (https://www.drupal.org/sandbox/vikrantr/2688987): sandbox module that could be used as a starting point for a custom module that supports logging to multiple files
* File Log (https://www.drupal.org/project/filelog): only a dev version / initial port to D7 exists besides the D6 versions, hasn't been updated in 6 years; a watchdog interface implementation which records system events directly into files as an alternative to the Syslog core module

# Answer
> 0 votes
Depending on your exact use case and needs you can use core's syslog module in place of the default database logging.

---
Tags: entities, database
---


title: Content Type no showing fields

text:
# Question
Title: Content Type no showing fields
I have been trying to created a content type programmatically in Drupal 7. I notice that I should use the hook\_node\_info to generate the content type with the title and to add the body I should use the `node_add_body_field`. I have been follow the examples modules

So this is what I got as my code ...
**non\_recruiter.module**

```
<?php

/**
 * Implements hook_node_info().
 */
function non_recruiter_node_info() {
  // We define the node type as an associative array.
  return array(
      'job_template_2' => array(
          'name' => t('Job Template 2'),
          'base' => 'job_template_2',
          'description' => t('A content type for posting your jobs.'),
          'title_label' => t('Job Template 2'),
          'locked' => TRUE,
      ),
  );
}

/**
 * Implements hook_node_type_insert().
 */
function non_recruiter_node_type_insert($content_type) {
  if ($content_type->type == 'job_template_2') {
      $body_instance = node_add_body_field($content_type, t('Job Description'));
        $body_instance['display']['non_recruiter_list'] = array(
        'label' => 'hidden',
        'type' => 'text_summary_or_trimmed',
    );

    // Save our changes to the body field instance.
    field_update_instance($body_instance);

    // Create all the fields we are adding to our content type.
    foreach (_non_recruiter_installed_fields() as $field) {
      field_create_field($field);
    }

    // Create all the instances for our fields.
    foreach (_non_recruiter_installed_instances() as $instance) {
      $instance['entity_type'] = 'node';
      $instance['bundle'] = 'non_recruiter';
      field_create_instance($instance);
    }
  }
}

/**
 * Implements hook_form().
 */
function non_recruiter_form($node, $form_state) {
  return node_content_form($node, $form_state);
}

function _non_recruiter_installed_fields() {
  return array(
      'non_recruiter_quantity' => array(
          'field_name'  => 'node_example_quantity',
          'cardinality' => 1,
          'type'        => 'text',
      ),
  );
}

function _non_recruiter_installed_instances() {
  return array(
      'non_recruiter_quantity' => array(
          'field_name'  => 'non_recruiter_quantity',
          'label' => t('Quantity required'),
          'type'        => 'text',
          'widget'      => array(
              'type'    => 'text_textfield',
          ),
          'display' => array(
              'non_recruiter_list' => array(
                  'label' => 'hidden',
                  'type' => 'hidden',
              ),
          ),
      ),
  );
}

```

So I took what they did and modify the code base on what I want.

My Goal is to have a content type that have the following fields...

* Job Title (title)
* Job Description (body)
* Quantity (text)

But I'm doing something wrong because the fields are empty. If I try to add new content using this content type this is what I got ...

An empty content type, without any fields.

Here is some extra information of how my Manage Fields & Display looks like..
**Manage Fields**

**Manage Display**

So, can anyone tell me why my fields are not showing up in my content type ?

# Answer
```
/**
 * Implements hook_node_info().
 */
function non_recruiter_node_info() {
  // We define the node type as an associative array.
  return array(
      'job_template_2' => array(
          'name' => t('Job Template 2'),
          'base' => 'job_template_2',
          'description' => t('A content type for posting your jobs.'),
          'title_label' => t('Job Template 2'),
          'locked' => TRUE,
      ),
  );
}

/**
 * Implements hook_node_type_insert().
 */
function non_recruiter_node_type_insert($content_type) {
  if ($content_type->type == 'job_template_2') {
      $body_instance = node_add_body_field($content_type, t('Job Description'));
        $body_instance['display']['non_recruiter_list'] = array(
        'label' => 'hidden',
        'type' => 'text_summary_or_trimmed',
    );

// Save our changes to the body field instance.
field_update_instance($body_instance);

// Create all the fields we are adding to our content type.
foreach (_non_recruiter_installed_fields() as $field) {
  field_create_field($field);
}

// Create all the instances for our fields.
foreach (_non_recruiter_installed_instances() as $instance) {
  $instance['entity_type'] = 'node';
  $instance['bundle'] = 'job_template_2';
  field_create_instance($instance);
}
  }
}

/**
 * Implements hook_form().
 */
function job_template_2_form($node, $form_state) {
  return node_content_form($node, $form_state);
}

function _non_recruiter_installed_fields() {
  return array(
      'non_recruiter_quantity' => array(
          'field_name'  => 'node_example_quantity',
          'cardinality' => 1,
          'type'        => 'text',
      ),
  );
}

function _non_recruiter_installed_instances() {
  return array(
      'non_recruiter_quantity' => array(
          'field_name'  => 'node_example_quantity',
          'label' => t('Quantity required'),
          'type'        => 'text',
          'widget'      => array(
              'type'    => 'text_textfield',
          ),
          'display' => array(
              'non_recruiter_list' => array(
                  'label' => 'hidden',
                  'type' => 'hidden',
              ),
          ),
      ),
  );
}

```
> 0 votes

---
Tags: entities, nodes
---


# Question
Title: Adding a non-link element to the end of the breadcrumb
For example, in a "blog post" page I'd like the breadcrumb to display like this:

> Blog \> Recipes \> Recipe

I'm controlling all breadcrumbs from a single place, a class that implements `BreadcrumbBuilderInterface`. Its `build` method looks like this:

```
public function build(RouteMatchInterface $route_match) {
  $b = new Breadcrumb();

  $node = $route_match->getParameter('node');

  if ($node && $node->getType() == 'blog_post') {
    $b->addLink(Link::createFromRoute($this->t('Blog'), 'blog.home'));
    $b->addLink(Link::createFromRoute($this->t('Recipes'), 'blog.recipes_landing'));

    //I want this next item to not be a link, and to show "Recipe" and not the node title.
    //$b->addLink(Link::createFromRoute($this->t('Recipe'), 'nothing!'));
  }

  return $b;
}

```

How can I make this happen? I saw somewhere (not sure where, in a code comment perhaps) that this last item is supposed to be added in the theme layer, but I don't want to split my logic, especially since I don't just want all breadcrumbs to show the page title as the last item (instead, for example, I want it to say "Recipe" if the content type is `blog_post`).

# Answer
You can do almost like in your suggestion. You just need to use `'<none>'` instead of `'nothing!'`.

```
$b->addLink(Link::createFromRoute($this->t('Recipe'), '<none>'));

```
> 5 votes

# Answer
Here's the (very) complicated solution I implemented for this.

In a custom module, extend the Breadcrumb class, like this:

```
<?php

namespace Drupal\mymodule;

use Drupal\Core\Breadcrumb\Breadcrumb as Source;

class Breadcrumb extends Source {
  private $current = NULL;

  /**
   * @param string|NULL $title
   */
  public function setCurrentTitle($title) {
    $this->current = $title;
  }

  public function toRenderable() {
    $array = parent::toRenderable();
    $array['#current'] = $this->current;
    return $array;
  }

}

```

Then my `build` method from the question becomes this:

```
public function build(RouteMatchInterface $route_match) {
  $b = new Breadcrumb();

  $node = $route_match->getParameter('node');

  if ($node && $node->getType() == 'blog_post') {
    $b->addLink(Link::createFromRoute($this->t('Blog'), 'blog.home'));
    $b->addLink(Link::createFromRoute($this->t('Recipes'), 'blog.recipes_landing'));

    $b->setCurrentTitle($this->t('Recipe')); //yayhere!
  }

  return $b;
}

```

But, then, in my .theme file, I added this beautiful thing:

```
function mytheme_theme_registry_alter(&$theme_registry) {
  $theme_registry['breadcrumb']['variables']['current'] = [];
}

```

And, finally, the twig file became this:

```
{% if breadcrumb %}
  <nav class="breadcrumb container" role="navigation" aria-labelledby="system-breadcrumb">
    <h2 id="system-breadcrumb" class="visually-hidden">{{ 'Breadcrumb'|t }}</h2>
    <ol>
    {% for item in breadcrumb %}
      <li>
        {% if item.url %}
          <a href="{{ item.url }}">{{ item.text }}</a>
        {% else %}
          {{ item.text }}
        {% endif %}
      </li>
    {% endfor %}
    {% if current %}
      <li>{{ current }}</li>
    {% endif %}
    </ol>
  </nav>
{% endif %}

```

*Nice, eh?*
> 3 votes

---
Tags: 8, breadcrumbs
---


# Question
Title: How do I avoid the HTML I enter is altered?
I use drupal 8.4.3 with ckeditor 4.7.2 (apparently)

When I press the "source" button, I want to be able to write whatever source I want, in just one line if I want to, I don't want the ckeditor to touch my source code AT ALL.

How is that possible? I think I have used 3 hours googling, without making it work completely.

I want to be able to write "`<br><br>`" without it turning by code into:

```
<br /> (-- LINE BREAK)
<br />

```

I don't want it to touch it!!! it should just be `<br><br>` (without the closing /)

when I write into the source, ckeditor shouldn't touch it! How is that possible?

# Answer
> 2 votes
It's probably not just CKeditor altering your HTML. You should look into the configuration of your input formats at `/admin/config/content/formats`. There is documentation on https://www.drupal.org/docs/8/core/modules/filter/overview, although it's not very detailed.

An input format applies one or more text filters to your input. Common filters are the *HTML Filter*, that allows only a limited number of HTML tags, and the *Line Break Converter*, which turns line ends into `<br>` or `<p>` tags. You can configure your input format, or create a new one, without any filters.

If I recall correctly, even if you don't have any text filters configured, Drupal may still strip some HTML tags that are considered particularly dangerous, like the `<script>` tag.

# Answer
> 1 votes
Go to /admin/config/content/formats, create new text format without ckeditor:

---
Tags: 8, wysiwyg
---


title: Multiple product selection drop-downs

text:
# Question
Title: Multiple product selection drop-downs
I want to set up products with the following attributes: Size, Shape, Power and Colour. Each product will have one of the following attributes. The shape attribute determines the picture. Each shape will exist in multiple sizes, power ratings and colours. For many products having a single dropdown - which is the normal way to use Commerce - will present a confusing number of options 20 sizes, 5 power options and 10 colours - would give 1000 options.

Is it possible to set Commerce up with the 1000 products referred to above which a presented to the purchaser via 4 dropdowns ? The first selects the shape ( this pulls the picture ) and then below there are three other dropdowns for each of the other attributes. Selecting the other options needs to be able to pull different prices.

Any thoughts on how to approach getting Commerce to do this would be good. Thanks.

# Answer
> 0 votes
Create the product page with a 'multi-select' product(sku) field by setting the number of values to unlimited. Select those sku that relate to the product page when editing the content page.

By default you will get a display with a select list.

Making the interaction 'dependent'. Rather than just selecting blue-size-4 being able to select 'size' then 'colour' then custom javascript will be required.

Note that the product fields are customisable so you can always add a 'size' field to product type. If size results in different prices you are back to the n\*size product items. If you can find a way to communicate the logic to the customer the price could be adjusted using a rule on checkout.

---
Tags: commerce
---


# Question
Title: HOOK_entity_presave: field not accessible
I have been brooding on this problem for a while now and i can't figure it out:

I am trying to retrieve and finally modify two values of my entity. With the first one (field\_registro) it works, with the second one (field\_final\_note) it doesn't.

Both fields are of type Number (integer) with no restrictions.

This is how my hook looks like:

```
function mymodule_entity_presave(\Drupal\Core\Entity\EntityInterface $entity) {
  var_dump($entity->field_registro); // works
  var_dump($entity->field_final_note); // NULL
}

```

When i dump the whole entity i can see both fields (the second one should be empty and be set programatically, the first one has a user value).

See the dump here: https://pastebin.com/wcpyDt9h

I can see that there is clearly a difference in the structure, but i can't figure out WHY and HOW to fix it.

Can anybody point me in the right direction please?

# Answer
> 1 votes
Since Drupal 8 you need use OOP methods to get value from an entity field. For example:

```
// If you have a field with machine name "field_final_note".
$values = $entity->get('field_final_note')->getValue();

```

Also, have a look for the type of the entity:

```
if ($entity->getEntityTypeId() == 'node' && $entity->bundle() == 'node_type') {
 // Your code.
}

```

P.S. Well it is very helpful to know the next points

```
// An old entity state.
if (isset($entity->original)) {
  $old_entity = $entity->original;
  // Some code.
}

// If the entity is new.
if ($entity->isNew()) {
  // Some code.
}

```

---
Tags: 8, entities, hooks
---


# Question
Title: How do I create a view that uses data from an external site
I have a site that needs to get articles data from a view in site A in order to display these articles as a view in site B.

I found the module Services Views, which i don't completely understand. I have installed it in site A, and created a services resource of a view with services display.

But how do I create a view in site B that displays the articles using that services endpoint?

# Answer
You can use views\_database\_connector and include connection details to your settings.php and database will be available to views

add connection details to your settings.php

```
"example_db" = array (
  'default' =>
  array (
    'default' =>
    array (
      'database' => 'example',
      'username' => 'example_user',
      'password' => 'example_pass',
      'host' => 'xxx.xxx.xxx.xxx',
      'port' => '',
      'driver' => 'mysql',
      'prefix' => '',
    ),
  ),
);

```

and when you create a view you can choose specific table from this database to connect to

Should work for both drupal 7 & 8
> 1 votes

# Answer
You can do it in 2 ways, Store the data in site B and not store the data

# By Storing the data

1. expose data from the site A.
2. Grab the data and store it in site B.
3. Display the data in site B.

To achieve (1) you can use many modules for this; I would suggest Views data export

For (2) You can use Feeds module, it will grab the data and import it.

For (3) You just create a view of the content you store.

# Without Storing the data

Use Views Database Connector
> 1 votes

# Answer
A view was intended to pull data from the site DB, so you can not just add a view to site B.

After you added a services resource to site A you need to add some client code on site B that would pull this data and display it to the user. You can either code it all by yourself or use, for instance, Web Service Clients.
> 0 votes

---
Tags: 7, views, services
---


title: It doesn't work in the root directory

text:
# Question
Title: It doesn't work in the root directory
I'm trying to get Drush to work in a shared environment where I have limited SSH access. I've managed to install Composer and Drush. In PuTTY I can use Drush outside of my Drupal root folder, ie. /var/www/domain.com

Here I can successfully execute: `vendor/bin/drush help` and get the help output in return.

However, if I move (in PuTTY) to my web root folder where my Drupal installation is located: /var/www/domain.com/public\_html and try to execute `../vendor/bin/drush help` I get the following message: `: No such file or directory`

What am I doing wrong?

# Answer
> 0 votes
Ideally, you should be able to just run `drush help` by itself without having to specify a path to it. If you can't do that, then maybe your environment isn't getting paths set correctly. Something missing from .bashrc or .profile maybe?

If paths / environment is a problem, I'd try using the phar version of drush - it's a self contained single file, and might work better. You can just download it and run it from anywhere. There's nothing to install:

```
cd ~
wget https://github.com/drush-ops/drush/releases/download/8.1.11/drush.phar
chmod +x drush.phar
cd /var/www/sasclan.org/public_html
~/drush.phar help

```

# Answer
> -1 votes
I had the same problem and using Drush Launcher helped me.

> A small wrapper around Drush for your global $PATH.
>
> ### WHY?
>
> In order to avoid dependency issues, it is best to require Drush on a per-project basis via Composer (`composer require drush/drush`). This makes Drush available to your project by placing it at vendor/bin/drush.
>
> However, it is inconvenient to type vendor/bin/drush in order to execute Drush commands. By installing the Drush Launcher globally on your local machine, you can simply type `drush` on the command line, and the launcher will find and execute the project specific version of Drush located in your project's vendor directory.

---
Tags: drush
---


# Question
Title: How to add a reference to a view block in a field?
I am using Drupal 8. I created a block (*hotel*) with the Views module, and I would like to add a reference to the block in content type's field, but only custom blocks can be added. The *hotel* block cannot be added to a new field because it was created with the Views module.

How can I add a reference to a views block to a field? Alternatively, how can I convert a views block in a custom block?

# Answer
Both Views and Entity Reference are now part of the Drupal 8 core.

Go to
1) structure \>views and create a view of type page or block. In another display select entity reference as display.
2) In format settings select the search fields for this view and select the fields you wish your view should display. Now save the view.
3) Go to structure \> content types\> Content type to which you want to add the reference field. Create and new field of type content, set the label you wish to and save and continue.
4) In type of item to reference select, "view". Save field settings.
5) In field settings, under reference type, select "Views: filter by an entity reference view". Under "View used to select the entities ", select your entity reference view and save.
6) In manage display of content type for this reference field you can select Link to entity or rendered entity. I had selected rendered entity and save the manage display settings.
7) Now create a content of your content type and in the entity reference field give the name of entity to which you want to refer to.
> 1 votes

# Answer
There is a module for this, Viewfield, which currently supports both Drupal 7 & 8 (alpha version).

Or use the stable D8 version of EVA, which has a different, more powerful approach by attaching a Views display to an entity, which then appears as a configurable field in the display mode of the entity.

Or simply add the View to a template variable, for example in a preprocess hook:

```
$variables['view'] = views_embed_view('hotel', 'block_display');

```
> 0 votes

---
Tags: views, nodes, entities, 8, blocks
---


# Question
Title: How to programmatically set the field formatter for a field given certain conditions
I have an entity 'house' with an address field. The address field comes with a default field formatter plugin. This is perfect for when i view my entity at its canonical route and where its view\_mode is 'full'.

However I want to change how the address field is displayed when the 'house' has view\_mode 'teaser'. For example at a page that displays a list of all my houses. To be specific I want my address to appear on one line.

Now, I have gotten all this working. Like this:

`house_entity/src/Plugin/Field/FieldFormatter/AddressTeaserFormatter`

```
<?php

namespace Drupal\rrre_entities\Plugin\Field\FieldFormatter;

use Drupal\address\Plugin\Field\FieldFormatter\AddressPlainFormatter;
use Drupal\Core\Field\FieldItemListInterface;

/**
 * Plugin implementation of the 'address_teaser' formatter.
 *
 * @FieldFormatter(
 *   id = "address_teaser",
 *   label = @Translation("Teaser"),
 *   field_types = {
 *     "address",
 *   },
 * )
 */
class AddressTeaserFormatter extends AddressPlainFormatter {

  /**
   * {@inheritdoc}
   */
public function viewElements(FieldItemListInterface $items, $langcode) {
  $elements = parent::viewElements($items, $langcode);
  foreach ($elements as &$element) {
    $element['#theme'] = 'address_teaser';
  }
  return $elements;
}

```

`house_entity/house_entity.module`

```
/**
 * Implements hook_theme().
 */
function house_entity_theme($existing, $type, $theme, $path) {
  return [

    'house' => [
      'render element' => 'listing',
    ],

    'address_teaser' => [
      'variables' => [
        'recipient' => '',
        'organization' => '',
        'address_line1' => '',
        'address_line2' => '',
        'postal_code' => '',
        'sorting_code' => '',
        'dependent_locality' => [],
        'locality' => [],
        'administrative_area' => [],
        'country' => [],
      ],
    ],
  ];
}

```

and in the same `house_entity.module` file:

```
/**
 * Implements template_preprocess_HOOK().
 */
function template_preprocess_house(&$variables) {
  $addressDisplayOptions = [
    'type' => 'address_teaser',
  ];
  $house->address->getItemDefinition()->getFieldDefinition()->setDisplayOptions('view', $addressDisplayOptions);
}

```

Finally I have my template for my new address fieldformatter all set up at `house_entity/templates/address-teaser.htm.twig`

This all works fine.

*Except* that the custom field formatter does not apply to the first 'house' in my list of 'houses' (it does apply to all subsequent 'houses') ... and adding a xdebug\_break() immediately after the line:

`$listing->address->getItemDefinition()->getFieldDefinition()->setDisplayOptions('view', $addressDisplayOptions);`

Triggers the following error - basically that the twig template was not found:

Question?:

Do I have my template in the right place? Is there a more convenient way of setting a field formatter for a particular field on an entity?

# Answer
> 1 votes
> Is there a more convenient way of setting a field formatter for a particular field on an entity?

Yes, choose the formatter in the view mode settings (configure in the user interface) rather than using template preprocess.

(I found this old question looking for how to make a field formatter, and ended up copying Drupal\user\Plugin\Field\FieldFormatter and simplifying it by dropping the configuration parts, and then simply selecting that formatter on the view modes and Views tables i wanted to use it on.)

For ensuring this formatter doesn't show up in places it shouldn't, the key part is "isApplicable"; here's what mine looked like for a custom entity 'give\_donation' and a field named 'recurring':

```
  /**
   * {@inheritdoc}
   */
  public static function isApplicable(FieldDefinitionInterface $field_definition) {
    return $field_definition->getTargetEntityTypeId() === 'give_donation' && $field_definition->getName() === 'recurring';
  }

```

---
Tags: 8, entities
---


# Question
Title: How do I create a year-only drop-down field?
How do I create a year-only drop-down field?

I want to create a Drupal 8 field that shows a year drop-down with 100 years to the current year.

# Answer
The Year Only module provides this feature by defining a new field type.

.

It comes with a range configuration.

It produces the following result in the entity (node, ...) edit form. Configured with unlimited number of values in this example.
> 4 votes

# Answer
I would personally recommend following https://drupal.stackexchange.com/a/242011/5438. It's a little more work with some coding but it doesn't mean you need to add another module that needs to be supported in relation to many drupal areas. You can use a List (integer) field and add things there.

You can can also use a field\_integer textfield and use a form alterer.
> -1 votes

# Answer
You can use Date module.

> This package contains both a flexible date/time field type Date field and a Date API that other modules can use.

When you add field you can choose what you want to show (day, month, year) and + and - from current year.
> -2 votes

---
Tags: 8, entities
---


title: How do I add related products?

text:
# Question
Title: How do I add related products?
I want to display, let's say, three additional SKUs (e.g., skuredring3 and skuredring4) similar to the one of the displayed product (e.g., skuredring).

Is this even possible?

# Answer
> 4 votes
Related products in Drupal Commerce can be accomplished in a variety of ways:

1. As entity references, rendered in a related products view Using this approach, relationships are defined manually by Store/site managers (they curate/associate what specific products/skus to show as related) as they edit each product node. Then the view is setup with a contextual filter for the current node ID and a relationship to show all values assigned to the "related products" entity reference field. Refer to this "Related Products Guide using Views and Entity Reference" post that walks you through the approach.
2. As taxonomy tags, rendered in a related products views Using this approach, relationships are defined manually by Store/site managers (they tag products with specific classifications) as they edit each product node. Then the view is setup with a contextual filter for the taxonomy terms on the current node and a relationship for terms in the specific taxonomy on that node. See this similar post, "Related Articles - A Block View Of Nodes With Common Taxonomy Terms"
3. As a view that programmatically looks for skus of a particular pattern Using this approach, store/site managers don't have to tag products- they just need to ensure following a standard ruleset in defining skus for products. Then the site manager would setup a view of Commerce Products with a filter on the product sku field containing "skuredring" in your example. This approach locks the view into showing only those products with the sku.

---
Tags: commerce
---


title: How do I manually sort articles?

text:
# Question
Title: How do I manually sort articles?
I need to know of a way to manually order the articles displayed in the Drupal 8 front page by displaying a title between each piece. For example,

**Title A**

Article 2 Article 5 Article 3

**Title B**

Article 1 Article 7

I've tried configuring the front page view and looked into the Drupal 8 article and basic page settings but couldn't determine an effective way by which the above could be achieved. I also looked into whether there are any featured content modules available to suit my above needs but couldn't find any. And also the content needs to be able to be added to any page (not just the front page) as well.

If you anyone could point me in the right direction it would be greatly appreciated

# Answer
* `Title a,Title b` could be **terms** of a vocabulary
* add this vocabulary as term reference to article
* edit your nodes to include desired term
* modify front page view to group by term on this vocabulary

to have specific sorting for each of the term articles you can add integer field `position` to article and use it as sorting criteria in the view

for ordering the terms sort them in the vocabulary term list and use `term weight` as sorting criteria on view

For sorting one could also use draggable views and even nodequeue as suggested in the comments
> 1 votes

---
Tags: nodes
---


# Question
Title: Migration from one domain to other domain
I have build a D8 website on domain **www.example.com/abc** and now wants to copy this site to **www.example.com/xyz**

Hosting is same

What I did is: 1) copied all files from **abc** to **xyz**. 2) Exported Database from **abc** and imported it to **xyz**. 3) Assigned new Database name, Username and Password to **xyz** in **settings.php**.

When I go to **www.example.com/xyz** Homepage looks perfect but when I go to inner pages it takes me back to domain **www.example.com/abc**.

How should I update the URLs?

# Answer
Additionally to the suggestions of @Anson W Han, you will have to clear all your database stored routing caches. The easiest way to do this is running `drush cr` on the console from within your Drupal installation's root folder, if you have drush installed.

You can also run the database update script at yourdomain/xyz/update.php, which will flush the caches as well.

Third way is to logging in to your back-end and navigating to "Administration / Configuration Development / Performance" where you can clear the caches using the admin UI.
> 0 votes

# Answer
* More than likely, you have a redirect base directive in your .htaccess. This is used when serving your Drupal site out of a subfolder of your webhosting provider's webroot. You should check your .htaccess file for the directive `RewriteBase /abc` and replace with `RewriteBase /xyz`
* If that still doesn't work, check the vhost entry of your webserver for the same directive.
* Otherwise, if the site still redirects to "/abc", then you may have a $base\_url defined in settings.php causing the redirect.
> 1 votes

---
Tags: migrations
---


title: Get field value by machine name

text:
# Question
Title: Get field value by machine name
I developed a custom module in Drupal 7. I asked a similar question here: Drupal 7 Get field value by machine name and pass to javascript

But the difference in this question is, instead of a taxonomy term, I want to get the field value of a regular text field.

Here is the code that I use to get the field value of a taxonomy term to pass to javascript, which currently resides in my theme's hook\_process\_page function:

```
if ($node = menu_get_object('node')) {
  $tid = $node->field_test['und'][0]['tid'];
  $term = taxonomy_term_load($tid);
  drupal_add_js(array('mymodule' => array('test' => $term->name)), 'setting');
}

```

Some things that I can see might ned to be changed right away are "tid," "taxonomy\_term\_load."

How can I change this code to instead get the text value of a field instead of a taxonomy term, to pass to mymodule?

EDIT:

Per a suggested change, I've modified the code, though I'm not sure this is what was meant:

```
if ($node = menu_get_object('node')) {
  $fieldValue = $node->field_test['und'][0]['value'];
  $term = taxonomy_term_load($fieldValue);
  drupal_add_js(array('jsblock' => array('test' => $fieldValue->name)), 'setting');
}

```

The in response to Drupal.settings.jsblock.test, the console outputs null.

Here is the Drupal notice:

Devel results:

How can I get the field value and pass it to my jsblock module?

# Answer
> 0 votes
The suggestion you wrote for your code

```
$fieldValue = $node->field_test['und'][0]['value'];
$term = taxonomy_term_load($fieldValue);

```

If you require only value then your purpose gets solved at this line of code

```
$fieldValue = $node->field_test['und'][0]['value'];

```

Secondly the function taxonomy\_term\_load() expects tid as parameter and you are sending a value string, hence it will throw an error. See the API document. https://api.drupal.org/api/drupal/modules!taxonomy!taxonomy.module/function/taxonomy\_term\_load/7.x

You should just send the variable to javascript file as this

```
drupal_add_js(array('jsblock' => array('test' => $fieldValue)), 'setting');

```

# Answer
> 0 votes
For text fields you can use

```
$value = $node->field_my_field_name['und'][0]['value'];

```

or, if you want sanitized value, use `['safe_value']`.

---
Tags: theming, entities, javascript
---


# Question
Title: Rules (not) triggered with Bulk Media Upload
Rules (not) triggered with Bulk Media Upload

I have a node type called 'uploads' that includes a user reference field to make each upload particular/available to a certain user.

I have added a rule so when a new upload is added, they are e-mailed to let them know there's something new for them to see once they're logged in.

This works fine when adding uploads (nodes) one at a time, but I'm also using "Bulk Media Upload" (https://www.drupal.org/project/bulk\_media\_upload) to allow for multiple uploads/node creation, at which point the rules fail with the following error:

"Unable to get the data value for the variable or parameter id. Error: Unable to get the data property uid as the parent data structure is not set."

I realize that Bulk Media Upload is on/past the outs; but I do need the functionality it provides and am unsure as to why the data isn't available doing things this way when they are doing things one at a time. The references are made the same way in either case since Bulk Media Upload uses/requires the same values.

Edit - Ok, here's the rule being used:

```
            { "rules_results_uploaded" : {
                "LABEL" : "Results Uploaded",
                "PLUGIN" : "reaction rule",
                "OWNER" : "rules",
                "REQUIRES" : [ "rules", "php" ],
                "ON" : { "node_insert--uploads" : { "bundle" : "uploads" } },
                "DO" : [
                  { "entity_fetch" : {
                      "USING" : { "type" : "user", "id" : [ "node:field-for-user:uid" ] },
                      "PROVIDE" : { "entity_fetched" : { "entity_fetched" : "Fetched entity" } }
                    }
                  },
                  { "drupal_message" : { "message" : "Receipt of the sample on \u003C?php echo $data[\u0027components\u0027][\u0027sample_received\u0027][\u0027value\u0027][0]; ?\u003E has been acknowledged.  \r\n\r\nAn e-mail will be sent to [entity-fetched:field-practitioner-name] at [entity-fetched:mail]" } },
                  { "mail" : {
                      "to" : "[entity-fetched:mail]",
                      "subject" : "Your Sample Results Have Been Uploaded",
                      "message" : "Dear [entity-fetched:field-practitioner-name],\r\n\r\nNew sample results are now available on your account.",
                      "from" : "results@afakewebsite.com",
                      "language" : [ "" ]
                    }
                  }
                ]
              }
            }

```

Again, the rule works fine when fine when adding a new node of the type 'uploads' one at a time, it just doesn't work using bulk media upload (though triggering multiple times.) Perhaps I'm misunderstanding how BMU works.

Any thoughts or alternatives still much appreciated.

# Answer
As noted, your rule is setup for serial upload operations; BMU sets the entities in a batch process, rather than one reference/file at a time.

You may be able to overcome the race condition resulting from the rule firing and batch processing by triggering the rule on ***node save*** rather than individual file uploads while editing the node. This will ensure each file has a Drupal FID assigned and has been fully added to the files table in Drupal for referencing.
> 0 votes

---
Tags: 7, rules, media
---


# Question
Title: Basic Page POST request to Contenta JSON_API endpoint fails
UPDATE 2:

Wow... Seems that if I manually request an OAuth token and then copy/paste that into an `Authorization: Bearer ...` header manually, my POST request works!!!

Why the built-in Postman OAuth2.0 functionality does not work, for the specific Request, is beyond me??!!!

UPDATE:

## Here are the errors that show up when I turn on database logging...

**OAuth Error ???**

**Invalid Type ???**

**My Environment**

* "Out of the box" Contenta CMS Distribution
* New user, consumer, and role created with all "create and view" permissions enabled.
* Oauth token request working as expected
* All CORS setup and configured correctly and tested with JSON\_API view subrequests

---

I can't understand why the following basic page post request is failing:

Here's the error:

```
{
    "errors": [
        {
            "title": "Bad Request",
            "status": 400,
            "detail": "Invalid type specified for related resource: 'node_type--node_type'",
            "links": {
                "info": "http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.4.1"
            },
            "code": 0
        }
    ]
}

```

Here's the body I'm sending:

```
{
 "data": {
  "type": "node--page",
  "attributes": {
    "title": "Hello Page",
    "body": {
        "value": "Custom value",
        "format": "plain_text"
      }
  },
  "relationships": {
    "type": {
      "data": {
        "type": "node_type--node_type",
        "id": "page"
      }
    },
    "uid": {
      "data": {
        "type": "user--user",
        "id": "1"
      }
    }
  }
 }
}

```

Based off the youtube video here: https://www.youtube.com/watch?v=vEfH2TZAxDg&index=14&list=PLZOQ\_ZMpYrZsyO-3IstImK1okrpfAjuMZ

The documentation here doesn't seem to really help too much with the Contenta basic page as the post body object, provided by the API, is significantly different from the example.

https://www.drupal.org/docs/8/modules/json-api/creating-new-resources-post

Any strategies for translating the API provided post to the actual request that needs to be sent is greatly appreciated.

---

Based off the Contenta API, the correct post url is: `/api/pages`

Below is a screen capture gif showing all of the required fields as defined on the API Screen

Here is my configuration for the consumer, role, user, and permissions

Here is my Post initiated from PostMan. Note the OAuth Token appears to be returned and appended to the header as expected.

---

PostMan Exported JS

```
var data = "{\n \"data\": {\n  \"type\": \"node--page\",\n  \"attributes\": {\n    \"title\": \"Hello Page\",\n    \"body\": {\n        \"value\": \"Custom value\",\n        \"format\": \"plain_text\"\n      }\n  },\n  \"relationships\": {\n    \"type\": {\n      \"data\": {\n        \"type\": \"node_type--node_type\",\n        \"id\": \"page\"\n      }\n    },\n    \"uid\": {\n      \"data\": {\n        \"type\": \"user--user\",\n        \"id\": \"1\"\n      }\n    }\n  }\n }\n}";

var xhr = new XMLHttpRequest();
xhr.withCredentials = true;

xhr.addEventListener("readystatechange", function () {
  if (this.readyState === 4) {
    console.log(this.responseText);
  }
});

xhr.open("POST", "http://contenta.loc/api/pages?XDEBUG_SESSION_START=PHPSTORM&_format=api_json");
xhr.setRequestHeader("Content-Type", "application/vnd.api+json");
xhr.setRequestHeader("Authorization", "Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsImp0aSI6IjViM2RmNmU5NDViYWIzMjFmOWJiMGYyZGM4MzE4N2MxYmFjN2FmZGFkMTA1NTdlMDkzMzEyMDM4NmM1ZTUyOWExYzRmZjY3YjRkY2VmYzZhIn0.eyJhdWQiOiI3N2U0MDUwNi00YjJhLTQzMTctYjZjMC01ZWQ1YjI3Y2U4ODYiLCJqdGkiOiI1YjNkZjZlOTQ1YmFiMzIxZjliYjBmMmRjODMxODdjMWJhYzdhZmRhZDEwNTU3ZTA5MzMxMjAzODZjNWU1MjlhMWM0ZmY2N2I0ZGNlZmM2YSIsImlhdCI6MTUxMzEwMjQwMSwibmJmIjoxNTEzMTAyNDAxLCJleHAiOjE1MTMxMDI3MDEsInN1YiI6IjIxIiwic2NvcGVzIjpbImF1dGhlbnRpY2F0ZWQiLCJjb25zdW1lcl8yXzBfcm9sZSJdfQ.KGbWtYfFwUceVViu1hEEkSZFYiIO1-AznDKaYfzUqgMlwfMQFL1AOeALMrNgtZmSHtKLnPCSp0wrwBQlL7OcJ2DAy8IJOKgCmPv3BDEMkbVvPIY8ho8qeRLkuDIJQFmzBSFxkjb5KajAZm81CdWC13jeQo25E5S1CePM4i1zWL6vNYJJaI9WO0OtMELrTwcFq-gNr-p0bvfrna0JJLPmNVVLCmTj8z34Du_LjfM9oivu62vo3w3PLfpB_UpjOms1eOZ97FV1avtmOjM7ojG7HbNQ4VB5f6fb0XDQUL9QpSWCKwOskNV6nfR_hzoDb2g9dSdE257TZh3RGKbNKurmhOwv2EFnxzLlBCnwMjg72q8PnUhmGkKVO_8g5tui2nj_QDXzACiL-u6YCj4ZMvwGTmRTudJ_Bb0YnQnDjI8vnjMzEWTyLctXQxAKQBbmZxBRdCGrCF0vwFXS8iVNmdfeBmoneKbfvbZpzdvxQ19Q51BaobfNcN0nBcghs1VsbG17OfZmP1OufxEzcFF1ySuWLYZFR1JcH-Fmz-AVs9qHSkyJuKc8T5Yr3vKFwhiTkQ3XwiF4lSpOqChJqoIIA2rHO8Tz4UQ0M-3ae3bCw67c3pTh0t-9JndCaVXt-UTrZqTKQcCufjSq6rrcx5_5yegx-8ulAT6zIuXyytdllbmsA5M");
xhr.setRequestHeader("Cache-Control", "no-cache");
xhr.setRequestHeader("Postman-Token", "d596f540-f26d-f933-5ed8-0a0453f99d13");

xhr.send(data);

```

# Answer
A couple things worth checking:

1. In your PostMan request- note the url has "pages", and not "page". You'll need to confirm the machine name of the content type and see what the /node/add/\[node-type\] path is when adding content through Drupal's administration backend. Your API request should have the same \[node-type\] url parameter.

Assuming the url is correct,

2. Have you confirmed that user 1/admin role has permissions to create new "Page" nodes (from People \> Permissions)?
3. Are there any required fields on the node type that you need to set/pass data for in your JSON?
4. Turn on error logging and check the Watchdog log upon making a request to post a new node, as it may provide hints as to what is missing/failing.

In the JSON data you're sending, you don't necessarily need to set a relationships.type (even though the tutorial video shows it), as it will inherit that from the node type you specify in data.type.
> 1 votes

---
Tags: javascript, 8
---


# Question
Title: Form in controller does not render as usual
In Drupal 8.4.3, I tried to render a form inside a controller's method, but it does not render as usual.

* The value of #default\_value is not taken into account
* Fields have no *name* attribute (which causes them not to be sent)

This is the smallest code I've been able to write to reproduce the issue.

```
public function list()
{
  $render = array(
    '#type' => 'form',
    'search' => array(
      '#type' => 'textfield',
      '#title' => 'Search',
      '#default_value' => 'Lorem ipsum'
    ),
    'actions' => array(
      '#type' => 'actions',
      'submit' => array(
        '#type' => 'submit',
        '#value' => 'Apply'
      )
    )
  );

  return $render;
}

```

The rendered markup is the following.

```
<form method="post" accept-charset="UTF-8">
  <div class="js-form-item form-item js-form-type-textfield form-type-textfield js-form-item- form-item-">
    <label>Search</label>
    <!-- No name attribute, nor a value -->
    <input type="text" size="60" maxlength="128" class="form-text">
  </div>
  <input type="submit" name="op" value="Apply" class="button js-form-submit form-submit">
</form>

```

The sent data is the following. Obviously, the *search* field is not sent as it does not have a name.

```
op=Apply

```

I can overcome the missing *name* attribute with a *#name* key, but I cannot understand why it is needed here, but no where else.

This is the most basic route/controller pattern.

What could interfere in my context?

# Answer
> 0 votes
As stated by @Clive, I was bypassing the form builder. Even if the form was visually rendered, it was far from something fully working.

This answer shows how I managed to stick to my original need, which was to load a form and render it *inside* a controller.

You'll first need a class inheriting `FormBase`, as any form you would usually create. No need for a route.

```
class CustomForm extends FormBase
{
  public function getFormId()
  {
    return 'custom_form';
  }

  public function buildForm(array $form, FormStateInterface $form_state, $id = null)
  {
    $form['search'] = array(
      '#type' => 'textfield',
      '#title' => 'Search',
      '#default_value' => 'Lorem ipsum'
    );
    $form['actions'] = array(
      '#type' => 'actions',
      'submit' => array(
        '#type' => 'submit',
        '#value' => 'Apply'
      )
    );
    return $form;
  }

  public function submitForm(array &$form, FormStateInterface $form_state)
  {
    return;
  }
}

```

You then will need the `formBuilder` service to properly load it inside your controller:

```
class CustomController extends ControllerBase
{
  public function foobar()
  {
    $render = array();

    $form = \Drupal::formBuilder()->getForm(CustomForm::class);
    $render['form'] = $form;

    // $render['whatever'] = ...

    return $render;
  }
}

```

# Answer
> 1 votes
It's not possible to use form elements in a controller directly, only render elements. You find a complete list of both types here: https://api.drupal.org/api/drupal/elements/8.4.x

To use form elements in a page controller you need a form route:

*example.routing.yml:*

```
example.form:
  path: '/example-form'
  defaults:
    _title: 'Example form'
    _form: '\Drupal\example\Form\ExampleForm'
  requirements:
    _permission: 'access content'

```

And then build the class `ExampleForm` by extending `FormBase`. See https://www.drupal.org/docs/8/api/form-api/introduction-to-form-api

This is the most basic route-controller pattern for forms.

---
Tags: forms
---


title: Prepend drag icon to each form element

text:
# Question
Title: Prepend drag icon to each form element
I am building a configuration form with a few sortable elements. I know, you can build a table using builtin Drupal draggable functionality (**drupal\_attach\_tabledrag**), but it's a bit too complicated for my task.

I am saving new order of elements inside a hidden input field value using Jquery UI **Sortable** function and dynamically set **#weights** in form elements:

```
    $weights = $config->get('sort_order');
    parse_str($weights, $weights);

    $form['el1'] = [
        '#type' => 'checkbox',
        '#title' => 'Title1',
        '#default_value' => $config->get('el1'),
        '#weight' => $weights['el1']
    ];

    $form['el2'] = [
        '#type' => 'checkbox',
        '#title' => 'Title2',
        '#default_value' => $config->get('el2'),
        '#weight' => $weights['el2']
    ];

```

Elements are draggable and sorting works fine. The only difficulty I have is prepending an icon to each element so that others could use that icon to drag elements up and down (just like Drupal does in a lot of configuration UIs).

I know you can create custom elements using **#markup** with an image tag inside it, or some div with image background. But adding custom markup to each element is problematic for several reasons:

1. I'll have to write different names for each markup separately. For example if I have a markup element:

```
$form['drag-icon'] = [
    '#type' => '#markup',
    '#markup'=> '<p class="drag-icon"></p>'
];

```

its name is **drag-icon** and to prepend it to another element, I'd have to use a different name each time (this is horrible).

2. Although it can be aligned well with the element using css, dragging on that icon, breaks the line while moving it up/down.
3. Would have to write this mark up manually for each element.

I also tried using a template file for this form, but among other things, I couldn't keep track of sort order inside it so easily as in **buildForm()** function using **#weight**.

I wrote a lot of explanations to show what I have tried.

I just want a simple method to append an icon to each element of the form to achieve something like this:

# Answer
I want to implement this dragging functionality in Drupal 8, may i know how you achieve draggable functionality in that or can you share the code
> 0 votes

---
Tags: 8, forms
---


title: How to change the label of title field

text:
# Question
Title: How to change the label of title field
How to change the label of title field bydefault its showing **Title** I need to change it to **"Custom-title"** of **node edit form** programatically.

I tried

```
 function mymodule_form_alter(&$form, FormStateInterface $form_state, $form_id) {
if ($form_id =="slices_slices_cta_5_edit_form")
{
    kint($form[title][widget][0]['#title']);
    dpm($form[title][widget][0]['#title']->jsonSerialize());
   $form[title][widget][0]['#title']->jsonSerialize()==t("Custom-title");
     //dpm($form[title][widget][0]['#title']->getArguments());

}

```

I just want to change \[string\] property of class TranslatableMarkup's object of above screen shot.

How to access the value of a Drupal\Core\StringTranslation\TranslatableMarkup object within a form

**I want to do something like below example:**

```
$form[title][widget][0]['#title']->string = t('New-title');

```

Not working above solution.

# Answer
> 2 votes
You can change the title label by editing the node type settings by going to Admin \> Content Types \> (type) \> Edit. No code needed, and this can be exported to configuration.

I’m not even sure what your code is trying to do, but you don’t need it.

---
Tags: 8
---


title: Using twig extensions in Drupal 7

text:
# Question
Title: Using twig extensions in Drupal 7
I would like to be able to use some custom PHP code that generates an SVG image in my .tpl.twig file. Since I can't write PHP in a twig template I figured I should try and make a twig extension (http://symfony.com/doc/current/cookbook/templating/twig\_extension.html)

How could this be done in Drupal? Or is there another way?

# Answer
When you are using tfd7 you can use extensions, functions, etc. The easiest way to go is to create an own module for handling all the php-functions.

In your `OWN_MODULE.module`:

```
function OWN_MODULE_twig_function() {
  $functions = [];
  $functions['XYZ_unset_key'] = new TwigSimpleFunction('XYZ_unset_key', 'XYZ_unset_key_callable');

  ...

  return $functions;
}

function XYZ_unset_key_callable($key, $array) {
  unset($array[$key];
  return $array;
}

```

After that you can use the function `XYZ_unset_key` in your twig-files:

```
<div>
  {{ XYZ_unset_key('field_xyz', 'content') }}
</div>

```
> 0 votes

---
Tags: 7, theming
---


# Question
Title: Is it easy to save changes as draft on a published page?
I'm editing a published page using Drupal and would like to save my changes as draft before publishing an updated version. This must be possible, but how?

# Answer
> 2 votes
> Is it easy to save changes as draft on a published page?

**No!** The proof of that is what the Workflow Initiative is all about (it takes an *initiative* to get it done). Here is a quote from it:

> The 'Draft' workflow state is a long-requested usability improvement, but may seem like a small change. What is more exciting is that the list of workflow states is fully configurable

Refer to Moving the Drupal 8 workflow initiative along, from *famous* Dries, for a very good article (and interesting animations) about it.

---
Tags: 8
---


# Question
Title: Edit of page with captcha requires solving captcha?
I just added a captcha to a page and it seems that the users with edit permission have to solve the captcha in order to edit/save the page. Is this normal behavior? Is there a setting that will allow for editing w/o having to solve the captcha?

# Answer
> 1 votes
Making the assumption that you're using the CAPTCHA module there is a permission called Skip CAPTCHA you should configure for your editor's roles to skip it.

---
Tags: captcha
---


# Question
Title: How to Embedd youtube video in body field (converts URLs into embedded players)?
Is there a simple way to insert youtube video in body field like other CMS where you copy a youtube link in the article body and it is automatically converted into a video player in front end.

I’ve search here and some topics talk about modules but there are not drupal 8 yet.

Is there a module that can do that or Drupal 8 maybe can do that natively ?

# Answer
> 4 votes
I’ve found and tested this module which do excaly what I want :

Url to Video Filter

> This module adds a new input filter that automatically converts URLs for various video sharing websites into embedded players into the text.

Here is a screenshot of the CKEditor filter :

I’ve tested this module on multiple sites and it works very well.

Currently this module supports the following services : YouTube / Vimeo

**EDIT** Now, It also supports Youtube URL with parameter like `?rel=0` (`rel=0` is used to disable related videos shown at the end of a video)

# Answer
> -1 votes
* Get the embed URL of the Youtube video which will be a iframe.
* Place that iframe markup in body field. Use Full HTML format to allow iframe tag.
* Since CKeditor is the default editor in Drupal 8, you can also use iframe tool.

---
Tags: 8, files
---