# Question
Title: How do I get an array of all entitytypes of a specific entity?
Hey there what I'm trying to do is to get all entity type ids from my custom config entity. To load them all.

Example give:

I have an entity 'foo' and I create a new 'foo' named 'bar1' and another 'bar2' and so on how do I get those ids programmatically?

Better question

How do I get all entity\_type\_ids(or bundles dunno don't found a good entity hirarchie doku yet :( ) of an entity for example all types of the node entity?

# Answer
Do you mean "How do I get an array of all entities of a specific entity type?"

```
$ids = \Drupal::entityQuery($entity_type_id)->execute();

```

Because an entity can only be of one type, to get the id of the entity type:

```
$entity_type_id = $entity->getEntityTypeId();

```

**Answer to the edited question:**

"How do I get an array of all bundle id's of a specific entity type?"

```
$bundles = \Drupal::entityManager()->getBundleInfo($entity_type_id);

```

Or all content types, which are bundles of the entity type `node`:

```
$content_types = \Drupal::entityManager()->getBundleInfo('node');

```

This function will be moved to it's own class before Drupal 9:

```
\Drupal\Core\Entity\EntityTypeBundleInfoInterface::getBundleInfo()

```

This is provided as a service:

```
$content_types = \Drupal::service('entity_type.bundle.info')->getBundleInfo('node');

```
> 8 votes

# Answer
If your entity type was an 'article' for example, you could perform

```
$query = \Drupal::entityQuery('node')
    ->condition('type','article');
$nidlist = $query->execute();

```

$nidlist would then be an array that contains all the IDs in the results in the query.
> 1 votes

---
Tags: 8
---


# Question
Title: What is the need to have the Unicode class?
Why is it necessary to have the `Unicode` class?

What does `Unicode::strtoupper()` or `Unicode::strtolower()` do that cannot be done just using native the PHP functions `strtoupper()` or `strtolower()`?

# Answer
> 9 votes
The reasons to have its own replacement of `strtoupper` and `strtolower()` is to support multi-bytes string in those sites where the Multibyte String extension is installed, and in those sites where that extension is not installed.

`strtoupper()` and `strtolower()` don't support multi-byte strings. Even in the case Drupal would not try to use the *Multibyte String* extension when installed, `Unicode::strtoupper()` and `Unicode::strtolower()` would not be reduced to simply calls to `strtoupper()` and `strtolower()`. Their code would probably be the following one.

```
public static function strtoupper($text) {
  // Use C-locale for ASCII-only uppercase.
  $text = strtoupper($text);
  // Case flip Latin-1 accented letters.
  $text = preg_replace_callback('/\xC3[\xA0-\xB6\xB8-\xBE]/', '\Drupal\Component\Utility\Unicode::caseFlip', $text);
  return $text;
}

```

```
public static function strtolower($text) {
  // Use C-locale for ASCII-only lowercase.
  $text = strtolower($text);
  // Case flip Latin-1 accented letters.
  $text = preg_replace_callback('/\xC3[\x80-\x96\x98-\x9E]/', '\Drupal\Component\Utility\Unicode::caseFlip', $text);
  return $text;
}

```

If Drupal required the *Multibyte String* extension to be present, then `Unicode::strtoupper()` and `Unicode::strtolower()` would not be necessary, since Drupal would use directly `mb_strtoupper()` and `mb_strtolower()`.

That is not different from what happened in previous versions, except they implemented `drupal_strtouppper()` and drupal\_strtolower(). If you look at the code, it is not much different.

```
function drupal_strtoupper($text) {
  global $multibyte;
  if ($multibyte == UNICODE_MULTIBYTE) {
    return mb_strtoupper($text);
  }
  else {
    // Use C-locale for ASCII-only uppercase
    $text = strtoupper($text);
    // Case flip Latin-1 accented letters
    $text = preg_replace_callback('/\xC3[\xA0-\xB6\xB8-\xBE]/', '_unicode_caseflip', $text);
    return $text;
  }
}

```

```
public static function strtoupper($text) {
  if (static::getStatus() == static::STATUS_MULTIBYTE) {
    return mb_strtoupper($text);
  }
  else {
    // Use C-locale for ASCII-only uppercase.
    $text = strtoupper($text);
    // Case flip Latin-1 accented letters.
    $text = preg_replace_callback('/\xC3[\xA0-\xB6\xB8-\xBE]/', '\Drupal\Component\Utility\Unicode::caseFlip', $text);
    return $text;
  }
}

```

---
Tags: 8
---


# Question
Title: How to reduce the delay in sending email notifications about new content?
I've set up a workflow rule to send an email to all users of a role when new content is saved. I've tested it with three test users and have noticed that the email takes quite a while to actually be delivered.

I thought it was related to cron, so, I changed the setting to ***Run cron every 1 hour***. The emails are eventually delivered, but, not in a timely fashion. It seems like they're delivered according to the cron schedule, but, I'm not sure.

I'd like to have the emails sent as soon as possible when the content is posted. Some of the content can be time sensitive. Is there any way to speed the delivery of the email?

# Answer
> 1 votes
As an alternative to what you're trying to get to work, you might want to consider using the Rules module. Below is a summary of how you can get this to work:

1. Introduce an additional flag to allow "flagging" these (new) nodes by all users "*with the role that should receive these eMails*" (as in your question). Let's assume you label that flag as "eMail notification outstanding" (to indicate that something still needs to happen to send that eMail later on).
2. Create a rule to flag the newly saved content, using the new flag (from step 1) for each of the users "*with the role that should receive these eMails*". A possible approach for this is to build a list of these users using Views bulk operations (VBO) module, which is then processed by the rule to actually flag this content by those users.
3. Use the Views and the Views bulk operations (VBO) modules to create a VBO list of all flagged nodes (flagged by the new flag in step 1), sorted by flagging date (oldest first), and limit the results to the first X users only (pick a value for X that fits your needs).
4. Create a new Rules Component that "loads the VBO list" (from step 3) and add a loop to that rule to perform these Rules Actions:

* eMail each of the users in that VBO list.
    * unflag (using flag from step 1) the node (for the user for which you just produced an eMail). This to indicate that the eMail notification was completed (no longer outstanding).
    * In that same rule, as the very last Rules Action, add an action to reschedule the exectuion of the same rule within Y minutes or hours (pick a value for Y that fits your needs).
5. Use the Rules UI to manually trigger the very first execution of that self-rescheduling Rules Component (from step 4.).

Using the above approach, every Y minutes (or hours), Rules will notify X users "as requested". Obviously, you'd have to think a bit about what the best values for X and Y would be in your case. E.g. if you have thousands of users in that role (to receive the eMails), you've to be careful to prevent that your eMails would be considered as spamming. However, if you only have a few users in that role, you should be OK with a low value of Y (even like every 5 minutes or so?).

---
Tags: 7, cron, emails
---


# Question
Title: features for same content type but different structure collide in multi site
I have a multi site and one content type has different fields in it than the same content type in a different site.

When I make a feature for this content type, they conflict with each other even though I have not enabled one of them in the other multi site.

Is it possible to have different features that don't conflict within a multi site if content type is the same but with different fields?

# Answer
> 0 votes
Diana,

Why not move the features into their specific site directories? Then they dont 'see' each other in the other sites.

For example:

Feature 1 is located in sites/site1/modules/feature1

Feature 2 is located in sites/site2/modules/feature2

Then they are "unaware" of each other.

Would this work?

---
Tags: 7, features, multi-sites
---


# Question
Title: Unable to debug drush command using xdebug with batch api
I have been debugging drush commands with xdebug and my IDE (currently PHPStorm 7) for a while, but I have been noticing that there are certain commands that die whenever I have the dubegger enabled in the IDE. From what I can tell, it's commands that do batch processing and therefore call drush\_backend\_batch\_process(). In tracking it down as far as it will let me with the debugger, it looks like it dies in \_drush\_backend\_proc\_open().

An off the shelf example is the solr-index command in the apachesolr module. I can debug up to the point where drush\_backend\_batch\_process() is called, but it never returns from that call.

Is this a known issue with xdebug on the command line with drush with no way around it? Or is there something I can do in my configuration?

Thanks.

# Answer
> 1 votes
You're debugging your script using IDE which require valid `xdebug.idekey` to be present in the session which probably isn't passed correctly to the forked process.

It's probably the bug of XDebug (see: #938) which doesn't debug well the forked processes.

I assume you've `xdebug.remote_port` working correctly and there is no any communication issue. Remote debugging generates log file (defined by `xdebug.remote_log`), so you should check further debugger communications details there.

As for workaround, you should debug your script manually by calling the functions: `xdebug_start_trace()` and `xdebug_stop_trace()`.

In case debugging on demand won't work with forked processes, enable `xdebug.auto_trace`, restart Apache, so all forked processes can be debugged properly which will generate huge trace file which you can analyze (defined by `xdebug.trace_output_dir`/`xdebug.trace_output_name`).

Check my `xdebug.ini` for suggestions, especially these settings are useful to see all the details:

```
; Data
xdebug.default_enable = 1           ; bool: The stacktraces will be shown by default on an error event.
xdebug.collect_vars = 1             ; bool: Gather information about which variables are used in a certain scope.
xdebug.show_local_vars=1            ; int: Generate stack dumps in error situations.
xdebug.collect_assignments=1        ; bool: Controls whether Xdebug should add variable assignments to function traces.
xdebug.collect_params=4             ; int1-4: Collect the parameters passed to functions when a function call is recorded.
xdebug.collect_return=1             ; bool: Write the return value of function calls to the trace files.
xdebug.var_display_max_children=256 ; int: Amount of array children and object's properties are shown.
xdebug.var_display_max_data=1024    ; int: Max string length that is shown when variables are displayed.
xdebug.var_display_max_depth=5      ; int: How many nested levels of array/object elements are displayed.
xdebug.show_mem_delta=0             ; int: Show the difference in memory usage between function calls.
xdebug.show_exception_trace=0       ; bool: Show a stack trace whenever an exception is raised.
xdebug.max_nesting_level=200        ; int: Controls the protection mechanism for infinite recursion protection.

```

If XDebug still won't work, then consider using `phpdbg` instead.

For suggestions how to debug Batch API process, see: How to debug Batch API more efficiently?

# Answer
> 0 votes
I'm not sure if this is the issue or not; but I THOUGHT I had this issue while running migrations with Drush into Drupal 8 from command line. Would just die and hang on Drush's proc\_close.

Apparently, increasing the number of debug connections mattered, inside of my IDE (PHPStorm).

https://confluence.jetbrains.com/display/PhpStorm/Simultaneous+debugging+sessions+with+PhpStorm

Perhaps since Batch API makes multiple requests, this is necessary?

---
Tags: drush
---


title: how to insert simple gmaps in a block

text:
# Question
Title: how to insert simple gmaps in a block
How can I insert a simple google map in a block?

I have a contact page with a contact-form (that one can fill in and send), and I want to add to this page a google map.

thanks alot in advance!

# Answer
> 4 votes
There are many ways you can do this.

1. Go to maps.google.com, type in the address, get the link, then click the customize and preview embedded view. A popup should appear. Select the map size you want. Copy the html code and go to structure -\> blocks -\> add block, paste your code and select full html filter. And add your block to where you want it
2. Download the gmaps module and use it. By default is has a block created called location map

> The GMap module provides an interface to the Google Maps API within Drupal. It integrates with the Location module to provide users a clickable map for entering latitude and longitude, as well as to display maps of Drupal nodes and users. GMap can be used to create interactive maps with various map markers and content in map bubbles, taking advantage of Drupal's other content management features. The module also provides a Views display plugin which allows users to display the results of a view on a Google map.

# Answer
> 1 votes
With regards to the previous answer above; There has been some changes to the Google maps GUI, thus in other to access the "embed link" option, you will have to navigate as follows;

1. Click the little gear option to the right had corner of the screen
2. Then you will see the option "share and embed maps" option

# Answer
> 0 votes
I'm not sure if you can do this with a block, but I have an iframe field attached to my basic page. Then adding the Google Maps API is easy with this doc: https://developers.google.com/maps/documentation/embed/guide. Copy the line with your API key `https://www.google.com/maps/embed/v1/place?key=YOUR_API_KEY&q=Space+Needle,Seattle+WA` to the Iframe URL, and it should work!

---
Tags: google-maps
---


# Question
Title: How do I get multiple references from the autocomplete?
I am using the following form element.

```
$form['group']['one'] = array(
    '#type' => 'entity_autocomplete',
    '#title' => t('Tags'),
    '#target_type' => 'user',
);

```

I submit values similar to the following ones.

> user00 (0), user01 (1), user02 (2), user0x (3)

What I receive from the form is the following:

> one = 3

It only picks up the last ID.

How can I get all the references entered in the form element? How does the form element handle the references to not existing entities?

# Answer
The comma is used to separate multiple references, but looking at the code in `Name::valueForm()` I would say the form element needs to use a property more.

```
  $form['value'] = array(
    '#type' => 'entity_autocomplete',
    '#title' => $this->t('Usernames'),
    '#description' => $this->t('Enter a comma separated list of user names.'),
    '#target_type' => 'user',
    '#tags' => TRUE,
    '#default_value' => $default_value,
    '#process_default_value' => $this->isExposed(),
  );

```

Settings `#tags` to `TRUE` makes the the form element accept multiple values.

The format of the values assigned to the form element is evident in `EntityAutocomplete::validateEntityAutocomplete()` (its validation handler), which uses this code.

```
  $input_values = $element['#tags'] ? Tags::explode($element['#value']) : array($element['#value']);

  foreach ($input_values as $input) {
    $match = static::extractEntityIdFromAutocompleteInput($input);
    if ($match === NULL) {
      // Try to get a match from the input string when the user didn't use
      // the autocomplete but filled in a value manually.
      $match = static::matchEntityByTitle($handler, $input, $element, $form_state, !$autocreate);
    }

    if ($match !== NULL) {
      $value[] = array(
        'target_id' => $match,
      );
    }
    elseif ($autocreate) {
      /** @var \Drupal\Core\Entity\EntityReferenceSelection\SelectionWithAutocreateInterface $handler */
      // Auto-create item. See an example of how this is handled in
      // \Drupal\Core\Field\Plugin\Field\FieldType\EntityReferenceItem::presave().
      $value[] = array(
        'entity' => $handler->createNewEntity($element['#target_type'], $element['#autocreate']['bundle'], $input, $element['#autocreate']['uid']),
      );
    }

```

The form element value is an array of item whose `target_id` key is an object of the requested entity.

(From that code, it is also clear that `#tags` makes the form element accepts multiple references separated by commas.)

As for the using reference that aren't found, you can decide what the autocomplete does by setting `#validate_reference`: If you set it to `TRUE`, and `#autocreate` is not set to `TRUE`, the autocomplete will accept only existing references.
> 7 votes

---
Tags: 8, entities, ajax
---


# Question
Title: Why is my sub-menu not loading in main menu?
```
<div class="row" id="mainNav">
 <?php print theme('links__system_main_menu', array(
    'links' => $main_menu,
    'attributes' => array(
      'class' => 'menu',
    ),
  )); ?>
</div>

```

I've used the above code to load main menu in page template. This code fails to display submenus. Please suggest.

# Answer
For Drupal 8:

You must configure the block settings of Main navigation or any other menu. The default setting for *Maximum number of menu levels to display* is set to 1. Change this setting to **Unlimited** to see children displayed.
> 4 votes

# Answer
1. Go to `/admin/structure/menu/manage/main-menu`
2. Edit your parent link
3. Enable "Show as expanded" checkbox
4. (Repeat the same for all the parent links)
5. Go to the front page and see the main menu expanded.

**Update:**

You can use next code to render menu:

```
 $main_menu = variable_get('menu_main_links_source', 'main-menu');
 $tree = menu_tree($main_menu);
 print render($tree);

```
> 4 votes

---
Tags: theming, routes
---


# Question
Title: How to make different slogan for each content type?
I have several content types, I want the slogan that shows up on the page to be different for each slogan. Is this possible?

# Answer
You can use a preprocess function:

```
function mymodule_preprocess_page(&$variables) {
  if (isset($variables['node'])){
    switch ($variables['node']->type) {
      case 'my_content_type2':
        $slogan = "my super slogan 1";
        break;
      case 'my_content_type2':
        $slogan = "my super slogan 2";
        break;
      default:
        $slogan = "my super slogan 3";
    }
    $variables['site_slogan'] = $slogan;
  }
}

```

In this case, you preprocess the page before it is sended to the template engine. More exactly, you change the 'site\_slogan' variable according to the node type.

You can add this function in a module: in this case replace "mymodule" in the function's name by the name of your module

or you can add this function in the "template.php" file of your theme folder: in this case replace "mymodule" in the function's name by the name of your theme.
> 4 votes

---
Tags: 7, nodes
---


# Question
Title: How do I add a node from a view to user profile field?
I have list of courses of course content type in a view. I want to add "add course" button with every listing of node in view. When a user is logged in he can add a course to its profile information. so that profile information shows all the added courses from view in the profile. For example: List of courses taken by user. I have used entityreference module to attach nodes to user profile. But I have no idea how to do it from a view listing.

How do I add a node from a view to user profile field?

# Answer
You can simply add a `Global: text area` in views header and input below HTML in the content.

```
<a href="/node/add/course">Add Course</a>

```
> 0 votes

---
Tags: 7, views, nodes, users
---


title: How can I get sub-directory names?

text:
# Question
Title: How can I get sub-directory names?
How can I get the list of the folders inside public:// (or sites/default/files) location?

I have to show all the folder names to users, so that they can choose the subdirectory where they prefer to upload their documents.

I tried with the following code, but it returns the path together the folder name.

```
$directories = glob($somePath . '/*' , GLOB_ONLYDIR);

```

The value returned from my code is similar to the following one.

```
    [0] => sites/default/files//folder_name
    [1] => sites/default/files//new1
    [2] => sites/default/files//newfolder

```

# Answer
> 1 votes
You can ready the directory using read() function and `drupal_realpath('public://')` will give you the actual path to the public files folder.

```
$path = drupal_realpath('public://');
$dirs = array();
// directory handle
$dir = dir($path);

while (false !== ($entry = $dir->read())) {
    if ($entry != '.' && $entry != '..') {
       if (is_dir($path . '/' .$entry)) {
            $dirs[] = $entry;
       }
    }
}

echo '<pre>';print_r($dirs);echo '</pre>';

```

# Answer
> 1 votes
I was going to suggest to use `file_scan_directory()`, but it returns only files. I am then going to suggest a modified version.

```
function scan_for_directories($dir, $mask, $options = array()) {
  // Merge in defaults.
  $options += array(
    'nomask' => '/(\.\.?|CVS)$/',
    'recurse' => FALSE,
    'key' => 'filename',
  );

  $options['key'] = in_array($options['key'], array('uri', 'filename', 'name')) ? $options['key'] : 'uri';
  $dirs = array();
  if (is_dir($dir) && $handle = opendir($dir)) {
    while (FALSE !== ($filename = readdir($handle))) {
      if (!preg_match($options['nomask'], $filename) && $filename[0] != '.') {
        $uri = "$dir/$filename";
        $uri = file_stream_wrapper_uri_normalize($uri);
        if (is_dir($uri)) {
          if ($options['recurse']) {
            // Give priority to files in this folder by merging them in after any subdirectory files.
            $dirs = array_merge(file_scan_directory($uri, $mask, $options), $dirs);
          }
          if (preg_match($mask, $filename)) {
            $dir = new stdClass();
            $dir->uri = $uri;
            $dir->filename = $filename;
            $dir->name = pathinfo($filename, PATHINFO_FILENAME);
            $key = $options['key'];
            $dirs[$dir->$key] = $dir;
          }
        }
      }
    }

    closedir($handle);
  }

  return $dirs;
}

```

Call it as `$dirs = scan_for_directories('public://', '/.*/');` and it will returns a list of all the directories contained in public://; call it as `$dirs = scan_for_directories('public://', '/.*/', array('recurse' => TRUE));`, and it will return you the directories inside over directories.
By default, the returned array has the following format.

```
'directory name' => object with the uri, filename, and name properties

```

---
Tags: 7
---


# Question
Title: Create URL aliases for Entityform submissions
I have the **Entityform** module installed on a Drupal 7 portal and I've created a new entityform type (let's call it "Preview").

When I land on the list of "Preview" submissions, each submission View link points to `[host]/[drupal_base]/entityform/[entityform_id]`

What I'd like to get is to change "entityform" term in that url path with something like "preview" term, so that I'll have `[host]/[drupal_base]/preview/[entityform_id]`

I tried to define a URL alias from the admin configuration panel, but from what I've understood, I can't define an alias with a dynamic `[entityform_id]` (maybe using a kind of placeholder). Am I wrong about this?

I'm not so skilled in Drupal, so I wonder if there's a way to achieve that result?

# Answer
> 1 votes
*Note: This answer only applies specifically for the input form (I misunderstood the question above)*

I was able to accomplish this by using simply modifying the entityform made configuration.

* Go to /admin/structure/entityform\_types
* Click on the *edit* link for the entity form you wish to change
* Scroll to the bottom and in the *URL path settings* set the specific custom paths that you wish
* Save

It's that easy and it works for both the preview and the actual form :)

# Answer
> 1 votes
You can dynamically create URL aliases for Entityform Type submissions by using the contributed Pathauto and Pathauto Entity modules.

Here's how:

1. Download, install and enable the **Pathauto** and **Pathauto Entity** modules (if they aren't already)
2. Within Pathauto, enable the *Entityform Submission* entity type at:

Administration \> Configuration \> Search and Metadata \> URL Aliases \> Entities `admin/config/search/path/entities`
3. Create a new default Pathauto pattern for Entityform Submissions using the following replacement patterns:

`[entityform:type:label]/[entityform:entityform-id]`

> *The `[entityform:type:label]` token is the **key ingredient** and corresponds to the Entityform Type's name or label (e.g. "Preview") and will be lowercased and hyphenated in the alias (e.g. `/preview/1234`).*
4. Save the Pathauto configuration

Once this is complete, all new Entityform Type submissions will no longer use the default path registered by the Entityform module (i.e. `/entityform/1234`) and instead use the new alias pattern we defined (i.e. `/preview/1234`).

You can use the "Bulk Update" feature in Pathauto to add/update/delete any pre-existing Entityform Submissions aliases.

# Answer
> 0 votes
Pathauto\_entity

> You can select the entities to be enabled in Home » Administration » Configuration » Search and metadata » URL aliases » Entities tab, and they will appear in Home » Administration » Configuration » Search and metadata » Patterns, where you can define the desired aliases for them.
>
> Make sure to define those patterns before trying to create new URL aliases (including bulk update), as otherwise they won't be created.
>
> If the Entities tab does not appear, it means that the site has no custom entities defined, apart from the standard content types, taxonomies, comments and users.

---
Tags: 7, uri, entities
---


# Question
Title: Entityfrom spam protection module without captcha
Is there a module which I can use with entity forms without needing captcha field?

# Answer
You may be looking for Hidden CAPTCHA.

Even though you need the CAPTCHA module for this, Hidden CAPTCHA module will not display any captcha field and you don't absolutely need to have a human enter a text, number, etc.
> 2 votes

# Answer
For spam protection on Entityforms, you can use Honeypot and Honeypot Entityform to add an invisible "honeypot" field to your Entityform Types.

It's a simple and unobtrusive alternative to the CAPTCHA module and effortless to configure.
> 0 votes

# Answer
You can also use the Mollom module, which has native integration with Entityforms and offers spam protection among many other features.
> 0 votes

---
Tags: entities
---


# Question
Title: Allowing content access only though aliases and views
I'm building a site in Drupal 8 that will have complex content best viewed using views. The basic pages should use nice and clean URL aliases.

Is there a way to stop the visitor from accidentally using **/node/x** in the URL and only allow accessing the views and pages that have aliases and organised in the website menus?

# Answer
> 1 votes
Yes, in Drupal 7 this functionality was covered under the Global Redirect module. It has since been merged in the Drupal 8 version of Redirect.

Under the Redirect settings (**/admin/config/search/redirect/settings**), the **Global Redirect** section contains options to enable alias, non-clean, & canonical redirecting. This will enable you to redirect any requests from **/index.php?q=node/X** or **/node/X** to **/my-canonical-content-alias**.

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


# Question
Title: How can I set site.com/node/1 into site.com (clean)?
I am trying to get my site as site.com and when I type the URL, I get site.com/node/1.

How can I get this done? If you can specify step by step, highly appreciated.

AB

# Answer
I think @JimmyKo and @Gulok, misunderstood the question OR **I myself misunderstood the question**(*If so comment me I will delete the answer*).

As stated in the question,

> I am trying to get my site as site.com and when I type the URL, I get site.com/node/1.

The issue is user want site.com as his Front-Page but when he types site.com he is redirected to site.com/node/1.

If this is the case. You need to set your home page. Now to set the home page, you need to go `Configuration/Site information` for D7 and `Configuration/Basic site setting` for D8, there you set the front page path as shown in following images.

For D7 case,

>

For D8 case,

>

---

**Now Reverse Case,** In case I misunderstood the question

If you want to make your front page to some node like node/1, Go the same path as mentioned above and put your path there as shown in follwoign image. NOTE: There is a difference between D7 and D8 path which is `'/'`, you can see in following images.

For D7 case,

>

For D8 case,

>

---

**Other case(Less likely):** Have downloaded other Font-page creating module or are you using panel which provides the option of making any panel a front-page. If that is the case, those modules are overriding this default setting, Hence you have to modify accordingly.
> 1 votes

# Answer
I guess you are asking for the way to set front page.

You can visit **admin/config/system/site-information** to input `/node/1`.

It works on both Drupal 7 and 8.
> 0 votes

# Answer
In addition to @Jimmy Ko answer. It seems that your clean URL is turned off. You should enable that to have a nice URL.

To answer your original question.

What you need is to put the path there which is `node/1`. Additionaly if you have Drush installed you can set the frontpage path by running `drush vset site_frontpage PATH`.

Example:

```
drush vset site_frontpage node/1

```

To enable clean URL.

To enable clean url using Drush.

```
drush vset clean_url 1

```

NOTE: Clean URL needs to have `rewrite` (in Apache) module enabled.
> 0 votes

---
Tags: uri
---


# Question
Title: How to show a page create with the view module in the administrative overlay?
I've created a view with the view module which is a kind of administative page and i'd like to show that page using the administrative overlay, how can i do that?

# Answer
Showing a view in the overlay just requires you to implement `hook_admin_paths_alter()`.

```
function mymodule_admin_paths_alter(&$paths) {
  // Treat all user pages as administrative.
  $paths['the path of your view'] = TRUE;
}

```

Keep in mind this:

* In the path you can also use asterisks (e.g. node/\*/edit), useful in the case the view is using contextual filters
* If the overlay is not accessible from the user, the page will be shown using the administrative theme, which could also be the default theme used by Drupal, if the site doesn't set a the administrative theme to be another one
> 0 votes

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


# Question
Title: Writing unit tests for a method that calls static methods from another class
I have a custom service defined by my module and in one of its methods I call a static method from a class defined by a module mine depends on. Since this method is static I do not need to instantiate an object but this also means I cannot inject the dependency. Soooo... How do I mock the static call?

Here is some psuedo code to illustrate:

```
use some/other/class/called/FOO

...

function myMethod() {
  // Do some things...
  $some_var = FOO::staticMethodToGetValue();
  // Do more things...
  return "something";
}

```

# Answer
You can't mock static calls directly.

A relatively easy way to fix this is what core uses in quite some places to mock functions that haven't been converted to objects/services yet. You create a method in your own class that does nothing but call the static method.

Then for your test, you can either mock your own object and only mock that method or create a test subclass that overrides that method and return something else.
> 6 votes

---
Tags: 8, testing
---


# Question
Title: Which Rules Event can be used with Drupal Commerce when a cart is updated?
I have created a rule which add the shipping methods on cart page. It works fine when we add or delete the items from cart. BUT there is no event available on rules which fire when we increase the product quantity and update the cart.

I already used the event "After updating an existing commerce line item" but it is also not doing the job.

Here is my rule:

```
{ "rules_auto_add_shipping_service" : {
    "LABEL" : "Auto-add shipping service",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [
      "commerce_order",
      "commerce_shipping",
      "commerce_cart",
      "commerce_rules_extra"
    ],
    "ON" : {
      "commerce_cart_product_add" : [],
      "commerce_cart_product_remove" : [],
      "commerce_rules_extra_line_item_quantity_changed" : []
    },
    "IF" : [
      { "commerce_order_compare_total_product_quantity" : {
          "commerce_order" : [ "commerce_order" ],
          "operator" : "\u003E=",
          "value" : "1"
        }
      }
    ],
    "DO" : [
      { "commerce_shipping_method_collect_rates" : {
          "shipping_method_name" : "flat_rate",
          "commerce_order" : [ "commerce-order" ]
        }
      },
      { "commerce_shipping_rate_apply" : {
          "commerce_order" : [ "commerce-order" ],
          "shipping_service_name" : [ "" ]
        }
      }
    ]
  }
}

```

# Answer
> 0 votes
Make sure you have the Commerce rules extra module installed. This module will provide, among other things, the extra Rules Event "Quantity of line item has changed" (as described on its project page):

> Line item quantity has changed (occurs when adding or removing a product to cart and when an amount has been modified in the cart form).

That should help to achieve your goal.

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


# Question
Title: How to make product views display also show up for Anonymous users in Drupal Commerce?
I created a Product listing view with Add to Cart Buttons. The view displays perfectly for the Super User, but it is not displaying for Anonymous or Authenticated users.I do have a relationship "referenced product" but it is still not working for anonymous users.

What I did to solve the problem is to go to the permissions page and give everybody the "view all products" permission. This works. BUT: It might open up a security issue. Please let me know what am I doing wrong?

# Answer
> 1 votes
Inspired by what's written in some of the comments to issue nr 1276450, such as in comment nr 158 of it:

> **edit your View**: \> "Advanced" \> "Query settings" : check "Disable Query Rewriting"

For sure worth trying to see if it helps in your case. If it does, it'll be way better then the permission you granted as described in your question I think.

---
Tags: 7, views, commerce
---


title: Variables in module using colons

text:
# Question
Title: Variables in module using colons
I think this may be related to using "tokens" when developing a module, but I am seeing this:

```
'og:updated_time' => array('value' => '[node:changed:custom:c]'),

```

The question I have is about: \[node:changed:custom:c\]

What is this? What is it even called?

In my particular case, I am adjusting a module to retrieve a new value from a custom field.

```
'og:image' => array('value' => '[node:field_social_image]')

```

I have successfully used this for other custom fields, using the exact same syntax, but this one does not work.

# Answer
> 2 votes
These are the tokens, more specific a custom/dynamic tokens implemented by Drupal core (`token.inc`) and managed by Token module.

See: List of tokens page for more details:

> Custom format `[node:changed:custom:?]` "`?`" is a single, unquoted PHP date formatting character. Use this token multiple times to build a full custom format.

# Answer
> 1 votes
If your `field_social_image` is not a date field (it's probably an image field ...), and taking into consideration the accepted answer from kenorb, it would explain why that that "`c`" doesn't work.

Because it's a PHP date formatting character, i.e. related to "***ISO 8601 date (added in PHP 5) 2004-02-12T15:19:21+00:00***"

In other words: use "`c`" only for date fields.

---
Tags: 7, entities
---


# Question
Title: How to get field values of a just created (or not yet) node?
I am calling `node_load()` function in a custom module and it returns only part of the variables like `title`, `uid`, `vid`, `status` (all the meta), but it never returns actual field contents. I tried `node_page_view()`, tried `menu_get_object()` \- all in vain, no field values.

What am I doing wrong? Is this because maybe my module is calling `node_load()` too early before the saving node, but then how it has already `$node->title`, `$node->nid` and other values? If they are some kind of prepared values, then how can I get the same prepared value for a custom field?

And here is the code from the Community documentation page Sending Notification Messages that I am using in my module:

```
/*
 * Implements hook_node_insert().
 */
function foo_node_insert($node) {

  $message = message_create('foo_message_type', array('uid' => $node->uid));

  $wrapper = entity_metadata_wrapper('message', $message);
  $wrapper->field_node_ref->set($node);

  $options = array(
     'rendered fields' => array(
       'message_notify_email_subject' => 'field_rendered_subject',
       'message_notify_email_body' => 'field_rendered_body',
     ),
  );

  message_notify_send_message($message, $options);
}

```

and it works just fine for the message subject, however for some reason I can't get node body to be mailed properly.

I tried to see the content of the $node variable in the following code from example module:

```
elseif (isset($message['params']['message_entity']->field_node_ref)) {
    // This is a node.
    $nid = $message['params']['message_entity']->field_node_ref[LANGUAGE_NONE][0]['target_id'];
    $node = node_load($nid);
    $messageid_params['uid'] = $node->uid;
    $messageid_params['nid'] = $node->nid;
    $messageid_params['cid'] = 0;
    $messageid_params['time'] = $node->created;
    if (variable_get('mailcomment_alter_subjects', 1)) {
      $subject = $message['subject'];
      $subject = variable_get('site_name', '') ? '[' . variable_get('site_name', '') . '] ' . $node->title : $subject;
      $message['subject'] = $subject;
    }
    dpm($node);
   }

```

and unfortunately my custom node field always returns empty:

```
field_description (Array, 0 elements)
$...->field_description

```

# Answer
All that I needed to do was using

```
$node = node_load($nid, null, true);

```

instead of just

```
$node = node_load($nid);

```

and now the node is loading as expected.
> 1 votes

# Answer
Try

```
hook_entity_postinsert();

```

from the Hook Post Action module. It loads field values always by Entity metadata wrappers.
> 0 votes

---
Tags: 7, nodes
---


title: Variable with placeholder

text:
# Question
Title: Variable with placeholder
I am implementing a couple of **translatable variables** that are exposed via `hook_variable_info()`.

Can I use placeholders in these variables, and process them to replace with the actual values?

As an example: I have a variable that holds the following informational text that will be shown on a page that has a registration form below.

> Please signup here to gain access to the restricted area for @yourcompany

I have been googling around for this, but cannot seem to find any good leads on how to do this (if at all possible?)

# Answer
The simplest way is using format\_string(), you can have 3 kind of replacement token for different sanitisation and formatting.

> **@variable**: Escaped to HTML using check\_plain(). Use this as the default choice for anything displayed on a page on the site.
>
> **%variable**: Escaped to HTML and formatted using drupal\_placeholder(), which makes it display as *emphasized* text.
>
> **!variable**: Inserted as is, with no sanitization or formatting. Only use this for text that has already been prepared for HTML display (for example, user-supplied text that has already been run through check\_plain() previously, or is expected to contain some limited HTML tags and has already been run through filter\_xss() previously).

Example code:

```
$message = variable_get_value('variable_name');
$message = format_string($message, array('@yourcompany' => $company_name));

```
> 0 votes

---
Tags: 7
---


# Question
Title: What's the explanation for my product permission issue in a Drupal Commerce view?
I'm very confused with some permissions and product displays in Views. Maybe you can help me to understand it.

I'm trying to make a view of product displays. In the view I include a relationship for the referenced product field, so I can get fields of the referenced product like for example Image, SKU, price, ...

I save the view, and if I go to the view's page as admin I can see the view correctly, but if I visit the view as authenticated user or anonymous no items are displayed in the view.

So I went to the permissions config page, and I checked the permission "`View any product of any type`" for anonymous and authenticated users.

After doing so, normal users and anonymous can see the view correctly. But while configuring that permissions it says:

```
"Warning: Give to trusted roles only; this permission has security implications."

```

So I do not know if I'm doing things correctly. And I wonder how to make a view of product displays and also get the referenced product fields and make it visible for anonymous and normal users?

# Answer
> 1 votes
Yes, you make right changes to show your commerce views for non-admin users. Here they found that's **dummy permission** and provide patches, I assume in future commerce versions it will included.

# Answer
> 2 votes
Below is another recommendation to address your "***... I went to the permissions config page, and I checked the permission "`View any product of any type`" for anonymous and authenticated users***" ... and your "***So I do not know if I'm doing things correctly***".

Have a look at the (old) Drupal Commerce issue "Views results empty for unprivileged user when using Relationship: Content: Referenced Product". Especially what's written in comment nr 158, i.e.:

> **edit your View**: \> "Advanced" \> "Query settings" : check "Disable Query Rewriting"

So instead of granting that permission (so that "*normal users and anonymous can see the view correctly*", as in your question), it may be sufficient to just adapt these advanced query settings as mentioned above. If it does, it'll be way better then granting that permission with that scary warning.

If you want more info about what the real issue is (and why this is only a work around), then have a look at comment nr 101 of the same issue, which states:

> The issue is not with Commerce. It's a node access issue, and it's triggered when you use a Views Relationship with a node access module (such as OG or Domain Access), and there's no related item the user has access to. The quick work-around is to disable SQL rewriting, which allows the view to get all results and ignore the node\_access rules -- of course, this will show content the user should not otherwise have access to.

---
Tags: 7, views, commerce, users
---


# Question
Title: How to implement Administration UI notifications for new revisions?
I'm new to Drupal and I'm customizing an administration theme to be designed to our needs.

1. One of the things we would like to have is a visual notification of a new REVISION (content needing approval/revising/reverting, not already published). I've set this up via email, using Rules, but we need the visual indicator, like a red circle with the number of new revisions in it somewhere in the header.
2. Extending from that, when they click on the icon, then a page where they can administrate all the revisions needing their attention. The page would list all content types needing approval from an admin for publishing, where the admin can approve, go to the type to edit or revert to previous revision.

I thought I would have access to at least #1 via a module but cannot find something similar. Does anyone know of a module or modules that can fulfill the above requests? If the module was specifically written for something else, like notification of comments, I'm happy to rewrite it to fit - just anything that can me some time.

# Answer
> 0 votes
Eventually decided on using the Flag module for this since it seems less bulky than other workflow alternatives. It also allows us to use flags for other things as well and am quite happy with how easy it is to setup with Rules. I have to do code some of the display we want but it seems worth it. Thank you for your suggestions!

# Answer
> 0 votes
If you're still looking for a "*visual indicator, like a red circle with the number of new revisions in it somewhere in the header*" (as in your question), then have a look at the Menu Badges module to add such notifications to any **menu item** and/or **menu tab** of your choice.

Here are some details about it (from its project page):

> Provides a method for adding iOS-style badges to menu items. (see screenshot)
>
> ### Adding Badges to Menus
>
> Once enabled, go to `Administration > Structure > Menus`, and click "list links" next to the menu containing the target item. Click "edit" next to the item and select the badge to display with the Display Menu Badge select box.
>
> ### Adding Badges to Tabs
>
> For adding badges to menu tabs, there is a tab under `Administration > Structure > Menus` called "Tab Menu Badges". Search for the menu router path of the tab you want to alter, then select a badge from the corresponding select box.
>
> ### Badge Types
>
> The module includes five example badges, and new badges can be created easily with Views. Modules can also supply their own badges with a hook implementation. See the README.txt file for details.

Because of how it integrates with the Views module, you basically reduce the solution for any type of notification to something like "Just create an appropriate view of it".

Be aware: you cannot click on those badges, though you can click on the menu links/tabs that they are related to (which is literally pretty close, no?).

### Video tutorials:

---
Tags: 7, nodes, notifications
---


title: Prevent dual submit on form submission

text:
# Question
Title: Prevent dual submit on form submission
I've got a form that submits via AJAX and in the callback I need to rebuild certain parts of the page to reflect the newly submitted data. One of these parts is the form, which I need to clear all user input values from so it's ready to use again.

```
$response = new AjaxResponse();

// Remove all user submitted values
$form_state->setValues( array() );
$form_state->setRebuild( TRUE );

// Build a new instance of the form
$form_object = \Drupal::service('class_resolver')->getInstanceFromDefinition('Drupal\tpl_project\Form\MultiContactForm');
$form_object->setCompany( $company );
$replacement_form = \Drupal::formBuilder()->buildForm( $form_object, $form_state );

// Replace the old form with the new one
$response->addCommand(new HTMLCommand('.form-container', $replacement_form));

return $response;

```

When the form is submitted it runs the validation callback, the submit handler, then calls the above ajax handler. When it rebuilds the form in the above process, it fires the validation and submit handles again, thus storing two records.

How can I prevent this from happening and still rebuild the form to display no user input all within the same request?

Any help greatly appreciated.

# Answer
See if this will help: How can I implement AJAX form submission?

It's a pretty decent checklist for ajax form operations.
> 0 votes

---
Tags: forms, 8, ajax
---


# Question
Title: exposed filter autocomplete suggestions sort
I have more than 10 terms in vocabulary: car, red car, blue car, yellow car etc. I know that 10 results is hardcoded value for autocomplete widget. My problem is that after typing "car", I only get various other terms, simple "car" is not in suggestions.

How does the autocomplete widget work? Is there any way how to sort/alter results? Why it does not show the exact term first "car" and then all other terms containing "car"?

# Answer
The filter handler class `views_handler_filter_term_node_tid` uses the autocomplete path **admin/views/ajax/autocomplete/taxonomy** and is driven by the callback `views_ajax_autocomplete_taxonomy()`.

This autocomplete callback explicitly excludes the term typed in and doesn't do any explicit sorting (thus defaults to whatever your RDBMS does):

```
$query = db_select('taxonomy_term_data', 't');
$query->addTag('translatable');
$query->addTag('term_access');

// Do not select already entered terms.
if (!empty($tags_typed)) {
  $query->condition('t.name', $tags_typed, 'NOT IN');
}
// Select rows that match by term name.
$tags_return = $query
->fields('t', array('tid', 'name'))
  ->condition('t.vid', $vid)
  ->condition('t.name', '%' . db_like($tag_last) . '%', 'LIKE')
  ->range(0, 10)
  ->execute()
  ->fetchAllKeyed();

```

If you'd like to alter the results or how it's sorted, the query is using tagging, thus available for altering via `hook_query_alter()`.
> 0 votes

---
Tags: 7, views, ajax
---


# Question
Title: How to limit edit permission to individual values on a multi value field?
If I have an image field with multiple values, for example, how could I let users create edit and delete only their own images (i.e. that they upload and not anyone else)? I tried the field permissions module but it does not limit individual values of nodes.

# Answer
> 0 votes
I think your goal is to create a gallery which different people can upload their own images into it and then modify those images. Reaching this goal you can create a gallery content type with multiple images and a taxonomy or a referenced field so you can relate two galleries owned by two different people and in this case any user can modify, create or delete his/her own gallery. At the end you can create a global view for all images using Views module so all images posted by all users are listed inside and can be categorized using the reference field you have added.

If you want all images being uploaded to same content then you must use another approach which needs the ability of drupal module development, first of all you must create a new field type using drupal Field API. This field type must contain a image subfield and a user reference so you can have both image and its uploader in a same place. Then you can use hook\_field\_access to restrict access to field values in different operations.

---
Tags: entities, users
---


title: XAMPP localhost - admin access denied

text:
# Question
Title: XAMPP localhost - admin access denied
Does anyone has issue with mac Xampp localhost? Everything seem fine after I imported online Drupal site and database to Xampp(1.8.2-4) localhost. However, after I hit the login button on the login page( \[https://localhost/user\]\[1\] ), it gave me "access denied". That's mean I cant login at all.

Best, CocoSkin

---

it gave me the error message after i run `drush upwd admin --password=YOURNEWPASSWORD`

~ here is the error message ~

```
HH5765-122A-M1:~ cocoskin$ cd /Applications/XAMPP/xamppfiles/htdocs
HH5765-122A-M1:htdocs cocoskin$ drush upwd admin --password=MYNEWPASSWORD
Command user-password needs a higher bootstrap level to run - you    [error]
will need to invoke drush from a more functional Drupal environment
to run this command.
The drush command 'upwd admin' could not be executed.                [error]
Drush was not able to start (bootstrap) the Drupal database.         [error]
Hint: This may occur when Drush is trying to:
 * bootstrap a site that has not been installed or does not have a
configured database. In this case you can select another site with a
working database setup by specifying the URI to use with the --uri
parameter on the command line. See `drush topic docs-aliases` for
details.
 * connect the database through a socket. The socket file may be
wrong or the php-cli may have no access to it in a jailed shell. See
http://drupal.org/node/1428638 for details.

Drush was attempting to connect to:
 Drupal version         :  7.26
 Site URI               :  http://default
 Database driver        :  mysql
 Database username      :  test_drupal
 Database name          :  test_drupal
 Default theme          :  garland
 Administration theme   :  garland
 PHP executable         :  /usr/bin/php
 PHP configuration      :
 PHP OS                 :  Darwin
 Drush version          :  6.0-rc4
 Drush configuration    :
 Drush alias files      :
 Drupal root            :  /Applications/XAMPP/xamppfiles/htdocs
 Site path              :  sites/default
 File directory path    :  sites/default/files

```

# Answer
> 1 votes
If you are sure that your password is correct go to the Data base and empty( truncate) `Sessions` & `Flood` and all `cache`(I mean all tables has prefix cache\_) tables,finally clear your browser cookie then try to login otherwise(If you are not sure about password) try to reset password programmatically

# Answer
> 0 votes
if you have drush installed you can run `drush upwd admin --password=YOURNEWPASSWORD`. Hope this helps

---
Tags: 7
---


# Question
Title: Translate site name in multi language site
How can I translate site name for multi language site in drupal 8 ?

For Example:

> in site/en -\> site name : Hello
>
> in site/fr -\> site name : Bonjour

# Answer
I found it .

1 ) Install "Configuration Translation" module.

2 ) Go to "Basic site setting" ( admin/config/system/site-information )

3 ) Click "Translate system information" tab.

4 ) In front of your language click on "Add" button.

5 ) Then set your site name and click on "save translate" .
> 7 votes

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


# Question
Title: How to create a module that shows some fields of profile2 type?
I want to create a module that shows some fields of profile2 type, in fact I want to show some information about any user in profile page of theme. Profile2 type is "stores", field machine name is "field\_store\_name" and my module name is "profile\_header". I put below code in profile\_header.module

```
 <?php
function profile_header_block_info() {
  return array(
    'profile_header' => array(
      'info' => 'profile stores header',
      'cache' => DRUPAL_NO_CACHE
    )
  );
}

function profile_header_block_view($delta = '') {
  $block = array();

    global $user;
    $account = user_load($user->uid);
    $user_fields = user_load($uid);
    $profile = profile2_load_by_user($account, $stores = NULL);
    $field_store_name = field_get_items('profile2', $profile2['stores'], 'field_store_name');
    $block['subject'] = 'profile stores header ';
    $block['content'] =  theme(
          'profile_header',
          array(
            'field_store_name' => $field_store_name,
          )
        );
     return $block;
}

function profile_header_theme($existing, $type, $theme, $path) {
  return array(
    'profile_header' => array(
      'template' => 'profile_header',
      'path' => $path . '/theme',
      'variable' => array(
        'user_fields' => NULL,
      ),
    ),

  );
}

```

and put below code in profile\_header.tpl.php, and clearly I put this file in `profile_header/theme` directory.

```
<?php
?>

<section class="container">
    <aside class="store-bio">
        <div class="store-name">
            <?php print $field_store_name ; ?>
        </div>
    </aside>
 </section>

```

But unfortunately this module doesn't show anything.

# Answer
Your `hook_theme()` implementation is returning an array with missing details; the key should be `variables` and its value array should contain keys that matches the variable names in your template.

```
function profile_header_theme($existing, $type, $theme, $path) {
  return array(
    'profile_header' => array(
      'template' => 'profile_header',
      'path' => $path . '/theme',
      'variables' => array(
        'field_store_name' => NULL,
      ),
    ),
  );
}

```
> 0 votes

---
Tags: 7, theming, entities, hooks
---


title: How to alter a view sort order?

text:
# Question
Title: How to alter a view sort order?
I have used Views to create a view Display a summary by contextual filter.

**O/p**

**View settings like**

**Needs**

There are only two option for sorting "ASC" or "DESC".

But i need to show like

Pass(4)

Fail(2)

Waiting(1)

Tried for

```
function hook_views_query_alter(){

}

```

But did not get how achieve this.

VIEW QUERY

```
SELECT field_data_field_bid_test.field_bid_test_value AS field_data_field_bid_test_field_bid_test_value, COUNT(crm_core_contact.contact_id) AS num_records
FROM
{crm_core_contact} crm_core_contact
INNER JOIN {users} users_crm_core_contact ON crm_core_contact.uid = users_crm_core_contact.uid
LEFT JOIN {field_data_field_bid_test} field_data_field_bid_test ON crm_core_contact.contact_id = field_data_field_bid_test.entity_id AND (field_data_field_bid_test.entity_type = 'crm_core_contact' AND field_data_field_bid_test.deleted = '0')
GROUP BY field_data_field_bid_test_field_bid_test_value
ORDER BY field_data_field_bid_test_field_bid_test_value ASC

```

# Answer
Yes finally i am able to solve this one.

Using

```
function utility_views_query_alter(&$view, &$query) {

  if ($view->name == 'Viewname') {

    //dpm($view->query->orderby[0]);
 $view->query->orderby[0]['field'] = "CASE  field_data_field_bid_test_field_bid_test_value WHEN 'Pass' THEN 1 WHEN 'Fail' THEN 2 WHEN 'Waiting' THEN 3 ELSE 4 END";
  }
}

```
> 4 votes

# Answer
Another approach you may want to consider, is to slightly adapt the labels to be sorted like so:

* 2-Fail.
* 1-Pass.
* 3-Waiting.
* 4-Other.

The sorted version of this list would look like so:

* 1-Pass.
* 2-Fail.
* 3-Waiting.
* 4-Other.

It's what I often do for any software where I somehow want to overrule the whatever sorting (eg to ensure my most often used folder names are always at the top) ... And it works in pretty much every OS I ever used (including mainframes ...). Also for any release of Drupal ...
> 1 votes

---
Tags: 7, views
---


# Question
Title: Saving the value for a taxonomy term field
I'm trying to save a field value for a taxonomy term, my value appears in the term array, but the "fields" array is empty. I'm not sure if it's right what I am going to do. You can see everything about my case in the attached screenshot.

# Answer
Yes, as @Trupal said, forget about the internal properties of the term objects, that's internal details that are not relevant to you.

If you want to see what's inside, try $term-\>toArray() and look at the result of that in your debugger. Or access the field value with $term-\>field\_foo-\>value.
> 0 votes

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


title: How to customize the SMTP message

text:
# Question
Title: How to customize the SMTP message
When a message is send to the user a message like this is shown to him :

message screenshot

> SMTP -\> FROM SERVER: ...........
> SMTP -\> FROM SERVER: .......
> ............................................................................
> SMTP -\> FROM SERVER: .......
> SMTP -\> FROM SERVER: ......
> SMTP -\> FROM SERVER: .....................
> SMTP -\> FROM SERVER: ................................
> SMTP -\> FROM SERVER: .....................................
> Further instructions have been sent to your e-mail address.

I only want the last one: "Further instructions have been sent ..." to show. Is it also possible to personalize it ?

# Answer
I found an alternative method to solve my prob by using this two modules: Disable Messages Module and String Overrides Module
> 1 votes

# Answer
Those messages are shown as the result of enabling logging in the SMTP module. It's only set once from the `smtp_debugging` variable. If it's still logging after disabling it, you to debug the issue as there's no one cause (e.g. caching, forcing the setting in **settings.php**/**settings.local.php**, code base hack, etc.) and is out of scope of Q&A.

As for altering the "Further instructions have..." message, there are many ways to do this (e.g. form alter, translation files), but the simplest is probably utilizing the String Overrides module which will let you override any message wrapped in a `t()` function.
> 2 votes

---
Tags: 7, emails
---


# Question
Title: How can I restore the security of an old site with a sql injection vulnerability which was probably exploited?
Edit: Sorry, the question was marked as unclear. In a nutshell, there are two questions:

1. Does the code below indeed create an sql injection vector? (It seems clear that the answer is yes, even though I was unable to craft a successful attack on my current server architecture.)
2. Assuming someone successfully exploited that sql injection vector on the old server, what would I have to do to make sure that there are no leftover attack vectors? Would it be sufficient, for example, if I took the following actions:

* Move to a new server
    * Build a new Drupal codebase from scratch
    * Remove the insecure code from the theme
    * Block or delete all users except those that are recognized
    * Force password resets for the recognized users
    * Check the menu\_router table for bad items
    * Check all node and comment titles, bodies and fields for tags

...Or is the situation even more hopeless than that, and the site should simply be abandoned or rebuilt from scratch? For various reasons I don't think it is possible to restore from a backup, mostly because the attempted exploits go back 6 years.

=== Original post ===

I'm looking at an old D6 site that was done in a very non-standard way. What concerns me most are some .tpl.php files from the theme that use $\_POST parameters to insert data into some tables, e.g.:

```
<?php
  $uid = $user->uid;
  $name = $user->name;
  $title=$_POST['title'];
  $comment=$_POST['comment'];
  $nid=$_POST['nid'];
  $cid=db_result(db_query("select  max(cid) from  comments"));
  $cid2=$cid+1;
  $timestamp=mktime();
  db_query("insert  into  comments  values($cid2, 0, $nid,$uid,'$title' , '$comment', '127.0.0.1', $timestamp, 0, 3,'01/', '$name', null, null)");
 ?>

```

This seems like very straightforward sql injection vector, but I'm not really an expert at exploiting such things, and my relatively feeble attacks have been caught by the new server. However, there are 1000 entries in the database where the titles are pretty clear attempts to execute injection attacks, and worse yet are the 1000 more with empty titles which might represent attacks that were successful.

So how bad is this? Here is my scale:

1. 37GB of spam! Ha ha ha! No problem!
2. Removing the insecure code and moving to a new server should be safe.
3. The site will not really be safe until you switch to a new server, remove all the insecure code, and run some automated tests on the database and/or file structure to check for residual attack vectors.
4. The site will not really be safe until you switch to a new server, remove all the insecure code, and then go through each file and each database row and manually check to make sure that it isn't an attack vector — in other words, it's probably easier to give up and start over, no matter the size of the site.

# Answer
Theoretically, that SQL query could be used to do anything on that database server, including changing the password for a Drupal account not used so often, or creating a new account in the *users* table.

Suppose that `$_POST['title']` contains the following.

```
"ddddd', 'comment', 127.0.0.0.1, 1469987843, 0, 3, '01/', 'Tintin', NULL NULL); DELETE FROM {users} u WHERE u.uid > 0; -- "

```

This would change `""INSERT INTO {comments} VALUES($cid2, 0, $nid, $uid, '$title', '$comment', '127.0.0.1', $timestamp, 0, 3,'01/', '$name', NULL, NULL)"` into the following.

```
"INSERT INTO {comments} VALUES($cid2, 0, $nid, $uid, 'ddddd', 'comment', 127.0.0.0.1, 1469987843, 0, 3, '01/', 'Tintin', NULL NULL); DELETE FROM {users} u WHERE u.uid > 0; -- ', '$comment', '127.0.0.1', $timestamp, 0, 3,'01/', '$name', NULL, NULL)"`

```

I added a query to delete the *users* table, but I could have added any query, including the one to alter the password of an existing account, or creating a new user.

How that type of attack is effective depends only from how much the attackers know about your site: which software you are running, which version, etc. Once they have access as administrator, they could do enable the PHP input format, and execute arbitrary code. I would say that spam is the last of your problems.

As side note, as Clive said, template files should never contain SQL queries; eventually, those could be in preprocess functions, but in most of the cases, they should be in a module.
Also, in Drupal SQL query, you should wrap the database table names in {}. This allows Drupal to use prefixes in the table names, and even use tables from different databases.
> 1 votes

---
Tags: 6, database, security
---


# Question
Title: Why is the database not updated before a next Rule is launched?
I have two Rules (created with the Rules module) that are both launched when an article is flagged with the Flag *Approved*:

* **Rule 1**. Publish the flagged article with the action *Publish content*.
* **Rule 2**. Count the amount of published articles by the author of the flagged article. Display a message when this number is 5.

I'm using the following code in the condition of Rule 2:

```
return MYMODULE_count_articles($flagged_node->uid) == 5;

```

where my custom module contains the function

```
function MYMODULE_count_articles($uid) {
  $count = db_query("SELECT COUNT(*) FROM node WHERE uid=$uid AND status=1 AND type='article'")->fetchField();
  return $count;
}

```

The condition of Rule 2 is evaluated as `FALSE` when the 5th article is flagged with *Approved*, but evaluates as `TRUE` when a 6th article is flagged.

I suspect that this problem is caused because the database hasn't been updated yet when Rule 2 launches, because debugging the `$count` variable at the 5th flagging returns `4` instead of `5`. Also, executing the condition's code afterwards yields the correct value `5`.

Is this a know problem/phenomenon or a bug in the Rules module? Or is there an easy way to fix it (apart from changing the condition to `... == 4`, which is really dirty)?

# Answer
> 3 votes
Have a look at issue # 430274, about an event which is a variation of your event here, and somehow explains that "after saving something" actually happens ... "before saving something" (which is not a bug, simply how the Rules module works ...).

A possible compromise to avoid these kind of issues, is to transform what you're trying to do in your **Rule 2** in a Rules Component, so that your **Rule 1** "schedules the execution" (using the Rules Scheduler submodule) of that Rules Component. For example after only a few seconds or minutes later on (if your cron job runs frequent enough, otherwise it'll be next time cron runs). This compromise will ensure that, at the time the Rules Component is executed, the "Publish content" for sure completed, and your "number" will have been updated as expected.

---
Tags: 7, rules, database
---


# Question
Title: How to get current path for user profile field?
On the user profile page, I want to add link field which will link to a view page.

For example, if the current path is:

`sitename/user/1` *(profile page of user-1)*

The link should be:

`sitename/user/1/view-page`

It should take the `user-id` from the `current-path`. It should redirect to `sitename/user/1/view-page`, in general `sitename/user/%/view-page`, which is my contextual view path.

How can build this link field for the profile page?

# Answer
One way to go about this is a theme override of the user profile page:

* Copy over **core/modules/user/templates/user.html.twig** over to your theme's template directory.
* Have your theme implement `template_preprocess_user()` in your MYTHEME.theme file to inject a custom URL variable.
* Modify your theme's **user.html.twig** to contain the HTML for the link.

For example, in your MYTHEME.theme:

```
use Symfony\Cmf\Component\Routing\RouteObjectInterface;
use Drupal\Core\Url;

/**
 * Implements hook_preprocess_user() for user.html.twig.
 */
function MYTHEME_preprocess_user(&$variables) {
  if (\Drupal::request()->get(RouteObjectInterface::ROUTE_NAME) == 'entity.user.canonical') {
    $variables['view_page_path'] = Url::fromUri('base:' . \Drupal::service('path.current')->getPath())->toString() . '/view-page';
  }
}

```

In your **user.html.twig**:

```
{% if view_page_path %}
  <a href="{{ view_page_path }}">MY VIEW PAGE</a>
{% endif %}

```
> 3 votes

---
Tags: 8, navigation
---


# Question
Title: Creating several users in one request using Services/REST/Json
I'm using Services 7.x-3.12 and able to create a single new user using REST/Json post, and that works well.

Is it possible to create multiple new users in one request? I couldn't find any documentation on this and wasn't able to make it work. I tried separating the users with a comma inside the Json body, like so:

```
{{"username":"testuser27”,"mail”:"testuser27@gmail.com","pass”:"test","roles":"2","status":"1"},{"username":"testuser27”,"mail”:"testuser27@gmail.com","pass”:"test","roles":"2","status":"1”}}

```

but no success - I get this error:

```
[ "Missing required argument account" ]

```

Any help/pointers would be appreciated.

# Answer
> 0 votes
Out of the box no.

But you could write a module that supplies you're own resource that takes multiple user objects.

---
Tags: 7, services
---


# Question
Title: How to find out who and when created taxonomy term
Is it possible to know who and when created taxonomy term? Is that information stored anywhere?

I can't find it.

# Answer
No, not in Drupal core. Unlike the Node entity, the Taxonomy term entity does not define a field that stores a field denoting ownership. You'll need to add your own field to your taxonomy terms to give them an ownership property.
> 6 votes

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


# Question
Title: How can I fix the node list page broken by changing the reference field from a term reference to an entity reference
This answer explains the set up I currently have. I have cloned the Taxonomy Term view built into views, and added some extra filtering etc. To create a depth aware list of nodes for taxonomy terms as linked by pathauto (pattern `pub/by/[term:vocabulary]/[term:name]`). So for example previously a link to `/pub/by/publisher/asian-development-bank` would provide me with a list of nodes that had associated Asian Development Bank in a term reference field with the node.

This is site is bilingual, and the publisher vocabulary has an acronym field, and on the node creation form, I needed the autocomplete to return results for the name entered in either English or Japanese, or the acronym.(more detail in this question) Which required me to change the fields referencing the publisher vocabulary to be entity reference fields instead of term reference fields.

The problem is that now `/pub/by/publisher/asian-development-bank` is an empty list. I'd like to override `/path/by/publisher/%` links to use an entity reference relationship to search for the term rather than the means that the default Taxonomy Term view does. The issue is that the path in the Taxonomy Term view is `/taxonomy/term/%` utilizing the value coming from the destination query variable.

How can I create a view that will still use those links generated by pathauto, but actually return results from the entity references?

Just to complicate things a little, each node has two entity reference fields to the publisher vocabulary: `field_doc_copyright` and `field_doc_publisher`

# Answer
I got it. I had initially been trying to create a new view to operate on the `/pub/by/publisher/%` path, but I realized by inspecting the view, that the view I already had on `/taxonomy/term/%` was handling the route because links to one of the pathauto generated routes end up being to the equivalent of `/pub/by/publisher/term-name?destination=/taxonomy/term/tid`

The problem is then to get the existing view to show the results I want. In my case, since the existing view was showing no results for any publisher vocabulary term, and publisher terms should be the only terms that return results for my new view; I had the option of adding an attachment or other view in the no results section or to just create an attachment attached after the main view. I added an attachment and added it after the main view. Since I needed the results of two entity reference fields I needed an OR condition between my contextual filters. For this I used Views Contextual Filters OR.

One additional problem I faced was that my filters and contextual filters were being joined with an OR condition rather than an AND condition, meaning that I was effectively querying for public nodes or the right type OR the nodes I actually want, which returned way more results than intended. The solution for this, was to add a new empty filter group to my attachment, joined to the original filter group with an AND condition, this caused it to start joining my contextual filters with AND as well.

Finally, my main view had some exposed filters on it, but thought I had inherit exposed filters checked on the attachment, those exposed filters were not working. It turns out that you need to add the same exposed filters to the attachment before the inheritance on them will work.

I doubt many people will have exactly the same problems I had, but hopefully it will provide a clue for people with something similar. As seems to always be the case @no-sssweat was instrumental in providing the hints I needed to get to the answer. Thank You!
> 0 votes

---
Tags: 7, views, path-aliases
---


# Question
Title: How do I alter the page title h1 tag from a module?
I miss hook\_page\_alter()!

I want to create a module that adds some configurable markup to page titles (the H1 tag on the HTML document) for full node pageviews of certain, configurable content types. But according to this change record:

> You no longer can change $page\['content'\] (or, generally speaking, $page\[$region\_name\]) into something completely different.

I know I can override twig templates to achieve this, but can I do that without creating a theme? I'd like this to be a reusable module.

# Answer
The page title is now a block, so you can override its template file.
> 3 votes

# Answer
drupal 8 page title is block so you can use hook

```
function hook_preprocess_page_title(&$variables) {

     $node = \Drupal::routeMatch()->getParameter('node');
   $variables['title'] = "your custom text here ".$node->getTitle();
}

```
> 0 votes

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


# Question
Title: Should the maintenance template be used when the database API raises an exception?
I have created a maintenance-page.html.twig template for my site.

The settings.php file says:

> This applies when the site is explicitly set to maintenance mode through the administration page **or when the database is inactive due to an error**.

However, on my site, this only works if I explicitly turn on maintenance mode. If I intentionally break access to my database by changing the password I get a page with a PDO error, not my maintenance page.

Is this a bug, or am I missing something?

# Answer
> 1 votes
This looks to be the case of where the documentation is out-of-date. That comment has been around verbatim since D7. D8 doesn't produce a themed maintenance page like D7.

When looking at `_drupal_log_error()`, you can see that unless Drupal is going through the install process, a fatal error will output a bare error message with a 500 status then exit:

```
if ($fatal) {
  // We fallback to a maintenance page at this point, because the page generation
  // itself can generate errors.
  // Should not translate the string to avoid errors producing more errors.
  $message = 'The website encountered an unexpected error. Please try again later.' . '<br />' . $message;

  if ($is_installer) {
    // install_display_output() prints the output and ends script execution.
    $output = array(
      '#title' => 'Error',
      '#markup' => $message,
    );
    install_display_output($output, $GLOBALS['install_state'], $response->headers->all());
    exit;
  }

  $response->setContent($message);
  $response->setStatusCode(500, '500 Service unavailable (with message)');

  $response->send();
  // An exception must halt script execution.
  exit;
}

```

Whereas in D7, `_drupal_log_error()` passes through a themed maintenance page:

```
if ($fatal) {
  drupal_set_title(t('Error'));
  // We fallback to a maintenance page at this point, because the page generation
  // itself can generate errors.
  print theme('maintenance_page', array('content' => t('The website encountered an unexpected error. Please try again later.')));
  exit;
}

```

---
Tags: 8, maintenance-mode
---


# Question
Title: Why does the Google Analytics module restrict uid?
When I try to insert the `[current-user:uid]` token for a custom dimension in the Google Analytics module, it gives me an error that this is a forbidden item.

However, reading through the GA Terms of Service, I can only find a vague statement saying only "non-personally identifiable information" is allowed.

The GA module is the only documentation I have found that explicitly states the uid is forbidden.

Wouldn't an id be allowed because Google has no way of retrieving the Drupal user's information?

Does anyone have a reference to where in the GA policy they disallow uid?

# Answer
There is nothing specific in the GA documentation that forbids it. There is actually a section in the GA Help which explains how to use user ids: Benefits of using the User ID feature, so using user ids is not forbidden by GA at all.

Why it doesn't work in the GA Drupal module is because of this paragraph, as stated by one of its developers (found here):

> If you upload any data that allows Google to personally identify an individual, your Google Analytics account can be terminated, and you may lose your Google Analytics data.
> 1 votes

---
Tags: 7, google-analytics
---


# Question
Title: How to show a Views attachment in other region or create a block acting as attachment?
I have a view with two displays: *page* and *attachment*. The exposed filters are the same for both the displays, and I used the *Inherit exposed filters* in the attachment settings.

I want to put the attachment in a specific theme region. How can I print the attachment in a different region?

>

The "pink" box is the attachment, which contains a Leaflet map. The user can select either one of the filters and see the results in the box map and the page below (node1, node2, node3, ...).

This is a screenshot of the view page as it is now.

>

Either of these solutions could work for me:

* Be able to display the attachment display in another region, then the page display under it
* Have a block that functions in the same way as an attachment and inherits all exposed and contextual filters in the way an attachment would do

I tried to use `views_embed_view()` in a custom PHP block. The block shows correctly the attachment, but the filter doesn't work with the new block.

```
$view_name = 'indoor';
$display_id = 'attachment_1';
print views_embed_view($view_name, $display_id);

```

I think the problem is the AJAX parameter *view\_dom\_id* passed to the block.

This is what i want:

>

# Answer
At moment I fixed with contextual filter query by disabling the ajax and get query from URL. This way I can use separated block for the map.
> 1 votes

---
Tags: 7, views
---


# Question
Title: How to automatically skip intermediate redirects?
I've run into the issue where I end up with something like this:

```
about-us01 --> about-us02 --> about-us

```

The correct path is "about-us". But due to admins changing things I have ended up in a situation where there are sometimes old redirects lingering in the system. The problem is that these google says it's not good to redirect multiple times. So the above redirect is not very effective.

Is there a way that I can get Drupal 7 to automatically skip the 'middle' redirect if it knows that is only going to result in another redirect? So instead of:

```
about-us01 --> about-us02 --> about-us

```

I want:

```
about-us01 --> about-us
about-us02 --> about-us

```

In both cases of accessing the links, it must take you directly to the about-us page and not any inbetween links if it knows the true destination?

# Answer
> 1 votes
Use the Rules module with a custom rule which looks like so (in Rules export format):

```
{ "rules_redirect_multiple_paths" : {
    "LABEL" : "Disallow multiple paths",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "init" : [] },
    "IF" : [
      { "text_matches" : {
          "text" : [ "site:current-page:path" ],
          "match" : "about-us\\d+",
          "operation" : "regex"
        }
      }
    ],
    "DO" : [
      { "drupal_message" : {
          "message" : "Redirect to path about-us ...",
          "type" : "error"
        }
      },
      { "redirect" : { "url" : "about-us" } }
    ]
  }
}

```

Some details about how to use read this rule:

* **Rules Event**: use the "Drupal is initializing" event, to ensure that the rule gets triggered BEFORE the actual content (of a path to be redirected) is shown. If you'd use an event like "content is viewed", you'd be too late, the content "would" already be shown.
* **Rules Condition**: verify if the path to be redirected matches any of the paths you want to be redirected, such as `about-us01` or `about-us02` **( * )**.
* **Rules Actions**:
    + Show a message about the redirect, which is just for QA testing (feel free to remove that Rules Action after you saw it working).
    + Perform the actual redirect to the desired page.

**( * )** Note that the actual Regular Expression I used goes a bit further: it would also perform a similar redirect for paths such as `about-us03` or `about-us456`, though it would not trigger such redirect for (eg) `about-us/789`. Here is an attempt to translate the various parts used in the regular expression **`about-us\\d+`**:

* **`about-us`**: it must start with `about-us`.
* **`\`**: escape character.
* **`\d`**: it must be followed by a digit (anything from `0` to `9`).
* **`+`**: it may be followed by 1 or more of the preceding token (so one or more extra digits).

**PS**: If you're struggling with regular expressions, then have a look at RegExr.

---
Tags: 7, path-aliases, redirection
---


# Question
Title: How to use data in a content type from another content?
Is it possible to use data in a content type from another content?

I will create a website for a football club. I want to add a content type for clubmembers (approx. 250 members) with personal information.

The members could order clothes from the club through a board member, who will keep the orders per member through a page.

To not have to re-enter some data, is it possible to establish a link with the personal member page? For example, I want to use some fields that are contained in another content type.

If it's possible, how can I do that?

# Answer
> 2 votes
I will suggest to use Entity reference module.

> Provides a field type that can reference arbitrary entities.

Also you can take a look References module.

> This project provides 'node\_reference' and 'user\_reference' field types.

---
Tags: nodes
---


# Question
Title: Entity "changed" timestamp is not incremented on $entity->save() only on a form submit; feature or bug?
Anyone know why the changed timestamp is not updated when you save an entity programmatically (e.g. $entity-\>save()) but it is updated when you (for example) use the node form to edit the entity.

Is this intentional? If so, why?

If not, I'll open an issue on D.O.

Thoughts?

# Answer
Pretty sure it is being updated, but it is updated to the REQUEST\_TIME timestamp. If you have a long-running process or so, that will not work as expected.
> 0 votes

---
Tags: 8
---


title: Change pager text

text:
# Question
Title: Change pager text
I need to change the text that appears in pagers (first/previous/next/last). I would really prefer to not get into the overhead (and sloppiness IMO) of a string override module.

Pager.inc seems extremely themable, but man is it strangely designed ...

This is as far as I got -- in template.php:

```
function phptemplate_pager_first($text, $limit, $element=0, $parameters=array()) {
    return theme_pager_first('« Oldest', $limit, $element, $parameters);
}

function phptemplate_pager_previous($text, $limit, $element=0, $interval=1, $parameters=array()) {
    if (is_numeric($text)) {
        return theme_pager_previous($text, $limit, $element, $interval, $parameters);
    } else {
        return theme_pager_previous('‹ Older', $limit, $element, $interval, $parameters);
    }
}

function phptemplate_pager_next($text, $limit, $element=0, $interval=1, $parameters=array()) {
    if (is_numeric($text)) {
        return theme_pager_next($text, $limit, $element, $interval, $parameters);
    } else {
        return theme_pager_next('Newer ›', $limit, $element, $interval, $parameters);
    }
}

function phptemplate_pager_last($text, $limit, $element=0, $parameters=array()) {
    return theme_pager_last('Newest »', $limit, $element, $parameters);
}

```

Almost works, until you travel to the second to last page where (in pager.inc) `theme_pager_next()` delegates to `theme_pager_last()` and this replacement breaks ...

Isn't there a clean way to do this with themeing? Hopefully better than just copy/pasting `theme_pager()` and replacing strings there?

# Answer
> 2 votes
Hi I used this and it works very well. Put it into template.php

```
function yourTheme_pager($tags = array(), $limit = 10, $element = 0, $parameters = array(), $quantity = 5) {
  global $pager_page_array, $pager_total;

  // Calculate various markers within this pager piece:
  // Middle is used to "center" pages around the current page.
  $pager_middle = ceil($quantity / 2);
  // current is the page we are currently paged to
  $pager_current = $pager_page_array[$element] + 1;
  // first is the first page listed by this pager piece (re quantity)
  $pager_first = $pager_current - $pager_middle + 1;
  // last is the last page listed by this pager piece (re quantity)
  $pager_last = $pager_current + $quantity - $pager_middle;
  // max is the maximum page number
  $pager_max = $pager_total[$element];
  // End of marker calculations.

  $pager_delim = '';

  // Prepare for generation loop.
  $i = $pager_first;
  if ($pager_last > $pager_max) {
    // Adjust "center" if at end of query.
    $i = $i + ($pager_max - $pager_last);
    $pager_last = $pager_max;
  }
  if ($i <= 0) {
    // Adjust "center" if at start of query.
    $pager_last = $pager_last + (1 - $i);
    $i = 1;
  }
  // End of generation loop preparation.
$li_first_numb = theme('pager_first', (isset($tags[0]) ? $tags[0] : t('1')), $limit, $element, $parameters);
  $li_first = theme('pager_first', (isset($tags[0]) ? $tags[0] : t('<<')), $limit, $element, $parameters);
  $li_previous = theme('pager_previous', (isset($tags[1]) ? $tags[1] : t('<')), $limit, $element, 1, $parameters);
  $li_next = theme('pager_next', (isset($tags[3]) ? $tags[3] : t('>')), $limit, $element, 1, $parameters);
  $li_last = theme('pager_last', (isset($tags[4]) ? $tags[4] : t('>>')), $limit, $element, $parameters);
  $li_last_numb = theme('pager_last', (isset($tags[4]) ? $tags[4] : t($pager_max)), $limit, $element, $parameters);

  if ($pager_total[$element] > 1) {
    if ($li_first) {
      $items[] = array(
        'class' => 'pager-first',
        'data' => $li_first,
      );
    }
    if ($li_previous) {
      $items[] = array(
        'class' => 'pager-previous',
        'data' => $li_previous,
      );
    }

    // When there is more than one page, create the pager list.
    if ($i != $pager_max) {
    if ($i > 1) {
        $items[] = array(
          'class' => 'pager-first',
          'data' => $li_first_numb,
        );
      }
      if ($i > 1) {
        $items[] = array(
          'class' => 'pager-ellipsis',
          'data' => '...',
        );
      }
      // Now generate the actual pager piece.
      for (; $i <= $pager_last && $i <= $pager_max; $i++) {
        if ($i < $pager_current) {
          $items[] = array(
            'class' => 'pager-item',
            'data' => theme('pager_previous', $i, $limit, $element, ($pager_current - $i), $parameters).$pager_delim,
          );
        }
        if ($i == $pager_current) {
          $items[] = array(
            'class' => 'pager-current',
            /*'data' => '['.$i.']'.$pager_delim,*/
            'data' => $i,
          );
        }
        if ($i > $pager_current) {
          $items[] = array(
            'class' => 'pager-item',
            'data' => $pager_delim.theme('pager_next', $i, $limit, $element, ($i - $pager_current), $parameters),
          );
        }
      }
      if ($i < $pager_max) {
        $items[] = array(
          'class' => 'pager-ellipses',
          'data' => '...',
        );
      }
      if ($i < $pager_max) {
        $items[] = array(
          'class' => 'pager-max-numb',
          'data' => $li_last_numb,
        );
      }

    }
    // End generation.
    if ($li_next) {
      $items[] = array(
        'class' => 'pager-next',
        'data' => $li_next,
      );
    }
    if ($li_last) {
      $items[] = array(
        'class' => 'pager-last',
        'data' => $li_last,
      );
    }
    return theme('item_list', $items, NULL, 'ul', array('class' => 'pager'));
  }
}

```

In this part of the code

```
 $li_first_numb = theme('pager_first', (isset($tags[0]) ? $tags[0] : t('1')), $limit, $element, $parameters);
      $li_first = theme('pager_first', (isset($tags[0]) ? $tags[0] : t('<<')), $limit, $element, $parameters);
      $li_previous = theme('pager_previous', (isset($tags[1]) ? $tags[1] : t('<')), $limit, $element, 1, $parameters);
      $li_next = theme('pager_next', (isset($tags[3]) ? $tags[3] : t('>')), $limit, $element, 1, $parameters);
      $li_last = theme('pager_last', (isset($tags[4]) ? $tags[4] : t('>>')), $limit, $element, $parameters);

```

You can modify first/previous/next/last

# Answer
> 0 votes
You can use one of the following for a simple version (works in Drupal 7)

```
function THEMENAME_preprocess_pager(&$variables, $hook) {
  if ($variables['quantity'] > 5) $variables['quantity'] = 5;
  $variables['tags'][0] = '<<';
  $variables['tags'][1] = '<';
  $variables['tags'][3] = '>';
  $variables['tags'][4] = '>>';
}

```

or

```
function THEMENAME_pager($tags = array(), $limit = 10, $element = 0, $parameters = array()) {
  global $pager_page_array, $pager_total;
  $page_prev = $pager_page_array[$element] - 1;
  $page_curr = $pager_page_array[$element] + 1;
  $page_next = $pager_page_array[$element] + 1;
  if ($pager_total[$element] > 1) {
    $output = '<div class="previous-next">';
    if ($pager_page_array[$element]!=0) $output.= '<a href="?page='.$page_prev.'" class="previous">Previous</a>';
    $output.= '<div class="previous-next-page">Page '.$page_curr.'/'.$pager_total[$element].'</div>';
    if ($page_curr!=$pager_total[$element]) $output.= '<a href="?page='.$page_next.'" class="next">Older blog posts</a>';
    $output.= '</div>';
    return $output;
  }
}

```

---
Tags: 6, theming, paging
---


# Question
Title: How do I get my custom route to a custom menu link
What I am trying to do is: I want my custom form to show up on a custom path under

```
    /admin/config/content/mymodule

```

My routing.yml looks like this

```
    mymodule.mymoduleform:
      path: '/admin/config/content/mymodule'
      defaults:
        _form: '\Drupal\mymodule\Form\Mymoduleform'
        _title: 'Mymodule'
      requirements:
        _access: 'TRUE'

```

And my menu.links.yml like that

```
    mymodule.admin:
      title: 'Mymodule'
      description: 'Manage mymodule'
      parent: system.admin_confifg_content
      route_name: mymodule.mymoduleform
      weight: 100

```

Pityfully the doku is very thin about that hope you guys have a clue bout this :)

Or maybe i have to figure out how I get the right parent. **I want that menu link displayed under "Content Authoring"**

# Answer
Have a look at filter.links.menu from core. There you can see how the filter module is placing its link under 'Content Authoring'. You can do is the same way.
> 0 votes

---
Tags: 8
---