title: How to load content in a div with ajax?

text:
# Question
Title: How to load content in a div with ajax?
After validate with javascript that I'll be able to use the client location:

```
if (navigator.geolocation) {
...

```

I need to load the content of a view block with arguments (based in the position coords). I know how to obtain the HTML that I want to put inside the div, so at least I have this part.

I tried to follow the Simple Drupal AJAX load with jQuery and delivery callback article (that is write for Drupal 7 very different from Drupal 8) but I just arrived to load a page in a div (with headers and footer very far from my real objetive).

```
jQuery('#my-div').load('/admin/help');

```

Any ideas on how to load content in a div with ajax?

# Answer
> 20 votes
I've come up with a working solution. It might not be the best approach but it works.

You need to create your routing file:

**my\_module.routing.yml**

```
diocese_core.path_with_data:
  path: 'path-with-data'
  defaults:
    _controller: '\Drupal\my_module\Controller\MyController::Render'
  requirements:
    _access: 'TRUE'

```

Creating the controller for your page

**src/Controller/MyController.php**

```
<?php

namespace Drupal\my_module\Controller;

use Drupal\Core\Controller\ControllerBase;
use \Symfony\Component\HttpFoundation\Response;

/**
 * An example controller.
 */
class MyController extends ControllerBase {

  /**
   * {@inheritdoc}
   */
  public function Render() {
    $build = array(
      '#type' => 'markup',
      '#markup' => t('Hello World!'),
    );
    // This is the important part, because will render only the TWIG template.
    return new Response(\Drupal::service('renderer')->render($build));
  }

}

```

And you only need to call in **javascript**

```
jQuery('#my-div').load('path-with-data');

```

An this will be the output once the code is executed:

```
<div id="my-div">Hello World!</div>

```

**References:**

# Answer
> 19 votes
This is exactly what you need.

```
var endpoint = Drupal.url('modal/get-content');
Drupal.ajax({ url: endpoint }).execute();

```

where **endpoint** is the URL of your route. So you have controller for your route and this controller has AjaxResponse

```
public function getContent($modal_id) {
  $response = new AjaxResponse();

  $selector = '.modal.in .modal-body';

  // You can use markup, rendreable array, getForm via form_builder service.
  $content = [
    '#markup' => '....',
  ];

  $response->addCommand(new InvokeCommand($selector, 'removeClass', ['spinner-loading']));
  $response->addCommand(new HtmlCommand($selector, $content));

  return $response;
}

```

# Answer
> 6 votes
Add what you need to your build array, and to render without the Page template, you can pass to a new Response object:

```
$build['view'] = [
  '#type' => 'view',
  '#name' => 'my_view',
  '#display_id' => 'block_1',
  '#arguments' => $view_arguments,
];

$rendered = \Drupal::service('renderer')->renderRoot($build);

$response = new Response();
$response->setContent($rendered);
return $response;

```

# Answer
> 1 votes
I searched for same solution and was very surprised that in a drupal way we need only one line of code:

```
Drupal.ajax({ url: endpoint }).execute();

```

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


# Question
Title: How can I check if a request is an AJAX request?
I am looking for a Drupal way of detecting AJAX request. I need to check this inside `hook_form_alter()` when embedding views with AJAX support.

How can I understand a request is an AJAX request?

# Answer
> 35 votes
For Drupal 7 there's nothing special in the API, just use plain PHP:

```
if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
  // AJAX request
}

```

For Drupal 8, the Symfony request object has a helper method:

```
// Example for brevity only, inject the request_stack service and call
// getCurrentRequest() on it to get the request object if possible.
$request = \Drupal::request();
$is_ajax = $request->isXmlHttpRequest();

```

# Answer
> 10 votes
You may consider using 'current\_path()\` and verify the path contains *ajax* in it.

```
$current_path = current_path();
if (strpos($current_path, 'ajax') !== FALSE) {
  // This is an AJAX request.
}

```

# Answer
> 1 votes
AJAX request in scope of working with forms in Drupal would mean that form must be rebuild. To detect that form must be rebuild one should check for:

```
$form_state['rebuild'] == TRUE;

```

# Answer
> 0 votes
Since there is no bullet-proof method of checking AJAX request (as `HTTP_X_REQUESTED_WITH` can be spoofed), here is another alternative based on the URL:

```
if (end((arg())) == 'ajax') {
  // AJAX request
}

```

Works for views (in case when last URI item contains 'ajax' word).

See also: How to check if the request is an AJAX request with PHP?

# Answer
> 0 votes
How I did it was using:

```
$request = $_SERVER['REQUEST_URI']

```

There I detected the ?\_wrapper\_format=drupal\_ajax

---
Tags: ajax
---


# Question
Title: How to send an email once a new member is invited using the Group module?
I am using the Group module on a Drupal 7 project. I would like the system to send an email notification once a new member is invited.

I'm assuming I could use the Rules module to perform this task, but so far my new rule configurations for this task is not working.

Has anyone experienced this issue and resolved it? If so please share your steps on how you achieved this.

# Answer
The Group module, out of the box, does not seem to send any eMail notifications to some user who got invited to join some group. Note however that a special Drupal message is shown right after an invited user performs a login to the site (too bad if the invited user never performs a login ...). Here is a sample of such message (which includes a link to relative path `/user/uid/group/invite`):

> You have pending group invitations. Visit your profile to see them.

However, since Group is entirely entity based, it's a piece of cake to use Rules for creating such eMails. The clue to do so, is related to the *creation* of a new group membership, and which corresponds to Rules Event "After saving a new group membership\*". This Rules Event is one of the events added by the Group module, located with 'Rules group' (don't get confused ...) "Group membership". However, a Group membership also has a status, which can be any of these:

* Active
* Requested
* Blocked
* Invited

With the above in mind, you can create a rather basic rule to do what you're asking for. Just use the Rules UI to import the rule below (in Rules export format) in your own site:

```
{ "rules_notification_about_new_group_invitation" : {
    "LABEL" : "Notification about new group invitation",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "group" ],
    "ON" : { "group_membership_insert" : [] },
    "IF" : [
      { "data_is" : { "data" : [ "group-membership:status" ], "value" : "invited" } }
    ],
    "DO" : [
      { "drupal_message" : { "message" : "The user with name [group-membership:user] just got invited by [group-membership:invited-by:name] to join the group named [group-membership:group:title] (with group type [group-membership:group:group-type:label])." } },
      { "mail" : {
          "to" : [ "group-membership:user:mail" ],
          "subject" : "You\u0027re invited by [group-membership:invited-by:name] to join the group \u0022[group-membership:group:title]\u0022",
          "message" : "You\u0027re invited by [group-membership:invited-by:name] to join the group named [group-membership:group:title] (with group type [group-membership:group:group-type:label]).",
          "from" : [ "group-membership:invited-by:mail" ],
          "language" : [ "" ]
        }
      }
    ]
  }
}

```

Some more details about the Rules Actions in this rule:

1. show a Drupal message, each time a user is invited to join some group, similar to this sample message (which also shows various Group related tokens you can take advantage of, such as the name and type of the group):

> The user with name Demo.User just got invited by Pierre.Vriens to join the group named Using the Answers module (with group type Class).
2. Create an appropriate eMail, using the various (relevant) tokens, e.g. the eMail Id of the user who performs the invite (= from), and the user that is invited (=to).

Note that for some user who is "*added*" to a group (instead of "*invited*") by an authorized user to do so, such message will not be shown. That's because of the Rules Condition included: the status for the selected group is not "Invited" in that case, instead the status will be "Active".

BTW, if you'd be willing (and able) to also use the Message module, you could add an extra Rules Action to create an appropriate Message entity (like a custom log record) also. And if you'd then use the Views module to create a custom view of such Messages, you'd have a perfect audit trail of who invited who for any of your groups ...
> 0 votes

---
Tags: 7, users, rules, emails, group
---


# Question
Title: How to set up a repeated “field set” with unlimited time and event?
I am planning to set up a “patient visiting record” , the repeated “field set” is time and events, for instance, “2017-12-15, the first visit, patient has stomach pain”, “2017-12-30, the second visit, patient has vomiting, has a rash on the left leg\[image upload\]”....every time when I click on “add item” the “time and event set” will pop up as one field. And the series “daily like” records will show on the patient record page, of course every patient will have their own page. The records of course are only accessible for admin. Is that possible to realize?

# Answer
> 0 votes
This is possible using the "double field" module (https://www.drupal.org/project/double\_field) and using the "field permissions" module (https://www.drupal.org/project/field\_permissions).

In the users' account settings add a double field, set it up as date/text combination, allow unlimited values. Use the field permissions setting to permit access to specific roles only.

This does't allow to use images to be used, unfortunately.

An alternative idea is using a paragraphs field (https://www.drupal.org/project/paragraphs), where you can define a paragraphs item with any fields you need. Again, set to unlimited allowed values and setting field permissions.

---
Tags: entities
---


# Question
Title: How do I programmatically delete an order?
My head is about to pop. I'm trying to figure out how to delete commerce orders programmatically. I created a rest export with the order IDs I want to delete. I've parsed that and put the IDs into an array. Now I want to loop through that array and delete the orders.

json parsing, and retrieving order\_id work fine.

I'm so close but I can't figure out how to properly reference commerce\_order\_delete or commerce\_cart\_commerce\_order\_delete?

```
function afc_custom_node_view(array &$build, \Drupal\Core\Entity\EntityInterface $entity, \Drupal\Core\Entity\Display\EntityViewDisplayInterface $display, $view_mode) {
          if ($entity->id() == 803) {
            $url = 'my url';
            $jsonString = file_get_contents($url);
            $jsonDecoded = json_decode($jsonString, true);
            $object = new stdClass();
            foreach($jsonDecoded as $row){
            if ($row['order_id'] == 121) {
                $object->order_id = $row['order_id'];
                // $order = \Drupal::entityTypeManager()->getStorage('commerce_order')->load($row['order_id']);
                commerce_cart_commerce_order_delete($object);
            }

            }
          }
    }

```

**Error:**

```
TypeError: Argument 1 passed to commerce_cart_commerce_order_delete() must be an instance of Drupal\commerce_order\Entity\OrderInterface, instance of stdClass given,

```

**UPDATE #2** **New Code**

```
use Drupal\commerce_order\Entity\OrderInterface;

  if ($entity->id() == 803) {
    $url = 'https://myurl.com/pull-ghosts';
    $jsonString = file_get_contents($url);
    $jsonDecoded = json_decode($jsonString, true);

    $object = new OrderInterface;

    foreach($jsonDecoded as $row){
      if ($row['order_id'] == 121) {
        $object->setOrderNumber($row['order_id']);
        commerce_cart_commerce_order_delete($object);
        print 'deleted';
      }
    }
  }

```

**SAME ERROR:**

```
error: Cannot instantiate interface Drupal\commerce_order\Entity\OrderInterface in afc_custom_node_view()

```

# Answer
> 3 votes
Loading it like a normal entity did the trick.

**How to load and delete commerce order programmatically**

```
$ord_id=121;
$order = \Drupal::entityTypeManager()->getStorage('commerce_order')->load($ord_id);
$order->delete();

```

Here is the entire snippet on my ultimate goal which was deleting abandoned orders in the cart. **How to remove commerce orders automatically**

**How to delete ghost commerce registrations in cart**

**Custom cron to delete commerce orders programmatically**

**Load a view programmatically loop through values and delete orders**

```
/**
 * Implements hook_cron().
 */
 function my_module_cron() {
   //load a view showing orders still in cart
   $view = \Drupal\views\Views::getView('commerce_carts');
   //the name of your display, i chose a simple rest display with the order_id field
   $view->setDisplay('rest_export_1');
   $view->execute();

   foreach($view->result as $row){
     //load the order
     $order = \Drupal::entityTypeManager()->getStorage('commerce_order')->load($row->order_id);
     $oid = $order->id();
     //delete the order
     $order->delete();
     //log to dblog
     \Drupal::logger('afc_commerce_registration')->notice('Clearing ghost registration, deleted: @oid.',
       array(
           '@oid' => $oid,
       ));
   }
 }

```

You can add the Created date field to the view, and test time values before deleting. In my case, it doesn't matter.

Thanks for the help everyone

# Answer
> 1 votes
For one, in your updated code, you cannot instantiate an Interface in PHP. This is throwing the error. If you were to need a new instance, you would instead use the `Order` class which implements the `OrderInterface` Interface.

As Orders are Entities, you *should* be able to simply load the Order and delete it.

Example:

```
use Drupal\commerce_order\Entity\Order;

$my_order = Order::load(122); // Or, your Order ID
$my_order->delete();

```

This should delete the Entity, which is your Order in this case.

# Answer
> -2 votes
You need your object to be of the class `Drupal\commerce_order\Entity\OrderInterface` instead of an empty class.

Use this instead: (**Update**)

```
use Drupal\commerce_order\Entity\OrderInterface;

$object = new OrderInterface;

foreach($jsonDecoded as $row){
  if ($row['order_id'] == 121) {
    $object->setOrderNumber($row['order_id']);
    commerce_cart_commerce_order_delete($object);
    print 'deleted';
  }
}

```

---
Tags: 8, commerce
---


# Question
Title: How to password protect terms in Taxonomy
I have a taxonomy vocab "region" in the region, I have a bunch of provinces as the terms, and subpages for each province.

I would like to add a password protect or only allow authorized users to access the provinces.

etc, only username "ontario" "password" can access the term "ontario" in the taxonomy. Is this possible?

# Answer
These modules may help, for D7 & D8 on DEV version is Taxonomy Access Control Lite, on approved versions (recommended): D7 is Taxonomy Access Control and for D8 is Permissions by Term, review wich one fit best your needs.
> 0 votes

---
Tags: users
---


# Question
Title: Use orConditionGroup with query (non entity)
I've used orConditionGroups with queries before. Specifically with entity queries. But now I have a custom sql table I created separate from drupal but still on the same database I have access to. I want to update a row if any of the fields are different but I'm having generating the or statement. Here was my attempt.

```
$connection = \Drupal::database();
$orConditionGroup = $connection->orConditionGroup()->condition('address', $fulladdress, '!=')->condition('full_name', $fullname, '!=')->condition('telephone', $workphone, '!=');
  $connection->update($table)->fields(['full_name' => $fullname, 'address' => $fulladdress, 'telephone' => $workphone, 'email' => $email])->condition('id', $id)->condition($orConditionGroup);

```

But I get the error

> undefined method Drupal\Core\Database\Driver\mysql\Connection::condition()

Which makes sense since the connection class isn't a query object on its own, but not sure how else to tackle this. How would I create an orConditionGroup for just a plain direct sql query that isn't a drupal entity or anything like that?

# Answer
I was able to get it to work by added the select method to the connection object like so:

```
$orConditionGroup = $connection->select($table)
                    ->orConditionGroup()
                    ->condition('address', $fulladdress, '!=')
                    ->condition('full_name', $fullname, '!=')
                    ->condition('telephone', $workphone, '!=');

```
> 2 votes

---
Tags: 8, database
---


title: Increase max length of a text field?

text:
# Question
Title: Increase max length of a text field?
Is there a simple way to increase the maxlength value of a plain text field that has data in it already?

# Answer
> 1 votes
To directly answer the question, there is no simple way in Drupal 8 to modify the schema for a field once it's been populated with data.

But, there is a more complicated way to manage it.

We've used the work done here by J-P Stacey to update a field in our platform.

* ALTER the database tables directly using raw SQL.
* Change the site configuration for the field.
* Force the current, "desired" schema records in Drupal to match.
* Force the "most recently installed" schema records to also match.

Additional information can be found in this article written by Marcus Bernal.

---
Tags: 8, entities
---


# Question
Title: Strategy for unit testing classes that interact with the Entity API
Sometimes I find that I end up having to do lots of mocking just to make the class testable, especially if it is interacting with the Entity API. For example, if I have code like this:

```
$taxonomy_term_storage = $this->entityTypeManager->getStorage('taxonomy_term');
$category = $taxonomy_term_storage->load($product_category_tid);
$category_atlas_key = $category->get('field_name_key')->getValue();

```

So now, to mock the return value of one field I need to do all of this:

```
$fieldItemListMock = $this->getMockBuilder('\Drupal\Core\Field\FieldItemListInterface')
  ->disableOriginalConstructor()
  ->getMock();

$fieldItemListMock->expects($this->any())
  ->method('getValue')
  ->willReturn('foo');

$fieldableEntityMock = $this->getMockBuilder('\Drupal\Core\Entity\FieldableEntityInterface')
  ->disableOriginalConstructor()
  ->getMock()

$fieldableEntityMock->expects($this->any())
  ->method('get')
  ->willReturn($fieldItemListMock);

$entityStorageMock = $this->getMockBuilder('\Drupal\Core\Entity\EntityStorageInterface')
  ->disableOriginalConstructor()
  ->getMock();

$entityStorageMock->expects($this->any())
  ->method('load')
  ->willReturn($fieldableEntityMock);

$this->entityTypeManagerMock->expects($this->any())
  ->method('getStorage')
  ->willReturn($entityStorageMock);

```

As far as I'm aware I've done everything as I'm supposed to, injecting external dependencies via the constructor but it still seems like way too much effort. The problem gets exponentially worse when I'm working with multiple fields or other people's code who haven't injected dependencies properly. So I end up having to create a partial mock of the class I'm testing.

Browsing through core and contrib modules I notice that there seem to be more Kernel tests than Unit tests, which seems contrary to the testing pyramid

Which makes it seem like they have also found unit tests too hard to set up.

So I'm wondering, is it better to just write Kernel tests / Browser tests for classes that interact with the Entity API or am I simply writing my code wrong, which is making it hard to unit test?

# Answer
> 5 votes
> So I'm wondering, is it better to just write Kernel tests / Browser tests for classes that interact with the Entity API or am I simply writing my code wrong, which is making it hard to unit test?

In my opinion yes. The Entity API is not designed to work well for mocking/unit tests. Drupal 8 was a very different thing when we started designing and implementing it. Maybe we'd do things differently today, but the kind of extensibility it offers is hard to manage. And we also needed something that we could gradually convert the large Drupal core code base or it would never have been possible.

In regards to the testing pyramid, that is the ideal scenario, but it's not always feasible. I also think that it is makes more sense in a scenario where you built and control the whole system. By building on top of Drupal (which in turn builds on top of Symfony), a huge amount of the complexity and heavily lifting is already taken away from you and covered with the test coverage of those projects. Given that, it makes sense to me that there is a bigger focus on integration/E2E tests as you are mostly integrating existing components.

And if you *do* have your own components that actually do things worthy of unit tests (and not just shuffle data between forms, entities and templates) then one thing you could do is work with Adapter/Value objects that hide away the complexity of Entity Field API with an interface that you can mock.

---
Tags: 8, testing
---


# Question
Title: Replace the date of a filtering criterion with "Views PHP"?
I created a "like" flag on the nodes.

I created a comment view.

I want my view to show only comments posted since the flag date.

The solution will be to create a filter criteria with the filter "Comment: Publication date" (Is greater than or equal to) and replace the value with the date of the flag.

The problem is that there are no tokens for the filter criteria.

How to do this with "Views PHP" ?

https://www.drupal.org/project/views\_php

# Answer
> 1 votes
Don't.

Views PHP or any other method of stored PHP is a bad idea (What are the downsides of using PHP Filter code in blocks, nodes, views-args, etc?). It's also extremely slow, because it usually involves loading all data and then doing all the processing in PHP.

Instead, build a module and define a views filter plugin there, then you can build the query there how you like it. How exactly to do that is IMHO too complex to answer in a single question, you should find plenty of examples and tutorials on how how to create views filter plugins (there are dozens of plugins in core alone), look for something similar to your use case and start from there.

---
Tags: views, 8, theming, flags
---


# Question
Title: What is the best way to update/add paragraphs with REST on a node
I have a node with a paragraph. This paragraph has a couple fields and there can be any number of these paragraphs on a node.

I want to update this node via REST. This is some of the GET output:

```
"field_region": [
    {
        "target_id": 13,
        "target_type": "taxonomy_term",
        "target_uuid": "2ae47cc7-c1c2-477d-8f23-b124e964f83a",
        "url": "/regions/california"
    }
],
"field_tactic_disbursements": [
    {
        "target_id": 9,
        "target_revision_id": 13,
        "target_type": "paragraph",
        "target_uuid": "1c98b1aa-f443-47fe-baff-1ecd0b499d1f"
    }
],
"field_year": [
    {
        "target_id": 1,
        "target_type": "taxonomy_term",
        "target_uuid": "58f65d10-143f-4a23-9315-52220c433602",
        "url": "/years/2018"
    }
]

```

Based on how this is, it looks like I will have to do a separate PATCH/POST request for each paragraph. Is there a way to do this in one request?

I'm thinking about creating a custom Resource to handle this but not sure if there is a better way.

# Answer
> 2 votes
https://www.drupal.org/project/entity\_reference\_revisions/issues/2848878 is an issue that allows to embed paragraphs on a field directly into the main resource.

We developed and use it exclusively for the use case of default\_content with hal\_json. It will likely not work out of the box with REST and patching/updating entities. But you're welcome to use it as a first step towards that, patches based on that are welcome.

---
Tags: 8
---


# Question
Title: Patch a contrib module with a patch that contains new files
How do I patch the recaptcha module with the invisible recaptcha patch using drush make? I patch modules all the time in project.make.yml with yml that looks just like this:

```
...
# Recaptcha 8.x-2.2 - 2016-07-30
recaptcha:
  subdir: contrib
  version: '2.2'
  patch:
    # Integrate Invisible reCAPTCHA option from Google
    - 'https://www.drupal.org/files/issues/recaptcha-invisible-option-2852269-56.patch'
...

```

What's different with the invisible recaptcha patch is the patch contains two new files.

# Answer
I would recommend you consider switching to composer and composer-patches. I don't think drush make is still actively maintained?

Quick google search pointed me to http://www.anexusit.com/blog/how-to-apply-patches-drupal-8-composer for example. That works fine, also for patches that add new files. The only case where that is a problem is core, due to different path structures in drupal/core and then it doesn't apply it correctly.
> 1 votes

---
Tags: 8
---


# Question
Title: Access custom block in page.html.twig template
I've added a custom block (which is an image) in the HEADER section of a view. I want to show this image at the top of my page but currently it appears in content **views-view.html.twig**.

How can I access to this image in **page.html.twig**?

# Answer
> 2 votes
Take away the block from the view header and use twig\_tweak module to be able to insert something like this in your twig template

```
{# No need to configure this block on "admin/structure/block" page. #}
<dt>Block:</dt>
<dd>{{ drupal_block('BLOCKID') }}</dd>

```

Or if you don't want to use an extra module add to your THEMENAME.theme

```
function THEMENAME_preprocess_page(&$variables) {
  $block = \Drupal\block\Entity\Block::load('BLOCKID');
  $content = \Drupal::entityTypeManager()->getViewBuilder('block')->view($block);
  $variables['my_block'] = $content;
}

```

and in your twig template just use

```
{{ my_block }}

```

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


title: Adding new text field to drupal 8 menu

text:
# Question
Title: Adding new text field to drupal 8 menu
I am trying to add a new text field to the menu in Drupal 8, and I have done it using the instruction in the following post:

Add field(s) to menu link?

```
function my_module_entity_base_field_info(\Drupal\Core\Entity\EntityTypeInterface
$entity_type) {
  if ($entity_type->id() === 'menu_link_content') {
    $fields['location'] = BaseFieldDefinition::create('string')
      ->setLabel(t('Location'))
      ->setDisplayOptions('view', ['label' => 'hidden', 'type' => 'string', 'weight' => 0, ])
      ->setDisplayOptions('form', array('type' => 'string', 'weight' => 0));

    return $fields;
  }
}

```

But I am not sure how to go about using hook\_update\_n to update the schema to reflect this change.

```
function menu_link_content_update_8201() { 'what do I put here to add the new field that I created'? }

```

I was able to workaround this issue by manually adding the `location` column in the mysql db and I can see the field showing up in the menu link editor and able to load and save it just fine in the cms UI.

But then I am not sure how to access this field in the twig file.

Any help would be grateful. Thanks!

# Answer
You only need an update hook if you want that your module can be updated on production sites already using the module. If you write a new module or the module is still in development you can simply reinstall the module. If you have data you want to keep during development use `drush entity-updates` after changing the code of the installed module.
> 0 votes

---
Tags: theming, hooks
---


title: Twig cache files on load-balanced setup

text:
# Question
Title: Twig cache files on load-balanced setup
The Twig cache key (twig\_cache\_prefix) is based the modify timestamp of the Twig template file and a randomly generated key. This gives a problem with a load-balanced Drupal setup where every host has it own copy of the Drupal source files, with different timestamps for the same template files across the hosts.

In this setup each Drupal instance keep generating a new prefix for every other request (when the balancer is in round-robin mode).

Is there a workaround for this?

# Answer
We host a platform in Acquia and we've run into this issue as well. For our needs, we get around it by logging into each webhead and clearing the appropriate cache.

There is an ongoing discussion for this in Drupal issue #2752961.
> 0 votes

---
Tags: theming
---


# Question
Title: What does "Revision translation affected" indicate?
In views there is a boolean field named **Revision translation affected**. The description for the field is "*Indicates if the last edit of a translation belongs to current revision*". To me it is not so clear. What exactly does it mean?

Does it indicate what language that was changed in that revision? And what happens when non-translatable fields are edited?

# Answer
I found this explanation in code comments:

> If a translation has changes in a certain revision, the translation is considered "affected" by that revision, and will be flagged as such via the "revision\_translation\_affected" field.

http://cgit.drupalcode.org/drupal/tree/core/lib/Drupal/Core/Entity/entity.api.php#n102
> 1 votes

---
Tags: 8, i18n-l10n
---


# Question
Title: Why isn't my .htaccess masking my drupal subdirectory?
I've got D8 installed in a subdirectory `example.com/drupal`, but I don't want "drupal" to appear in any of the URLs. I've added the following to my `example.com/.htaccess` file:

```
RewriteEngine On
RewriteBase /
RewriteRule ^(.*)$ /drupal/$1 [L]

```

This successfully allows my site visitors to browse to `example.com`, but any further interaction with the site (e.g. browsing to a node, searching for "foo", etc.) causes "drupal" to appear in the URL.

What do I need to completely mask "drupal" from all site URLs?

# Answer
Check this other question out, How do I change the base URL?
and this issue on drupal.org, https://www.drupal.org/node/2753591

In summary, Drupal 8 as of right now detects where it is automatically. On D7 there used to be a `base_url` option which could be used for this.

> In Drupal 8 this option has been removed. You don't have to configure base\_url to run your site. Drupal 8 can detect this without your help. If not, you should first check your webserver configuration.

---

`.htaccess` approach – You can't do this using the `.htaccess`. You'll end up with a redirect from `drupal/` going to `/` which will then request `/drupal` and go back to `/` and so forth. You'll end up with a redirect loop.

If you want to test it, add this to Drupal's `.htaccess` (`/drupal/.htaccess`):

```
RewriteCond %{REQUEST_URI} ^(/drupal)(/)(.*)
RewriteRule ^ %2%3 [L,R=301]

```

---

Options I see,

1. Move the files from the `drupal` directory one directory up
2. Point the virtualhost to the `drupal` directory.
A lot of people use `docroot` or `htdocs` for a similar setup. This allows for some files to be in the repo but outside the directory being served by the web server.
3. Try out the patch from the second link. It needs to be community reviewed for acceptance, so that would actually be great.
> 0 votes

---
Tags: 8, uri, .htaccess
---


title: Drupal multi-site in an add-on domain?

text:
# Question
Title: Drupal multi-site in an add-on domain?
How can I configure Drupal 8 with multi-site under an add-on domain using cPanel? I'm getting a 404 when I browse to my subdomain after following these steps:

1. Clean install of Drupal to my add-on domain: `/public_html/addondomain.com/drupal`. I can successfully browse to `addondomain.com/drupal`
2. In cPanel, create a sub-domain at `sub.addondomain.com` with a document root at `/public_html/sub.addondomain.com`
3. Create the directory `/public_html/addondomain.com/drupal/sites/sub.addondomain.com`
4. Create a `sites.php` within `public_html/addondomain.com/drupal/sites` that contains the following code: `<?php $sites = array('sub.addondomain.com' => 'sub.addondomain.com',);>`. File permissions are 644.
5. Copy `/public_html/addondomain.com/drupal/sites/default/default.services.yml` to `/public_html/addondomain.com/drupal/sites/sub.addondomain.com/services.yml`
6. Copy `/public_html/addondomain.com/drupal/sites/default/default.settings.php` to `/public_html/addondomain.com/drupal/sites/sub.addondomain.com/settings.php`
7. Remove the directory `/public_html/sub.addondomain.com`
8. Create a symbolic link in `/public_html/`: `ln -s addondomain.com sub.addondomain.com`

When I do all of the above, I get a 404 error when I browse to both `sub.addondomain.com` and `sub.addondomain.com/drupal`. Why am I not redirected to the Drupal installation page where I can enter in my database info, etc.? Is the error with my symlinks? My server (cPanel) configuration? My `.htaccess` under either my `/public_html`, `public_html/addondomain.com`, or `/public_html/addondomain.com/drupal`?

# Answer
My solution was to point the document root of `sub.addondomain.com` to `/public_html/addondomain.com/drupal`. I did this within cPanel, which - if I understand cPanel correctly - is going to directly edit the Apache VirtualHosts directives within Apache's config files for my site (something I wouldn't have access to directly with shared hosting).
> 0 votes

# Answer
You say this,

* Drupal is installed under `addondomain.com` in `/public_html/addondomain.com/drupal`
* The document root for `sub.addondomain.com` is set to `/public_html/sub.addondomain.com`

If this is accurate, they're looking for files in different places. Make sure these two are setup the same (either with or without the `drupal` suffix).

---

> Create a sites.php within public\_html/addondomain.com/drupal/sites that contains the following code: 'sub.addondomain.com',);\>. File permissions are 644.

Move or remove this file. It's not needed with your naming scheme and it's simply adding another step to debug.

> ```
>  * For example, for a fictitious site installed at
>  * https://www.drupal.org:8080/mysite/test/, the 'settings.php' file is searched
>  * for in the following directories:
>  *
>  * - sites/8080.www.drupal.org.mysite.test
>  * - sites/www.drupal.org.mysite.test
>  * - sites/drupal.org.mysite.test
>  * - sites/org.mysite.test
>  *
>  * - sites/8080.www.drupal.org.mysite
>  * - sites/www.drupal.org.mysite
>  * - sites/drupal.org.mysite
>  * - sites/org.mysite
>  *
>  * - sites/8080.www.drupal.org
>  * - sites/www.drupal.org #THIS PATTERN WILL MATCH
>  * - sites/drupal.org
>  * - sites/org
>  *
>  * - sites/default
>
> ```

More info here, https://github.com/drupal/drupal/blob/17ebfff72673728bc8495d67f35061ad8bdcc299/sites/default/default.settings.php#L13

---

~~\> My `.htaccess` under either my `/public_html`, `public_html/addondomain.com`, or `/public_html/addondomain.com/drupal`?~~

~~Could you explain a bit more why you have .htaccess files under `/public_html/addondomain.com` and under `/public_html/addondomain.com/drupal`?~~

I think I get my last question (above crossed out, leaving for reference of others). You created a directory under `addondomain.com` for drupal, `/drupal`. Now you are trying to access it via a subdomain. If you want to access it without `/drupal` at the end you should update the symlink to `ln -s addondomain.com/drupal sub.addondomain.com`
> 0 votes

---
Tags: multi-sites, subsites
---


# Question
Title: In a view how to replace the date of creation of the comment by the date of the flag?
I created a "like" flag on the nodes.

I created a view that displays the comments.

I want my view to show only comments posted since the flag date.

The solution will be to create a filter criteria with the filter "Comment: Publication date" (Is greater than or equal to) and replace the value with the date of the flag.

The problem is that there are no tokens for the filter criteria.

There is a tutorial here :

https://www.webomelette.com/creating-custom-views-filter-drupal-8

But I failed to create the criteria filter. This is the first time I've created code for a view.

Can you explain to me in an answer how to do this step by step ?

thank you in advance

I created a folder :

```
notify_node_new_comment

```

And a file `notify_node_new_comment.yml` that I placed inside :

```
name: Notify node new comment
description: Notification of new comments.
type: module
core: 8.x

```

I created an empty file `notify_node_new_comment.views.ink` in my folder (I do not know what to put as code).

I also added the following folders :

```
/scr/Plugin/views

```

# Answer
Views filters have nothing to do with tokens. What you need to do is build the necessary query for this, which is something that tutorial ignores completely as it is a pretty simple condition.

A bit of searching pointed me to `\Drupal\taxonomy\Plugin\views\filter\TaxonomyIndexTidDepth::query` as an example that builds a complex subquery condition in a filter.

I don't know your level of expertise with PHP/Drupal/SQL, so I would recommend you start by building the SQL that is needed for this by hand. In the views settings, enable to show the SQL query on the preview. Then copy that query, remove the `{`/`}` execute it by hand and try to adjust it to contain the filter you need. You probably want to add a relationship to flaggging already.

Once you have that, implement that in PHP in the query method of your filter.
> 0 votes

---
Tags: 8, theming, views, flags
---


# Question
Title: How to customize a node--type.html.twig template?
I activated the devel and devel kint modules. I also activated twig debugging, so, I can know which are templates used by Drupal.

So, I created a content-type named album that contains a field named tracks.

Now, I want customize this content type, so I created `node--album.html.twig` in templates folder of bartik, which works so I can begin to customize this template.

Now, I have to know which are variables used by this template. In comment section of `node--album.html.twig` I can read that `content` variable can be used to display content of page. I also read I can use subset of content, such as content.field\_example to display a field.

OK, so if I want to modify rendering of field\_tracks I can use `content.field_tracks`. Before using this variable I wanted to know all content variable, so I've written `[[ kint(content) ]]` in content section of this file. I rebuilt the cache, and I seen that content is an array, not an object as suggested in comment section of node file.

So, if I print `[[ content.field_tracks ]]` it returns nothing.

If I use `kinkt()` without parameters it breaks drupal and point me to core/install.php.

The same as I use `d()` without parameters.

At this point I am confused: there is a way to modify node--type twig templates without creating a file for each field?

# Answer
Here is some examples

Render the whole field markup

```
{{ content.field_text }}

```

Get just the value of the field

```
{{ content.field_text.value }}

```

Get a field value from authors object

```
{{node.uid.entity.field_gender.value}}

```

For field above you can get the machine name of the field as you see it for example in `admin/structure/types/manage/page/fields`

For multivalue fields look at some examples here

Read more about how to find more variables here
> 1 votes

---
Tags: 8, theming
---


title: Drupal 8 Webform Composite fieldset

text:
# Question
Title: Drupal 8 Webform Composite fieldset
Is there a way to add fieldsets inside of a custom composite? Not looking to add anything repeatable, just simply group the fields together.

This get's the fieldset to show but I don't know how to add fields as children.

```
$elements['grouped_fields'] = [
  '#type' => 'fieldset',
  '#title' => t('Grouped Fields')
];

```

# Answer
> 0 votes
Place the fields inside of the fieldset:

```
$elements['grouped_fields']['field1'] = [
  '#type' => 'textfield',
  '#title' => t('Field 1'),
];
$elements['grouped_fields']['field2'] = [
  '#type' => 'textfield',
  '#title' => t('Field 2'),
];
// ...

```

---
Tags: webforms
---


# Question
Title: Unable to set cache max-age on ResourceResponse
I'm trying to create a REST API GET response. My class extends `ResourceBase` and this is inside its `get()` method.

```
$response = new ResourceResponse(['time' => time()], 200);

$cache_meta_data = new CacheableMetadata();
$cache_meta_data->setCacheMaxAge(2);
$response->addCacheableDependency($page);
$response->addCacheableDependency($cache_meta_data);

return $response;

```

This will return the timestamp, but it will be cached forever until I manually clear the cache. When I run `curl 'https://mylocaldrupal.dd:8443/rest/upcoming_matches/1?_format=json' -i -k`, this is the output for the first hit.

```
HTTP/1.1 200 OK
Date: Sun, 11 Feb 2018 17:03:06 GMT
Server: Apache/2.4.17 (Unix) OpenSSL/1.0.1h mod_fcgid/2.3.9
X-Powered-By: PHP/7.0.14
Cache-Control: must-revalidate, no-cache, private
X-Drupal-Dynamic-Cache: UNCACHEABLE
X-UA-Compatible: IE=edge
Content-language: en
X-Content-Type-Options: nosniff
X-Frame-Options: SAMEORIGIN
Expires: Sun, 19 Nov 1978 05:00:00 GMT
X-Generator: Drupal 8 (https://www.drupal.org)
X-Drupal-Cache: MISS
Transfer-Encoding: chunked
Content-Type: application/json

{"time":1518368586}

```

This is the output of the second hit, after a few seconds.

```
HTTP/1.1 200 OK
Date: Sun, 11 Feb 2018 17:04:41 GMT
Server: Apache/2.4.17 (Unix) OpenSSL/1.0.1h mod_fcgid/2.3.9
X-Powered-By: PHP/7.0.14
Cache-Control: must-revalidate, no-cache, private
X-Drupal-Dynamic-Cache: UNCACHEABLE
X-UA-Compatible: IE=edge
Content-language: en
X-Content-Type-Options: nosniff
X-Frame-Options: SAMEORIGIN
Expires: Sun, 19 Nov 1978 05:00:00 GMT
X-Generator: Drupal 8 (https://www.drupal.org)
X-Drupal-Cache: HIT
Transfer-Encoding: chunked
Content-Type: application/json

{"time":1518368586}

```

I can't really figure it out. Drupal.org documents don't really seem to help me neither. Am I missing something obvious?

# Answer
> 2 votes
The referenced question from 4k4 describes how to disable the internal page cache completely.

To not disable but set an expiration on the anonymous/internal page cache, you can use the Expires header, just set it to a date in the future and that will be respected. That's the only thing that the internal page cache module currently respects.

See the linked core issue for more information, it's partially simply an overlook that it wasn't done before 8.0 but now it would be an API change to start respecting it and lots of things would then make Drupal uncacheable, like the language switcher block. So we'll have to be very careful with any change we make.

---
Tags: 8
---


# Question
Title: How to selectively import and export content between 2 Drupal websites?
How to merge simple core content into from site a to site b. Content is created using core functionality and modules.

Let's say I have 2 Drupal 7 sites, both have same configuration and modules.

Site A has:

* 3 content types
* 3 taxonomies
* 3 articles

Site B has:

* 1 content types
* 1 taxonomies
* 1 articles

How do I append content of site B to site A?

I want the content from site A to be appended to site B. If I do backup migrate, the content of site A will be overwritten.

I've noticed that backup migrate can have manual selection of what to export, but it will overwrite destination right?

What is the best procedure for this?

# Answer
> 0 votes
You could always write a couple of migration classes with the Migrate module, and hook up Site B as the datasource (the module would live in Site A).

You can do this by adding Site B's database credentials to the settings.php as another configuration, then calling on that in your script.

Here is an example of what a Migration class might look like:

```
class YourMigration extends Migration {
  public function __construct($arguments) {
    parent::__construct($arguments);

    $query = Database::getConnection('connection_name', 'connection_key');
    // other query arguments to execute
  }
}

```

Where the `Database::getConnection` arguments are the names of the items in your `$databases` array in settings.php. With a working script, you can then write other scripts (or a cron job) to periodically run the migrate job.

Others will say to use Feeds, but I've always been a big Migrate fan (not Drupal2Drupal migrate module, the main Migrate module itself).

> I've noticed that backup migrate can have manual selection of what to export, but it will overwrite destination right?

Pretty much. Site A would get wiped out. It also isn't as simple as moving MySQL data around, unless every data model in Site B is identical or exists in Site A even then its a fairly large technical challenge *not* to screw anything up. I would not do anything with SQL at this level - it needs to go through the API.

# Answer
> 0 votes
No code solution:

Use Feeds to import the data. But first, you'll need to create a CSV of your data. You can use Views Data Export.

Now that you have a CSV, simply import using feeds.

---
Tags: backups
---


title: One image style not generated

text:
# Question
Title: One image style not generated
UPDATE: After investigting this I have concluded that the problem concerns ALL new image styles, but "old" ones are still working. Old ones are the built-in (e.g. thumbnail) and one image style of my own.

Also: I use the patch to create the in core/modules/image/image.module, if it is a factor.

I have run a really strange problem: New image styles I have created don't work on one server (of course the production). I have tried to re-create the image styles, flush the caches etc ad nauseaum, but still the same thing. I have an exactly similar (apart the dimensions) image style that works just fine. The file permissions and owners are the replica of the working one...

The effect is Focal Point Scale and Crop (working dimensions 550 x 250, non working 1290 x 400). And in the development it's working just fine.

Any ideas, anyone?

wbr hank

# Answer
How large is the original image? It could be your production server php memory limit is being reached. Have you checked the error logs on the server?

Drupal needs to put the original image into memory to create the styled version so if this image is quite large it can cause memory to run out. Especially if you're on a cheap hosting
> 0 votes

# Answer
I finally got it. The problem lied in site nginx conf file. The following block was

```
 location ~* \.(?:ico|css|js|gif|jpe?g|png)$ {
     expires max;
     # add_header Pragma public;
     # add_header Cache-Control "public, must-revalidate, proxy-revalidate";
}

```

too early in my nginx file. After moving it to the end of the file (last entry in the server block), the problem vanished into thin air. Damn, one whole working day spent in vain :/ But at least, now the problem has gone away.

wbr

hank
> 0 votes

---
Tags: 8, media
---


# Question
Title: Add header and footer for every pages printed
I've used print module version 7.x-2.0. I've used pdf-version and print-friendly-version.

Now i want to do two different things. That is,

* Is it possible to add separate CSS for pdf, html or email templates like: print-pdf.css, print-html.css, print-email.css, print.css.?
* I have added header and footer. It only works for first page and last page, But I want to display them for every printed pages. How can I do that?

# Answer
> 0 votes
you can do it to inset html tag in header ot footer file in tpl.php

```
<div class="header_print">enter your header </div>
print $content of your page
<div class="footer_print">enter your footer</div>

<style type="text/css">

    .Footer {
            position: fixed;
            bottom: 0;
        }
    .Header {
            position: fixed;
            top: 0;
        }

</style>

```

# Answer
> 0 votes
You could try one of the css only solutions here https://stackoverflow.com/questions/1360869/how-to-use-html-to-print-header-and-footer-on-every-printed-page-of-a-document

The reports say that it does not work on all browsers maybe support is better nowadays with some of the NEWER answers.

---
Tags: files
---


# Question
Title: js-header and js-footer are not loading drupal 8
```
portfolio-library:
  version: 1.1
  css:
    theme:
      assets/css/main.css: {}
      #assets/css/font-awesome.min.css: {}
      assets/css/ie9.css: {IE: 'lte IE 9'}
      assets/css/ie8.css: {IE: 'lte IE 8'}

  js-header:
    header: true
    js:
      assets/js/ie/html5shiv.js: {IE: 'lte IE 8'}

  js-footer:
    js:
      assets/js/skel.min.js: {}
      assets/js/ie/respond.min.js: {IE: 'lte IE 8'}
      assets/js/main.js: {}

  dependencies:
    - core/jquery

```

This is my library file but my js files are not included in my theme can anyone please let me know what is going wrong.

# Answer
> 1 votes
You may be over-complicating this. HTML5 shiv is already in core, so you can just depend on it without any extra work. There's no `js-header` or `js-footer` keys, just use `js` as normal:

```
portfolio-library:
  version: 1.1
  css:
    theme:
      assets/css/main.css: {}
      #assets/css/font-awesome.min.css: {}
      assets/css/ie9.css: {IE: 'lte IE 9'}
      assets/css/ie8.css: {IE: 'lte IE 8'}

  js:
    assets/js/skel.min.js: {}
    assets/js/ie/respond.min.js: {IE: 'lte IE 8'}
    assets/js/main.js: {}

  dependencies:
    - core/jquery
    - core/html5shiv

```

If you need your own version for whatever reason, declare the shiv separately:

```
html5shiv:
  header: true
  js:
    assets/js/ie/html5shiv.js: {IE: 'lte IE 8'}

```

and depend on it:

```
portfolio-library:
  ...
  dependencies:
    - core/jquery
    - mytheme/html5shiv

```

---
Tags: theming
---


# Question
Title: Problem rendering paragraphs field - advanced but still not working
I am working on a site with one special page layout (lets call it originally "two columns"), which has basically two columns: The left one showing page contents and the right one an unlimited number of paragraphs.

There is still one problem:

1) The twig tries to show also the paragraphs in the end of left column not following the without-filter. If I show the field title (content type Manage display) it shows the title in the bottom of the left column but no other output is generated of the field\_aside paragraphs

2) I can't get the right column to show anything from the field\_aside, whatever I try.

The crucial code comes here (the best idea what to do so far, tried a multitude of alternatives with zero results)

```
<div class="column is-three-quarters left-aligned main-area"">
    {{ content.body }}
  </div>
  <div class="column is-one-quarter left-aligned aside-area">
    Aside...
    {{ bamboo_render_field('field_aside', 'node') }}
  </div>

```

The page is using a Bulma based theme but I'd reckon it has nothing to do with the problem.

I have Bamboo Twig and Bamboo Twig Loaders enabled.

The field\_aside should render the corresponding paragraph texts. wbr

hank

# Answer
I am sorry, there was just a dumb error in the paragraph template that I used in testing. So, never mind...
> 0 votes

---
Tags: 8, theming
---


# Question
Title: What are my alternatives to disable update notifications but without using module Update Notifications Disable?
I need to disable the update notification overall Drupal 7, rather than downloading the module Update Notifications Disable because it caused a fatal error, and the site went down.

Is there any other way?

# Answer
> 33 votes
The method below will stop the "available update" emails Drupal admins receive.

1. Go here: http://**yourwebsite**.com/admin/reports/updates/settings
2. Remove your email(s) from the textarea: "**E-mail addresses to notify when updates are available**"
3. Save

**Note**: If you want to stop the "available updates" emails and the update alert messaging then simply disable the update module from http://**yourwebsite**.com/admin/modules

# Answer
> 16 votes
You can disable the module Update in the module list, but you will never be aware about update and security updates.

# Answer
> 5 votes
you can do it with drush:

```
drush dis update
```

# Answer
> 3 votes
You can always disable the core Update module. There is, however, no SEO impact for these messages, as the messages are displayed only to administrative users by default, unless you manually and gave anonymous users permission to see the administrative messages, you will be fine.

It would be good if you could stay updated with your drupal version for security reasons, but if you can't for some reason or just don't want to (totally understandable!) just disable the Update module. :)

# Answer
> 2 votes
One way to keep track of updates is to enable the Update module on a development server. With the rate of security update the "There are security updates..." message practically stays up at all times.

# Answer
> 2 votes
Use Update Status Advanced to disable module by module

# Answer
> 1 votes
Use `drush dis update` or, if you not familiar with Drush, go to admin/reports/updates/settings, remove your email(s) from *E-mail addresses to notify when updates are available*, and save.

# Answer
> 0 votes
You might want to consider setting your site to only notify user/1 (or admins) of security updates only.

A quick look at the results of drush vget for one of my sites revealed this interesting variable/value pair:

update\_notification\_threshold: 'security'

So, to only be updated when there are security updates for core, modules and themes consider setting your site's variable for this to the above using drush vset. You can also do this via the UI, if you bother to read it :)

To be clear, the command is:

drush vset update\_notification\_threshold 'security'

I would advise to think carefully about what you are changing and why, and to test any changes in your local, dev, stage and/or test environments prior to pushing to prod, and of course, then testing prod.

# Answer
> 0 votes
If you don't mind modifying the module code (it's not good practice), comment out the line (around 155) `drupal_set_message($status[$type]['description'], 'error', FALSE);`.

These notices should still be logged, so consider adding `watchdog('Security Update', $status[$type]['description'], array(), WATCHDOG_WARNING);`

```
 if (isset($status[$type])
        && isset($status[$type]['reason'])
        && $status[$type]['reason'] === UPDATE_NOT_SECURE) {
     // drupal_set_message($status[$type]['description'], 'error', FALSE);
        watchdog('Update', $status[$type]['description'], array(), WATCHDOG_WARNING, 'http://www.sourceglobalresearch.com/admin/modules/update');
    }

```

# Answer
> 0 votes
If You want to remove alert message for the module update. So Go in .info file and change the Version for the module. In that cases, Some of the module unable to update Like OG group.

---
Tags: 7, updating
---


# Question
Title: How can I programmatically update the settings of a View display?
I can load a ViewExecutable and create a new Display programmatically:

```
$view = Views::getView('existing_view');
$display = $view->newDisplay('page', 'New page', 'page_2');

```

But how can I update the settings for the new display programmatically?

The display is an instance of \Drupal\views\Plugin\views\display\Page but I can't see any way of saving options to it.

The setOption method exists, but how can persist the options to storage?

# Answer
> 4 votes
Answering my own question: The settings are not made on the display, but on the *handler*.

```
$view = Views::getView('existing_view');
$display = $view->newDisplay('page', 'New page', 'page_2');

// ViewExecutable::setHandlerOption($display_id, $type, $id, $option, $value)
$view->setHandlerOption('page_2', 'argument', 'nid', 'admin_label', 'Foo');
$view->save();

```

Options and values correspond to the values in a View YAML config file, under `display_options`.

Important is that you find out the correct `$type` argument.

I had a look at the array keys returned from ViewExecutable::getHandlers.

* "field"
* "argument"
* "sort"
* "filter"
* "relationship"
* "header"
* "footer"
* "empty"

---
Tags: 8, views, configuration
---


# Question
Title: How can I dynamically set the site URL (in Drush9+)?
In Drush 8 I had that neat little reusable line in my `drushrc.php`:

```
$options['l'] = getenv('MY_SITE_URL_VAR');

```

I know that I can hardcode my site URL in a `drush.yml` file, but that does not fit my configuration workflows, where each server knows its URL.

So how can I set the `l` option from an environment variable?

# Answer
> 5 votes
I don't see how you can easily reproduce that (nice) configuration setup since the yaml files are indeed static.

The only solution I see is to write a little wrapper script that always calls drush with the `--uri` option, like:

```
drush --uri $MY_SITE_URL_VAR $@

```

## Recommended solution

A much simpler solution is to use the shell variable `DRUSH_OPTIONS_URI`.

```
export DRUSH_OPTIONS_URI=http://example.com

```

I wasn't able to find any documentation for this, but it seems to work.

---
Tags: drush
---


title: Delete locked fields, programmatically

text:
# Question
Title: Delete locked fields, programmatically
I have upgraded a website to drupal 8 that I found a field created and I need to delete that field as it became useless.

The field is locked, and this prevents me delete it from the interface. I tried to delete it using `field_purge_field()`, but it didn't work either.

The answer for How to properly delete fields, programmatically? didn't work for me.

**Edit**: I tried that piece of code but didn't do any thing

```
$field = \Drupal::entityManager()->getStorage('field_config')->load($entity_type.$bundle_name.$field_machine_name);
field_purge_field($field);

```

How do I delete fields that result locked? How do I unlock them before deleting them?

# Answer
Purging is the second step, after the field was deleted. field.module should do that automatically for you.

A field config is an entity, you delete it like any other entity:

```
$field->delete();

```
> 8 votes

# Answer
Here is this answer, more plainly, tested and working:

```
\Drupal::entityManager()->getStorage('field_config')->load('my_entity_type.my_bundle.my_field_name');

```

But remember, the best way to do this, if you can, is simply to delete the field through the UI and then export your configuration using `drush cex`
> 1 votes

---
Tags: entities, 8
---


# Question
Title: Draggable table: drupal_render, render, both yield an empty string for "#weight" types?
I am attempting to implement a draggable table in a Drupal 7 module. Whenever I invoke either `render()` or `drupal_render` on my element of type `#weight`, an empty string is returned. The table does render and I am able to drag the rows, but cannot see the weights. I cannot figure out what I am doing wrong: I've explored some core Drupal components that follow the same pattern (of invoking `drupal_render` on a `#weight` type element) and nothing is jumping out at me.

My form begins here:

```
$table_header = array_map(t, array('Order', 'Item', 'Manage'));
$form['table'] = array(
    '#theme' => 'mymodule_kw_table',
    '#header' => $table_header,
    '#rows' => $my_rows // array(string)
);

```

`hook_theme()` is implemented as such:

```
function mymodule_theme()
{
    return array(
        'mymodule_kw_table' => array(
            'render element' => 'form',
            'function' => 'mymodule_table'
        )
    );
}

```

Finally, `mymodule_table()` looks like this:

```
function mymodule_table($variables)
{
    $table_data = $variables['form'];
    $table_id = uniqid('tb');

    $rows = $table_data['#rows'];

    for ($i=0; $i < count($rows); ++$i) {
        $weight = array(
            '#type' => 'weight',
            '#title' => t('Order'),
            '#default_value' => $i,
            '#delta' => 1,
            '#attributes' => array('class' => array($table_id . '-weight'))
        );

        $rows[$i] = array(
            'data' => array_map(render, array($weight, $rows[$i], 'abcd placeholder')),
            'class' => array('draggable')
        );
    }

    $table = theme('table', array(
        'header' => array_map(t, array('Order', 'Item', 'Manage')),
        'rows' => $rows,
        'attributes' => array('id' => $table_id)
    ));

    $table .= drupal_render_children($table_data);

    drupal_add_tabledrag($table_id, 'order', 'sibling', $table_id . '-weight');

    return $table;
}

```

# Answer
> 0 votes
Weight objects can be rendered with `form_process_weight()`

```
    $weight = array(
        '#type' => 'weight',
        '#title' => t('Order'),
        '#default_value' => $i,
        '#delta' => 1,
        '#attributes' => array('class' => array($table_id . '-weight'))
    );

    $weight = form_process_weight($weight);

```

---
Tags: theming, hooks
---


# Question
Title: A contributed module without an issue tracker on Drupal.org?
The project page for the RNG - Events and Registrations module doesn't seem to have the typical block (column right) with title "Issues for moduleX" (similar to the block for pretty much any other moduleY on Drupal.org). Not sure if there are other modules for which this block is missing also.

Instead its project page does include some links to other sites (though not for "documentation requests" ...), i.e.:

* Bug reports and feature requests.
* Support requests.

What happened to this module's issue queue on Drupal.org?

# Answer
> 2 votes
It seems that within the **edit** section of any project page (which is available to e.g. the project maintainer), inside the `**Issues**` tab, there is a checkbox with label **`Enable issue tracker`**.

By default, this checkbox is enabled. But if you disable it, the block (column right) with title "Issues for moduleX" is not shown anymore.

And if you re-enable that checkbox again, the block is also shown again ... And the issues that existed before the block is disabled, seem to still exist. So unchecking that checkbox does not delete all existing issues (as it should be I think).

---
Tags: community-official-site
---


# Question
Title: How to hide a published Taxonomy page unless you're an authorized user?
I have a link on my website, I'm currently using Taxonomy Access Control Lite, I have a Taxonomy vocab "Manitoba" and I would like to not let the contents of this page be seen unless the user logged in has the permission role to view it.

How would I go about hiding contents from a page belonging to a taxonomy and all the sub-pages that entail?

# Answer
To get tac\_lite to work covering your question on a vanilla Drupal 7, one has to do the following:

1. Enable at least one tac\_lite permissions scheme for the target vocabulary, in your case, "Manitoba" (scrsht.1)
2. Configure the scheme to allow 'viewing' for authenticated users (scrsht.2)
3. Create a node, e.g. an article and assign a term to it. Authenticated users should be able to see it (scrsht.3), anonymous not (scrsht.4).

Hope that helps!
> 0 votes

---
Tags: 7, views
---


# Question
Title: why cannot I edit admin permissions for the permission page in D8?
All permission boxes for administrators are disabled "greyed out".

I can do it via drush but not through the UI.

# Answer
That's because administrator is an admin role, that means it has all the permissions all the time. Editing it via drush won't do anything.

If you want a role not have all permissions it must not be an admin role, but that means you need to manually add new permissions.
> 1 votes

---
Tags: 8, users
---


# Question
Title: How to add block to a single page that is not included in the allowed content type list?
We have a block (block\_description) that is some text that we want to be displayed on all the content type except the article content type. However, there is a requirement now to display the block on just one of the article content types.

How can this be done with the following settings below on the block?

Current settings (e.g. admin/structure/block/manage/block\_description):

1. Content type: Basic Page (allowed)
2. Other facet: default values
3. Content Types: Not restricted
4. Pages: No restrictions
5. Roles: no restrictions

Goal:

* Add block\_description to just article-1 (a single Article content type page)

# Answer
With Drupal 8 you can have multiple instances of a block. So, the easiest way to have this block show on the article page would be to do the following:

In the structure-\>block layout page, go to the region you already have the block created.

Place a new block and select your description block again.

In the configuration settings, set the page restrictions to use: `/node/<nid>` where is the article you want the block to be displayed. You can use aliases here but the nid is best because this supports alternate languages if you need them.

Note: I assume you already have a block instance set up limited to the other content types. If not, repeat and use the content types restriction to limit it.
> 1 votes

---
Tags: 8, blocks
---


# Question
Title: How do i rewrite path field in views-view-fields.html.twig inside a href tag?
i would like to rewrite the value of my view's path field in views-view-fields.html.twig template. I tried the following and the link is messed up.

```
<a href="{{ fields.path.content }}" alt="">{{ fields.title.content }}</a>

```

my guess is it needs to be written with some type of filter combination and i looked everywhere and can only find examples on how to do this in a node.html.twig file but not in views templates. would somebody kindly advise on how to write this? Many thanks!

# Answer
Probably because `{{ fields.path.content }}` actually is `<div class="something">/your/path</div>` and not just `/your/path`

So try with `<a href="{{ fields.path.content|striptags }}" alt="">`

If the above does not work

Try `<a href="{{ fields.path.content|raw }}" alt="">`

---

Another possibility is that if you have Twig Debug turned on, this will screw up your template. Turning the twig debug off will fix it.
> 2 votes

# Answer
You have to add several filters to the field, like mentioned here: https://www.drupal.org/project/drupal/issues/2672656#comment-12091013

```
<a href="{{ fields.path.content|render|striptags|trim }}" alt="">{{ fields.title.content|render|striptags|trim }}</a>

```
> 0 votes

---
Tags: views, theming, 8
---


# Question
Title: Drupal table name which has the name of person who last modified the node
Which is the name of the table which has the author / and or last modifier of the nodes I can find in the table node\_field\_data ? (drupal 8 )

# Answer
There are two tables to get node user information from:

node\_field\_data has the uid of the creator in it.

node\_revision has the last uid to edit a revision of the node.

Note that if you allow revisions, there can be multiple revisions including ones that have been rolled back. Use the node table's vid to find the current revision.
> 1 votes

---
Tags: 8, database
---


title: Views + Multiple dates

text:
# Question
Title: Views + Multiple dates
I have a view that will display content (nodes) in a fields display having a multiple date field. Another filter is set to date:enddate \> now.

What I want is just one row per node, but cant get it to work.

I've tried the following: a) In the date field's "Multiple field settings" I set "All values in the same row" and "show 1 value(s)" Did not work, no change in output

b) Under "Advanced - Query settings" -\> Use distinct. No changes in output

c) Adding a filter date:delta = 0 This will remove the duplicates, but because of my other filter (date:enddate \> now) the row will also not show up

d) Use the module "Views distinct". The problem here is that this module will filter away nodes that happen to have a date on the same day of another node, so there are others missing.

So I'm stuck here, do you have an idea how to solve this?

Drupal7

Thanks, Marc

# Answer
May be a long shot, but I had luck recently with turning on "Aggregation" for the View, so that similar fields are bundled together, and this solved duplication problems that distinct/the other settings you mentioned have failed to fix:
> 0 votes

# Answer
Solved. As It turned out, "views distinct" does also count filtered (duplicate) results. So if you set "Use pager: Display a specified number of items" this will also count filtered results, and therefore some will be missing.
> 0 votes

---
Tags: 7, views
---


# Question
Title: Include content of subdomain inside a block or view?
I have created a subdomain - example sub.homepage.com. The subdomain is pointing to a server. But I need the template to be the same as my website.

My question: Can I somehow include the content of that subdomain inside a block or view, or something else?

thanks

# Answer
I think I got the answer on this.

I've created a new block, added this:

```
<?php print file_get_contents("http://sub.homepage.com/"); ?>

```

Remember textformat should be PHP.

And it worked. It now shows my subdomain inside my template.
> 0 votes

---
Tags: views, nodes, blocks, subsites
---


# Question
Title: How to use Rules to add custom shipping cost per product?
I use Drupal Commerce on Drupal 7 site, using product displays and products.

Each product has a shipping cost field.

At checkout, the shipping costs of all products in the order need to be collected and shown.

My approach is this: I use the Commerce Flat Rate module which creates the Flat Rate shipping method. I then create a flat rate shipping service ´Custom Shipping Cost´. Then I create a new shipping Rule ´Apply custom shipping costs´ which has a loop that needs to get the field value of the field ´custom shipping cost´ for each product in the order.

Question: how should a rule look like that gets the field values of a product connected to a line item and adds it to the shipping cost.

The following rules (which are nested) are not working. I figured out using Rules logs that in the third rule, Entity has field is not passed. I try to get the product field value which needs to be added to the total shipping rate.

```
0.528 ms Evaluating the action component_rules_get_shipping_price_field_value. [edit]
" Evaluating rule get local shipping price field value. [edit]
0 ms Evaluating rule get local shipping price field value.
0.049 ms Evaluating conditions of rule get local shipping price field value. [edit]
0.11 ms The condition entity_has_field evaluated to FALSE [edit]
0.113 ms AND evaluated to FALSE.
0.123 ms Finished evaluation of rule get local shipping price field value.

```

================================================

```
{ "rules_apply_custom_product_shipping_costs" : {
    "LABEL" : "Apply custom product shipping costs",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "commerce_shipping" ],
    "ON" : { "commerce_shipping_calculate_rate" : [] },
    "DO" : [
      { "drupal_message" : { "message" : "Calculating shipping rates." } },
      { "variable_add" : {
          "USING" : {
            "type" : "commerce_price",
            "value" : { "value" : { "amount" : 0, "currency_code" : "USD" } }
          },
          "PROVIDE" : { "variable_added" : { "custom_shipping_cost" : "Custom shipping cost" } }
        }
      },
      { "component_rules_get_local_shipping_rate" : {
          "price" : [ "custom-shipping-cost" ],
          "line_item" : [ "commerce-line-item" ]
        }
      },
      { "component_rules_get_international_shipping_rate" : {
          "price" : [ "custom-shipping-cost" ],
          "line_item" : [ "commerce-line-item" ]
        }
      }
    ]
  }
}

```

==================

```
{ "rules_get_local_shipping_rate" : {
    "LABEL" : "Set local shipping rate",
    "PLUGIN" : "rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "commerce_line_item" ],
    "USES VARIABLES" : {
      "price" : { "label" : "price", "type" : "commerce_price" },
      "line_item" : { "label" : "line item", "type" : "commerce_line_item" }
    },
    "IF" : [
      { "data_is" : { "data" : [ "line-item:type" ], "value" : "shipping" } },
      { "data_is" : {
          "data" : [ "line-item:commerce-shipping-service" ],
          "value" : "local_shipping_rate"
        }
      }
    ],
    "DO" : [
      { "drupal_message" : { "message" : "Start loop: collect line item local shipping price field values" } },
      { "LOOP" : {
          "USING" : { "list" : [ "line-item:order:commerce-line-items" ] },
          "ITEM" : { "lineitem" : "lineitem" },
          "DO" : [
            { "variable_add" : {
                "USING" : {
                  "type" : "commerce_price",
                  "value" : { "value" : { "amount" : 0, "currency_code" : "USD" } }
                },
                "PROVIDE" : { "variable_added" : { "custom_shipping_cost" : "custom shipping cost" } }
              }
            },
            { "component_rules_get_shipping_price_field_value" : {
                "custom_shipping_cost" : [ "custom_shipping_cost" ],
                "line_item" : [ "line_item" ]
              }
            },
            { "commerce_line_item_unit_price_add" : {
                "commerce_line_item" : [ "line-item" ],
                "amount" : [ "price:amount" ],
                "component_name" : "flat_rate_local_shipping_rate",
                "round_mode" : "1"
              }
            },
            { "drupal_message" : { "message" : "Single product shipping cost is" } },
            { "drupal_message" : { "message" : [ "custom-shipping-cost:amount" ] } }
          ]
        }
      }
    ]
  }
}

```

==============

```
{ "rules_get_shipping_price_field_value" : {
    "LABEL" : "get local shipping price field value",
    "PLUGIN" : "rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "USES VARIABLES" : {
      "custom_shipping_cost" : { "label" : "custom shipping cost", "type" : "commerce_price" },
      "line_item" : { "label" : "line item", "type" : "commerce_line_item" }
    },
    "IF" : [
      { "entity_has_field" : { "entity" : [ "line-item" ], "field" : "commerce_product" } },
      { "entity_has_field" : {
          "entity" : [ "line-item:commerce-product" ],
          "field" : "field_shipping_rate_local_countr"
        }
      }
    ],
    "DO" : [
      { "drupal_message" : { "message" : "line item has field commerce_product" } },
      { "data_set" : {
          "data" : [ "custom-shipping-cost" ],
          "value" : [ "line-item:commerce-product:field-shipping-rate-local-countr" ]
        }
      }
    ]
  }
}

```

=========================== EDIT The following issue was causing my problem: In this whole rules setup i used multiple variables as line items. I mistakenly used a lineitem variable outside the loop, instead of the lineitem variable inside the loop. at a certain point i had lineitem and line-item and mixed them up which made it not work. Also, the product needed to be added as variable in the loop.

# Answer
> 1 votes
Below is an attempt to answer this (most important?) part of your question:

> The following rules (which are nested) are not working. I figured out using Rules logs that in the third rule, Entity has field is not passed. I try to get the product field value which needs to be added to the total shipping rate.

* In your 3rd rule, add another parameter, to also pass the "Commerce Product" that the line item is related to. Say you name that "`product_related_to_item`".
* In your 2nd rule, pass the value of that extra parm (= `product_related_to_item`) to invoke the 3rd rule, using the line item token related to the product (for sure you'll have that in your 2nd rule).
* In your 3rd rule, replace your 2nd "Entity has field" by a similar Rules Condition, but now referring to the (same) field for entity `product_related_to_item` (not sure if you still need your first Rules Condition then, homework for you ...).

By doing these corrections, the typical Rules magic (after you add such Rules Condition) applies again. E.g you can use their values in subsequent Rules Actions. And yes I know/realize, this may look like "*this makes no sense*", or "*you're basically doiing the same thing*". At least that's what I first thought myself just a few days ago when I ran into a similar issue. But sure enough, this was the solution (and it turned out this has to do with some limitation when processing "referenced entities (i.e. product referenced in a line item) in Rules.

# Answer
> 1 votes
The following approach worked, thanks to hints of Pierre Vriens, although my specific use case is a bit complex because it uses two product fields for local and international shipping. I also used extra variables here and there, to make tokens available in system messages..so not all variables are actually required to make this work.

---
Tags: 7, commerce, rules
---


title: How do I solve this error?

text:
# Question
Title: How do I solve this error?
I started facing AJAX issues on my site, due to which I was unable to create views. Googling, I found that updating the Views module might help. I added a new Views module under all/sites/modules/custom (not touching the old module at all). Now my entire site is gone and I am getting the following error:

> The website encountered an unexpected error. Please try again later.

I am not even able to login. What should I do?

I deleted the new Views module, in vain.

# Answer
> 0 votes
After you've deleted that views module in the custom folder. Go into your database and empty any table that starts with "cache\_" that will clear Drupal's cache and hopefully it will rediscover there is now only the original views module

# Answer
> -1 votes
If you have any database backup then restore it and refresh the page. Also you can use drush commands to view the error log.

---
Tags: views
---


# Question
Title: Image styles are not created 404 Not Found
I'm running on Nginx. All permissions are set to `777` and owner is `www-data:www-data`.

1. Create/edit a node with image\_field, upload an image.
2. Original image is uploaded and stored at `sites/default/files/image.jpg`
3. Preview works, etc. Save node, no image shown (style Large or any custom).
4. Error `404 Not Found` e.g. URL `https://test.example.com/sites/default/files/styles/product/public/image-hd-wallpapers-3_0.jpg?itok=1E64uuXF`
5. The `styles` subfolders are created like e.g. `product/public` even the `sample.png` file is created inside `sites/default/files/styles/product/public/modules/image/`
6. But no image style is created when uploading image to a node and saving.

I followed and tried everyting done in this image style (imagecache) images are not being created and this Aplying image styles to images return 404 for images

I have this in my nginx conf:

```
location ~ ^/sites/.*/files/styles/ { # For Drupal >= 7
    try_files $uri @rewrite;
}

```

Permissions: htdocs/sites/default/files # ls -al

```
drwxr-xr-x 10 www-data www-data   4096 Feb 13 13:01 .
drwxr-xr-x  3 root     root       4096 Nov 17 12:58 ..
drwxr-xr-x  3 www-data www-data   4096 Nov 25 18:57 bootstrap
drwxr-xr-x  2 www-data www-data   4096 Feb  8 13:01 ctools
drwxr-xr-x  2 www-data www-data   4096 Nov 19 23:17 fonts
-r--r--r--  1 www-data www-data    476 Nov 17 13:00 .htaccess
-rw-rw-r--  1 www-data www-data 243154 Feb 13 12:40 image-hd-wallpapers-3_0.jpg
-rw-rw-r--  1 www-data www-data 243154 Feb 13 12:49 image-hd-wallpapers-3_1.jpg
-rw-rw-r--  1 www-data www-data 243154 Feb 13 13:01 image-hd-wallpapers-3_2.jpg
-rw-rw-r--  1 www-data www-data 243154 Feb 13 12:37 image-hd-wallpapers-3.jpg
drwxrwxr-x  2 www-data www-data   4096 Feb  8 21:22 js_injector
drwxrwxr-x  2 www-data www-data   4096 Jan 25 00:35 mailsystem
drwxrwxr-x  2 www-data www-data   4096 Nov 17 13:02 pictures
drwxrwxr-x  4 www-data www-data   4096 Feb 13 12:41 styles
drwxrwxr-x  3 www-data www-data   4096 Dec 29 13:00 videos

```

/styles/ incl. subfolders.

```
drwxrwxr-x  4 www-data www-data 4096 Feb 13 12:41 .
drwxr-xr-x 10 www-data www-data 4096 Feb 13 13:01 ..
drwxr-xr-x  3 www-data www-data 4096 Feb 13 12:41 large
drwxr-xr-x  3 www-data www-data 4096 Feb 13 12:41 product

```

I tracked down the issue causing it, but still need to figure out why it is causing it, because we need that setting to keep our images and other files optimized with correct headers, etc.

The issue is this snipped in the domain's nginx config:

```
location ~* \.(?:css|js|ico|gif|jpeg|jpg|png|woff|ttf|otf|svg|woff2|eot)$ {
    expires 1w;
    #add_header Pragma public;
    #add_header Cache-Control "public";
    add_header ETag "";
    add_header Cache-Control "max-age=2628000, no-transform, public";
}

```

Removing it, solves the problem, but we need to keep it.

# Answer
> 1 votes
The solution is to add `try_files $uri $uri/ @rewrite;` at the bottom right after `add_header`, final snippet with more edits:

```
location ~* /sites/default/files/.*\.(?:css|js|ico|gif|jpeg|jpg|png|woff|ttf|otf|svg|woff2|eot)$ {
    expires 1w;
    add_header ETag "";
    add_header Cache-Control "max-age=2628000, no-transform, public";
    try_files $uri $uri/ @rewrite;
}

```

This solves the issue, we use this snipped with AdvAgg module.

---
Tags: 7, media
---


# Question
Title: Concatenating user submission fields or components in webform Drupal 7
using Drupal 7 webform module. The module is set to email out results. The problem is that the form submissions are going via email into Zendesk, which ideally would be able to parse out first/last name from the sender.

The problem is that the email from name is set to use the component first name from the form.

The help text below the selector says "Any textfield, select, or hidden form element may be selected as the sender's name for e-mails." Is there a way to concatenate the first and last name fields from the form into the from name field?

the form was previously set (before I started working on it) with 'Value of First Name' in the "cusstom" from field. That wasn't working. Would \[submission: first\_name\] \[submission: last\_name\] or a similar token work?

# Answer
If you'd be willing to also use the Rules module for actually sending such eMails (together with Webform Rules), you'd have all sorts of flexibility about how you want those eMails to look like.

As an example, consider this custom rule for sending an eMail (in Rules export format):

```
{ "rules_process_submitted_webform" : {
    "LABEL" : "Process submitted webform",
    "PLUGIN" : "reaction rule",
    "ACTIVE" : false,
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "webform_rules" ],
    "ON" : { "webform_rules_submit" : [] },
    "DO" : [
      { "mail" : {
          "to" : "[site:mail]",
          "subject" : "A new webform submission has occured",
          "message" : "A new webform submission has occured (with form-id \u0022[form-id:value]\u0022). It was submitted by the user with id = [user:id], name = [user:name] and eMail Id = [user:mail] ...",
          "language" : [ "" ]
        }
      }
    ]
  }
}

```

I intentionally did not include any Rules Conditions here, just to illustrate that by using such basic rule, you do have access to a limited set of tokens related to the user who submitted the webform, such as `[user:id]`, `[user:name]` and `[user:mail]`. In other words, you don't need a Rules Action like "*fetch entity by ID*" for these kinds of tokens to be available.

But wait, there is more ... You can also include any of the "Webform data" in such eMails. To do so, you could use a technique similar to what is described in my answer to "How to do a data comparison to submitted webform data when using the Rules module?". For short:

* Add an extra Rules Action to `Add a variable`, with a value assigned to it equal to your Webform data you want to use (and with an appropriate data type). You'd need 1 such variable for each Webform component for which you want to access its Webform data.
* In your subsequent Rules Actions (e.g. in which you create an eMail) you can refer to the value of these variables you just added (that's the clue!).
> 1 votes

---
Tags: webforms, tokens
---


# Question
Title: I need to display a different link for anonymous users and register users for same content
I have a webform containing a link. I want to change the link depending on the users accessing the webform.
For anonymous users, the link should point to user/register?destination=\[current page\]; for authenticated users, the link should point to form/event-registration.

# Answer
In `build > elements` you will need to create 2 `html markup` or `Advanced HTML/Text` elements

Each one will have the links mentioned

There is a setting `access` that you can choose who has access to it

For the other link you can choose **anonymous**

For one of the elements you will choose **authenticated**

If this solution is not satisfactory 100% you will need to override webform
> 0 votes

---
Tags: navigation
---


# Question
Title: In Commerce 2, how can I load an order item's 'purchased entity' object given its ID?
I have need to load an order item's 'purchased entity' object so that I can object the base product's title for an order item.

In my scope, I have the order\_item object and, from there I have access to the 'purchased entity' **ID** number. But I can figure out how to load the 'purchased entity'object from this ID number.

EDIT:

Thanks to Chance G I was able to achieve what I needed by:

```
  $product_variation = $order_item->getPurchasedEntity();
  $product_id = $product_variation->product_id->getString();
  $product = \Drupal\commerce_product\Entity\Product::load($product_id);
  $product_title = $product->getTitle();

```

# Answer
If your $order\_item is an instance of the OrderItem class you should be able to do:

```
$product_variation = $order_item->getPurchasedEntity();
$title = $product_variation->getTitle();

```

If you have an $order you should be able to do:

```
foreach ($order->getItems() as $order_item) {
  $product_variation = $order_item->getPurchasedEntity();
  $title = $product_variation->getTitle();
}

```
> 5 votes

---
Tags: commerce
---


# Question
Title: How to access the full html of a drupal basic page?
This is probably a dumb question. But I have not been able to find the full html of a basic page. When I create a basic page, I can put a title and texts/images in the body. How can I access the `<head>...</head>` portion of a specific basic page so that I can edit that part and put a js script? or better yet the full html of the page?

Thanks!

# Answer
You will need to edit your themes tpl files to make changes to those areas. If you are adding a js file you can add it in your themes template.php file. I would recommend you read through this link for

Drupal 7:

https://www.drupal.org/docs/7/theming

Drupal 8:

https://www.drupal.org/docs/8/theming
> 0 votes

---
Tags: theming
---


# Question
Title: Mathjax module does not render on edit ckeditor
I have installed mathjax module and ckeditor module, but when I try to insert math code using math button on ckeditor, the math codes does not rendered correctely, math code become hidden. Math code rendered successly after content is submited.

is there anyone can help me to fix?

## here my screenshot

# Answer
Assuming you are using D7, it seems like the solution is in this MathJax issue. Requires some patching / adding plug-ins to ckeditor.
> 0 votes

# Answer
Just copy the mathjax CDN url from the config/content authoring/mathjax, and paste it in CKEditor-full html-advanced options-custom Javascript configuration, then it works! Note the pasted format should be “config.mathJaxLib=url”.
> 0 votes

---
Tags: wysiwyg
---


# Question
Title: Date popup form field doesn't show the default value correctly
I am creating a custom form with "date\_popup" form fields.
The only issue I have is that the default\_value for the date popup form field shows only the first digit of the year, not the whole date.

Can anyone help with this?

# Answer
Clive was absolutely right: The default value MUST be set using the date format "Y-m-d", such as with `date('Y-m-d', $date)`.

The difference is that I used "Y-M-d" instead of "Y-m-d" for #default\_value.
> 10 votes

# Answer
For Drupal 8:

```
use Drupal\Core\Datetime\DrupalDateTime;

$form['mydatefield']['widget'][0]['value']['#default_value'] = DrupalDateTime::createFromTimestamp(strtotime($mydatestring));

```
> 1 votes

---
Tags: 7, forms
---


# Question
Title: Change max length of signature field to more than 255 characters
How can I change the max length of the drupal 7 signature field to more than 255 characters? I've already changed the sql data type from 255 to varchar(900), yet drupal still shows the error, as soon as a user wants to update his signature to more than 255 characters.

# Answer
In a mysql database varchar can only store 255 characters.
> 0 votes

# Answer
I know this isn't the case but you can look around the module(code) and do this but you are on your own ,, because its dangerous

enter link description here

> This module allows you to change (uneditable) settings for fields.
>
> READ WITH CAUTION: Please don't use this module unless you know what the hell is this module does which I'm NOT sure about 100% ,, so I'd recommend using it in stage/dev/local environment until you are sure about it
> 0 votes

---
Tags: 7, users, database
---


# Question
Title: l() Link function adding Icon before Link Text
Is there a way to pass in an icon inside the tag of the link built by using the link (*l()*) function?

```
<a href="#"><icon> Link Text</a>

```

I use it like so currently:

```
l('text','path',options)

```

Options all seem to be attributes of the tag itself besides the "text". Using html =\>true, I can add before the link text:

```
print l('<span class="' . implode(" ",$link[options][attributes]["class"]) . '"></span> ' . $link["link_title"]

```

However, I cannot check if the span isset inline there, unless I am missing something...

This works (below), but all my `<a> have <a><span></span> linktext...` even if span is empty, and I don't want that blank tag in there:

```
<li class="nav-item"><?php print l('<span class="' . implode(" ",$link[options][attributes]["class"]) . '"></span> ' . $link["link_title"],$link["link_path"],array('attributes'=> array('class'=>array($link[options][item_attributes]["class"], 'nav-link')),'html' => TRUE)); ?></li>

```

How can I add an icon, without CSS, before my link text as well as check if that span is empty?

# Answer
> 0 votes
you can use something like this:

```
l(t('Back'), 'node/' . implode(" ",$link[options][attributes]["class"]) . '/edit/', array('attributes' => array('class' => array('btn btn-default btn-back'))))

```

---
Tags: 7, theming, navigation
---


# Question
Title: How do I know from which page the users are coming?
I'm looking for a way to determine where the users are coming from to build the breadcrumb for a page.

Is there something I can do with `hook_breadcrumb_alter(&$active_trail, $item)`, or should I use the Flag module or any activity tracker module?

# Answer
If you have control over the Urls linking to your target page, append a page-specific parameter. Suppose the page you are linking to is `http://www.example.com/target-page`:

* On the first referring page, make this Url: `http://www.example.com/target-page?referer=page-1`
* On the second referring page, make this Url: `http://www.example.com/target-page?referer=page-2`

Then in your `hook_menu_breadcrumb_alter` function, the referer will be available in the `$_GET` variable, and you will be able to do something like this in the `template.php` file for your theme:

```
function mytheme_breadcrumb(&$variables) {

  if (request_uri() == '/target-page') {
    switch($_GET['referer']) {
      case 'page-1':
        $variables['breadcrumb'][] = l('First referring page', '/page-1');
        break;
      case 'page-2':
        $variables['breadcrumb'][] = l('Second referring page', '/page-2');
        break;
    }
  }
}

```

If you don't want to add parameters to the Url, and are not using HTTPS, you could use the approach above except with `$_SERVER['HTTP_REFERER']` in the `switch` statement. Or alternatively, you could set a cookie on the referring pages and read it on the target page.

The example above is probably the easiest way to manipulate breadcrumbs but strictly speaking, there should not be business logic in a theme function. See these questions for more detailed info on how to manipulate breadcrumbs:
> 2 votes

---
Tags: breadcrumbs
---


title: Detecting jQuery UI version in module

text:
# Question
Title: Detecting jQuery UI version in module
I am developing a module in Drupal 7.56 that is going to rely on jQuery UI 1.12.1. I want my module to check to see if that version is installed on the site, if it is not I am going to use drupal\_add\_js() to add the correct version. I don't want to just add the js file if it already exists in the system.

I do not have access to the site the module is going to be installed on. I want this module to be used on many different sites and don't want the module to add the js if it is already there.

What is the best way to do this?

# Answer
> 1 votes
If you call `drupal_add_js()` without parameters it will return an array of all the JavaScript already installed. You can iterate over the elements to look for the jQuery UI version you need. For example

```
  $installed_js = drupal_add_js();
  foreach ($installed_js as $file => $details) {
    if (preg_match('/jquery\.ui/', $file)) {
      $version = $details['version'];
      break;
    }
  }
  list($major, $minor, $update) = explode('.', $version);
  if ($major != '1' && $minor != '12' && $update != '1') {
    // Add drupal_add_js call here
  }

```

You might need a more robust regex to check for a wider variety of possible filenames but the above code should work in principle. I should also point out, it's not totally robust - if for some bizarre reason the file was named `blah.js,` this approach would not find it, so your module's jQuery code should also check to make sure the right version is loaded.

---
Tags: 7, javascript
---


# Question
Title: How can I list all of the pages that display a certain view?
In Drupal 7, is there a way either programmatically or through the UI to generate a list of all of the pages that display a particular view?

# Answer
> 1 votes
There is no way to do this through the UI and even to do it programmatically would be a tall order. Views can contain page, block, panel pane, and other types of display. Those displays can be embedded in pages via blocks, panels, or custom code.

If you have a specific view display in mind, e.g. a block, it would narrow the scope of the task, but the task would still be very difficult.

---
Tags: 7, views
---


# Question
Title: "Codebase is assembled with Composer instead of Drush" (but it wasn't!) message
I'm using D7 and I'm seeing the following error message any time I try to use Drush to install a module:

> This codebase is assembled with Composer instead of Drush. Use `composer update` and `composer require` instead of `drush pm-updatecode` and `drush pm-download`. You may override this error by using the --pm-force option.

Why does Drush generate that error message? The website was not built using Composer (though there are other Composer-based Drupal project on the same web server).

FWIW, using the `--pm-force` option works just fine. I would just understand the reason of that error message.

# Answer
It comes from a command file like policy.drush.inc.
> 2 votes

---
Tags: 7, drush
---


# Question
Title: I need get the MID for specific Entity Drupal 8
I am using the message module, so I have an entity of type 'message', as for the children I can get the machine name or the Uuid.

The problem I have is that by means of a 'hook\_update\_n' I need to update a field. The code I am using is:

```
function hook_update_8001() {

  //Change content in text field for 'caregiver_referral_incomplete'.
  $field_value = array(array('value' => 'Hello My formatted text', 'format' => 'basic_html'));

  entity_load('message', 2166)->getTemplate()->set('text', $field_value)->save();
}

```

With this structure, I need the Mid, but I only have the machine name or the Uuid, some way to find it with that data?

# Answer
> 1 votes
If you want to load by uuid, you can use this:

```
\Drupal::service('entity.repository')->loadEntityByUuid($entity_type_id, $uuid);

```

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