# Question
Title: How to change user field value after node form is submitted?
I currently have a user field called `field_reputation` with a default integer value of 0 (if a user registeres).

The idea is that this field increases when certain actions are executed. For example, when a user publishes a new article, `field_reputation` should be its current value + 10.

I am trying to achieve this using a form hook:

```
function MYTHEME_form_alter( &$form, &$form_state, $form_id ) {
  if ( TRUE === in_array( $form_id, array( 'node_article_form') ) ) {
    foreach (array_keys($form['actions']) as $action) {
        if ($action != 'preview' && isset($form['actions'][$action]['#type']) && $form['actions'][$action]['#type'] === 'submit') {
          $form['actions'][$action]['#submit'][] = '_increase_reputation';
        }
      }
}

```

And then this function is called:

```
function _increase_reputation(array &$form, FormStateInterface $form_state) {
  // Do something here
}

```

However I can't seem to figure out what code should be written in this function.

# Answer
As @Clive says, form submit handler is a bit too late. Do it in `hook_node_presave` or `hook_entity_presave`. If you do it in `hook_node_presave`:

1. Check the node type first: `if ($node->bundle() === 'article')`
2. Get the current user: `$user = User::load(\Drupal::currentUser()->id());`
3. Then set the field value: `$value = (int) $user->get('field_reputation')->getString() + 10; $user->set('field_reputation', $value);` (I'm not 100% sure on this code, but I'm sure there are better ways to do it when you have more than 5 minutes :D. Feels dirty to use `getString()` and then type-cast it into `int`)
4. Save the user entity with `$user->save();`

If you use `hook_entity_presave` then you just need to check for the entity type additionally: `$entity->getEntityType->Id() === 'node'`
> 3 votes

---
Tags: 8, nodes, forms, hooks
---


# Question
Title: Can't get Flagging API to accept POST request
trying to use the REST API that comes with the flagging module on Drupal 8.

I've enabled and secured the endpoint that comes with the module: /entity/flagging: POST

I'm nearly there, but following examples from earlier releases don't seem to work; What I'm trying to achieve is adding a flag for one user (1) for one content item (34). I got this far on the POST:

```
{
"entity_id":[{"target_id":34}],
"flag_id": "my_flag",
"uid": [{"target_id": 1 }],
"flag_action": "flag"
}

```

But I get this error:

```
InvalidArgumentException: Field flag_action is unknown.

```

Without the flag\_action argument though I get:

```
{"message":"You are not authorized to create this flagging entity of bundle my flag."}

```

I'm not sure how I can not be authorised i'm sending credentials of the sys admin (using basic\_auth).

Anybody know how I can add or remove a single flag from an entity using the Rest API? thanks!

# Answer
I tried to create a flag, however, I had the same results.

To solve this, I have created a module.

***note: to make tests I installed the "Flag Bookmark" module.*** file test\_api.info.yml.

```
    name: Test API
    type: module
    description: Custom RESTful API module with GET/POST/PUT/DELETE etc.. method examples.
    author: Minnur Yunusov
    core: 8.x

```

file test\_api.routing.yml.

```
# Test API endpoints

  test_api.get:
  path: 'my-api/get.json'
  defaults: { _controller: '\Drupal\test_api\Controller\TestAPIController::get_example' }
  methods:  [GET]
  requirements:
    _access: 'TRUE'

test_api.put:
  path: 'my-api/put.json'
  defaults: { _controller: '\Drupal\test_api\Controller\TestAPIController::put_example' }
  methods:  [PUT]
  requirements:
    _access: 'TRUE'

test_api.post:
  path: 'my-api/post.json'
  defaults: { _controller: '\Drupal\test_api\Controller\TestAPIController::post_example' }
  methods:  [POST]
  requirements:
    _access: 'TRUE'

test_api.delete:
  path: 'my-api/delete.json'
  defaults: { _controller: '\Drupal\test_api\Controller\TestAPIController::delete_example' }
  methods:  [DELETE]
  requirements:
    _access: 'TRUE'

```

we create the following directories and file TestAPIController.php src/Controller/TestAPIController.php

```
<?php

/**
 * @file
 * Contains \Drupal\test_api\Controller\TestAPIController.
 */

namespace Drupal\test_api\Controller;

use Drupal\Core\Controller\ControllerBase;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\JsonResponse;
use Drupal\user\Entity\User;

/**
 * Controller routines for test_api routes.
 */
class TestAPIController extends ControllerBase {

  /**
   * Callback for `my-api/get.json` API method.
   */
  public function get_example( Request $request ) {

    $response['data'] = 'Some test data to return';
    $response['method'] = 'GET';

    return new JsonResponse( $response );
  }

  /**
   * Callback for `my-api/put.json` API method.
   */
  public function put_example( Request $request ) {

    $response['data'] = 'Some test data to return';
    $response['method'] = 'PUT';

    return new JsonResponse( $response );
  }

  /**
   * Callback for `my-api/post.json` API method.
   */
  public function post_example( Request $request ) {

    // This condition checks the `Content-type` and makes sure to
    // decode JSON string from the request body into array.
    if ( 0 === strpos( $request->headers->get( 'Content-Type' ), 'application/json' ) ) {
      $data = json_decode( $request->getContent(), TRUE );
      $request->request->replace( is_array( $data ) ? $data : [] );
    }

    //get value json
    $flag_id= $data["flag_id"];
    $entity_type= $data["entity_type"];
    $entity_id = $data["entity_id"];
    $uid= $data["uid"];
    $created = REQUEST_TIME;

    //get user
    $user= User::load($uid);

    //get field uuid
    $user_uuid= $user->get('uuid')->value;

    //add entity_id to the field field uuid (unique value);
    $user_uuid= $user_uuid.'-'.$data["entity_id"];

    $fields=array(
      'flag_id' => $flag_id,
      'uuid' =>$user_uuid, //unique value
      'entity_type' =>$entity_type,
      'entity_id' => $entity_id,
      'uid' =>$uid,
      'global' =>0,
      'created' => $created
    );

    if ($data["flag_action"]=='flag') {

        //verify if exists record
        $sql="select * from {flagging} where entity_type ='$entity_type' and entity_id=$entity_id and flag_id='$flag_id' and uid=$uid ";
        //execute query
        $connection = \Drupal::database();
        $result = $connection->query($sql);
        $result=$result->fetchAll();

        //if not exists record, create flag
        if (count($result)>0) {
          $response['¿Flag exists?'] = 'true';
        }
        else {

              $resultado= db_insert('flagging')
              ->fields($fields)
              ->execute();

              $response['newflag'] = $resultado;

        }

        $response['data'] = $data;

    }

    else if ($data["flag_action"]=='unflag') {

        //verify if exits record
        $sql="select * from {flagging} where entity_type ='$entity_type' and entity_id=$entity_id and flag_id='$flag_id' and uid=$uid ";
        //execute query
        $connection = \Drupal::database();
        $result = $connection->query($sql);
        $result=$result->fetchAll();

        //if exists record, delete flag
        if (count($result)>0) {

          $num_deleted = db_delete('flagging')
          ->condition('entity_type', $entity_type)
          ->condition('entity_id', $entity_id)
          ->condition('flag_id', $flag_id)
          ->condition('uid', $uid)
          ->execute();

          $response['¿Delete flag?'] = 'true';
        }
        else {

          $response['¿Flag exists?'] = 'false';

        }

        $response['data'] = $data;

    }

    /*

    //send json example
    //change "bookmark"  by "my_flag"

    {
      "entity_id":31,
      "entity_type":"node",
      "flag_id": "bookmark",
      "uid": 1,
      "flag_action": "flag"
    }

    */

    return new JsonResponse( $response );
  }

  /**
   * Callback for `my-api/delete.json` API method.
   */
  public function delete_example( Request $request ) {

    $response['data'] = 'Some test data to return';
    $response['method'] = 'DELETE';

    return new JsonResponse( $response );
  }

}

```

Note: in the tests change "bookmark" by "my\_flag"

test: url: http://jeremiselxi.260mb.net/drupal8/my-api/post.json method:post; headers: Content-type: application/json X-CSRF-Token: token()

note: this token is obtained through the GET method to the url localhost/session/token

create flag

```
{
  "entity_id":34,
  "entity_type":"node",
  "flag_id": "bookmark",
  "uid": 1,
  "flag_action": "flag"
}

```

result:

```
200 OK

Headers
{
  "newflag": "22",
  "data": {
    "entity_id": 34,
    "entity_type": "node",
    "flag_id": "bookmark",
    "uid": 1,
    "flag_action": "flag"
  }
}

```

note: If the flag does not exist, then create the flag

```
"newflag": "22"

```

else

```
"¿Flag exists?": "true"

```

create unflag

```
{
  "entity_id":34,
  "entity_type":"node",
  "flag_id": "bookmark",
  "uid": 1,
  "flag_action": "unflag"
}

```

result:

```
200 OK

Headers
{
  "¿Delete flag?": "true",
  "data": {
    "entity_id": 34,
    "entity_type": "node",
    "flag_id": "bookmark",
    "uid": 1,
    "flag_action": "unflag"
  }
}

```

note: If the flag exists, then delete the flag

```
"¿Delete flag?": "true"

```

else

```
"¿Flag exists?": "false",

```
> 2 votes

---
Tags: 8, flags
---


# Question
Title: How to allow access to create terms in a specific vocabulary?
If you remove "Administer vocabularies and terms" from a role in Drupal 8.4, but you want to give access to a role for a specific Vocabulary, there is no out-of-the-box way to do this for "create" access for terms in specific vocabularies.

For example, for a Vocabulary called "Author".

You are given the option to "Delete terms from Author" and "Edit terms in Author", but no option to "Create terms in Author".

How would you add this option a role in Drupal 8 after you have removed the "Administer vocabularies and terms" permission?

# Answer
You can create a custom permission: "Create new authors" in mymodule.permissions.yml:

```
create new authors:
  title: 'Create New Authors'
  description: 'Create New Author Taxonomy Terms'
  restrict access: true

```

Assign the new permission to the roles you want.

Then using hook\__access\_entity\_create\_access():

```
function mymodule__access_entity_create_access(\Drupal\Core\Session\AccountInterface $account, array $context, $entity_bundle) {
  if ($entity_bundle == 'author' && $account->hasPermission('create new authors')) {
    return AccessResult::allowed();
  }
  // No opinion.
  return AccessResult::neutral();
}

```

This will give explicit access to roles with your custom permission, and in other cases it will defer to the default drupal permissions.
> 4 votes

---
Tags: 8, taxonomy-terms, users
---


# Question
Title: Preprocess a Paragraph when Added to Content Type
I'm trying to disable a field in a Paragraph when it's added to a certain content type. Currently I'm using the following:

```
function my_module_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
  switch($form_id) {
    case "node_content_type_form":
        $form['field_paragraph_content']['widget'][0]['subform']['field_paragraph_field']['#disabled'] = 'disabled';
      break;
  }
}

```

This works only after the node containing the paragraph has already been saved. When the paragraph in question is first added to the node the `field_paragraph_field` is not disabled.

How can I preprocess the Paragraph form when it is initially added to the content type so this field is always disabled?

# Answer
> 2 votes
If you want it to work when creating a node and when editing the node, you should make the change using both the node add form and the node edit form:

```
mymodule_form_node_content_type_form_alter()

mymodule_form_node_content_type_edit_form_alter()

```

Or in your hook\_form\_alter in the question:

```
case "node_content_type_form":
case "node_content_type_edit_form":

```

There's another way to do this using hook\_field\_widget\_form\_alter():

```
function mymodule_field_widget_form_alter(&$element, FormStateInterface $form_state, $context) {

  if ($context['items']->getFieldDefinition()->getTargetBundle() == 'content_type' && $context['items']->getFieldDefinition()->getName() == 'field_paragraph_field') {
    $element['#disabled'] = TRUE;
  }

}

```

---
Tags: 8, paragraphs
---


# Question
Title: Drupal 8 custom type content, getting values for a field of type Taxonomy (hence, Entity Reference), which can have multiple values in the field
I have a custom content type (we'll call it '**book**')... and it has a field (We'll call the field '**category**') which is of type *Taxonomy Term* and which **can hold say ten items**.

I can load the content programmatically:

```
$nids = \Drupal::entityQuery('node')->condition('type','custom content type machine name')->execute();

        $nodes =  \Drupal\node\Entity\Node::loadMultiple($nids);

```

I can then scroll through the items of node using something like

```
  foreach ($node as $node_item){
      echo $node_item->title
   }

```

However, how would I output the content of the **reference entity** 'category' ... say if category has 3 items assigned to it, it would be something like this:

```
  foreach ($node as $node_item){
      echo $node_item->title,
      echo $node_item->category[0]->target_id,
      echo $node_item->category[1]->target_id,
      echo $node_item->category[2]->target_id,
   }

```

But, this does not work...

There is the suggestion that $node\_item-\>category has to be loaded as an entity reference but using $node-\>cateogry-\>referenceEntities () does not load anything.

Any ideas? Thanks in advance.

# Answer
> 2 votes
I think $node\_item-\>category-\>referencedEntities() is what you want to use.

You have misspelled the method in your question.

```
 if ($node_item->category->isEmpty() === FALSE) {
    $vars = [];
    // Get referenced entities and add each to array of terms.
    foreach ($node_item->category->referencedEntities() as $term) {
      $vars[] = [
        'name' => $term->label(),
        'phone' => $term->field_phone_number->value,
        'email' => $term->field_email_address->value,
      ];
    }
  }

```

---
Tags: 8, nodes, entities
---


title: How do I query node sort by randomize?

text:
# Question
Title: How do I query node sort by randomize?
I want to get all articles content type, but I want to get it randomize, how can I do that? Refer to my code below:

```
$nids = \Drupal::entityQuery('node')->condition('type', 'articles')->sort('RAND()')->execute();

```

I'm using drupal 8

# Answer
I don't think this is possible with an entity query directly, but you can alter entity queries after they are converted into select queries.

Add a tag to your entity query and then you can alter it there.

```
  $nids = \Drupal::entityQuery('node')
    ->condition('type', 'article')
    ->addTag('sort_by_random')
    ->execute();

```

Then add a query alter function to your custom module using the tag you added. Drupal's select query even has a built in function to make a query sort on "RAND()":

```
function mymodule_query_sort_by_random_alter(\Drupal\Core\Database\Query\AlterableInterface $query) {
  $query->orderRandom();
}

```

If you're going to have to tag an entity query to alter it, and it's not essential that you use an entity query, you might want to just replace it with a select query.

```
$query = \Drupal::database()->select('node_field_data', 'n')
  ->fields('n', ['nid'])
  ->condition('type', 'article')
  ->range(0, 10)
  ->orderRandom();

$results = $query->execute()->fetchCol();

if (!empty($results)) {
  $nodes = \Drupal::entityTypeManager()->getStorage('node')->loadMultiple($results);
}

```
> 17 votes

---
Tags: 8
---


# Question
Title: What kind of index to create for solr search?
I have got a solr instance up and running locally on my drupal 7 server. I have added the server to the search config on my drupal site and now I'm trying to create the 'index' part of the search configuration.

As per this guide http://valuebound.com/resources/blog/installing-configuring-apache-solr-520-with-drupal-7-using-search-api-ubuntu-1404 I have gotten to the very end where I must set up the index for the files.

The guide says to select 'Node' from the drop-down list under 'Item type' but I don't see that option. Is there another option I can select?

I am planning on indexing a bunch of 'rich' file types such as PDFs, DOCS, XLS as well as JSON and XML.

I am looking for help in setting up the search index for my solr server.

# Answer
> 0 votes
The item dropdown says "Content" instead of "node". But "content" == "node" in this case.

---
Tags: search
---


# Question
Title: Apply multiple Content Type filters to Search Block Form in hook_form_alter()
I'm trying to figure out how to apply multiple content type filters to the search results of the Search Block Form (not the normal search form). I've successfully filtered by current language and ONE content type. So far, here's what I have:

```
function mytheme_form_search_block_form_alter(&$form, &$form_state) {
  $manager = \Drupal::languageManager();

  $form['advanced-form'] = [
    '#type' => 'hidden',
    '#value' => 1,
  ];
  $form['f[0]'] = [
    '#type' => 'hidden',
    '#value' => 'language:' . $manager->getCurrentLanguage()->getId(),
  ];
  $form['f[1]'] = [
    '#type' => 'hidden',
    '#value' => 'type:Insight',
  ];
}

```

There doesn't appear to be any documentation about adding filters this way. But I did find this: NodeSearch::buildSearchUrlQuery. It appears that one should somehow be able to use OR and Negation in this, but I just can't figure it out.

I've tried this:

```
$form['f[1]'] = [
    '#type' => 'hidden',
    '#value' => 'type:Insight OR type:Event',
];

```

This just filters by the last one listed. I also tried this:

```
$form['f[1]'] = [
    '#type' => 'hidden',
    '#value' => 'type:Insight OR Event',
];

```

And this:

```
$form['f[1]'] = [
    '#type' => 'hidden',
    '#value' => 'type:["Insight","Event"]',
];

```

And none of these were working to filter in (or out) multiple content types.

Any help would be greatly appreciated. Or just pointing me to some documentation on using filters this way. Thanks.

# Answer
So, I figured out how to make it work without actually finding any documentation. I just added a new filter for each content type I want to search:

```
$form['advanced-form'] = [
    '#type' => 'hidden',
    '#value' => 1,
];
// add filter for current language
$form['f[0]'] = [
    '#type' => 'hidden',
    '#value' => 'language:' . \Drupal::languageManager()->getCurrentLanguage()->getId(),
];
// add filter for each full-page content type
foreach (fullPageNodeList() as $key => $full_page_type) {
    $form['f['.($key + 1).']'] = [
        '#type' => 'hidden',
        '#value' => 'type:'.$full_page_type
    ];
}

```
> 0 votes

---
Tags: theming, 8, forms, hooks, search
---


# Question
Title: How can I remove username from title on profile page?
I am trying to remove the user name from the users profile page. I tried to remove the div using CSS, but it is the same div as for all other nodes, so this means all other titles disappear. I only want to remove the user name on the profile page. I am using the module Real Name, so this is the last place where the user name is visible. I have only found tips for drupal7 dated years back when googling. Any ideas on how this could be done?

# Answer
> 3 votes
I discovered now that "Page Title" is in a block in Drupal 8. I set this block to not show on /user/\*, which worked great.

---
Tags: 8, users
---


# Question
Title: How to remove "Show row weights" option on File Upload field?
I have created a file field with multiple uploads allowed. Is there any way(except CSS) I can remove "Show row weights" link from file upload field? Or is there any way to remove weight drop down entirely from file field?

# Answer
You need to disable/alter `settings.tableDrag` function.

```
<?php
/**
 * Implements hook_js_alter().
 */
function MODULENAME_js_alter(&$javascript) {
  unset($javascript['misc/tabledrag.js']);
}
?>

```
> 4 votes

# Answer
The first part of your question is regarding removal of link "Show row weights" (or "Hide row weights" if dragging functionality is disabled) in a form where table rows are draggable, so I'm going to answer that.

"Show row weights" string appears in `Drupal.tableDrag.prototype.showColumns()` method and "Hide row weights" appers in `Drupal.tableDrag.prototype.hideColumns()` method that is included in `tabledrag.js` file (see head in Drupal 7.x branch) so you need to override these methods in order to replace or remove these strings without losing row dragging functionality.

Place this code in a .js file that is loaded along with the form that uses tabledrag.js:

```
(function ($) {
  // Copy hideColumns() method
  var hideColumns = Drupal.tableDrag.prototype.hideColumns;
  Drupal.tableDrag.prototype.hideColumns = function() {
    // Call the original hideColumns() method
    hideColumns.call(this);
    // Remove the 'Show row weights' string
    $('.tabledrag-toggle-weight').text('');
  }

  // Copy showColumns() method
  var showColumns = Drupal.tableDrag.prototype.showColumns;
  Drupal.tableDrag.prototype.showColumns = function () {
    // Call the original showColumns() method
    showColumns.call(this);
    // Remove the 'Hide row weights' string
    $('.tabledrag-toggle-weight').text('');
  }
})(jQuery);

```
> 6 votes

# Answer
Here is a solution for Drupal 8 using `hook_preprocess_field_multiple_value_form()`

First find the field you want to remove re-ordering ability from:

```
/**
 * Implements hook_preprocess_field_multiple_value_form().
 */
function MY_MODULE_preprocess_field_multiple_value_form(&$variables) {
  if($variables['element']['#field_name'] == 'MY_FIELD_NAME') {
    MY_MODULE_remove_table_reordering($variables['table']);
  }
}

```

And then call a helper function to actually remove the tables re-ordering functionality:

```
/**
 * Removes the ability for a table to be re-ordered.
 */
function MY_MODULE_remove_table_reordering(&$table) {
  unset($table['#tabledrag']);

  // Remove re-order header column
  foreach($table['#header'] as $header_i => $header) {
    if(is_object($header) && (string) $header == 'Order') {
      unset($table['#header'][$header_i]);
    }
  }

  // Loop table rows
  foreach($table['#rows'] as &$row) {

    // Remove draggable class from tr
    $i = array_search('draggable', $row['class']);
    if($i !== FALSE) {
      unset($row['class'][$i]);
    }

    // Loop columns in row
    foreach($row['data'] as $col_i => &$col) {

      if(empty($col['class'])) {
        continue;
      }

      // Remove td with drag handle
      $i = array_search('field-multiple-drag', $col['class']);
      if($i !== FALSE) {
        unset($row['data'][$col_i]);
      }

      // Remove td with re-ordering select
      $i = array_search('delta-order', $col['class']);
      if($i !== FALSE) {
        unset($row['data'][$col_i]);
      }
    }
  }

}

```
> 3 votes

# Answer
You can also try a theme-override, as in https://api.drupal.org/api/drupal/modules!field!field.form.inc/function/theme\_field\_multiple\_value\_form/7

Paste the function to your theme's template.php, rename 'theme\_' in the function name to your theme's name and clear the cache.

Find the line saying

```
drupal_add_tabledrag($table_id, 'order', 'sibling', $order_class);

```

and comment it out.
> 1 votes

# Answer
I'm not sure about disabling for a single field, but I found myself wanting to disable the row dragging for an entire form.

monymirza suggested an answer to disable it entirely. However in D7, that approach is not reliable, because in some forms drupal\_add\_tabledrag() will be called after your hook\_js\_alter(). This is typical Drupal - everything is theoretically customizable, but in practice it's error prone and sensitive.

In the end I used the following hook\_form\_alter() to disable table drag for just one specific form:

```
<?php

/**
 * Implements hook_form_alter()
 */
function sunflower_custom_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'field_ui_field_overview_form' && $form['#bundle'] == 'sunflower_habitat') {
    // The habitat form is wizardized based on row weights.  This is a sensitive thing, and drupal's row weight javascript is not at all sensitive, completely changing all values when it feels like it.  So we don't want that "feature" on this form.

    // Disable it, if already enabled.
    $javascript = &drupal_static('drupal_add_js', array());
    unset($javascript['misc/tabledrag.js']);

    // Prevent it from being enabled later.
    $tabledrag_added = &drupal_static('drupal_add_tabledrag');
    $tabledrag_added = TRUE;
  }
}
?>

```
> 1 votes

# Answer
Adding on to moneymirza's answer to remove the weights and add a qualifyer, since we don't want to disable `tabledrag.js` from the entire site.

```
<?php
/**
 * Implements hook_js_alter().
 */
function MODULENAME_js_alter(&$javascript) {
  // Use a more specific page condition as desired.
  if(arg(0) == "node" && arg(2) == "edit") {
    unset($javascript['misc/tabledrag.js']);
    drupal_add_js(drupal_get_path('module', 'MODULENAME') . '/MODULENAME.js');
  }
}

```

Then make a MODULENAME.js file:

```
(function ($) {
  Drupal.behaviors.NoTabledragWeights = {
    attach: function (context, settings) {
      // Again, get more specific if desired.
      $('td:nth-child(2),th:nth-child(2)').hide();
    }
  };
}(jQuery));

```
> 1 votes

---
Tags: 7, files
---


# Question
Title: How do I delete all entities of a bundle?
I am using Paragraphs module and I can't delete paragraph type until I delete the content of the paragraph. I can use admin/modules/uninstall/entity/paragraph, but this will delete the paragraphs of all types.

# Answer
There are some examples of removing nodes of a certain content type. In that case `node` is the entity type and `article` could be bundle (content type). This is no different. `paragraph` is the entity and `[paragraph type]` is the bundle.

For instance this post: https://stackoverflow.com/questions/34593060/drupal-8-delete-all-nodes-of-the-same-type

There are a few alternatives listed, but I suppose this should work:

```
$paragraphs = \Drupal::entityTypeManager()
    ->getStorage('paragraph')
    ->loadByProperties(array('type' => 'your_paragraph_type')); // System name

foreach ($paragraphs as $paragraph) {
    $paragraph->delete();
}

```
> 10 votes

# Answer
This seemed to work for me ...

```
$paragraph_types = array('your_paragraph_types');
foreach ($paragraph_types as $paragraph_type) {
    $para_type = \Drupal::entityManager()->getStorage('paragraphs_type')->load($paragraph_type);
    if ($para_type) {
      $para_type->delete();
    }
  }

```
> 2 votes

---
Tags: entities, paragraphs
---


# Question
Title: How do I remove container div from a specific view?
I have tried for a few days now, to figure this one out on my own, but have had next to no luck getting a working solution.

**The issue:**
I have a view that displays a list of images, where all wrappers have been removed, so that it only contains the images themselves. I have also overwritten templates for this view, so that any additional wrappers from templates are also removed.

The issue is that views automatically adds `<div class="views-element-container">` around the entire views. Normally this would be fine, but I have no need for it for this view, it's just cluttering the markup.

I know that it in some cases is used for additional functionality, such as the contextual links, but this has also been disabled for this view.

**What I have tried:**

* I have tried to figure out if views also adds a template suggestion to container.html.twig, but sadly found no indication anywhere on what that might be (even if I used normal views template naming convention, it didn't override)
* I have tried to access the views render array in a preprocess function, to unset #theme\_wrappers, in hopes that this would prevent views from using the container. Sadly this also didn't do anything. Code example below.

```
function rodekors_preprocess_views_view__paragraph_gallery(&$variables) {
  unset($variables['view_array']['#theme_wrappers']);
}

```

---

I simply want to remove the wrapper div from my specific view, yet have found no information on how to do that.

Does anyone know how to achieve this? Preferably without having to install a module for what should be such a simply thing to do.

# Answer
You can use a preprocess function to add a theme suggestion specifically for this view.

Something like:

```
function rodekors_theme_suggestions_container_alter(array &$suggestions, array $variables) {
  // since kint() / dpm() aren't working, use a js console.log
  echo "<script>console.log( 'Debug Objects: " . $variables['element']['#name'] . "' );</script>";

  if($variables['element']['#name'] = 'view_name') { // value from console.log
    $suggestions[] = 'suggested_template';
  }
}

```

Note: The above function is re-worked to function without dpm / kint, as OP had an unrelated debugging error. Usually, the `echo "<script...";` code would be replaced with a standard Drupal debug function.

Then you can copy the standard container template file, rename it 'suggested-template', and just remove the outermost wrapping div.

Because that views-element-container is a container **around the view,** you need to access / alter the code on the container level, instead of the view level. Most likely, even if your unset theme-wrappers code worked, the div would still exist, just without its class.
> 3 votes

# Answer
I was only able to solve this after much hair-pulling regarding Drupal not picking up my suggested template. Where I was hung up was that the template suggestion must start with `container__` otherwise Drupal will ignore the file and use the next template in the suggestion list (likely the default container.twig.html).

Here is my code:

```
/**
* Implements hook_theme_suggestions_user_alter().
*/
function myTheme_theme_suggestions_container_alter(array &$suggestions, array $variables) {
  // A list of view names in which to exclude the container markup.
  $exclude_views = [
    'someView',
  ];

  if (in_array($variables['element']['#name'], $exclude_views)) {
    $suggestions[] = 'container__no_wrapper';
  }
}

```

I then added `container.html` and `container__no_wrapper` to my theme at `templates/container/`.
> 4 votes

# Answer
```
if($variables['element']['#name'] = 'view_name') { // value from

```

should be

```
if($variables['element']['#name'] == 'view_name') { // value from

```

**AND**

```
$suggestions[] = 'suggested_template';

```

should be

```
$suggestions[] = 'suggested__template';

```

---

:)
> -1 votes

---
Tags: views, theming
---


# Question
Title: Get text_long field value with EntityMetadataWrapper
I am trying to get data from a `text_long` type field using `EntityMetadataWrapper`, and from what I'm seeing on the interwebs, I should be using something like this:

```
$wrapper->{$field}->value();

```

or

```
$wrapper->{$field}->value->value();

```

However, if I use the first one, I get an array with `format` and `value` keys, but if I try the latter, I get an Call to a member function value() on null\` error.

Do I have to use `$wrapper->{$field}->value();` and manually get the `value` from the array? Or is there a more direct method? I've looked through the class, I don't see another method that gets the `value` data.

# Answer
> 0 votes
Since the long text field is an array in the entity Metadata wrapper (due to fact that long text fields can have an input format applied to them), you should decode the text.

1. See the Drupal.org entity Metadata documentation and search for the example $wrapper-\>body-\>value-\>value(array('decode' =\> TRUE));
2. Also, check out this similar post about handling the formatting of long text fields when extracting with entity Metadata wrappers

---
Tags: 7, entities
---


# Question
Title: How to display unpublished contents in views for all the users?
I need to display published as well as unpublished content for all the authenticated users. Also, site also has workbench moderation module enabled.

I have tried by pass access control permission, view unpublished contrib module.

Please suggest.

# Answer
> 1 votes
Add Permission - Workbench Moderation : View all unpublished content.

# Answer
> 0 votes
In your view's settings under Other, click Query settings and check Disable SQL rewriting.

This disables node access checks so be sure to set up the view carefully.

---
Tags: 7, views, nodes, workbench
---


# Question
Title: How to trigger the click on the field collection button "add another item" using jQuery
I want to trigger click on "Add Another item" button of field collection on some jQuery event.

# Answer
> 1 votes
```
jQuery('.field-add-more-submit').mousedown();

```

works in Inspector.

```
$('.field-add-more-submit').mousedown();

```

probably works from a module.

`.click()` doesn't work for some reason. More info here.

---
Tags: javascript, entities
---


# Question
Title: Create a drop down list of notifications with an unread item count that resets or hides on click
I've used the message module to create a notifications system on my site. It works fantastically, however the final task I would like to complete has been less pioneered via contributed modules. This is the creation of a drop down menu item that lists unread notifications. It requires several characteristics.

**1.** Drop down functionality. Options I have investigated:

A) Menu views. Will allow immediate attachment of an item count badge via menu badges module. Would require addition of custom drop down javascript in theme and one additional module compared to option B.

B) Quick tabs accordion. Don't set a default tab and it behaves exactly like a drop down menu toggle. No additional modules or javascript necessary.

**2.** A badge that counts the # of unread items in the views list attaches it to the link that activates the drop down. Menu badge provides this for option A and link badge(required by menu badge so it's installation is a given) MAY provide this for option B but I don't know how to go about doing so.

**3.** Removing/resetting the badge after the drop down is viewed. Rules link may be the solution to this by marking the messages in the list as read + some css that hides the badge after click until it can be updated on next page load. May be possible to use views auto refresh module to do this through ajax, but it seems like this single feature would be a little too module heavy at that point.

I want to achieve this in the most lightweight manner possible, but I'm unsure how to proceed.

Re-written for clarification.

# Answer
Your question consist of (at least) 3 questions. You should really split them in separate ones. Read on for an answer to your bullet "3." ...

Have a look at my answer to "How to allow users to manage their own Message Stack messages?", which IMO is pretty close to the question here. It can be summarized like so:

1. Create a flag (using the the Flag module).
2. Create a view 'Messages by user'.
3. Use Rules to flag/unflag messages.
4. Trigger the Rules Component to mark messages (using the VBO module).
5. Create notifications about Unread Messages (using the "Menu Badges" module).

Bonus: by using the suggestion as in item "5.", you probably also solved your bullet "2." (combined with "A.")

**Note**: no custom coding involved, only using some of the commonly used contributed modules (and "Menu Badges", a hidden gem ...).
> 0 votes

# Answer
I have done the exact thing you're describing here.. But it's a custom solution as the menus are built in my own tpl. I don't use Drupal's menu system.

Basically, there's a 'seen' flag for messages and when a user clicks their history button, a "use-ajax" link gets pressed which triggers my custom module to flag all the messages for the user.

This is the module that flags messages. I have a view that returns all unflagged messages for that user and then flag them.

```
<?php

function custom_ajax_flag_seen_init() {
    drupal_add_js('misc/jquery.form.js');
    drupal_add_library('system', 'drupal.ajax');
}

function custom_ajax_flag_seen_menu() {
    $items['messages-seen'] = array(
        'page callback' => 'ajax_flag_messages',
        'access callback' => 'user_access',
        'access arguments' => array('access content'),
        'type' => MENU_CALLBACK,
    );
    return $items;
}

function ajax_flag_messages($type = 'ajax', $uid = 0) {
  if ($type == 'ajax') {
    $flag_msg = flag_get_flag('seen');
    $list = views_get_view_result('messages_vbo_seen');
        foreach($list as $activity_item){
            $flag_msg->flag('flag', $activity_item->mid, user_load($uid), TRUE);
        }
    }
}

```

This is the code for the hidden link which calls the module above.

```
if ($unread_count > 0) {
    print '<a class="hidden use-ajax" id="seen_id" href="/messages-seen/nojs/' . $user->uid .'">seen</a>';
}

```

This is the jQuery for when the history button is clicked.

```
$('.menu_unread').click( function () {
    if ($('#seen_id').length) {
        document.querySelector('#seen_id').click();
        $('.badge_unread').hide();
        //So the rule fires once only
        $('#header_notification_bar').removeClass('menu_unread');
    }
});

```

Pierre mentioned the Rules Link module and I actually used that at first but changed to the custom module for some reason. (You can see my view has "vbo" in the name and my comment mentions rules). I honestly can't remember why so you should probably try it first. Although to be honest, the module I created is less effort.

Btw, this isn't supposed to be a working solution but it should give you ideas on your own implementation.
> 0 votes

---
Tags: 7, notifications
---


# Question
Title: How do I programmatically disable a form?
I want disable the user register form depending some conditions. The user go to the "/user/register" page, and he must see 'Registration is disable because ...'.

From my "form\_user\_register\_form\_alter" hook, I don't find anywhere how can I disable all the form programmatically (I mean removing all fields form). I think I can unset all form elements, but I feel that is an ugly way.

Is there a method (from the FormStateInterface class) or a Drupal function (for the form variable) to properly disable the form?

This is my most recent tentative.

```
function mycustommodule_limit_form_user_register_form_alter(&$form, FormStateInterface $form_state){
  if (...) {
    $form['#access'] = FALSE; // Drupal 7 (ugly?) way
    drupal_set_message('This form is disable because...');
  }
}

```

When I go to the /user/register form, the form is disable ! but I get this error.

> Notice: Undefined index: #markup in Drupal\Core\Render\RenderCache-\>getCacheableRenderArray() (line 323 of core/lib/Drupal/Core/Render/RenderCache.php).

>

I would like to hide/remove *Create new account* too.

# Answer
The D8 way to do this is to write a custom access check.

This is the one which now checks the access for the user register form:

**src/Access/RegisterAccessCheck.php**

```
<?php

namespace Drupal\user\Access;

use Drupal\Core\Access\AccessResult;
use Drupal\Core\Routing\Access\AccessInterface;
use Drupal\Core\Session\AccountInterface;

/**
 * Access check for user registration routes.
 */
class RegisterAccessCheck implements AccessInterface {

  /**
   * Checks access.
   *
   * @param \Drupal\Core\Session\AccountInterface $account
   *   The currently logged in account.
   *
   * @return \Drupal\Core\Access\AccessResultInterface
   *   The access result.
   */
  public function access(AccountInterface $account) {
    $user_settings = \Drupal::config('user.settings');
    return AccessResult::allowedIf($account->isAnonymous() && $user_settings->get('register') != USER_REGISTER_ADMINISTRATORS_ONLY)->cacheUntilConfigurationChanges($user_settings);
  }

}

```

**user.services.yml**

```
services:
  access_check.user.register:
    class: Drupal\user\Access\RegisterAccessCheck
    tags:
      - { name: access_check, applies_to: _access_user_register }

```

**user.routing.yml**

```
user.register:
  path: '/user/register'
  defaults:
    _entity_form: 'user.register'
    _title: 'Create new account'
  requirements:
    _access_user_register: 'TRUE'

```

Put these files in a module and change `user` to `mymodule` and choose a custom class name.

To successfully override the route in mymodule.routing.yml you have to adjust the module weight. Or instead change the access settings of the existing route in a RouteSubscriber, which is a bit more work to do, but the better solution.
> 3 votes

# Answer
A simple way to do it in Drupal 8 hook\_form\_alter:

```
$form = [
  '#parents' => [],
  '#markup' => t('Access Denied.'),
];

```

If you have errors with the above solution, you can try to modify an existing form:

```
  $form['#access'] = FALSE;
  $form['#markup'] = t('Access Denied.');
  $form['#cache'] = [
    'contexts' => [],
    'max-age' => 0,
  ];

```
> 3 votes

# Answer
You can create a form template and show a form or some markup according to some conditions. In your\_theme.theme or your\_module.module file add this:

```
/**
 * Implements hook_theme().
 */
function your_theme_theme($existing, $type, $theme, $path) {
  $theme = array('user_register_form' =>
          array(
    'render element' => 'form',
    'path' => drupal_get_path('theme', 'your_theme') . '/templates',
    'template' => 'user-register-form'
  ));
}

```

Create user-register-form.html.twig.

Define some condition (it is just for example as i don't know how and what condition you want to add) in hook\_form\_FORM\_ID\_alter

```
function your_theme_form_YOUR_FORM_ID_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
  if ($some_variable == 'some condition') {
       $form['condition'] = TRUE;
   }

}

```

In your template file:

```
{% if form.condition %}

<p>Registration is disable because ..</p>

{% else %}
   {{ form.some_field_1 }}
   {{ form.some_field_2 }}
   {{ form }}
{% endif %}

```
> -1 votes

---
Tags: forms, 8
---


# Question
Title: Change Boolean field status on clicking submit button
I have placed an additional button to the term edit page, and when the user clicks on the additional ("**Archieve**") button, the status of the boolean field should change from 0 to 1 in the database.

I have written the following code for achieving the above:

```
function security_settings_form_alter(&$form, &$form_state, $form_id)
{
    if($form_id == 'taxonomy_form_term')
    {
        dpm($form);
        $form['actions']['push'] = array(
            '#type' => 'submit',
            '#value' => t('Archieve'),
            '#submit' => array('my_custom_submit_function'),
            '#weight' =>25
        );
    }
}

function my_custom_submit_function($form, &$form_state)
{
    $form_state['values']['field_test_button']['und'][0]['value']=1;
    db_query("UPDATE {field_data_field_test_button} SET field_test_button_value = :val WHERE entity_id = :eid",
             array(':val' => $form_state['values']['field_test_button']['und'][0]['value'], ':eid' => $form_state['values']['tid']));
    drupal_set_message(t('Your form has been archieved.'));
}

```

The above functionality is working fine.

But if the user clicks on the same **archieve** button again, its status should change from 1 to 0 in the database.

Any idea how can achieve this?

# Answer
> 0 votes
I would do it.

```
function my_custom_submit_function($form, &$form_state)
{
    //if value is 1, then value=0
    if ($form_state['values']['field_test_button']['und'][0]['value']==1) {
        $form_state['values']['field_test_button']['und'][0]['value']=0;
    }
    else
        //if value is 0, then value=1
        if ($form_state['values']['field_test_button']['und'][0]['value']==0) {
            $form_state['values']['field_test_button']['und'][0]['value']=1;
        }
    //$form_state['values']['field_test_button']['und'][0]['value']=1;
    db_query("UPDATE {field_data_field_test_button} SET field_test_button_value = :val WHERE entity_id = :eid",
             array(':val' => $form_state['values']['field_test_button']['und'][0]['value'], ':eid' => $form_state['values']['tid']));
    drupal_set_message(t('Your form has been archieved.'));
}

```

---
Tags: 7
---


# Question
Title: How do I change the redirect page for unpublished nodes?
It seems that the standard Drupal behaviour for unpublished nodes is this: If a visitor types in a URL to an unpublished node they are redirected to a login page. To -me- that signals that the content is 'there' but they just need credentials.

So: Is there a way to change this behaviour so that if they type in a URL to an unpublished node, literally -nothing- happens? Or perhaps they are redirected to the home page?

Below is my attempt to redirect to home page. The page still redirects to the Access Denied. What I don't get is that if I alter the Rule so that it tests for role 'Administrator' it works -fine-. So apparently an Anonymous user has some special property?

`{ "rules_redirect_unpubished_content_url_to_home_page" : {
 "LABEL" : "Redirect Unpubished Content URL To Home Page",
 "PLUGIN" : "reaction rule",
 "OWNER" : "rules",
 "REQUIRES" : [ "rules" ],
 "ON" : { "node_view--bags_cases" : { "bundle" : "bags_cases" } },
 "IF" : [
 { "NOT node_is_published" : { "node" : [ "node" ] } },
 { "user_has_role" : {
 "account" : [ "site:current-user" ],
 "roles" : { "value" : { "1" : "1" } }
 }
 }
 ],
 "DO" : [ { "redirect" : { "url" : "/" } } ]
 }
}`

I also tried this:

`function jch_utilities_node_view($node, $view_mode, $langcode) {
 if ($node->status != 1) {
 drupal_goto('/some-page');
 }
}`

...and again, the 403 fires before this has a chance to run

Finally, I tried hook\_init, but yet again, the 403 fires before this has a chance to run.

What am I missing?

# Answer
The default behaviour is an "Access denied" page, because a visitor hasn't access to unpublished nodes. It's not possible "nothing appens". You could use Rules and create a Rule like this:

* event: viewing a node
* condition: user has role "anonymous"
* condtion: node is unpublished
* action: redirect to a custom page
> 1 votes

# Answer
this module will allow you to:

"setup redirects for each node type on their site. They can also set different types of redirects per node type. Developers can alter the node type list if required"

https://www.drupal.org/project/unpublished\_nodes\_redirect
> 0 votes

# Answer
You could actually use this to get the node status:

```
if ($node = menu_get_object()) {
  // Get the status
  $status = $node->status ;
}

```

Your final module would then be something like this:

```
function your_module_init() {
  if (!function_exists('drush_main')) { // prevents issue with drush
    if ($node = menu_get_object()) {
      if ($node->status != 1) {
        drupal_goto('some-page'); // without the preceding /
      }
    }
  }
}

```
> 0 votes

---
Tags: 7, redirection, nodes
---


# Question
Title: Do I need to build out CCK fields before migrate_d2d_ui?
Using the migrate\_d2d\_ui module to migrate Drupal 6 cck content to Drupal 7, I previously asked "Do I need to create CCK content types before migrate\_d2d\_ui?" and presume the answer is "Yes" based on my personal experience.

This follow-up question is whether it is necessary to also build out all the cck fields for content types containing cck fields. I am hoping the answer is "No" as this would imply a lot of work.

It would seem that migrate\_d2d\_ should be smart enough to recognize the D6 cck fields and create the corresponding D7 fields.

Thanks

# Answer
I eventually concluded that the answer to this question is 'yes' and ended up persisting my content structure (content types and field definitions) in features so it could be easily replicated when some errant step in the migration corrupted the database.
> 0 votes

---
Tags: 7, entities, migrations
---


# Question
Title: How to export cck field list from Drupal 6 to CSV files for import in Drupal 7?
I am migrating a D6 site to D7 using migrate\_d2d\_ui but find that the cck fields for my various content types are not automatically migrated.

I would like to build a csv file containing the D6 cck field structure (name, type, length, #values, help text, etc) so that a csv file can be built for each content type and imported into D7, perhaps using feeds, to build out the full D7 content type and field structure. Hopefully, migrate\_d2d-ui can be mapped to bring over the content once the full D7 structure is built out.

I have investigated Features, Views Data Export, Feeds, Content Copy, and Bundle Copy, but have not found a combination that works with both D6 and D7 platforms.

Any suggestions for creating and importing this csv file or do I need to manually recreate each field in D7?

Thanks.

# Answer
I gave up on this approach and ended up using the features module because I could not find a complete or workable solution using csv export/import.
> 0 votes

---
Tags: 7, entities, migrations
---


# Question
Title: How to use the same EntityListBuilder for entity A and an extended version B
I have used the content entity example coming from the example project.

This example define a Contact entity.

Next I have extended this Contact class in an Artist class with some added fields (let say a Bio and a Cv field).

```
class Artist extends Contact  {

```

My Idea was to share the list\_builder defined in the Contact class in order to get an administrative list showing the Contacts and the Artists at the same place.

To do so, I have those annotations in the **Artist** class:

```
 * @ContentEntityType(
  * id = "mymodule_artist",
  * label = @Translation("Artist entity"),
  * handlers = {
  * "view_builder" = "Drupal\Core\Entity\EntityViewBuilder",
  * "list_builder" = "Drupal\mymodule\Entity\Controller\ContactListBuilder",
  * ...

```

As you can see, **ContactListBuilder** is the list builder of the Contact entity... in other words, it is used in Contact and in Artist.

In the routing.yml I have the following

```
entity.mymodule_artist.collection:
  path: '/mymodule_contact/list'
  defaults:
    _entity_list: 'mymodule_contact'
    _title: 'Contact List'
  requirements:
    _permission: 'view contact entity'

```

Unfortunately, this is not working at all... the ContactListBuilder shows only the Contact entities; not the Artists. (I couldn't understand why)

After many tries, I drop this idea... My new plan was now to create a view that will show all Contacts and all Artists.

Thus, I added this line in the annotations of the Contact and the Artist classes (in the "handlers" section):

```
 * "views_data" = "Drupal\mymodule\ContactViewsData",

```

And here is my **ContactViewsData** class definition

```
class ContactViewsData extends EntityViewsData  {
}

```

As you can see it is empty: it only extends EntityViewsData. In fact I really don't understand what to do in the `getViewsData()` function. I couldn't find any doc on it (But this is maybe something I should ask in another question)

Anyway, this does the job, and I could create a view (in the UI) for the Contacts and another view for the Artists. But I have no clue on how to create a view that are showing both.

To summarize, my questions are:

1. Is extending the Contact class (for the Artists) a good idea? Maybe it is much simpler to just add the Artist's fields in the Contact Class.
2. What is the best way to list a Mix of 2 entities that are sharing some common fields (Ex: Name, Surname, ID,...): Is it a view?
3. Is it a good Idea to try to use the same ListBuilder for 2 entities (Of course, this Listbuilder will only list the common fields)
4. Where to find some doc on the getViewsData()\` function, or at least, what is the purpose of this function.

# Answer
Your questions cover quite a few unrelated concepts, but here's an attempt at answering nonetheless.

1. **Create a 'Person' base class** and extend that into 'Contact' and 'Artist' classes. This approach will isolate your Artist entity type form changes you need to make to the Contact class and vice versa. Adding a company-field would, as an example, probably not apply to your artists.
2. I would use a **content-view with a filter**, only showing *contacts* and *artists* types. Re-using common fields on the 2 entities will make creating such a view a no-brainer.
3. Afaik the parent list-builder class does not support multiple entity types. The constructor for the list-builder class, accepts *$entity\_type* as one of its arguments, so unless you write your own list-builder, you are limited to **1 type per list**.
4. The getViewsData() method exposes properties from your entity type to the views api. Extending the EntityViewsData class, like you did, auto-generates the view-data through the inherited methods. Core provides some usage examples; e.g. UserViewsData. Use your IDE to search for "extends getViewsData()" for more examples.
> 0 votes

---
Tags: 8, views
---


# Question
Title: Fetching(GET) image url with applied image styles using jsonapi module
Looking to make request using the jsonapi module to GET all urls that point to the images optimized version of the image.

If I use the Drupal front-end with Twig and view my page and inspect the images on the page I get something like this

`http://local.mysite.com/sites/default/files/styles/promo_background_image/public/promo-backgrounds/MYIMAGE.png?h=df23a951&itok=fslZ-kmD`

If I make a request to my api endpoint and drill down to the image field it does not have the included image style url. \`\`\`

```
{
"data": {
    "type": "file--file",
    "id": "b74b73fb-19fd-48a2-ac91-8a7aacd7fe18",
    "attributes": {
        "fid": 2,
        "uuid": "b74b73fb-19fd-48a2-ac91-8a7aacd7fe18",
        "langcode": "en",
        "filename": "MYIMAGE.png",
        "uri": "public://promo-backgrounds/MYIMAGE.png",
        "filemime": "image/png",
        "filesize": 37624,
        "status": true,
        "created": 1508723420,
        "changed": 1508723610,
        "url": "/sites/default/files/promo-backgrounds/MYIMAGE.png"
    },
    "relationships": {
        "uid": {
            "data": {
                "type": "user--user",
                "id": "b044b880-ab4e-495b-b2d1-6a4fe58dc609"
            },
            "links": {
                "self": "http://local.mysite.com/api/file/file/b74b73fb-19fd-48a2-ac91-8a7aacd7fe18/relationships/uid?language=en",
                "related": "http://local.mysite.com/api/file/file/b74b73fb-19fd-48a2-ac91-8a7aacd7fe18/uid?language=en"
            }
        }
    },
    "links": {
        "self": "http://local.mysite.com/api/file/file/b74b73fb-19fd-48a2-ac91-8a7aacd7fe18?language=en"
    }
},
"links": {
    "self": "http://local.mysite.com/api/file/file/b74b73fb-19fd-48a2-ac91-8a7aacd7fe18?language=en"
}

```

}

\`\`\`

How can one get access the image style uri using the jsonapi as my api server?

# Answer
I would do it

create file: test\_api.info.yml

```
name: Test API
type: module
description: Custom RESTful API module with GET/POST/PUT/DELETE etc.. method examples.
author: Minnur Yunusov
core: 8.x

```

create file: test\_api.routing.yml

```
test_api.getparameter:
  path: 'my-api/get/{nid}'
  defaults: { _controller: '\Drupal\test_api\Controller\TestAPIController::getpara_example' }
  methods:  [GET]
  requirements:
    _access: 'TRUE'

```

create file: /src/Controller/TestAPIController.php

```
<?php

/**
 * @file
 * Contains \Drupal\test_api\Controller\TestAPIController.
 */

namespace Drupal\test_api\Controller;

use Drupal\Core\Controller\ControllerBase;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\JsonResponse;
use Drupal\user\Entity\User;

/**
 * Controller routines for test_api routes.
 */
class TestAPIController extends ControllerBase {

  /**
   * Callback for `my-api/get.json` API method.
   */
  public function getpara_example($nid, Request $request ) {

    //get node;
    $node=node_load($nid);

    //get image uri
    $image =$node->field_image->entity->getFileUri();

    $style = \Drupal::entityTypeManager()->getStorage('image_style')->load('thumbnail');

    $url = $style->buildUrl($image);

    $response['nid'] = $nid;
    $response['uri'] = file_create_url($image);
    $response['image_original'] = file_create_url($image);
    $response['image_style_thumbnail'] =file_create_url($url);

    return new JsonResponse( $response );
  }

}

```

test: url: localhost/drupal8/my-api/get/30 method: get

note: 30 is nid.

result:

```
{
  "nid": "30",
  "uri": "public://2017-10/generateImage_1RwT72.png",
  "image_original": "http://jeremiselxi.260mb.net/drupal8/sites/default/files/2017-10/generateImage_1RwT72.png",
  "image_style_thumbnail": "http://jeremiselxi.260mb.net/drupal8/sites/default/files/styles/thumbnail/public/2017-10/generateImage_1RwT72.png?itok=Dzg02oew"
}

```
> 1 votes

---
Tags: javascript, ajax, media, 8
---


title: Display user's name instead of username

text:
# Question
Title: Display user's name instead of username
For various compatibility reasons, I would like my usernames to be standard no-spaces combinations, so jbloggs / jdoe / etc. This becomes unsightly when displaying blogs ("jdoe's blog") or node authorship ("15/09/2016 jbloggs").

I've added first/last name fields to the account, but can't find a way to have them displayed by default instead of the username. I am on Drupal 8, so Profile2 isn't yet ready, which means this answer isn't an option. Likewise, this answer proposes using the "Real Name" module, which doesn't have a D8 version.

If it's any help, I would basically like the full name used in every display context, so if there's a blanket solution that would do that, rather than giving me control by node-type, that would be more than acceptable.

Lastly, if the above isn't possible without a module, can someone point me to some info on referencing account/profile fields in twig? That way I could at least override it in the most prominent places using templates.

# Answer
> 4 votes
I'd add a new field called Display Name (or similar), then then use `hook__user_format_name_alter()` to load in that field, and change the display name to use the field value instead of the user name.

Here's the change record for D7 -\> D8, where it used to be `hook_username_alter()`: https://www.drupal.org/node/1408514

# Answer
> 3 votes
Drupal now has a module that does exactly what you're looking for, Real Name:

https://www.drupal.org/project/realname

I just used it recently. Once configured, it uses tokens to allow you to rewrite the username to appear pretty much any way you want it to.

---
Tags: users, 8
---


# Question
Title: Feature revert deletes existing Strongarm variable
I got a Drupal 7 feature, which contains certain Strongarm variables, such as admin\_theme. This feature has been created, released and reverted multiple times, always without fault. Suddenly, the last feature revert leaded to a deletion of some variables which are clearly defined in Strongarm.

The only thing that helped "a bit" was to remove the variables from the feature, release & revert them, and then add the variables again and release and revert once again.

This can't be a solution for the production release because this one has to work in one time. Why can it be that a Feature revert deletes variables from the database (variable table) which are clearly stated in the feature?

# Answer
> 0 votes
In case someone gets on this question: We finally managed to find the answer to our problem.

We had an old version of the strongarm module (7.x-2.0-beta2) instead if 7.x-2.0 which is stable now (since 2012). The update hook from this update saved a lot of variables from the features to the drupal variable table, and on every further feature revert, no more variables would be deleted, so the problem was fixed. Credits to @Weri!

---
Tags: features, configuration, strongarm
---


# Question
Title: How do I allow an entity reference to be null in my custom entity?
I am working on adding taxonomy to the poll module. This is my BaseFieldDefinition:

```
$fields['category'] = BaseFieldDefinition::create('entity_reference')
  ->setLabel(t('Category'))
  ->setDescription(t('Section this poll is to appear on'))
  ->setSetting('target_type', 'taxonomy_term')
  ->setTranslatable(TRUE)
  ->setDisplayOptions('form', array(
    'type' => 'entity_reference_autocomplete',
    'weight' => -10,
    'settings' => array(
      'match_operator' => 'CONTAINS',
      'size' => '60',
      'autocomplete_type' => 'tags',
      'placeholder' => '',
      'options_list_callback' => 'my_callback',
    ),
  ))
  ->setDisplayConfigurable('form', TRUE)
  ->setRequired(FALSE);

```

However, I would like the category to be optional, but when creating a poll if it is left blank it returns an SQL error and this error appears on screen.

> The website encountered an unexpected error. Please try again later.
>
> Drupal\Core\Entity\EntityStorageException: SQLSTATE\[23000\]: Integrity constraint violation: 1048 Column 'category' cannot be null: INSERT INTO {poll\_field\_data} (id, langcode, uid, question, category, runtime, anonymous\_vote\_allow, cancel\_vote\_allow, result\_vote\_allow, status, created, default\_langcode) VALUES (:db\_insert\_placeholder\_0, :db\_insert\_placeholder\_1, :db\_insert\_placeholder\_2, :db\_insert\_placeholder\_3, :db\_insert\_placeholder\_4, :db\_insert\_placeholder\_5, :db\_insert\_placeholder\_6, :db\_insert\_placeholder\_7, :db\_insert\_placeholder\_8, :db\_insert\_placeholder\_9, :db\_insert\_placeholder\_10, :db\_insert\_placeholder\_11); Array ( \[:db\_insert\_placeholder\_0\] =\> 3 \[:db\_insert\_placeholder\_1\] =\> en \[:db\_insert\_placeholder\_2\] =\> 1 \[:db\_insert\_placeholder\_3\] =\> TEST poll \[:db\_insert\_placeholder\_4\] =\> \[:db\_insert\_placeholder\_5\] =\> 0 \[:db\_insert\_placeholder\_6\] =\> 0 \[:db\_insert\_placeholder\_7\] =\> 1 \[:db\_insert\_placeholder\_8\] =\> 0 \[:db\_insert\_placeholder\_9\] =\> 1 \[:db\_insert\_placeholder\_10\] =\> 1442410281 \[:db\_insert\_placeholder\_11\] =\> 1 ) in Drupal\Core\Entity\Sql\SqlContentEntityStorage-\>save() (line 755 of core/lib/Drupal/Core/Entity/Sql/SqlContentEntityStorage.php).

If `->setRequired(FALSE)` doesn't allow null columns in the database what does?

# Answer
The 'not null' instruction is automatically set to TRUE if that field is set in your entity's (entity\_keys) annotations:

ex:

```
entity_keys = {
 *     "id" = "id",
 *     "uuid" = "uuid",
 *     "uid" = "uid",
 *     "price" = "price",
 *     "langcode" = "langcode",
 *     "complete" = "complete",
 *   },

```

In this case `->setRequired(FALSE)` will be ignored. However, if you really have to, you can force it to FALSE if you provide your custom storage schema handler.

Todo so add the handler in your entity annotations:

```
handlers = {
 *     "storage_schema" = "Drupal\YOUR_MODULE\YourEntityStorageSchema",
...
}

```

And the create YourEntityStorageSchema.php file:

```
<?php

namespace Drupal\YOUR_MODULE;

use Drupal\Core\Entity\ContentEntityTypeInterface;
use Drupal\Core\Entity\Sql\SqlContentEntityStorageSchema;
use Drupal\Core\Field\FieldStorageDefinitionInterface;

class YourEntityStorageSchema extends SqlContentEntityStorageSchema {

  protected function getEntitySchema(ContentEntityTypeInterface $entity_type, $reset = FALSE) {
    $schema = parent::getEntitySchema($entity_type, $reset);

    //then target your annoying field and set the 'not null' key to FALSE!
    if (!empty($schema['rp_payment']['fields']['operator_id']))
      $schema['rp_payment']['fields']['operator_id']['not null'] = FALSE;

    return $schema;
  }
}

```

Hope it helps! ^^
> 2 votes

---
Tags: entities, 8
---


# Question
Title: How to escape square brackets in web forms?
consider the following HTML element in (View) Source page

```
district:
  '#type':select
  '#title':District
    '#attributes':
       data-district: '[{Test!test!:Test!Test!}]'

```

To my suprise when I check the browser for data-district it is an empty string. So my question is how to escape square brackets in (View) Source page if they are placed at the beginning(\[) and end (\]) of string

# Answer
> 0 votes
The below YAML render the data-district attribute without any problems via the Bartik theme,

```
district:
  '#type': select
  '#title': District
  '#options':
    one: One
    two: Two
    three: Three
  '#attributes':
    data-district: '[{test!Test!}]'

```

Below is a screenshot of the output.

In your example, the #attributes YAML is indented incorrectly.

---
Tags: webforms, 8
---


title: How do I sort by node authored on date?

text:
# Question
Title: How do I sort by node authored on date?
In Drupal 7, I have created a view to show a list of nodes I need to sort by node authored on date.

Does anybody know how to do this?

# Answer
In your view, go to section: SORT CRITERIA. Add field "Content: Post date" Sort ascending or Sort descending.
> 1 votes

# Answer
\[!This is a picture of Views UI\]

Edit the View and go to (SORT CRITERIA) and Checked (**Content: Post date**)
\[1\]: https://i.stack.imgur.com/5xq2F.png
> 0 votes

---
Tags: 7, views
---


# Question
Title: Save boolean data types in serialized array
I'm writing a CRUD front end application that talks to a hand-written Drupal endpoint. The data I'm pulling from the database is serialized in one field, or cell. It comes out as a keyed array.

One of the actions a user can do is to set a value true/false. The problem I'm running into is that when I send that data to the database from Javascript, it's coming in as a string:

```
 request.post('/my-api/save/' + id )
  .set('Content-Type', 'application/json')
  .send('{"' + prop + '":"' + val + '"}')

```

And when it's serialized and saved the the database `val` is written as a string. The problem is when `val` it is equal to "false." I'm using `drupal_write_record` to save the array. When this comes back to the front end, it's still a string, which in Javascript gets coerced to true.

What I'm struggling with is how/where to turn that string into a boolean. I'm guessing I should be doing this on the save action, but maybe there's a Drupal specific way to do this.

I'm doing this to the incoming json at the moment, I don't like it but it works for now.

```
$received_json = file_get_contents("php://input",  TRUE);
$json = drupal_json_decode($received_json);
foreach($json as $key => $val) {
  // Typecast the "false" string
  $json[$key] = $val === 'false' ? (bool) FALSE : $val;
}

```

# Answer
> 0 votes
This would be much easier to do on the client side. Assuming val is your boolean value, you can just add a single line to handle this:

```
val = +val;

```

That will coerce your boolean to an integer (1 or 0). No need to check all of the json data on the server side.

---
Tags: 7, database
---


# Question
Title: Use field from current node in filter in view
I have a content type called 'article\_landing' and a content type called 'article'.

They both have an entity reference field called 'field\_focus\_area'. I'm attempting to create a view that appears as a block on an article landing node and only displays articles that have the same field\_focus\_area as the current node. I'm having trouble figuring out how to do this though. I thought this would need to be accomplished with contextual filters but I'm not getting any results. Below is the method I was using.

I also tried using regular filters and using tokens like \[node:field\_focus\_area\] but that didn't work either.

Is there a way I can use fields of the node that a view block appears on inside filters in the view?

# Answer
> 3 votes
Niall Murphy's concept is correct but there are some differences between how it's performed in D8 and D7. Here is the code I ended up using which was successful.

```
function my_module_views_pre_view(&$view, &$display_id,&$args){
    if($view->id() == 'news'){
        if($view->current_display == 'block_2'){
            $current_node = \Drupal::routeMatch()->getParameter('node');
            if(!empty($current_node)){
                $focus_area = $current_node->field_focus_area->entity->id();
                $args[0] = $focus_area;
                $view->setArguments($args);
            }
        }
    }
}

```

# Answer
> 0 votes
EDIT: For correct implementation, OP has added the proper way to do this in D8.

That contextual filter will show nodes that reference the current node, so it's not what you're looking for.

As far as I know, this requires a custom module and this is what I do with D7 but I assume it's the same in D8 since the function didn't change much.

For this example, keep that Contextual filter from the screenshot, but click `Hide View` instead of `Provide default value`.

MYMODULE.info

```
name = Contextual Filter: field_focus_area
description = "Provide Contextual Filter for block."
core = 8.x

```

MYMODULE.module

```
<?php

function MYMODULE_views_pre_view(ViewExecutable $view, $display_id, array &$args) {
  // Check for view
  if($view->name == 'MYVIEWNAME') {
    // Explode url to get /node/xxx
    $current_args = explode('/', current_path());
    // Check that the path has xxx
    if (isset($current_args[1])) {
      // Load node
      $current_node = node_load($current_args[1]);
      // Send the node's field_focus_area to the view
      if (isset($current_node->field_focus_area['und'][0]['target_id'])) {
        $args[0] = $current_node->field_focus_area['und'][0]['target_id'];
      }
    }
  }
}

```

That will probably work. I haven't worked with D8 much and the function is slightly different. In D7, it's `hook_views_pre_view(&$view, &$display_id, &$args){`

I assume the `->field_focus_area['und'][0]['target_id']` part is the same but if not, you can find it using the Devel module.

---
Tags: views, 8
---


# Question
Title: How to update the URL Redirect module v1.4 to its latest version without losing redirects?
When I last went to update the URL redirect module from 8.x-1.4 to its latest version I saw this note:

> After 8.x-1.4 version URL Redirect changed as config entity. If you are using before 8.x-1.4 version, it's strongly recommended to not upgrade module as it deletes all existing redirects in your system.

Since I didn't want to lose all my redirects, I just left the module as it was. Unfortunately, as of yesterday, v8.x-1.4 is no longer supported.

What is the best fix for updating this module?
Is it just a matter of updating to v8.x-2.3 and redoing the redirects (fortunately I do not have a lot of redirects) or is there an easier way of doing it?

# Answer
> 1 votes
You can update module to v8.x-2.3 and run drush updb or update.php. In 8.x-2.3 version all existing redirects get converted to an entity in an update hook.

```
/**
 * Migrate old redirect data.
 */
function url_redirect_update_8103() {

  $db_connection = \Drupal::database();

  if ($db_connection->schema()->tableExists('url_redirect')) {
    $query = $db_connection->select('url_redirect', 'ur');
    $query->fields('ur');
    $all_data = $query->execute()->fetchAll();

    foreach ($all_data as $key => $data) {
      $values = array(
          'label' => 'Migrated Redirect',
          'id' => 'migrated_' . $key . '_' . time(),
          'path' => $data->path,
          'redirect_path' => $data->redirect_path,
          'roles' => Drupal\Component\Serialization\Json::decode($data->roles),
          'users' => Drupal\Component\Serialization\Json::decode($data->users),
          'status' => $data->status,
          'message' => $data->message,
          'checked_for' => $data->check_for,
      );
      $url_redirect_entity = \Drupal\url_redirect\Entity\UrlRedirect::create($values);
      $url_redirect_entity->save();
    }

    // We can drop 'url_redirect' table once we confirm everything is migrated properly.
    // $db_connection->schema()->dropTable('url_redirect');
  }
}

```

---
Tags: 8, redirection
---


# Question
Title: How do I create a tax calculation rule that runs by default before the customers address has been set?
With Drupal Commerce and the Australian GST calculation module, I have been trying to calculate taxes as early as possible.

Most of the customers to the site are Australian and will have to pay the taxes. Rather than give them a nasty surprise I'd like to add GST by default and then get rid of it if the person's shipping address isn't Australian.

I created a secondary OR condition in the GST rule as below:

If the country component of the order address is AU or if it is not set, then calculate GST.

The current effect is that GST never get calculated.

# Answer
> 1 votes
It looks like your problem might be caused by the incorrect usage of the "OR" (within your Rules Conditions). The logic you have in your "conditions" is like so:

* Order address component comparison.
* **AND** one of the next conditions in the **OR** group must be true:
    + Data value is empty.

Here is an attempt to translate your current Rules Conditions:

> "Order address component comparison must be TRUE" **AND** "Data value is empty".

I doubt that is what you wanted to implement as Rules Conditions, but that is how Rules actually interprets them ...

I'm not sure which (at least 2!) set of Rules Conditions you wanted to combine with the "**OR**"-operator, but what is shown in your question for sure cannot be right. Maybe you want to try to see what happens if you adapt your Rules Conditions like so:

* **OR** one of the next conditions in the **OR** group must be true:
    + Order address component comparison.
    + Data value is empty.

That is: move the "Order address"-condition below the **OR**, and also indent it (same indent as for "Data value is empty).

So if either (or both) of those 2 Rules Conditions are satisfied, then the Rules Actions will be performed. That should be pretty close to "\*If the country component of the order address is AU ***OR*** (repeat: ***OR*** !!!) if it is not set, then calculate GST\*" (as in your question).

For an interesting video tutorial about this, refer to "Combining conditions". Somewhere around '9:00' (near the end), it has a similar **OR** condition. Here is a summary of that tutorial:

* How to be confused over the positioning of the AND and OR statements
* How to combine conditions with AND requirements
* How to combine conditions with OR requirements
* How to combine AND and OR groups to create complex conditions
* Some advice about the order of conditions
* How to delete reaction rules
* Why you shouldn't use the "send e-mail to all users in a role" action
* Why it might be useful to have messages printed out when configuring complex rules

---
Tags: commerce, rules
---


# Question
Title: How can I programmatically recalculate an order total after changing the billing country
I have various international tax rules in place, specifically for EU VAT at different rates. This is all working as expected.

On the checkout form, when you enter a non-EU address, like Australia, when you go to the next page in the checkout process, the UK VAT line has been totally removed from the order total, exactly as I would expect.

My client wants to update the order summary on the billing page by AJAX to avoid confusion. Australian customers still see the UK VAT rate before they submit their address.

I've got the AJAX update working fine, and can load the order, update the billing country, and save the order. When I then refresh the page the address remains as I changed it, but the order total still reflects the old country.

I have traced through the code to see how the submit handler deals with this and I can't see what I need to do.

Is there a way I can recalculate the order total in code, either in form\_alter or the AJAX callback, so that the order object reflects the correct price for the billing country already set?

So, in short, if I change the billing address for an order, in code, how do I tell that order to recalculate it's totals?

I hope that makes sense and thanks for any help you can give.

This is what I'm trying, in hook\_form\_alter:

```
  if ($form_state['order'] &&
    !empty($form_state['input']['customer_profile_billing']['commerce_customer_address'][LANGUAGE_NONE][0]['country'])) {

    $new_country = $form_state['input']['customer_profile_billing']['commerce_customer_address'][LANGUAGE_NONE][0]['country'];
    $order = commerce_order_load($form_state['order']->order_number);
    $order_wrapper = entity_metadata_wrapper('commerce_order', $order);
    if (!empty($order->commerce_customer_billing)) {
      if ($new_country !== $order_wrapper->commerce_customer_billing->commerce_customer_address->country->value()) {

        $order_wrapper->commerce_customer_billing->commerce_customer_address->country = $new_country;
        $order_wrapper->commerce_customer_billing->save();
        $order_wrapper->save();

        commerce_order_calculate_total($order);
        commerce_cart_order_refresh($order);
      }
    }
  }

```

Stepping through each call watching the `commerce_order_total` and the number of components never changes, no the VAT line never changes and the price never changes. When I press "Continue to next step" the VAT line changes (is either added or removed appropriately).

Very frustrating. I've looked at the submit call and tried to trace through it but can't find where the total is being changed. I'm guessing it's in rules somewhere. If it makes a difference we're using `commerce_eu_vat`

# Answer
I've recently run into the exact same problem as you after changing the shipping address in an ajax call.

`commerce_order_calculate_total()` was the function that got everything working as expected for me.

You may or may not also need to use `commerce_cart_order_refresh()`.

First try without but if you are still not seeing it updated then try both.

If possible run these functions directly before your actually sending the order total value to be rendered.
> 1 votes

# Answer
Hmm, it's hard to say exactly what's going on, because saving the order actually does result in a call to commerce\_order\_calculate\_total() automatically. Since that isn't achieving your desired outcome, I wonder what else may be going wrong.

Is it possible that even though you're saving the order you didn't actually update the related customer profile and save that first before triggering a recalculation of the order total? The order itself doesn't have the address, just a reference to the customer profile that contains the address, so you would need to update the customer profile first in order for the new value to be taken into account during price calculation.
> 0 votes

# Answer
It turns out that all you really need to do is...

Update the **shipping** address, not the billing address. The above code works if you update the **shipping** address, call `commerce_cart_order_refresh()`, iterate all the line items and save them to force a recalculation of sale price, then call `commerce_order_calculate_total()`

Thanks to both that replied but I think I'll give the real answer to Felix as he correctly pointed me at the `commerce_order_calculate_total()` function.
> 0 votes

---
Tags: commerce
---


# Question
Title: Displaying a Block on 2nd level pages but not 3rd level
I have a block that I would like to only display on documents/\* but not on /documents/*/*.

I have set 'Show block on specific pages - only the listed pages' 'documents/\*' but this displays the block on all children of documents.

How do I set it to only display on documents/company (etc) and not documents/company/board?

# Answer
> 2 votes
The drupal.org/project/context module can do this. In addition to the typical wildcard `*` operator ... its Path conditions support a Not operator `~`.

# Answer
> 1 votes
you can do it in page.tpl.php

put this code their

```
if(arg(1)=='documents' && !isset(arg(3)==''))
{
//render block here
}

```

# Answer
> 1 votes
If PHP filter is enabled you can use this in "Show block on specific pages - PHP"

```
$whitelist = "documents/*";
$blacklist = "documents/*/*";
$path = drupal_get_path_alias($_GET['q']);
if (drupal_match_path($path, $whitelist) && !drupal_match_path($path, $blacklist)) {
   return TRUE;
}
return FALSE;

```

# Answer
> 0 votes
Assuming this question is about D7, there is another alternative to answer it: use the Rules block visibility module. Here is a quote from its project page:

> The Rules block visibility module allows Rules components to be used to control block visibility. This provides Drupal administrators and developers extreme flexibility in controlling when blocks should be displayed on their websites, in addition to the default visibility options provided by Drupal.
>
> The general idea is that if you can do it with Rules, you can use it to control block visibility, so the possibilities are limitless.
>
> Need to show a block only for users registered more than a month ago?
>
> Perhaps you have a block that must be shown only between 8am-5pm on weekdays?
>
> What about displaying or hiding a block based on current weather conditions?
>
> All of this can be done by using Rules block visibility.

With that, and as per the "*if you can do it with Rules, you can use it to control block visibility*" above, you've reduced your question to making Rules "***check the path of the current page***" (so that the block is only shown on your pages with a path that **starts with** "`documents/`", but not on those pages that have a path like "`documents/*/*`").

For an illustration of how to use this module, refer to my answer to "How to stop a Views block from displaying to administrators, such as user/1?". It includes a Rules Component (in Rules export format), which you should replace by this variation of it to make it match your specific question):

```
{ "rules_block_visibility_show_on_selected_profile_pages" : {
    "LABEL" : "Show block on selected profile pages",
    "PLUGIN" : "rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "USES VARIABLES" : {
      "module" : { "label" : "Module", "type" : "text" },
      "delta" : { "label" : "Delta", "type" : "text" },
      "result" : { "label" : "Result", "type" : "boolean", "parameter" : false }
    },
    "IF" : [
      { "AND" : [
          { "text_matches" : {
              "text" : [ "site:current-page:path" ],
              "match" : "documents\/",
              "operation" : "starts"
            }
          },
          { "NOT text_matches" : {
              "text" : [ "site:current-page:path" ],
              "match" : "documents(\/[a-z]*)?(\/)?$/",
              "operation" : "regex"
            }
          }
        ]
      }
    ],
    "DO" : [ { "data_set" : { "data" : [ "result" ], "value" : "1" } } ],
    "PROVIDES VARIABLES" : [ "result" ]
  }
}

```

**Note**: the 2nd Rules Condition in the above Rules Component (with the regular expression in it) may need further refinements to perfectly fit your case. I.e. the "`documents(\/[a-z]*)?(\/)?$/`" part of it (though I think it's pretty close to what your question is about).

---
Tags: blocks
---


# Question
Title: How do I convert AddressField "Administrative Area" abbreviation to full name
The Address Field module automatically converts administrative area (i.e., State/Province) abbreviations to full names on node display. I need to do this in my own custom module but can't find the function that the Address Field module uses to do this. How can it be done?

# Answer
> 4 votes
As mentioned earlier, there's no function in addressfield that does this, it's hard coded and not re-usable. Instead, there's a function in addressfield\_tokens module which DOES do this.

Using this function isn't really good practice because it's not an official hook (so it could change at anytime without notice), but as long as you're aware of what's going on and you use the proper checks that the module exists, it's the most flexible way to make this happen. Here's how to use it:

First, ensure that addressfield\_tokens.module is installed. Then you can use this function from line 338 in the .module file:

```
_addressfield_tokens_state($country, $state)

```

You need the $country because abbreviations are sometimes the same for different countries. So, if we wanted to find the full name of California, we would do this:

```
$california_fullname = _addressfield_tokens_state('US', 'CA')
return $california_fullname;

```

# Answer
> 4 votes
Drupal 8,

For Country List

`$full_country_list = \Drupal::service('country_manager')->getList();`

State or Administrative\_area list

`$full_state_list = \Drupal::service('address.subdivision_repository')->getList(['US']);`

Hope, it will be helpful to someone.

# Answer
> 1 votes
For someone who wants to convert the country name as well, use:

```
_addressfield_tokens_country($country)

```

# Answer
> 1 votes
Address field contains a very useful function:

```
addressfield_get_administrative_areas($country);

```

This returns the administrative areas for the country specified, keyed by the abbreviations.

e.g.

```
$australian_states = addressfield_get_administrative_areas('AU');

```

This would result in the following array:

```
$australian_states = array(
   'ACT' => t('Australian Capital Territory'),
   'NSW' => t('New South Wales'),
   'NT' => t('Northern Territory'),
   'QLD' => t('Queensland'),
   'SA' => t('South Australia'),
   'TAS' => t('Tasmania'),
   'VIC' => t('Victoria'),
   'WA' => t('Western Australia'),
);

```

# Answer
> 0 votes
Take a look at example/plugins/format/addressfield-example.inc. This file handles all the formatting changes. These look like they're hardcoded in.

Take a look at plugins/format/address.inc as well.

# Answer
> 0 votes
## Background

I needed to output the Province code as the full Province name as well. I dug into the module and in `addressfield.address_formats.inc` I found the following comment:

```
- render_administrative_area_value: True if the value should be rendered

```

I also found the following in address.inc:

```
'#render_option_value' => $address_format['render_administrative_area_value'],

```

From this, it appears that, if you retrieve the render array for the addressfield for a given entity, you can simply set the `administrative_area` sub-field's `#render_option_value` attribute to `TRUE`. I did this (code sample below) and, lo and behold, the Addressfield default formatter is observing this attribute nicely. I've got the full province name just as I wanted.

**PS:** I am making use of entity and uuid\_entity modules to store some static content that needs to be version controlled in code and made deployable - thus, instead of `node_load($nid)` you see `entity_load_single_by_uuid('node', $somvar['uuid']);` in the code sample below.

## Code Sample

```
$node = entity_load_single_by_uuid('node', $somvar['uuid']);
$address = field_view_value(
  'node',
  $node,
  'field_address_primary',
  $node->field_address_primary[LANGUAGE_NONE][0],
  'default'
);
$address['locality_block']['administrative_area']['#render_option_value'] = TRUE;

return render($address);

```

Hope this proves useful!

---
Tags: commerce, entities
---


title: Adding block in view tabs

text:
# Question
Title: Adding block in view tabs
I have tabs created using views and has contextual filter of group parent(Group ID from URL). I created a block that has a contextual filter of GID. In the block layout, I placed the block in the content region, select `Group from URL` to `Group ID:` and specify path to be shown--that is links of my tabs.

My goal is that whenever I access each tab links, the block content will be shown according to group ID from the URL.

**Given example:**

**Problem:**

My tab view with contextual filter is working but block is not showing up. How can I properly configure the block view setting to be consistent according to the GID?

**See photo below for my block settings:**

# Answer
In your view, change the contextual filter to the following: change: Hide view by Provide default value In Type, select the option that applies.
> 0 votes

# Answer
Okay. The specific fix for my concern is on the block view, I have to select `Provide default value:Raw value from URL:2`.
> 0 votes

---
Tags: 8, blocks
---


# Question
Title: How to create a filter in Views for filtering dates by day, month, or year?
I have a few thousand nodes with different dates as one of the fields. I am trying to create an exposed filter in views that allows the user to filter by day, month, or year.

For example, I would like someone to be able to enter "July" and get all the nodes associated with July, regardless of their day or year. I would also like users to be able to filter for "July 6" of any year or only "July 1973." Likewise, I would also like the user to have the ability of drilling right down to "July 6 1973" with the filter.

I have created a view with day granularity and an "equal to" operator. While this allows the user to select by day, month, and year ("July 6 1973"), any time only day, month, or year is put in, the form indicates that the other parts of the date need to be entered as well.

Does anyone have any suggestions?

# Answer
> 1 votes
I ended up creating a module that made three new fields - month, day, and year - and then processed the date field to populate these new fields. Then it was simply a matter of adding a view with exposed filters for month, day, and year.

# Answer
> 0 votes
Check if using the Views Date Format SQL module could be a solution for you. Here are some quotes about it (from its project page):

> ... allows to format date fields using SQL.
>
> The core functionality is to remove the date formatting from render() and put it in query(). I.e. format date values using SQL's DATE\_FORMAT rather than PHP's format\_date. This is achieved by assigning a new default handler to node 'created' and 'changed' date fields. This handler extends and overrides views's build in views\_handler\_field\_date.
>
> The UI is completely unobtrusive, only a single checkbox "Use SQL to format dates" is added to the handler configuration popup.

Your question is not about creating charts in Drupal, but you may want to refer to this comment also for an example of how we typically use it within the Charts module.

---
Tags: views, datetime
---


# Question
Title: "Your site was unable to contact the Apache Solr server"
We have been using Drupal 6 for 2 years and we wanted to use SOLR to have a better search and index more documents.

I have did everything right with Apache Solr as per the documentation, my Solr was working fine but I am able to access it on `http://localhost/solr/admin`.

I have different Solr in different servers, and none work with this Drupal. So I think there is an inherent problem within Drupal, which makes drupal not to find the solr properly.

Previously, I had encountered this issue several times configuring different servers, I am used to reinstall Drupal which made solr work fine but I cant do it to this one because its been running for long with lot of content.

Can anyone help me?

# Answer
> 3 votes
There a lot of apache solr variables set. Can you uninstall the solr module, remove the variables if left over and re-install. Sometimes, when you do a wrong config and it can't connect, it presists this in variable. Un-installing and re-installing should help.

# Answer
> 2 votes
I follow this article https://www.lullabot.com/blog/article/installing-solr-use-drupal ,some day comes this errors after I reconfig of my site& apache. but I sloved like this

# Answer
> 2 votes
If your site runs on Pantheon and you restored a database export from Pantheon in a local development environment, you have to disable the Pantheon Apache Solr module. It will not use the configured Solr URL if this module is running.

# Answer
> 0 votes
Belated answer:

check whether your Solr-serving process is running, and whether you are serving up Solr on the correct port.

The default Solr install seems always to come with Jetty (a Java based server) which runs on port 8983.

Solr can also be installed over Tomcat (another Java based server) which runs on port 8080.

Check if the process (whichever you chose - Jetty or Tomcat) is running, e.g.: ps -ef | grep tomcat

Your web logs may offer a clue.

# Answer
> 0 votes
You just need to add your collection in solr by following the step given in this url ( Apache Solr 4.6.0 installation and compatibility with Drupal7... ) and then select your collection from your solr which is running on localhost or live site (http://localhost:8983/solr/) and go to schema tab. Click schema tab and then you can see you schema file attach in apachesolr module.

You now just need to your schema url which just look like this http://localhost:8983/solr/your\_core\_name/. Now add this url in apachesolr module.

Then it will show that your site has contacted apache solr server in your drupal site.

---
Tags: 6, search
---


# Question
Title: Comment Author details are not displayed when comment is submitted by REST API
Currently I am using the following Drupal 8 REST method

POST: http://example.com/entity/comment

Content-type: application/json

```
    {
      "entity_id":[{"target_id":123}],
      "entity_type":[{"value":"node"}],
      "comment_type":[{"target_id":"comment"}],
      "field_name":[{"value":"comment"}],
      "subject":[{"value":"Goodbye World"}],
      "comment_body":[
        {"value":"<p>See you later!</p>","format":"basic_html"}
      ]
    }

```

201 - Created

This I referred from this link https://goo.gl/kXCS8Q The comment is getting created properly but the Comment's Author Details are not been displayed.

Can anyone tell what else I need to send the parameters for Comments?

# Answer
Just adding the solution here.

To get or determine a specific REST parameters, add these fields in your view or content manage fields, then try to access it by running the GET method command. It will show up all parameters of the content/node you need.

Then you can use POST method when planning to update or creating node of your need.
> 0 votes

---
Tags: views, comments, 8
---


# Question
Title: Fatal error: Call to undefined function field_create_instance()
I'm helping to convert a Drupal 7 module across to Drupal 8 and getting an error on the install.

> Fatal error: Call to undefined function field\_create\_instance()

I've seen in the Drupal 7 database that a table is created for *field\_first\_name* as *field\_data\_field\_first\_name*. Does this still happen in Drupal 8?

I resolved the fact that `field_info_field()` and `field_info_instance()` are now deprecated in Drupal 8 and have updated accordingly with `\Drupal::entityManager()->getFieldMap()` and `FieldConfig::loadByName()` respectively, but I can't find anything to suggest what to use instead of `field_create_instance()`; can someone suggest how I get around this?

My code is this.

```
/**
 * Implements hook_install().
 *
 * Adds custom fields used by module.
 */
function indicia_api_install() {
  $fields = array(
    'field_indicia_user_id' => (object) array(
      'type' => 'number_integer',
      'title' => 'User ID for this key on the warehouse',
      'name' => 'field_indicia_user_id',
    ),
  );

  foreach ($fields as $fielddef) {
    if (!\Drupal::entityManager()->getFieldMap($fielddef->name)) {
      \Drupal::logger('ima', 'Adding field: ' . $fielddef->name);
      $field = array(
        'field_name' => $fielddef->name,
        'type' => $fielddef->type,
      );
      if (isset($fielddef->required)) {
        $field['settings'] = array('required' => TRUE);
      }
      field_create_field($field);
    }
    else {
      \Drupal::logger('ima', 'Field already exists: ' . $fielddef->name);
    }
    if (!FieldConfig::loadByName('user', $fielddef->name, 'user')) {
      \Drupal::logger('ima', 'Adding instance: ' . $fielddef->name);
      $instance = array(
        'field_name' => $fielddef->name,
        'entity_type' => 'user',
        'label' => $fielddef->title,
        'bundle' => 'user',
        'required' => isset($fielddef->required) && $fielddef->required,
      );
      field_create_instance($instance);
    }
    else {
      \Drupal::logger('ima', 'Instance already exists: ' . $fielddef->name);
    }
  }
}

```

# Answer
> 0 votes
Just to update this question, if anyone else comes across this - I worked out the solution in the end. Rather than implementing the hook\_install() function I added the field information to the config/install/ folder which adds the necessary user fields instead.

---
Tags: 8, entities
---


title: Views PDF : class not found

text:
# Question
Title: Views PDF : class not found
I am running Drupal 7.56

I have been using Views extensively for some months now. I want now to create custom pdf pages from some Views.

I have installed jQuery\_update, then Views PDF Display Module, then copied fpdi and tcpdf libraries into the Libraries folder (via FTP).

Now, when I want to add a PDF Page to a View, I get the following error message :

> Fatal error: require\_once(): Failed opening required 'sites/all/libraries/fpdi/fpdi2tcpdf\_bridge.php' (include\_path='/home/my\_hostname/www/www/sites/paroisse/civi\_extensions/nz.co.fuzion.cmcic-master/:/home/my\_hostname/www/www/sites/paroisse/civi\_extensions/nz.co.fuzion.extendedreport/:/home/my\_hostname/www/www/sites/paroisse/civi\_extensions/org.civicrm.sms.twilio/:/home/my\_hostname/www/www/sites/paroisse/civi\_extensions/com.drastikbydesign.stripe/packages/:/home/my\_hostname/www/www/sites/paroisse/civi\_extensions/com.drastikbydesign.stripe/:/home/my\_hostname/www/www/sites/default/fpdf:.:/home/my\_hostname/www/www/sites/all/modules/civicrm:/home/my\_hostname/www/www/sites/all/modules/civicrm/packages:.:/home/my\_hostname/www/www/sites/all/modules/civicrm:/home/my\_hostname/www/www/sites/all/modules/civicrm/packages:/home/my\_hostname/www/www/sites/all/modules/civicrm/vendor/tecnickcom:/home/my\_hostname/www/www/sites/all/modules/civicrm/vendor/phpseclib/phpseclib/phpseclib:/home/my\_hostname/www/www/sites/all/modules in /home/my\_hostname/www/www/sites/all/modules/views\_pdf/views\_pdf\_template.php on line 22

I suspect that this is due to a bad installation, but find no clear and up-to-date installation tutorial.

I must say that : \- I am not a programmer, \- I use civicrm, a big Drupal Module, which explains the big include path

Any help is welcome

# Answer
> 0 votes
You need to copy the entire fpdi folder into the libraries folder.

It should have multiple files. Check for fpdf\_tpl.php. There should also be a filters folder into the fpdi folder.

# Answer
> 2 votes
I went back to fpdi-1.6.2, and the error disappeared (the internal fpdi folder content has completely changed between the two versions).

---
Tags: 7, views
---