title: Get the language from route

text:
# Question
Title: Get the language from route
Is there a way to get the language from a routeMatch in Drupal 8?

E.g. if I do:

`$route_match = \Drupal::routeMatch();`

Currently I can't find any language information in the returned object. It looks like as if all language information has been stripped out, and the route object know's nothing about the language it is in.

I've looked into using the language manager, but can't find a way to combine this with the routeMatch class.

Scenario: I'm writing my own AccessInterface class, and want to hide entities from certain languages. I need the information of the language for the route (and **not** the site's current language).

# Answer
> 1 votes
I actually had the same problem with a Drupal 8 site.

I know this is unlikely to sound like a problem, but I can think of at least one situation (the situation I am in!) where it is.

We have the CMS setup so that the admin interface is in the users preferred langauge (a request by the client) so they can copy-paste translated content in whilst keeping the admin interface in a language they can understand.

However this creates confusion, as `\Drupal::languageManager()->getCurrentLanguage()` returns the langauge the admin system is using, not the lanuage the content is in.

The easiest way I found around this was to do the following:

`$node = \Drupal::routeMatch()->getParameter('node');
$currentLanguage = $node->langcode->value;`

(if anyone is curious as to why `$node->langcode->value` works, this question has some good answers: How to get the property of a content object in Drupal 8)

This literally gets the current node you've viewing, and then the language the node is displaying in.

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


# Question
Title: How can I set frequency of each content type with the XML sitemap module?
I use the XML sitemap module (7.x-2.0-beta3) to generate the XML sitemap for my site. The problem is that I cannot set the change frequency of the content types.

In "admin/config/search/xmlsitemap/settings" I have a "Change frequency" combobox, but this is only for the front page.
I have some other content types and taxonomy tags. How can I change the frequency for them?

# Answer
> 1 votes
As far as I can see, the priority form field is added to the content type form from `xmlsitemap_add_link_bundle_settings()`, which is called by `xmlsitemap_node_form_node_type_form_alter()`.

The first function, in the development snapshot, is using the following form field definitions.

```
  $form['xmlsitemap']['status'] = array(
    '#type' => 'select',
    '#title' => t('Inclusion'),
    '#options' => xmlsitemap_get_status_options(),
    '#default_value' => $bundle_info['status'],
  );

  $form['xmlsitemap']['priority'] = array(
    '#type' => 'select',
    '#title' => t('Default priority'),
    '#options' => xmlsitemap_get_priority_options(),
    '#default_value' => $bundle_info['priority'],
    '#states' => array(
      'invisible' => array(
        'select[name="xmlsitemap[status]"]' => array('value' => '0'),
      ),
    ),
  );

```

The form field for the priority is invisible when the "status" field is set to 0.

# Answer
> 0 votes
I was also having trouble with "yearly" and "never" coming up unexpectedly under the `<changefreq>` tag. This is a separate setting from `<priority>` \- it's a different XML tag and they don't seem to be related based on what you choose for priority.

I wish I found a better solution that did actually allow you to control this setting in the UI per content type. But since this does not seem to exist, I simply disabled `changefreq` completely:

* Go to /admin/config/search/xmlsitemap/settings
* expand Advanced Settings
* uncheck Change frequency

Probably better to allow google to determine for itself how frequently to index in most cases. And if you need more control over crawling to try and control it using Webmaster Tools instead of the changefreq tag.

---
Tags: 7, xml-sitemap
---


# Question
Title: Enable/ disable „Display author and date information“ per node?
It is passible to enable or disable the „Display author and date information“ for each node depending on the content of a field?

The base:

* Drupal 8.3.0 (rc2)
* field „Where to publish“

---

* Case 1: field „Where to publish“ = „public“
* Case 2: field „Where to publish“ = „internally“

-\> in Case 1: disable „Display author and date information“

-\> in Case 2: enable „Display author and date information“

How can this be realized? Is that possible? Or should I use two different content types?

---

First part runs:

```
function kanu_preprocess_node(&$variables) {
if ($variables['node']->getType() != 'test') {
    return;
  }
$field = $variables['node']->field_where_to_publish;
}

```

Completed it returns an unexpected error:

```
function kanu_preprocess_node(&$variables) {
  if ($variables['node']->getType() != 'test') {
      return;
  }
  $field = $variables['node']->field_where_to_publish;

  if (!field->isEmpty() && $field->entity->label() == 'public') {
     $variables['display_submitted'] = FALSE;
  }
}

```

# Answer
You can override the variable `display_submitted` in a preprocess hook:

**mytheme.theme:**

```
function mytheme_preprocess_node(&$variables) {

  // check if this is the right content type where the field exists
  if ($variables['node']->getType() != 'article') {
    return;
  }

  // plain field
  if ($variables['node']->field_where_to_publish->value == 'public') {
    $variables['display_submitted'] = FALSE;
  }

  // taxonomy field
  $field = $variables['node']->field_where_to_publish;
  if (!$field->isEmpty() && $field->entity->label() == 'public') {
    $variables['display_submitted'] = FALSE;
  }

}

```
> 3 votes

---
Tags: 8, nodes
---


# Question
Title: Reset password via Services by email, and not by uid
I'm trying to POST an email address to the password\_reset Services endpoint so that it generates and sends a password reset email for a user. When I post the uid to the endpoint, it does this successfully. That said, I want to post the user's email to the endpoint (e.g. they type in their email to retrieve their password recovery email). How can I change the below in order to allow this? I tried changing user\_load($uid) to user\_load\_by\_mail($uid), but this didn't work.

**Endpoint format:**

> mydomain.com/myendpoint/user/emailhere@go.com/password\_reset\_email

**user\_resource.inc**

```
  $definition = array(
  'user' => array(
  'operations' => array(
  'actions' => array(
    'help' => 'Send forgot password email',
    'callback' => '_user_resource_password_reset_email',
    'access callback' => 'services_access_menu',
    'args' => array(
      array(
        'name' => 'email',
        'optional' => FALSE,
          'source' => array('data' => 'email'),
        'type' => 'string',
        'description' => 'The email address of the user whose password should be reset.',
      ),
      ),
    ),
    ),
    ),
  ),

       function _user_resource_password_reset_email($data) {
  global $language;

  $mail = _services_arg_value($data, 'data');
  $account = user_load_by_mail($mail);

  if (empty($account)) {
    return services_error(t('There is no user with email @email.', array('@email' => $mail)), 404);
  }

  // Mail one time login URL and instructions using current language.
  $mail = _user_mail_notify('password_reset_email', $account, $language);
  if (!empty($mail)) {
    watchdog('user', 'Password reset instructions mailed to %name at %email.', array('%name' => $account->name, '%email' => $account->mail));
  }
  else {
    watchdog('user', 'There was an error re-sending password reset instructions mailed to %name at %email', array('%name' => $account->name, '%email' => $account->mail));
}

  $result = "success";
  return $result;
}

```

Obj-C

**ViewController.m**

```
- (IBAction)sendButton:(id)sender {

[DIOSUser userSendPasswordRecoveryEmailWithEmailAddress:self.forgotField.text
                                                            success:^(AFHTTPRequestOperation *operation, id responseObject) {

                                                                NSLog(@"Password being sent!");

                                                                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Retrieving Password"
                                                                                message:@"We're helping you retrieve your password! Please check your email in a few minutes for a rescue link."
                                                                                delegate:self
                                                                                cancelButtonTitle:@"OK"
                                                                                otherButtonTitles:nil];
    [alert show];

      }failure:^( AFHTTPRequestOperation *operation , NSError *error ){

      if(!error){

     }
      }];

        }

```

**DIOSUser.m**

```
 + (void)userSendPasswordRecoveryEmailWithEmailAddress: (NSString*)email
                                              success:(void (^)(AFHTTPRequestOperation *operation, id responseObject)) success
                                              failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error)) failure {

   NSString *path = [NSString stringWithFormat:@"user/%@/request_new_password", email];

    [[DIOSSession sharedSession] sendRequestWithPath:path method:@"POST" params:nil success:success failure:failure];
}

```

# Answer
It would be better if this was externalised into a custom module instead of 'hacking' the services module.

This is fine on my system

```
$definition = array(
  'user' => array(
    'operations' => array(
       ...
       'actions' => array(
          ...
         'password_reset_email' => array(
         'access callback' => 'services_access_menu',
         'callback' => '_user_resource_password_reset_email',
         'args' => array(
          array(
                'name' => 'email',
                'optional' => FALSE,
                'source' => array('data' => 'email'),
                'type' => 'string',
                'description' => 'The email of the user whose password to reset.',
        ),
    ),

```

Function is

```
function _user_resource_password_reset_email($data) {
  global $language;

  $mail = _services_arg_value($data, 'data');
  $account = user_load_by_mail($mail);

  if (empty($account)) {
    return services_error(t('There is no user with email @email.', array('@email' => $mail)), 404);
  }

  // Mail one time login URL and instructions using current language.
  $mail = _user_mail_notify('password_reset', $account, $language);
  if (!empty($mail)) {
    watchdog('user', 'Password reset instructions mailed to %name at %email.', array('%name' => $account->name, '%email' => $account->mail));
  }
  else {
    watchdog('user', 'There was an error re-sending password reset instructions mailed to %name at %email', array('%name' => $account->name, '%email' => $account->mail));
}

  $result = "success";
  return $result;
}

```
> 1 votes

# Answer
I Think this is existing in the services module, As per the below question and provided answer, you only need to send to the correct resource "?q=rest/user/request\_new\_password.json"

Below answer is copied

> This feature was added with the resolution of this issue:
>
> https://www.drupal.org/node/1303400 To use this resource, make a POST to:
>
> ?q=rest/user/request\_new\_password.json ...and send along a name
>
> name=john ...or e-mail address:
>
> name=john@example.com

You can see the original question and answer here:

Requesting a new password via services

I tested it with HTTPRequester Plugin with below JSON sample and it worked by posting to **q=rest-mobile/user/request\_new\_password**

But do not forget to activate this resource as in below screen shot

And this is a shot of how it is sent as JSON request

{"name":"user1"} or {"name":"user1@example.com"}
> 1 votes

# Answer
**Drupal 7**

Since you have tagged **7** I presume you are working on **Drupal 7**. I remember having done something like this last year. If you are using hook\_services\_request\_preprocess\_alter() to alter the incoming parameters for your password reset request. You can use the hook to implement the following logic:

* Check if it is a password reset request;
* If it is a password reset request, then see if an email address has been passed as an argument. You can do this by checking if the argument is a number or if it is a string resembling an email with an `@` sign, etc.
* If the argument is an email, then read the relevant user ID from the database and replace the argument with the user ID.

This should be a clean solution. I had done it this way for a project last year. Unfortunately, I do not have the code. Hope this algo helps.
> 0 votes

---
Tags: 7
---


# Question
Title: hook_commerce_checkout_complete is never called
I need to send out a PDF via mail upon order completion, and according to DrupalContrib, I can use `hook_commerce_checkout($order)` to achieve this.

this is my module code:

```
<?php

function pdf_checkout_commerce_checkout_complete($order) {
  // No example.
  \Drupal::logger('pdf_checkout')->info('Hook called.');
}

```

My problem is, that it is never called, I've tried everything from just sending a log message when it is used, to creating a new, clean, module just to test it.
None of it has worked.

Is the hook still being used in Commerce 2.x? If not, what should I look at instead to achieve a similar effect?

Thanks in advance.

# Answer
> Is the hook still being used in Commerce 2.x?

No.

> If not, what should I look at instead to achieve a similar effect?

Commerce 8.x-2.x depends on the state\_machine module which has events that are triggered when an order is placed (=checkout complete) as well as other state changes.

See Assigning (adding) an entity reference when an Order process is completed
> 3 votes

---
Tags: 8, commerce, hooks
---


# Question
Title: Include custom Product Fields in an email
I have added a new "Courses" Product Type that has a field called "Course Link". The store admin can add a url to this field and we want to email the value to the customer after they purchase.

I have a Rule to fire on "Completing the checkout process" with action "Send HTML e-mail" and the email includes the token \[commerce-order:commerce\_line\_items\] This is all working except my "Course Link" field is not included in the email. I do not have a token for "Course Link" field listed to include in the email.

I do have the "Course Link" field included under "Product Types \> Courses \> Manage Display \> Line Item". Not sure what that even does.

My question is what should I be looking at to do this.

1. Try to bring it into scope in my current emailing Rule? Possibly through a Component that loops through line items and provides a value back?
2. Add it in the View that drives the \[commerce-order:commerce\_line\_items\] token?
3. A module like Commerce Messages or Commerce Invoice Receipt?
4. Some other approach?

# Answer
The solution here (Drupal Commerce - Add Product Fields to Cart Form through Line Items) for adding Product Fields to the Cart View answered my question.

I edited the "Line Item" View to include my custom Product Field. This is the View that drives the \[commerce-order:commerce\_line\_items\] token but per the answer linked above:

*For that you'll need to add I believe the "Commerce Line Item: Referenced Products" relationship in the view.*

You also need to give anonymous users the Permission "View own orders of any type" (I also gave them "View own Order Orders" but probably not needed) or the email says "No Line Items Found" for anonymous checkouts.
> 0 votes

---
Tags: commerce
---


# Question
Title: How can I query and order nodes with multiple date field values within a specific range?
I'm trying to get nodes that have date fields (multiple instances in some cases) and display them sorted ascending by start time for a given date. For illustrative purposes, here are some events and their date field values (start time).

**Event A**

* 4/2/17 8:00AM
* 4/3/17 2:00PM

**Event B**

* 4/3/17 11:00AM
* 4/3/17 5:00PM

**Event C**

* 4/3/17 6:00PM

**Event D**

* 4/4/17 4:00AM

I'm using EntityFieldQuery to gather the events with dates on 4/3/17 and order them using this code;

```
$query
->entityCondition('entity_type', 'node')
->entityCondition('bundle', 'event')
->propertyCondition('status', 1)
->fieldCondition('field_datetime', 'value', array('2017-04-03/T00:00:00', '2017-04-04/T00:00:00'), 'BETWEEN')
->fieldOrderBy('field_datetime', 'value', 'ASC');

```

I get the nodes ordered like this;

A, B, C

but I want them ordered like this;

B, A, C

I guess the fieldOrderBy method is looking at all the date field values and ordering that way, which includes dates other than my target (4/3/17).

Anyone know how to accomplish this (with EntityFieldQuery or without)?

# Answer
Are the date/time values stored as a varchar in your database? If I'm not mistaken, in that case the ordering is performed by comparing the String values (which is inline with the outcome of your example, i.e., A:2, B:5, C:6).

You could alter your query, using hook\_query\_alter(), and cast/convert the datatype to datetime (not sure whether every database supports this).

The easiest solution would be to sort the query result afterwards, using the usort() function and in your comparison function you can use PHP's DateTime object or the strtotime() to compare the values.
> 0 votes

---
Tags: 7, entities, database
---


# Question
Title: How to add an HTML comment to the head of every page?
I'm looking to add a copyright message to every page of my website using Drupal 7. The easiest way to do this would be to add it into the header, since that appears everywhere. I know that changes can be made to html.tpl.php.

But I'm unfamiliar (for now) with php, and need to know if I need to add any special commands to the php or can I just inject my comment into the file?

# Answer
You're better off using a more Drupal-centric solution. If you're looking to place some static copyright info, you can create a block of HTML and place it in a footer region of your site's theme (under the block administration area).

If you're just looking to play around with the Drupal CMS & PHP coding in general (off topic for Drupal Answers), as long as you make your changes outside of the `<?php ?>` tags you should be fine to make changes to your template file.
> 0 votes

# Answer
So over a year later, there's two paths to do this:

If the (c) needs to appear publicly create a block with the copyright information and then add the block to a region on your page. In my case it was added to the footer.

If you're looking to add it to the source code (and therefore not publicly listed) add it to html.tpl.php down toward the bottom but above the `</body>` tag. Using a standard HTML comment (i.e., `<!--- Copyright (c) 2017, Ad Nauseam corp. --->` ) no php commands needed. (Note: this probably isn't the most Drupalific way of doing this.)
> 0 votes

---
Tags: 7
---


# Question
Title: 8 - SQL error "String data, right truncated..." when creating/updating a node programmatically, but OK when inserting via the CLI. Why?
When I attempt to programmatically update an event node, I get the error: `SQLSTATE[22001]: String data, right truncated: 1406 Data too long for column 'field_event_end_date_and_time_value'...`

For most date fields. If I insert the record(s) with the same information into MySQL directly via the CLI, it updates/inserts correctly. Anyone have any idea what's going wrong here?

**Full error from logs:**

> Drupal\Core\Entity\EntityStorageException: SQLSTATE\[22001\]: String data, right truncated: 1406 Data too long for column 'field\_event\_end\_date\_and\_time\_value' at row 1: INSERT INTO {node\__field\_event\_end\_date\_and\_time} (entity\_id, revision\_id, bundle, delta, langcode, field\_event\_end\_date\_and\_time\_value) VALUES (:db\_insert\_placeholder\_0, :db\_insert\_placeholder\_1, :db\_insert\_placeholder\_2, :db\_insert\_placeholder\_3, :db\_insert\_placeholder\_4, :db\_insert\_placeholder\_5); Array ( \[:db\_insert\_placeholder\_0\] =\> 7159 \[:db\_insert\_placeholder\_1\] =\> 7750 \[:db\_insert\_placeholder\_2\] =\> events \[:db\_insert\_placeholder\_3\] =\> 0 \[:db\_insert\_placeholder\_4\] =\> en \[:db\_insert\_placeholder\_5\] =\> 2014-06-18CDT21:30:00 ) in Drupal\Core\Entity\Sql\SqlContentEntityStorage-\>save() (line 770 of /var/www/acg/html/core/lib/Drupal/Core/Entity/Sql/SqlContentEntityStorage.php).

**My queries:**

```
UPDATE node__field_event_end_date_and_time SET field_event_end_date_and_time_value = '2014-06-18CDT21:30:00' WHERE delta = 0 AND langcode = 'en' AND entity_i
d = 7159 AND deleted = 0;

```

and

```
INSERT INTO node__field_event_end_date_and_time (entity_id, revision_id, bundle, delta, langcode, field_event_end_date_and_time_value) VALUES(7159, 7750, '
events', 0, 'en', '2014-06-18CDT21:30:00');

```

work correctly through the CLI.

**Output of `show columns FROM node__field_event_end_date_and_time`**

```
+-------------------------------------+------------------+------+-----+---------+-------+
| Field                               | Type             | Null | Key | Default | Extra |
+-------------------------------------+------------------+------+-----+---------+-------+
| bundle                              | varchar(128)     | NO   | MUL |         |       |
| deleted                             | tinyint(4)       | NO   | PRI | 0       |       |
| entity_id                           | int(10) unsigned | NO   | PRI | NULL    |       |
| revision_id                         | int(10) unsigned | NO   | MUL | NULL    |       |
| langcode                            | varchar(32)      | NO   | PRI |         |       |
| delta                               | int(10) unsigned | NO   | PRI | NULL    |       |
| field_event_end_date_and_time_value | varchar(20)      | NO   | MUL | NULL    |       |
+-------------------------------------+------------------+------+-----+---------+-------+

```

Does anyone see it?

# Answer
The CLI works because then you're not in strict mode and it just cuts the string off.

Your date format is wrong. It must be in the format defined by `DATETIME_DATETIME_STORAGE_FORMAT` and converted to the correct timezone `DATETIME_STORAGE_TIMEZONE`.
> 2 votes

---
Tags: 8, nodes, database
---


# Question
Title: page which display only $content (no header,footer,sidebars)
I wanted to show a page which displays only `$content`. I successfully got the output when I used this code in template.php inside my theme.

```
function THEMENAME_preprocess_page(&$vars) {
  if (isset($_GET['ajax']) && $_GET['ajax'] == '1') {
    $vars['template_file'] = 'page-ajax';
  }
}

```

In page-ajax.tpl.php, I used the following code.

```
<?php
  echo $content
?>

```

Is there anyway to achieve the same thing using a custom module?

# update

I think you all misunderstood my question, i want to override page.tpl with only $content, Not how to create a tpl using hook\_theme! Currently i have used the same code in my module, but the problem is i have to manually copy page-ajax.tpl to my active theme directory. You can refer the module i created http://drupal.org/project/ajax\_links\_api

# Answer
Finally found solution

```
/**
 * Implements hook_theme_registry_alter().
 */
function MODULE_theme_registry_alter(&$theme_registry) {
  // get tpl path in my custom module.
  $mod_path = drupal_get_path('module', 'MODULE') . '/tpl';
  $theme_registry_copy = $theme_registry; // Munge on a copy.
  _theme_process_registry($theme_registry_copy, 'phptemplate', 'theme_engine', 'pow', $mod_path);
  $theme_registry += array_diff_key($theme_registry_copy, $theme_registry);
  $hooks = array('page');
  foreach ($hooks as $h) {
    if (is_array($theme_registry[$h]['theme path'])) {
      $first_element = array_shift($theme_registry[$h]['theme path']);
      array_unshift($theme_registry[$h]['theme path'], $first_element, $mod_path);
    }
  }
}

```
> 0 votes

# Answer
Drupal works its way down a function call stack to find and use hooks defined in other places. So, in much the same way that THEMENAME\_preprocess\_page() works, so does MODULENAME\_preprocess\_page - See http://drupal.org/node/223430 for the specific order that these preprocess functions are called.

Now, as for setting up the template. You define it using http://api.drupal.org/api/function/hook\_theme \- As an example from the block module:

```
function block_theme() {
return array(
'block' => array(
      'render element' => 'elements',
      'template' => 'block',
    ), // Omitted remainder.

```

Notice the 'template' attribute. That maps to block.tpl.php. So assume the following:

```
function myModuleName_theme() {
return array(
    'my_themehook_special' => array(
        //notice I am setting this up to look for the file in a subdirectory of the module
        'template' => 'moduleSubdirectory/filenameOfTemplate',
        'arguments' => array('yourArgumentObject' => null),
    )
);
}

```

That would register your template. Check out this blog post for more: http://www.trevorsimonton.com/blog/tplphp-hooktheme-drupal-variable-template-module
> 4 votes

# Answer
Colorbox Node lets you load just content of a menu callback in a colorbox modal via Drupal ajax framework and works well in your case.

> When you create your links manually, you will need to add the class "colorbox-node" to the link. That is the only class required and the module will handle the colorbox loading internally. Your link should look like this: `<a class="colorbox-node" href="blogs/my-example?width=600&height=600">My Example</a>`
> 4 votes

# Answer
This is going to be a long answer but I read your module and I understand what you're trying to do. Here it goes (FYI, I've done this before):

What you're trying to do should not be done with a theme function or a hook\_preprocess\_page(). What you should be looking at is implementing what is called a "Delivery Callback". If you want any link to be returned via AJAX no matter what the link is based on your query string.

You should really do something like :

```
/**
 * Implements hook_page_delivery_callback_alter().
 */
function hook_page_delivery_callback_alter(&$callback) {
  // jQuery sets a HTTP_X_REQUESTED_WITH header of 'XMLHttpRequest'.
  // If a page would normally be delivered as an html page, and it is called
  // from an ?ajax Javascript lets render it as ajax_deliver.
  if (isset($_SERVER['HTTP_X_REQUESTED_WITH']) &&
    $_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest' &&
    $callback == 'drupal_deliver_html_page'
    && $_GET['ajax'] == '1') {
    // Here we change the callback. Now In my example I'm using ajax_deliver
    // but if needed can create your own. That being said ajax_deliver should
    // be more than enough.
    $callback = 'ajax_deliver';
  }
}

```

If for some reason you need to modify the content being returned, you can actually accomplish that by using hook\_ajax\_render\_alter() like so:

```
function ugc_ajax_render_alter(&$commands) {
  if ($_GET['ajax'] == '1') {
   // Add my special ajax commands to render the data how I want.
   }
}

```

But in your case you're only replacing content, a simple ajax command of "ajax\_command\_html" should work because that's what you're doing in your JavaScript.

Also some comments on the JavaScript file. You shouldn't have to do the $.ajax request yourself.

Instead you can easily simplify the whole thing by just adding a class to your links. The same way the use-ajax class works. So in your case you can look at http://drupalcode.org/project/drupal.git/blob/refs/heads/7.x:/misc/ajax.js#l40 for an example of how to generate your AJAX request. If you change your JavaScript to work like that you won't actually have to write your callback, since the Drupal Ajax framework would handle the ajax\_commands being return and replace the content with wat ever selector is on the request.

I hope this is helpful and I know it's a lot but you can read the docs Drupal 7 AJAX Framework to learn more about how to work with AJAX requests and Drupal. Reading Drupal 6, the same concept can be accomplished by using the Ctools module.

Feel free to ask any questions. I know these aren't easy answers to implement. lol but the question wasn't an easy question ;-)
> 3 votes

# Answer
As per your question update, if you would like to include your page-ajax.tpl.php using your module rather than copying it to your active theme you can do the following.

Function in your .module add the path so Drupal knows where to look for your template.

```
/**
 * Implements hook_theme()
 */
function MODULE_theme() {
  return array(
    'popup' => array(
      'arguments' => array('content' => null), //Array of variables in page-ajax.tpl.php
      'template' => 'ajax',
      'path' => drupal_get_path('module', 'MODULE') .'/theme',
    ),
  );
}

```

Content in your MODULE/theme/popup.tpl.php file

```
<?php echo $content; ?>

```
> 2 votes

# Answer
I think that you can use the same hook `MODULENAME_preprocess_page` but you need to register your template file using `hook_theme` read more about it here

I didn't do it before but I think it works that way. A quick search returns this which may help.
> 1 votes

# Answer
Just to add to the answers. If all you want is to output the node content (or any content) without going through Drupal templating engine, there is a much simpler way.

```
function <MODULE_NAME>_menu() {
    $items = array();

    $items['some_path/%node'] = array(
        'page callback' => '_output_content', // Name of the function to call
        'page arguments' => array(1),
        'access callback' => 'node_access',
        'access arguments' => array('view', 1)
    );

    return $items;
}

function _output_content($node) {
    $node_view = node_view($node);
    print drupal_render($node_view);

    exit;
}

```

NOTE: Replace "\<MODULE\_NAME\>" with your module name, replace "some\_path" with the path that you want to use with your service (you can check it with http://\<YOUR\_DRUPAL\_SITE\>/some\_path/1234 ), and choose a good name for your callback function, something better then "\_output\_content", something that has less chance to clash with other module. It's a good practice to use your module name as a prefix.

You can also output arbitrary text content:

```
function _output_content($node) {
    print('Hello');

    exit;
}

```

Or even output JSON:

```
function _output_content($node) {
    drupal_json_output(array(
        'key' => 'value'
    ));

    exit;
}

```
> 0 votes

---
Tags: theming
---


title: How do I exclude/blacklist admin paths?

text:
# Question
Title: How do I exclude/blacklist admin paths?
Is there still a way to exclude administrative paths from using the CDN module in Drupal 8?

It appears you have to use advanced mappings, but I don't understand how.

# Answer
> 1 votes
No, not currently. As the UI suggests, the complex mappings can be set in the module's install/config/cdn.settings.yml config file, but it only allows for segmenting traffic to different CDNs based their extension.

The `FileUrlGenerator` service object handling the file URL rewriting doesn't consider a path context while deciding when/when not to serve file from the CDN.

You could replace this service class via the `ServiceModifierInterface` and its `::alter()` method with a custom service class that does consider the path context.

---
Tags: cdn
---


title: How to access values in node object?

text:
# Question
Title: How to access values in node object?
Hi i am unable to access values from a node object inside a **preprocess\_views\_view** . Below is a screenshot of my object and i want to access the value highlighted. How can i do that?

# Answer
> 3 votes
There are several options:

You can use the getter method for the node id (available for all entities):

```
$node->id()

```

You can use *magic methods* to access any field of any content entity:

```
$node->nid->value

```

The above code will actually trigger the below:

```
$node->get('nid')->get(0)->get('value')->getValue()

```

# Answer
> 1 votes
To get the node id you can use `$node->id()`. Any object extending ContentEntityBase has this method.

You can look at the Node class to see what public getter methods are available (also, ContentEntityBase and Entity).

Note that protected values cannot be overwritten without a setter method - so you'll need to create a new variable from your preprocess hook to do this.

# Answer
> 1 votes
Debugging a content entity object is not very useful. Instead, debug its array representation (`$node->toArray()`), you can access that data then like this:

`$node->get('field')->property`. For example `$node->get('nid')->value`.

For base fields like the ID, there are usually also methods, in this case `$node->id()` as mentioned by others.

See Entity API Cheat Sheet for more information.

---
Tags: 8, hooks
---


# Question
Title: How to count the number of values in a multi value field with the Paragraphs module?
I’m currently using the Paragraphs module. I have pretty much set up a simple bundle with a title, image and text area. I went into the basic page content type and added the paragraph field reference which worked fine. This had a limit of up to 6 paragraphs per basic page. They can add less than 6, just not any more than 6.

My question is, how do I count how many paragraphs have been entered on that particular basic page. I’m trying to count the amount of paragraphs added so each time it’s added it can dynamically modify the class containing the paragraph.

For example, using Foundation 5 I want to count how many entries have been made and if there is 3 paragraphs then I want the name of the class to be `foo` for example.

# Answer
> 3 votes
if you have a multi-value paragraph field, then in your twig template file you can use

```
content.YOUR_FIELD_NAME['#items']|length

```

provided that you are using Drupal 8

# Answer
> 1 votes
If you're theming the paragraph field using a theme template or a preprocess function, an `$id` or `$variables['id']` variable is available that has the count of the current paragraph item.

---
Tags: nodes, theming
---


# Question
Title: How to submit a user profile form through ajax?
I want to submit the user profile form through ajax.

I see the ajax\_register module but it does not support the user profile form. Is there any contrib module which I can use?

Or this can done custom. But with custom approach I have to look for the form validation also?

# Answer
> 0 votes
Below module will help you

**Modal forms (with ctools)**

> Modal forms make use of the modal feature in the ctools module to open some common forms in a modal window.
>
> ```
> Log in (modal_forms/nojs/login)
> Request new password (modal_forms/nojs/password)
> Create new account (modal_forms/nojs/register)
> Contact (modal_forms/nojs/contact)
> Comment (modal_forms/nojs/comment/reply/%node)
> Webform (modal_forms/nojs/webform/%node)
>
> ```
>
> Function that rewrite normal links to modal forms links (except for webforms) can be activated on the modules configuration page

---
Tags: 7, users
---


# Question
Title: Is it possible to have common content for several users?
For example, sometimes there is a situation when several project's users need to work with common content not using one account for them. That is, each member of the group has his own account with his login and password. But they need to have possibility edit and delete data inputed by other member of the group before. Are there any solutions which can realize it ? And it is desirable to the solution wouldn't be the Organic Groups module or based on creating of a lot of roles.
And if there isn't the solution, how, by you opinion, is the best way to create this feature ? Can one try to use the Relation module and overriding Access control to perform it ?

# Answer
> 3 votes
Have a look at the Group module (commonly perceived as an alternative for Organic Groups).

Group allows for creating arbitrary collections of your content and users on your site, and grant access control permissions on those collections. It is available as of D7, and has a D8 version also. The Group module creates groups as entities, making them fully fieldable, extensible and exportable. Which also makes it integrate very well (out of the box) with commonly used modules such as Rules, Views, etc.

Some more questions you may want to look at for more details:

# Resources

---
Tags: 8, users
---


# Question
Title: How can I render an URL path from a custom route?
In my module.routing.yml (and using D8), I have a *module\_new* route associated with the /module/name path.

I want to render this path in my module. How can I show http://example.org/module/name on a page?

# Answer
> 11 votes
**Twig**

You can use the route name in the twig function `url()`:

```
<a href="{{ url('module_new') }}">{{ 'View my module content'|t }}</a>

```

**Controller**

Or you can do the same in a controller:

```
use Drupal\Core\Url;

  $url = Url::fromRoute('module_new', [], ['absolute' => TRUE]);

  // get the path as string (not recommended)
  $path = $url->toString;

  // better put the complete url object in a render array and let the template render it
  $build['link'] = [
   '#title' => $this->t('My module content'),
   '#type' => 'link',
   '#url' => $url,
  ];

  return $build;

```

---
Tags: routes
---


title: What exactly is the global context?

text:
# Question
Title: What exactly is the global context?
I have been reading the documentation for `module_load_include()` and there's a warning that says:

> Do not use this function in a global context since it requires Drupal to be fully bootstrapped, use require\_once DRUPAL\_ROOT . '/path/file' instead.

Now I'm not sure what this "global context" means. I guess a page callback function is not in global context because I'd have to do a `global $user` to access the user entity. The only global context instance I can think of is in the `index.php` file at the root directory, but I don't think people normally code on this file because it'd be "hacking" Drupal core.

Am I just missing the whole concept of global context as used in Drupal?

# Answer
It means the global *scope*, ie anything outside a function and namespace. It's the PHP 'global', not anything specific to drupal.

People tend to use `module_load_include` at the top of .module files to bring in includes, much like in a traditional standalone PHP project.

This is potentially bad because the required elements might not have been bootstrapped at that point, which can lead to errors; hence the warning not to use it in a global context.
> 2 votes

# Answer
*In a global context* means *outside any function, method or class*. If you were to use the following code, it would not give you the right result.

```
<?php

// Load the files containing the module code.
module_load_include('inc', 'mymodule', 'common.functions');

/*
 * Implements hook_node_load().
 */
function mymodule_node_load($nodes, $types) {
  // Decide whether any of $types are relevant to our purposes.
  if (count(array_intersect($types_we_want_to_process, $types))) {
    // Gather our extra data for each of these nodes.
    $result = db_query('SELECT nid, foo FROM {mytable} WHERE nid IN(:nids)', array(':nids' => array_keys($nodes)));
    // Add our extra data to the node objects.
    foreach ($result as $record) {
      $nodes[$record->nid]->foo = $record->foo;
    }
  }
}

```

Instead, in that case, you should use `require_once()`.
> 1 votes

---
Tags: 7
---


title: Can you add methods to node-entities?

text:
# Question
Title: Can you add methods to node-entities?
What is the preferred way to add functionality to nodes? More explicitly stated: What is the node-entity equivalent of the Entity-class from the entity-API-module?

Sometimes you want to add methods to a entity. That is possible when using the entity-module, where each entity has a "entity class" property. You can take this entity class and extend it to your heart's content.

However, this is not possible with node-entities, since these don't use the "entity class" attribute.

So, the following code would work if drupal-core worked like the entity-module, but throws an error as is:

```
function myNode_entity_info_alter(&$info){
    $info['node']['entity class'] = 'MyNode';
}

class MyNode extends Entity{
    public function sayHi(){
        drupal_set_message("Hi!");
    }
}

function myNode_entity_load($entities, $type){
    if($type == 'node'){
        foreach ($entities as $entity) {
            $entity->sayHi(); # Error: Call to undefined method stdClass::sayHi()
        }
    }
}

```

How can I make this work with node-entities?

PS: as a follow-up question: is this any easier using drupal8?

# Answer
> 1 votes
I believe I have found something that does what I want: https://www.deeson.co.uk/labs/extending-entitydrupalwrapper

The basic idea is that, since drupal-core doesn't facilitate the extension of entity-classes, we use the entity-metadata-wrapper instead.

The above example would then be reformulated as such:

```
class MyNodeWrapper extends EntityDrupalWrapper{
    public function __construct($data) {
        parent::__construct('node', $data);
    }

    public function sayHi(){
        drupal_set_message("Hi!");
    }
}

function myNode_entity_load($entities, $type){
    if($type == 'node'){
        foreach ($entities as $entity) {
            $emw = new MyNodeWrapper($entity);
            $emw ->sayHi();
        }
    }
}

```

This appears to be a very reasonable approach. Only thing I dislike about it is that you can't use `entity_metadata_wrapper` to get the MyNodeWrapper-wrapper.

---
Tags: 7, entities
---


# Question
Title: Display newly added form element at the bottom
I altered a form, and I added a `$form['priorities']` form element.

Why is it appearing right after the title form element, and not at the bottom of the form? How can I make it at the bottom?

# Answer
Like KrishaWeb said you need to add a #weight attribute to your new element.

It would look like:

```
$form['priorities'] = array(
  ...
  '#weight' => 99,
  ...
);

```

You can also set weights on the other form elements so the form is explicitly in order.
> 1 votes

---
Tags: forms
---


# Question
Title: Passing an array of object from custom module to template in drupal 8
Follow this about passing an array to template. But my array is array of object so I'm getting some errors on the page, this is the one of them:

> User error: "0" is an invalid render array key in Drupal\Core\Render\Element::children() (line 97 of core/lib/Drupal/Core/Render/Element.php)

**This is my code :**

**Controller**

```
  public function content() {
      return array(
        '#theme' => 'my_page',
        '#text' => "Lorem Ipsum",
        '#myvariable' => array('key' => $myArrayofObjects),
      );
  }

```

**mymodule.module**

```
function my_page($existing, $type, $theme, $path) {
  return array(
    'my_page' => array(
        'variables' => array(
            'text' => NULL,
            'myvariable' => array(),
        ),
    ),
  );
}

```

**my-page.html.twig**

```
<p>Test twig template!</p>
<p>{{text}}</p>

{% for key, value in myvariable %}
  Key : {{ key }}
  Value : {{ value }}
{% endfor %}

```

**This is the array :**

```
Array
    (
        [0] => stdClass Object
            (
                [name] => User1
                [user_id] => 1
                [email] => user1@website.com
            )

        [1] => stdClass Object
            (
                [name] => User2
                [user_id] => 2
                [email] => user2@website.com
            )

        [2] => stdClass Object
            (
                [name] => User3
                [user_id] => 3
                [email] => user3@website.com
            )
     )

```

How the best way to pass an array of object from module to template and render or loop it using twig engine?

# Answer
In your controller why you are using like this

```
'#myvariable' => array('key' => $myArrayofObjects),

```

Change it as

```
'#myvariable' => $myArrayofObjects,

```

and in **my-page.html.twig**

```
<p>Test twig template!</p>
<p>{{text}}</p>

{% for key, value in myvariable %}
  Key : {{ key }}
  Name : {{ value.name }}
  User ID : {{ value.user_id }}
  Email : {{ value.email }}
{% endfor %}

```
> 4 votes

---
Tags: theming, 8
---


# Question
Title: Customized Node Display for 'Document Template' Content-Type
I want to filter the nodes of content-type `Document Template`. I know this can be done with `.tpl.php` files.

I was wondering, what was the right file name convention. I tried the the naming convention but it does not work.

```
node--document template.tpl.php

```

Where did I go wrong?

# Answer
> 0 votes
> Where did I go wrong?

You used the wrong format. Replace the space with a `-`:

```
node--document-template.tpl.php

```

---
Tags: 7, theming, nodes
---


# Question
Title: How to prolong time of displaying of images in carousel slideshow
I use Bootstrap 3-based Drupal 8 theme (Jethro). In the header, I have carousel of sliding images. They change every 5 seconds. I'd like to prolong this time to e.g. 30 seconds, so that every image is displayed for 30 seconds, not 5. So far I found only how to change speed of the change, animation, which is not the task. Any idea how to do it?

# What I tried

In `bootstrap.css` and `bootstrap.min.css`:

```
.carousel-inner .item {
  ...
  transition: 30s ease-in-out left; # Increase time here
  } # Together with below it makes sliding slower, nothing more

```

and in `bootstrap.js` and `bootstrap.min.js`:

```
this.interval = 50000 // It does nothing
interval: 5000 * 10 // In Carousel.DEFAULTS; it makes sliding slower

```

# Answer
Comparing with w3schools example (specifically line `<div id="myCarousel"...`) - inserting `data-interval="30000"` there (the line then looks like `<div id="myCarousel" class="carousel slide" data-ride="carousel" data-interval="30000">`) does the trick.

In the Jethro theme (and probably in any similar case), this backbone is in the file `templates/page.html.twig` (in version 2.0 line 85). So that inserting `data-interval="30000"` there does the trick. The line then looks like `<div id="myCarousel" class="carousel slide" data-ride="carousel" data-interval="30000">`. Might be this is not the most elegant way, but it works well.
> 1 votes

---
Tags: theming, 8
---


# Question
Title: Passing Date arguments to Contextual Filters from QuickTabs to a Block View
I am using QuickTabs to display, by year, a field-collection of a PDF and a Date. But I can't figure out how to send the argument from the QT to the contextual filter in the view because it is a block, not a page, so I don't have the arguments being submitted in the path to grab.

Here is my view without the contextual date filter, showing all the content (it is already being filtered by NID and type):

Here is a working, fixed-value contextual date filter:

This successfully filters the date to only 2017 items:

So, it is working with a fixed value. Now, trying to get it to use the argument from my QuickTabs is what isn't working. Here is my QuickTab (with the fixed contextual filter removed):

Here is what outputs on the tab WITHOUT the argument:

And here's the output on a tab with the argument (not working because there's no contextual filter anymore):

Seeings as how this isn't a block, I can't use the path arguments to the contextual filters. QuickTabs says "Additional arguments to send to the view as if they were part of the URL in the form of arg1/arg2/arg3. You may use %0, %1, ..., %N to grab arguments from the URL." I'm not totally sure how to use these but I tried using %0 as a fixed-value in the contextual filter. I've tried setting the argument in my quicktab to be "%0/%1/2017-01-01--2017-12-31". I've tried extensively using "Raw Value from URL" but no avail.

I've got all the modules enabled that I need to make this happen (i.e. date-views so that it accepts a range). So I'm sure it's just some very specific set of configuration and argument syntax that I just haven't guessed correctly yet.

Anyone able to help me with this issue has my sincerest thanks!!! Following is the view export:

```
$view = new view();
$view->name = 'resource_view';
$view->description = '';
$view->tag = 'default';
$view->base_table = 'node';
$view->human_name = 'Resource View';
$view->core = 7;
$view->api_version = '3.0';
$view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */

/* Display: Master */
$handler = $view->new_display('default', 'Master', 'default');
$handler->display->display_options['title'] = 'Resource View';
$handler->display->display_options['use_more_always'] = FALSE;
$handler->display->display_options['access']['type'] = 'perm';
$handler->display->display_options['cache']['type'] = 'none';
$handler->display->display_options['query']['type'] = 'views_query';
$handler->display->display_options['exposed_form']['type'] = 'basic';
$handler->display->display_options['pager']['type'] = 'some';
$handler->display->display_options['pager']['options']['items_per_page'] = '20';
$handler->display->display_options['style_plugin'] = 'default';
$handler->display->display_options['row_plugin'] = 'fields';
/* Relationship: Content: Resource (field_resource) */
$handler->display->display_options['relationships']['field_resource_value']['id'] = 'field_resource_value';
$handler->display->display_options['relationships']['field_resource_value']['table'] = 'field_data_field_resource';
$handler->display->display_options['relationships']['field_resource_value']['field'] = 'field_resource_value';
$handler->display->display_options['relationships']['field_resource_value']['delta'] = '-1';
/* Field: Field collection item: Resource Date */
$handler->display->display_options['fields']['field_resource_date']['id'] = 'field_resource_date';
$handler->display->display_options['fields']['field_resource_date']['table'] = 'field_data_field_resource_date';
$handler->display->display_options['fields']['field_resource_date']['field'] = 'field_resource_date';
$handler->display->display_options['fields']['field_resource_date']['relationship'] = 'field_resource_value';
$handler->display->display_options['fields']['field_resource_date']['label'] = '';
$handler->display->display_options['fields']['field_resource_date']['element_label_colon'] = FALSE;
$handler->display->display_options['fields']['field_resource_date']['settings'] = array(
  'format_type' => 'month_only',
  'fromto' => 'both',
  'multiple_number' => '',
  'multiple_from' => '',
  'multiple_to' => '',
  'show_remaining_days' => 0,
  'addtocalendar_show' => 0,
  'addtocalendar_settings' => array(
    'style' => 'blue',
    'display_text' => 'Add to Calender',
    'atc_title' => array(
      'field' => 'token',
      'tokenized' => '',
    ),
    'atc_description' => array(
      'field' => 'token',
      'tokenized' => '',
    ),
    'atc_location' => array(
      'field' => 'token',
      'tokenized' => '',
    ),
    'atc_organizer' => array(
      'field' => 'token',
      'tokenized' => '',
    ),
    'atc_organizer_email' => array(
      'field' => 'token',
      'tokenized' => '',
    ),
    'atc_date_end' => array(
      'field' => 'token',
      'tokenized' => '',
    ),
    'atc_privacy' => 'public',
    'data_secure' => 'auto',
    'data_calendars' => array(
      'iCalendar' => 0,
      'Google Calendar' => 0,
      'Outlook' => 0,
      'Outlook Online' => 0,
      'Yahoo! Calendar' => 0,
    ),
  ),
);
/* Field: Field collection item: Resource File */
$handler->display->display_options['fields']['field_resource_file']['id'] = 'field_resource_file';
$handler->display->display_options['fields']['field_resource_file']['table'] = 'field_data_field_resource_file';
$handler->display->display_options['fields']['field_resource_file']['field'] = 'field_resource_file';
$handler->display->display_options['fields']['field_resource_file']['relationship'] = 'field_resource_value';
$handler->display->display_options['fields']['field_resource_file']['label'] = '';
$handler->display->display_options['fields']['field_resource_file']['alter']['alter_text'] = TRUE;
$handler->display->display_options['fields']['field_resource_file']['alter']['text'] = 'Download to View';
$handler->display->display_options['fields']['field_resource_file']['alter']['make_link'] = TRUE;
$handler->display->display_options['fields']['field_resource_file']['alter']['path'] = '[field_resource_file]';
$handler->display->display_options['fields']['field_resource_file']['alter']['absolute'] = TRUE;
$handler->display->display_options['fields']['field_resource_file']['element_label_colon'] = FALSE;
$handler->display->display_options['fields']['field_resource_file']['click_sort_column'] = 'fid';
$handler->display->display_options['fields']['field_resource_file']['type'] = 'file_url_plain';
/* Contextual filter: Content: Nid */
$handler->display->display_options['arguments']['nid']['id'] = 'nid';
$handler->display->display_options['arguments']['nid']['table'] = 'node';
$handler->display->display_options['arguments']['nid']['field'] = 'nid';
$handler->display->display_options['arguments']['nid']['default_action'] = 'default';
$handler->display->display_options['arguments']['nid']['default_argument_type'] = 'fixed';
$handler->display->display_options['arguments']['nid']['default_argument_options']['argument'] = '6783';
$handler->display->display_options['arguments']['nid']['summary']['number_of_records'] = '0';
$handler->display->display_options['arguments']['nid']['summary']['format'] = 'default_summary';
$handler->display->display_options['arguments']['nid']['summary_options']['items_per_page'] = '25';
/* Filter criterion: Content: Published */
$handler->display->display_options['filters']['status']['id'] = 'status';
$handler->display->display_options['filters']['status']['table'] = 'node';
$handler->display->display_options['filters']['status']['field'] = 'status';
$handler->display->display_options['filters']['status']['value'] = 1;
$handler->display->display_options['filters']['status']['group'] = 1;
$handler->display->display_options['filters']['status']['expose']['operator'] = FALSE;
/* Filter criterion: Content: Type */
$handler->display->display_options['filters']['type']['id'] = 'type';
$handler->display->display_options['filters']['type']['table'] = 'node';
$handler->display->display_options['filters']['type']['field'] = 'type';
$handler->display->display_options['filters']['type']['value'] = array(
  'resource_page' => 'resource_page',
);

/* Display: View: Pedestrian Resources */
$handler = $view->new_display('block', 'View: Pedestrian Resources', 'block');
$handler->display->display_options['defaults']['fields'] = FALSE;
/* Field: Field collection item: Resource Date */
$handler->display->display_options['fields']['field_resource_date_1']['id'] = 'field_resource_date_1';
$handler->display->display_options['fields']['field_resource_date_1']['table'] = 'field_data_field_resource_date';
$handler->display->display_options['fields']['field_resource_date_1']['field'] = 'field_resource_date';
$handler->display->display_options['fields']['field_resource_date_1']['relationship'] = 'field_resource_value';
$handler->display->display_options['fields']['field_resource_date_1']['settings'] = array(
  'format_type' => 'date_only_full',
  'fromto' => 'both',
  'multiple_number' => '',
  'multiple_from' => '',
  'multiple_to' => '',
  'show_remaining_days' => 0,
  'addtocalendar_show' => 0,
  'addtocalendar_settings' => array(
    'style' => 'blue',
    'display_text' => 'Add to Calender',
    'atc_title' => array(
      'field' => 'token',
      'tokenized' => '',
    ),
    'atc_description' => array(
      'field' => 'token',
      'tokenized' => '',
    ),
    'atc_location' => array(
      'field' => 'token',
      'tokenized' => '',
    ),
    'atc_organizer' => array(
      'field' => 'token',
      'tokenized' => '',
    ),
    'atc_organizer_email' => array(
      'field' => 'token',
      'tokenized' => '',
    ),
    'atc_date_end' => array(
      'field' => 'token',
      'tokenized' => '',
    ),
    'atc_privacy' => 'public',
    'data_secure' => 'auto',
    'data_calendars' => array(
      'iCalendar' => 0,
      'Google Calendar' => 0,
      'Outlook' => 0,
      'Outlook Online' => 0,
      'Yahoo! Calendar' => 0,
    ),
  ),
);
/* Field: Field collection item: Resource File */
$handler->display->display_options['fields']['field_resource_file']['id'] = 'field_resource_file';
$handler->display->display_options['fields']['field_resource_file']['table'] = 'field_data_field_resource_file';
$handler->display->display_options['fields']['field_resource_file']['field'] = 'field_resource_file';
$handler->display->display_options['fields']['field_resource_file']['relationship'] = 'field_resource_value';
$handler->display->display_options['fields']['field_resource_file']['label'] = '';
$handler->display->display_options['fields']['field_resource_file']['alter']['alter_text'] = TRUE;
$handler->display->display_options['fields']['field_resource_file']['alter']['text'] = 'Download to View';
$handler->display->display_options['fields']['field_resource_file']['alter']['make_link'] = TRUE;
$handler->display->display_options['fields']['field_resource_file']['alter']['path'] = '[field_resource_file]';
$handler->display->display_options['fields']['field_resource_file']['alter']['absolute'] = TRUE;
$handler->display->display_options['fields']['field_resource_file']['alter']['target'] = '_blank';
$handler->display->display_options['fields']['field_resource_file']['element_label_colon'] = FALSE;
$handler->display->display_options['fields']['field_resource_file']['click_sort_column'] = 'fid';
$handler->display->display_options['fields']['field_resource_file']['type'] = 'file_url_plain';
$handler->display->display_options['defaults']['arguments'] = FALSE;
/* Contextual filter: Content: Nid */
$handler->display->display_options['arguments']['nid']['id'] = 'nid';
$handler->display->display_options['arguments']['nid']['table'] = 'node';
$handler->display->display_options['arguments']['nid']['field'] = 'nid';
$handler->display->display_options['arguments']['nid']['default_action'] = 'default';
$handler->display->display_options['arguments']['nid']['default_argument_type'] = 'fixed';
$handler->display->display_options['arguments']['nid']['default_argument_options']['argument'] = '6781';
$handler->display->display_options['arguments']['nid']['summary']['number_of_records'] = '0';
$handler->display->display_options['arguments']['nid']['summary']['format'] = 'default_summary';
$handler->display->display_options['arguments']['nid']['summary_options']['items_per_page'] = '25';
$handler->display->display_options['block_description'] = 'View: Pedestrian Resource View';

/* Display: View: Monthly Indicator Resources */
$handler = $view->new_display('block', 'View: Monthly Indicator Resources', 'block_1');
$handler->display->display_options['defaults']['arguments'] = FALSE;
/* Contextual filter: Content: Nid */
$handler->display->display_options['arguments']['nid']['id'] = 'nid';
$handler->display->display_options['arguments']['nid']['table'] = 'node';
$handler->display->display_options['arguments']['nid']['field'] = 'nid';
$handler->display->display_options['arguments']['nid']['default_action'] = 'default';
$handler->display->display_options['arguments']['nid']['default_argument_type'] = 'fixed';
$handler->display->display_options['arguments']['nid']['default_argument_options']['argument'] = '6783';
$handler->display->display_options['arguments']['nid']['summary']['number_of_records'] = '0';
$handler->display->display_options['arguments']['nid']['summary']['format'] = 'default_summary';
$handler->display->display_options['arguments']['nid']['summary_options']['items_per_page'] = '25';
$handler->display->display_options['block_description'] = 'View: Monthly Indicator Resource View';

```

////////////////////

UPDATE IN RESPONSE TO Stefanos-Petrakis

////////////////////

I've tried it your way but the contextual filter just filters everything out.

Here's the field settings:

As you can see, it takes out everything...

The date field takes Year and Month only, not that it should matter. Other than that, it is a normal date field. Definitely have dates in 2016, as well.

I'd be happy to provide any other screenshots that may be helpful. Thank you so much.

/////////////////////

# Answer
You don't need any coding for this, you should simply activate the date\_views submodule (comes with the Date module).

After you do that, your contextual filters will include some useful choices, namely the granularity one:

Setting up your contextual filter like that, should already make it possible, inside Views admin, to test your contextual filter:

Once this is working as expected, you simply need to pass the year argument to your quicktab:

Your QT-block now can filter by year tab:

(example for 2017)

(example for 2016)

Good luck!
> 1 votes

# Answer
Use

```
views_embed_view():
views_embed_view('view_machine_name', 'block_1');
views_embed_view('view_machine_name', 'block_1', $param);

```

if you want to pass a parameter to the view.
> -1 votes

---
Tags: 7, views, blocks
---


# Question
Title: Is there sny module for auto-posting on social media networks?
Is there any module to automatically post contents of our Drupal site into social media networks (e.g. Facebook, Twitter)?

For WordPress there is the Social Networks Auto-Poster plugin. What is the equivalent module for Drupal?

# Answer
> 3 votes
There is no module for doing that in Drupal as far as I know. However, there is a way you can achieve this.

You can create an rss feed ( you can use drupal default feed, syndication or views) and then use a service called twitterfeed

See tutorial here

# Answer
> 1 votes
I know its maybe a late answer but you can try this module for drupal 8 :

> Autopost social is a module to publish posts to multi Social network (Facebook, Twitter) when you add/edit a new content. https://www.drupal.org/project/autopost\_social

---
Tags: 7
---


title: Drupal post to facebook

text:
# Question
Title: Drupal post to facebook
Is there a way to make Drupal post to facebook?

I want the user to be able to create an article, and when user does that, it automatically posts information of the new article to a Facebook account. Is this possible?

# Answer
I think you should have a look at Drupal For Facebook, although there's only a dev version for `D7`
> 1 votes

# Answer
You should check out Facebook Autopost. There is a video tutorial on how to set up everything to do it easily.

With this module you will be able to post Links, Posts, Events, Questions, … linked to Drupal events.
> 3 votes

# Answer
You can try Autopost social module is still in dev version, but it work for facebook, twitter.

> Autopost social is a module to publish posts to multi Social network (Facebook, Twitter) when you add/edit a new content.
> 0 votes

# Answer
For drupal 8 the social api was introduced. Acutally the rewritten and harmonised successor of Drupal for facebook.
> 0 votes

---
Tags: 7, social-network
---


# Question
Title: How do I get all the aliases defined for a route?
I want to get all the path aliases defined for a route. Using `AliasStorage::lookupPathAlias()` or `AliasManager::getAliasByPath()`, I get a single path alias, even when there are more path aliases defined for that route.

If I were using Drupal 7, I would use the answers given to Find all aliases for a given node.

How can I get all the path aliases defined for a single route?

# Answer
The answer is the same as in Drupal 7, because there is no API to return multiple aliases for a single source path, so your only option, if you really need that (I guess there is a reason that you are not using redirects), is a custom query, which is the same as in 7.x, with the only difference that it has a leading /.

So, copied from the other issue:

```
$aliases = \Drupal::database()->query('
  SELECT alias
  FROM {url_alias}
  WHERE source = :source
', array(':source' => '/node/' . $nid))->fetchAll();

```
> 2 votes

---
Tags: 8, path-aliases
---


# Question
Title: Put menus into separate file for better handling caching with expires
I am trying to clear the page cache of drupal as micro invasive as possible by using Cache Expires and custom logic. On each page, the menu is shown down to Level 2 in a footer and a hover area. Therefore I did only rebuild all menu trees and remove pages from cache if an item on the second or first menu level has been changes.

Now we have got an additional menu for mobile devices which is load with each page and shows down to four menu levels. Changing a menu on the first to fourth level would no lead to a clear of almost any pages.

To avoid this, it would be great to put all that menu stuff out of the page html and put in a single file, containing just the menu information in e.g. json format. So if a menu changes I would only need to update the menu file and the changed node.

Are there any smart hacks out there or even modules dealing with that?

# Answer
There are several ways to achieve this - maybe more.

1. Ajax call and include the menu via jquery / javascript from drupal at runtime
2. Ajax call and iclude the menu via jquery / javascript from a static generated file by cron
3. SSI or ESI include at proxy level of a static file generated by cron

At the moment my favorite is 2. Option as the First option has a major performance drawback because the menu has to be generated for each page visit

Number 2. and 3. inlcude the menu within under 10 milliseconds but 3. would be perfect as it makes the least problems with SEO. As I do not yet have nginx as reverse proxy available in production I stick at 2. as I could not get to work SSI and PHP with apache and php virtual() is not cached by the drupal page cache (in fact it breaks it)

There is a module which helps with SSI and ESI called https://www.drupal.org/project/esi
> 0 votes

---
Tags: navigation, caching
---


# Question
Title: Facet API pretty paths in combination with solr search form
I'm building a website with the panopoly distribution in Drupal 7. One of the client requests is a faceted search page combined with a search box to search on specific keywords and the possibility to sort on date and name.

To build this I used the following modules:

* apachesolr
* apachesolr\_sorts
* apachesolr\_panels

After configuring everything I got this search page working (without clean url's)

https://i.stack.imgur.com/1RZAn.png

To enable clean url's I used the following module:

* facetapi\_pretty\_paths

Now the search box always uses the first argument in the url, after I enable the pretty paths module the first argument in the url is the active filter (taxonomy field name in combination with the taxonomy term name).

https://i.stack.imgur.com/ERU2I.png

What would be the best approach to use the search box in combination with the facets and pretty paths (and the sorting option)?

# Answer
There are two ways to avoid this issue which depend on module what you use.

1) If Search API module is used. (It was taken from https://www.drupal.org/node/2625298)

```
function hook_search_api_query_alter(SearchApiQueryInterface $query) {
    $original_keys = $query->getOriginalKeys();
    if ($original_keys == 'field_facet_filter')) {
        $query->keys(NULL);
    }
}

```

2) If Apache Solr Search module is use

```
function hook_apachesolr_query_prepare(DrupalSolrQueryInterface $query) {
  if ($query->getParam('q') == 'field_facet_filter') {
    $query->removeParam('q');
  }
}

```
> 1 votes

# Answer
if you use search\_api, the search term is put into a get parameter rather than as a path argument. this fixes the problem.

i would believe though, that people have also found a solution for the apachesolr module suite.
> 0 votes

---
Tags: uri, search, panels
---


# Question
Title: Override front page to not display promoted article
Is it possible to override front page template to not display the promoted articles? I am using the `promote to front page` option to filter the contents in a view so I cannot uncheck it.

# Answer
You can simply remove nodes attached to the front page in the preprocess.

```
/**
 * Implements template_preprocess_page()
 */
function THEME_preprocess_page(&$vars) {
  // Remove 'Promoted to front page' nodes
  if ($vars['is_front']) {
    unset($vars['page']['content']['system_main']['nodes']);
  }
}

```
> 2 votes

# Answer
You have quite a few options for this -

* Use drupal's own configuration settings to override the front page at `admin/config/system/site-information` under `Default front page` option and via Menu API you can pass that path here,
* Use Views module : create a page/block, display this block on the front page as `<front>` in Block config UI,
* Use Drupal Panels module to completely change the front page.

As far as you are using `promote to front page` option in Views, can you please put some light on this, I think you are doing it the wrong way..
> 1 votes

# Answer
You can create a view for your frontpage with the right filters and exclude promoted articles in it.
> 0 votes

# Answer
What i assume to answer that you actually do not want to display the articles for `promote to front page` on the frontpage. Right?

Yes. You can create a article view as mentioned by 'user34680'.

Also in the edit mode of a view, you need to add a filter `Content: Promoted to front page` and select to `no` option. Please see the attached screenshot

**Or**

what i get from your questions is that you don't want to display the node with "promoted to front page" in your site home page.

1. So what you can do is to create a page--front.tpl.php without `$page['content']` region printed in it.
2. Another way, you can assign a node or any custom page as you home page from site information

Hope you are looking for this.

Regards
> 0 votes

---
Tags: theming
---


# Question
Title: How get a programmatically menu fields into template?
i add to my main menu an image field programmatically for build a megaMenu :

```
/**
 * Implements hook_entity_base_field_info().
 */
function hook_entity_base_field_info(EntityTypeInterface $entity_type) {

    $fields = [];

    if ($entity_type->id() == 'menu_link_content') {

        $year = date('Y');
        $month = date('m');

        $fields['image'] = BaseFieldDefinition::create('image')
            ->setLabel(t('Image'))
            ->setDescription(t('Image field'))
            ->setSettings([
                'file_directory' => 'imagesMenu'. '/' . $year . '/' . $month,
                'alt_field_required' => FALSE,
                'file_extensions' => 'png jpg jpeg',
            ])
            ->setDisplayOptions('view', array(
                'label' => 'hidden',
                'type' => 'default',
                'weight' => 0,
            ))
            ->setDisplayOptions('form', array(
                'label' => 'hidden',
                'type' => 'image_image',
                'weight' => 0,
            ))
            ->setDisplayConfigurable('form', TRUE)
            ->setDisplayConfigurable('view', TRUE);
    }

    return $fields;
}

```

After a drush update-entity, i can see the field on my form and i can add the image.

Now i try to get this field into twig.

When i use kint with keys this is the result :

> menu--main.html.twig

I cannot see my field image.

Any idea how can i get my field in tempalte ? hook\_preprocess for the menu ?

# Answer
> 5 votes
This is how i get my custom image field from menu into twig

```
function hook_preprocess_menu(&$variables, $hook) {

    if($variables['theme_hook_original'] == 'menu__main'){

            $items = $variables['items'];
            foreach ($items as $key => $item) {

                if(count($item['below'])>0)
                {
                    foreach($item['below'] as $id=>$array)
                    {
                        $entity = \Drupal::entityTypeManager()->getStorage('menu_link_content')->loadByProperties(array('uuid'=>$array['original_link']->getDerivativeId()));

                        foreach($entity as $idMenu)
                        {

                            if($idMenu->get('image')->entity != null) {

                                $image = file_create_url($idMenu->get('image')->entity->getFileUri());

                                $items[$key]['below'][$id]['imageUrl'] = $image;

                            }
                        }

                    }

                }

            }

        $variables['items']=$items;

    }

}

```

I just work on my item menu and add 'imageUrl' into my array. I first load my entity by properties with the UUID for access to my menu item fields.

This method is only for my sub menu ( inside my mega menu, i want just add an image by item in submenu )

> that why i check count(item\['below'\]\>0)

For now i can't find better way.

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


title: Entity vs taxonomy vs content type?

text:
# Question
Title: Entity vs taxonomy vs content type?
I am setting a website up that will house multiple language schools, so I am mainly dealing with:

Individual language schools Language courses

I set up a content type called ‘Schools’ and have fields on this that are unique to a specific school, example:

* School Name
* School Location
* Tel no and contact details
* Description of school

I then used entities for these things that are also unique to a school but there are quite a few of them, so I thought I’d be better with entities, then use inline reference entity fields on the school nodes (is this correct?):

* Types of accommodation
* Activities
* Facilities
* Image Gallery

Now I have come onto adding courses, there is generally a theme for these at the top level such as: ‘Intensive English’ then each school has various classes, so you mght have ‘Intensive English’ MORNING or ‘Intensive English’ EVENING. Now I don’t want to create taxonomies for this classes as I’ll have URLs that don’t have anything on them, I’d have a table with the various classes in it. But the whole website needs to be searchable.

My question is, what do I need to do for courses? I used entities but now can’t create a view that shows the nodes referencing the schools nodes and place it on the taxonomy parent: General English, Intensive English etc. Anyone got an pointers on what I should do and if I have set this up correctly?

I am struggling to create a view that shows a course page and then the schools that offer it, despite creating a reference to it, as in the image. Tried everything with contextual and relationships.

# Answer
> 2 votes
You're right, something that is a 'descriptor' or category is best left as Taxonomy (i.e. Time \> Morning/Afternoon/Evening) where they are used to enrich the meaning of data.

> Now I don’t want to create taxonomies for this classes as I’ll have URLs that don’t have anything on them

If access to taxonomy paths is a concern, you can install the Rabbit Hole module to disable access to it while preserving the functionality of taxonomy behind the scenes.

You can also use other modules like Taxonomy Views Integrator to 'change' the way taxonomy paths behave. In this modules case, you can display a View on these paths instead of the default page callback for taxonomy. The View can be anything you'd like.

Otherwise, if you attempt to create a custom table to store this data, you will need to use the appropriate hooks in the Views API to describe the table and it's data, and how it relates - which can be a lot of work. In the end, it sounds like you'd wind up duplicating taxonomy current functionality.

---
Tags: entities
---


# Question
Title: Rating for all images in a singular node?
Setting up a private gallery for a photographer, so that their clients may log in, see images specific to a certain photoshoot, and check a box, or click a star to favorite different images. Any ideas of how I would set something like this up? An example of this currently being done would be Adobe's Lightroom.

# Answer
> 0 votes
You can take a look on FiveStar module : https://www.drupal.org/project/fivestar

---
Tags: 7, users, media
---


# Question
Title: How to transfer webform submission ID to client side
I need to transfer the submission ID to the client side after a webform is submitted. The problem is that after submission the Confirmation page is showed. And how can I attach the current sid to a page? I know how to do it on a node (se below) with Drupal behaviors on a client side JS-script.

Anyone? Or maybe the sid can be transfered to the client side another way?

```
function mymodule_webform_submission_insert($node, $submission) {
 // $node will give you the node id of your webform
 // $submission will give you the id of your data which you inserted in web form
 $sid = $submission->sid ? $submission->sid : FALSE;
 if($sid){
   $currentSid = array('mymodule' => array('sid' => $sid));
   $node->content['#attached']['js'][] = array(
     'data' => $currentSid,
     'type' => 'setting',
   );
 }
}

```

# Answer
You could start by putting the submission id into $\_SESSION and add it to Drupal's js settings

```
drupal_add_js(array('mymodule' => array('webform_id' => $_SESSION['webform_id'])), 'setting');

```

Then access it on the client side

```
webform_id = Drupal.settings.mymodule.webform_id

```
> 1 votes

---
Tags: 7, hooks, webforms
---


# Question
Title: How to perform a query using a specific field of a node entity reference
I have a content type that has a node entity reference field. My base query looks like

```
$event_nids = \Drupal::entityQuery('node')
    ->condition('type', 'my_content_type')
    ->execute();

```

I'd like though to be able to sort by the title field of the referenced field type. I attempted

```
$event_nids = \Drupal::entityQuery('node')
    ->condition('type', 'my_content_type')
    ->sort('field_referenced_node.title', ASC)
    ->execute();

```

But I receive the error

> Drupal\Core\Entity\Query\QueryException: Invalid specifier 'title' in Drupal\Core\Entity\Query\Sql\Tables-\>addField()

Is it possible to sort a node query by a field inside a referenced node?

# Answer
> 3 votes
I believe you want something like below. Note that this isn't really a database query at this level but an Entity Query:

```
$event_nids = \Drupal::entityQuery('node')
  ->condition('type', 'my_content_type')
  ->sort('field_referenced_node.entity.title', ASC)
  ->execute();

```

---
Tags: 8, database
---


# Question
Title: how to display the list of unread nodes and read nodes
I want to show the list of unread nodes and read nodes. Actually, My scenario is to show the article listing page. The page contains the drop-down contains all, read and unread. The all list all the articles, In read, need to list the contents already read by the user and In unread, need to list the contents not-read by the user. For read, I did with recently-read module but that is not tracking the unread nodes. Hope somebody have already worked with this.

Thanks advance.

# Answer
Using the Flag module seems like a no brainer to me to get this to work: introduce a flag that is used to flag relevant nodes as "read". To actually do so, just use the Rules module (using a Rules event like "When viewing content", a kind of getting started with Rules).

With the above in place, you've reduced your question to creating an appropriate view (using Views) which shows the node(s) for which their flagging status corresponds to "read", or "NOT read", or "all of them". If you want, you can created 3 tabs in your view to show these all / read / not read nodes.

Ps: I'm assuming this is about D7.
> 1 votes

# Answer
The following is a guide but you can continue to develop it In Drupal 8:

1) activate the statitics module.

2) Perform a query to the database for two tables

* node\_counter (statitics module)
* node\_field\_data
Query:

> $query = \Drupal::database()-\>select('node\_counter', 'nfd');
> $query-\>addField('nfd', 'nid');
> $query-\>join('node\_field\_data', 'ufd', 'ufd.nid = nfd.nid');
> $query-\>addField('ufd', 'title');
> $query-\>condition('ufd.type', 'article');
> $result = $query-\>execute()-\>fetchAssoc('nid');

This query shows the nid and title of the articles that have been viewed.
To achieve that of the unseen I believe that a condition is needed
> 0 votes

---
Tags: views
---


# Question
Title: Composer generated installation can't be completely cloned
I have a Drupal 8 installation where I removed all Composer generated folders from the root .gitignore, so that I can make a complete clone of the installation. The problem is that module folders which contain a .git folder themselves remain empty in the cloned folder. What am I missing?

# Answer
> 0 votes
This is perfectly explain on https://getcomposer.org/doc/faqs/should-i-commit-the-dependencies-in-my-vendor-directory.md

In short, that's because git kind of treats folders with a .git as submodules.

The composer.lock file exists to be able to re-install an exact copy with the same commits of dependencies and so on. Or another option is building .tar.gz, containers or similar packages that can be used for efficient deployments.

---
Tags: 8, version-control, composer
---


# Question
Title: Audio File Field is empty (null) on drupalgap app
What i want to do is create/view podcast node type inside DrupalGap App in Android. I am using drupal 7 on Centos 7. drupal module: audiofield (https://www.drupal.org/project/audiofield) drupalgap module added on www\app\modules: audiofield (http://drupalgap.org/project/audiofield) I am using HTML 5 player (default). But also tried before jplayer.

On content type named podcast i have fields: title, body and audio file with File (as type) and Audio Upload (as widget).

Permission given: Audio: Download own files Audio: Download All Audio Files Media-\>Use the media browser Podcast: Create new content Podcast: Edit own content Podcast: Delete own content

even i gave: Add and upload new files View own private files View own files Audio: Edit own files Audio: Delete own files Audio: Download any files

In browser i can listen and download and create new Podcast. All work well. In my android app (drupalgap) when viewing, i can see a player but nothing happens when i press play or download button. And when i try to create a podcast in the audio file field, DrupalGap shows Null and nothing else below.

P.S. I can provide test account if need be

Any suggestions?

Thank you

# Answer
The problem was that the url of the source audio file was wrong. It happened after i deleted originalsong.mp3 and reuploaded it. So, system gave it new name originalsong\_0.mp3 (Note the \_0 at the end of the filename). Probably drupal keeps track of files uploaded even when they are deleted so when i upload same mp3 with same filename it gets \_0, \_1 etc. Null object appears at www.example.com/mobile-application but when project is compiled and run in real Android device it works out of the box. Play button works but not Download button(minor problem for me).
> 0 votes

---
Tags: 7, javascript
---


# Question
Title: Alter core "Configure Block" contextual link path or text?
We're using blocks and Beans throughout a very large site. The issue is that the contextual links have "Configure Block" which takes you to the block configuration page for that particular block, and another contextual links labeled "Edit Block".

The "Edit Block" link is the correct link as it brings the user to the Bean admin page for that block with fields and settings.

I'm not able to find the hook to alter that main "Configure Block" link or text.

I've tried:

hook\_menu\_link\_alter() hook\_contextual\_links\_view\_alter() hook\_menu\_contextual\_links\_alter() hook\_block\_view\_alter()

None of these seem to expose the "Configure Block" text or URL.

I've also tried the Custom Contextual Link module, but it doesn't allow you to edit or remove this link.

I am not interested in hiding it with styling. That isn't fixing the problem. I want to programmatically alter that one contextual link.

# Answer
> 0 votes
I was able to accomplish this for Panels by using the following:

```
/**
 * Implements preprocess_panels_pane().
 */
function hook_preprocess_panels_pane(&$vars) {
  if ($vars['pane']->type == 'panels_mini') {
    unset($vars['admin_links']);
    $vars['admin_links'] = '';
  }

  // Load the currently logged in user.
  global $user;

  if ($vars['pane']->type == 'block') {

    // Check if content array is set
    $type = isset(array_keys($vars['content'])[0]) ? array_keys($vars['content'])[0] : '';

    // Check if the pane subtype is a bean
    if (strpos($vars['pane']->subtype, 'bean-') !== false) {

      // Get path of bean edit link
      $path = isset(array_keys($vars['content']['bean'])[0]) ? array_keys($vars['content']['bean'])[0] : '';
      unset($vars['admin_links']);

      // Check if the user has the 'administrator' or 'content editor' role.
      if (in_array('administrator', $user->roles)) {
        $vars['admin_links'] = '<div class="contextual-links-wrapper"><ul class="contextual-links"><li class="bean-  last"><a href="/block/' . $path . '/edit?destination=">Edit Block</a></li></ul></div>';
      } else {
        $vars['admin_links'] = '';
      }
    }
  }
}

```

---
Tags: 7, navigation
---


# Question
Title: How to get rid of "Designed by" in the theme?
I am using the business theme in Drupal 7. I was wondering how do I get rid of the "Designed by Devsaran." in the bottom right corner?

# Answer
You need to edit the `page.tpl.php` file and remove the line in the footer:

http://cgit.drupalcode.org/business/tree/templates/page.tpl.php?h=7.x-1.x

Its at the bottom.

```
  <div id="copyright">
    <?php if ($footer_copyright): ?>
      <?php print $footer_copyright; ?>
    <?php endif; ?>
    <?php if (theme_get_setting('footer_credits')): ?>
      <span class="credits"><?php print t('Designed by'); ?>  <a href="http://www.devsaran.com">Devsaran</a>.</span>
    <?php endif; ?>
  </div>

```

However, it seems like there is a theme setting you can just uncheck as well, under Admin \> Appearance \> Business \> Settings called 'Footer Credit'.
> 3 votes

---
Tags: 7, theming
---


title: Remove "submitted by"

text:
# Question
Title: Remove "submitted by"
How can I remove "submitted by"? I already try to remove it on admin/structure/types/manage/page, but i still see "Submitted by...".

>

# Answer
> 2 votes
You need to check your node and page level twig templates to make sure it is not outputting the submitted by information, despite what the setting is here. There could also be a Views block outputting this information in one of the regions, which would ignore the setting as well.

---
Tags: theming
---


# Question
Title: Default to original language in nodes list
I set up a multilingual blog with Drupal 8 (in English and Chinese), I want to list articles according to current language in the front page.

However, if an article does not has an translation in the current language, I want it to default to **the original untranslated version(whatever language)**, with a hint like "This content is not available in Chinese, we are showing the original article in English."

Assuming that I have 3 blog articles (nodes), with or without translation:

* Article 1 (original language: English; translated to: Chinese)
* Article 2 (original language: Chinese; translated to: English)
* Article 3 (original language: English)

When a user visits the English front page at `example.com/en`, they will see:

* Article 1 (in English, original)
* Article 2 (in English, translated)
* Article 3 (in English, original)

which is the default behaviour of Drupal 8.

---

Now, when a user visits the Chinese front page at `example.com/zh-hans`, **I would like them to see**:

* Article 1 (in Chinese, translated)
* Article 2 (in Chinese, original)
* Article 3 (**in English, with a hint**)

However, Drupal 8 out of the box will display:

* Article 1 (in Chinese, translated)
* Article 2 (in Chinese, original)

---

I tried editing the front page as it is a view in Drupal 8, but with the filters in view I could not achieve this.

(Filters in view)

Do I need to implement a custom filter for the front page view? Please suggest where should I start, I have no idea how to do this.

Thanks!

# Answer
> 1 votes
See the solution to How do I get Views content items in "my language" but fall back to "default" if the content isn't translated? whether it helps just by configuring in admin. It seems to solve the same problem.

Unfortunately, I have the same problem, and I can't get the solution described there to work. Reading all the issues linked in meta Make multilingual views work, it seems to me that there is no built-in solution. I tried to implement a `hook_views_post_execute()` and to filter the `ViewExecutable $view` manually, like in the following, but it did not work - either still shows multiple translations per entity, or entities are missing:

```
# File modules/contrib/modulename/modulename.module
# Enabled in admin/extend
function modulename_views_post_execute(ViewExecutable $view)
{
  $contentLangcode = \Drupal::languageManager()->getCurrentLanguage(LanguageInterface::TYPE_CONTENT)->getId();

  # trying either one of:
  # $Filtered = filterLangcodeOrEn($contentLangcode, $view->result);
  $Filtered = filterNodeOnce($view->result);

  $view->result = $Filtered;
  $view->total_rows = count($Filtered);
}

function filterNodeOnce($rows)
{
  $Nodes = array();
  foreach ($rows as $row) {
    $Nodes[$row->nid] = $row;
  }

  return array_values($Nodes);
}

function filterLangcodeOrEn($contentLangcode, $rows)
{
  # group by nid
  $EntitiesLangcodesRow = array();
  foreach ($rows as $row) {
    $EntitiesLangcodesRow[$row->nid][$row->node_field_data_langcode] = $row;
  }

  # select
  $Filtered = array();
  foreach ($EntitiesLangcodesRow as $LangcodesRow) {
    if (isset($LangcodesRow[$contentLangcode])) {
      $Filtered[] = $LangcodesRow[$contentLangcode];
    }
    else if (isset($LangcodesRow["en"])) {
      $Filtered[] = $LangcodesRow["en"];
    }
  }
  return $Filtered;
}

```

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


# Question
Title: In the Encrypt module, can I switch between phpseclib and mcrypt assuming I keep the Key Provider Settings in place?
A client uses the encrypt module as the basis to encrypt some database cells. The current server is RHEL 6/PHP 5.3. They're upgrading to RHEL 7 but will push to PHP 5.6.

The Encrypt module asks for either a method:

* PHP Secure Communications Library (phpseclib)
* Mcrypt AES (CBC Mode)
* None

Currently the client had the second choice selected. However, the `php-mcrypt` package doesn't exist in PHP 5.6, and from my understanding, it itself hasn't been updated in a while. The alternative of installing the Libraries Module and cloning down a copy of `phpseclib` from `git clone https://github.com/phpseclib/phpseclib.git` seems more palatable at the moment.

**Question**: can I switch out to using `phpseclib` assuming I keep the Key Provider Settings in place?

# Answer
No. You cannot just switch out the encryption methods. **Mcrypt AES (CBC Mode)** pads the input and also prepends two salts and an IV as well other information like the HMAC for authentication in it's output. `phpseclib` does none of this. Here are some examples:

```
encrypt('all your base');
// $text = "TUsE3Fwzvj6MT41ritVO/zUuJ/qWNmZJIBU3euDEX9iDMb3IqMyTJEFwssW/SI/GZ8ce/HxqrqPFWGzTNC0d7UZUtRjr2JReoqaCqw18GHyGhbjqr1zZbr/MCIT1rENM";

encrypt('all your base', array(), 'phpseclib');
// $text = "1r/WWYiCW9icZ93iUxStMQ==";

```

You can actually rewrite the existing `mcrypt` plugin to use `phpseclib` instead. You wouldn't necessarily need the HMAC stuff—it's there for added benefit but you can just skip it. But you likely could make a pain-free transition.

For example, replacing the existing decryption code in `_encrypt_encryption_methods_mcrypt_aes_cbc()`:

```
// Initialize for decryption.
mcrypt_generic_init($mcrypt, $ekey, $iv);

// Decrypt the data.
$processed_text = mdecrypt_generic($mcrypt, $text);

// Terminate decryption.
mcrypt_generic_deinit($mcrypt);

// Remove any padding.
$pad = ord($processed_text[strlen($processed_text) - 1]);
$processed_text = substr($processed_text, 0, -$pad);

// Close the Mcrypt handle.
mcrypt_module_close($mcrypt);

```

With this rewrite:

```
$path = libraries_get_path('phpseclib');
require_once $path . '/Crypt/AES.php';
$aes = new Crypt_AES();
$aes->setIV($iv);
$aes->setKey($ekey);
$processed_text = $aes->decrypt($text);

```

Returns the correct plain-text given the original `mcrypt` encryption ciphertext. At least, it should. I've got `mcrypt` on my system and so `phpseclib` is probably using it, but it should "just work" for you.

Oh yeah, FYI, use `phpseclib` 1.x. As the 2.x branch will not work.
> 1 votes

---
Tags: theming
---


# Question
Title: Can you create a tpl based on view page url? (Drupal 7)
There's a view page which takes in taxonomy terms to display related content topic/Easter, where Easter is the term. Now in this example, I would like to create a separate TPL for that page topic/Easter. Is that possible?

# Answer
You can use Taxonomy Views Integrator module. Create separate views for this taxonomy term page and set it. And You can create separate template for this views.

Or You can use **hook\_preprocess\_views\_view** for creating views template for custom view and custom view display. For ex.

```
     function THEMENAME_preprocess_views_view(&$variables) {
      $view = $variables['view'];
      if($view->name == 'your_view_name' && $view->current_display == 'main_page')
   {
        $variables['theme_hook_suggestions'][] = 'views_view__viewname';
      }

```

Your template will be views-view--viewname.tpl.php in this case
> 0 votes

# Answer
My solution does include Taxonomy Views Integrator module. You will need to start off with creating a view to replace default taxonomy term view. Once that's done, you can edit view (Other section \> Theme) and see what templates are being used. You can then make a copy of those templates and make changes based on your requirements. See screenshots below.

Please ensure that you select template specific to view otherwise the changes will be applied to all the views. In my example (Screenshot), I will create a view template like views-view--articles-admin--page.tpl.php to specifically target this view. If I make changes to views-view.tpl.php template this change will be applied to all views.

Let me know how you go.
> 0 votes

---
Tags: 7, views, theming
---


title: Parameters in URL go away after Login

text:
# Question
Title: Parameters in URL go away after Login
On my Drupal 7 site, I am using the Prepopulate module to pre-fill a field based on a parameter in the URL for authenticated users.

An example of a URL is:

> http://website.com/node/add/content-type?edit\[field\_test\]\[value\]=123456

When accessing the URL as an anonymous user, Context shows the login block.

After logging in, it redirects the user back the same URL BUT without the prepopulate info.

Simply something like:

> http://website.com/node/add/content-type

Is there anything that can be done so that the information in the URL is not lost after logging in?

# Answer
> 0 votes
I have found a solution.

Instead of the following URL that was posted originally:

> http://website.com/node/add/content-type?edit\[field\_test\]\[value\]=123456

I will send the User to the Login Page but with the Destination paramater set to that URL so that it retains the prepopulate data.

This is an example url:

> http://website.com/user/login?destination=node/add/content-type?edit\[field\_test\]\[value\]=123456

# Answer
> 1 votes
You can use a destination parameter in URL to retain those values. There is a good read on drupal.org (https://www.drupal.org/docs/7/theming/overriding-themable-output/how-to-add-a-destinationurl-to-the-request-new-password)

Let me know if you need any help.

---
Tags: 7, users
---


# Question
Title: Why does drupal_add_css and drupal_add_html not always work?
I have a drupal\_add\_css in my template.php, following a series of drupal\_add\_html calls.

The drupal\_add\_html calls, adding meta tags, work except for the first one (regardless of the order I put them in) which is for a meta generator tag, which the jquery form library I'm using requires. I've also tried getting it in by doing the call for markup rather than a tag...same...it doesn't appear.

The drupal\_add\_css call does not add the css file (I'm not aggregating), even if I specify the full url. If I add the css file to the list in the .info file, it appears, but I only want the file for a specific page, so I'm doing in the pre-render. When the file is not added, there is no reference to it in the page resources or network list as 404. It **does** get referenced in the js behaviors object that Drupal inserts.

# Answer
It turns out that it's a known problem that core provides a generator metatag without an option of replacing or disabling it. The metatag module will do this, or removing it in a custom module via hooking html\_head\_alter.

I'm not quite certain why drupal\_add\_css would not work, but adding it with drupal\_add\_html\_head worked.
> 0 votes

---
Tags: 7, theming
---


# Question
Title: How to set different themes for multiple domains
I am developing a multi-domain site with same code base and single data base. I am trying to set themes for multi domains which was previously supported by domains theme module in Drupal 7. Don't know how to achieve solution for this. Please help me for this.

# Answer
> 1 votes
I got an solution that my colleague suggested through a contrib module. But, not yet used it perfectly for themes.

`Steps for getting it are as follows -` 1. go to

> www.github.com and sign up for free. 2. Take a git clone of the https://github.com/agentrickard/domain.git in modules folder in your drupal code base. 3. Extend the module and try it out.

# Answer
> 1 votes
Here it is: https://www.drupal.org/sandbox/aloknarwaria/2691703 there is a module for that in drupal 8 if you are using domain module, but it is in sandbox mode currently.Go the code and explore.

# Answer
> 0 votes
domain\_theme\_switch Domain Theme Switch module for Drupal 8 community users.

* This module provide the administrator interface to manage the theme.
* The interface provide very basic setting to manage the theme against each domain.

---
Tags: theming, 8
---