# Question
Title: Is it better to use module_invoke_all(), or  module_invoke() and module_implements()?
Using `module_invoke_all('some_hook')` is easy, but is this better for performance?

```
foreach (module_implements('some_hook') as $module) {
  $data = module_invoke($module, 'some_hook');
}

```

# Answer
> 11 votes
There is little difference; `module_invoke_all()` runs the following code:

```
function module_invoke_all() {
  $args = func_get_args();
  $hook = $args[0];
  unset($args[0]);
  $return = array();
  foreach (module_implements($hook) as $module) {
    $function = $module . '_' . $hook;
    if (function_exists($function)) {
      $result = call_user_func_array($function, $args);
      if (isset($result) && is_array($result)) {
        $return = array_merge_recursive($return, $result);
      }
      elseif (isset($result)) {
        $return[] = $result;
      }
    }
  }

  return $return;
}

```

The only difference is that with `module_invoke_all()`, for example, `func_get_args()` is invoked only once, while when using `module_invoke()` `func_get_args()` is called each time `module_invoke()` is called; that is a marginal difference, though.
There are a few cases where `module_implementing()` and `module_invoke()` are used, normally when a module needs to know which module is invoked, such as in the case of `search_get_info()` that builds an array of information about the modules implementing search functions.

```
function search_get_info($all = FALSE) {
  $search_hooks = &drupal_static(__FUNCTION__);

  if (!isset($search_hooks)) {
    foreach (module_implements('search_info') as $module) {
      $search_hooks[$module] = call_user_func($module . '_search_info');
      // Use module name as the default value.
      $search_hooks[$module] += array(
        'title' => $module,
        'path' => $module,
      );
      // Include the module name itself in the array.
      $search_hooks[$module]['module'] = $module;
    }
  }

  if ($all) {
    return $search_hooks;
  }

  $active = variable_get('search_active_modules', array('node', 'user'));
  return array_intersect_key($search_hooks, array_flip($active));
}

```

Another example is image\_styles(), which gets the list of all the image styles implemented by the modules, and that uses the following code:

```
  foreach (module_implements('image_default_styles') as $module) {
    $module_styles = module_invoke($module, 'image_default_styles');
    foreach ($module_styles as $style_name => $style) {
      $style['name'] = $style_name;
      $style['module'] = $module;
      $style['storage'] = IMAGE_STORAGE_DEFAULT;
      foreach ($style['effects'] as $key => $effect) {
        $definition = image_effect_definition_load($effect['name']);
        $effect = array_merge($definition, $effect);
        $style['effects'][$key] = $effect;
      }
      $styles[$style_name] = $style;
    }
  }

```

In both the cases, the retrieved information is put in an array where the index is the short name of the module.

# Answer
> 5 votes
When you have a look at the code, module\_invoke\_all does just that, plus a couple of sanity checks. And it is easy. :-)

# Answer
> -1 votes
It's probably better to use neither, and instead use drupal\_alter().

As stated in the module\_invoke\_all() documentation,

> All arguments are passed by value. Use drupal\_alter() if you need to pass arguments by reference.

---
Tags: 7, hooks, performance
---


title: Entity Translation and Taxonomy

text:
# Question
Title: Entity Translation and Taxonomy
I'm having hard time integrating Entity Translation module with tags (Taxonomy and TagClouds modules). I want the following:

* Cloud of tags to be showed on the site
* Tags must be translatable, i.e. each tag must be showed in English or Russian, depending on the current language.

There are at least two problems. The first is that ET module breaks TagClouds. More specifically, **whenever I enable these two modules (in any order), showed cloud of tags disappears.** What is more suprisingly, it even doesn't matter was translation of tags enabled in ET module or not ( `admin/config/regional/entity_translation` -\> translatable entity types -\> taxonomy term) -- cloud of tags always ends up disappeared. Dblog doesn't show any errors. Is there any other place I can check for them?

The second problem is that if I make taxonomy term translatable in ET, I get strange errors when I'm trying to translate terms. For example:

* If I get to the page of some tag created before enabling ET, for example`en/taxonomy/term/8`, than click `Translate` tab, I will see that current name is not English nor Russian. If click `add` button in either language, I will get not found error -- see screenshots.
    + If I click to `edit` button in list of tags (`admin/structure/taxonomy/tags`), I will get even more interesting error -- `Access denied, You are not authorized to access this page.`
    + Finally, If I click `add items` on some vocabulary and save it, I will get the following exception: `Exception: Invalid translation language in EntityTranslationDefaultHandler->setTranslation() (line 635 of /var/www/drupal/sites/all/modules/entity_translation/includes/translation.handler.inc).`

`Name` and `Description` fields of tags are marked as translatable (`admin/structure/taxonomy/tags/fields/name_field` -\> `Field translation
Users may translate all occurrences of this field: Name in Теги`)

What I am doing wrong?

Drupal version is 7, all modules are up to date. I also use i18n modules for translating the interface, by the way.

# Answer
> 1 votes
The exception can be fixed by visiting the following page: 'admin/config/regional/entity\_translation'.

Then make sure that under the vertical tab 'taxonomy term' and the fieldset of your vocabulary the following is unchecked: 'Hide language selector'.

You may need to check 'Exclude Language neutral from the available languages' if that doesn't work.

---
Tags: taxonomy-terms, i18n-l10n
---


# Question
Title: How to get all node ids from same content type
I am using Drupal 8 and I want to create related content, but the problem is that I can't figure it out, how I can get all node IDs(except current one) for a specific content type.

# Answer
This is a basic query that returns last 10 changed nodes (published) of type 'article'. Modify for your needs.

```
$query = \Drupal::entityQuery('node')
  ->condition('status', NODE_PUBLISHED)
  ->condition('type', 'article')
  ->range(0, 10)
  ->sort('changed', 'DESC');
$nids = $query->execute();

```
> 0 votes

---
Tags: 8, nodes
---


# Question
Title: How to automatically add new users to a OG Group (MyCommunity) using Rules?
This is a configuration task.

it continues the request here: Automatic add user to organic groups

# Task

Using Rules UI: all new users are automatically members to group MyCommunity

# Steps

1. Events: After saving a new user account
2. Conditions : none
3. Actions: OG: Add entity to a group

But how to configure data selector to get a specific group: MyCommunity?

# UPDATE

Apparently there is no clean way to do that other by a patch: https://drupal.org/node/1706884

# Answer
> 1 votes
One of the elements you can use under actions is "Fetch entity by id". Say the node id of your MyCommunity group is 10, then the Entity type value will be Node, and the Identifier value is 10. In the Provided variables section, you give your fetched entity a label and variable name. Let's give it a label of MyCommunity, and name it my\_community. Save the action element. The next action element to add is "Add entity to group". The Entity data selector is the new user so give it the value of "account". Then under group, the data selector is the variable name we created in the previous step, which is "my\_community". I tested this out locally and it worked. Here's an export of the rule.

```
{ "rules_115407" : {
    "LABEL" : "115407",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "TAGS" : [ "stackexchange" ],
    "REQUIRES" : [ "rules", "og" ],
    "ON" : { "user_insert" : [] },
    "DO" : [
      { "entity_fetch" : {
          "USING" : { "type" : "node", "id" : "10" },
          "PROVIDE" : { "entity_fetched" : { "my_community" : "MyCommunity" } }
        }
      },
      { "og_group_content_add" : { "entity" : [ "account" ], "group" : [ "my_community" ] } }
    ]
  }
}

```

# Answer
> 0 votes
A much simpler approach tha works well on my site:

```
{ "rules_new_members_belong_to_this_group" : {
    "LABEL" : "22 - New members automatically belong to this group",
    "PLUGIN" : "reaction rule",
    "WEIGHT" : "0",
    "OWNER" : "rules",
    "REQUIRES" : [ "og", "rules" ],
    "ON" : { "user_insert" : [] },
    "DO" : [ { "og_subcribe_user" : { "user" : [ "account" ], "group" : "24" } } ]
  }
}

```

24 is the gid or group ID number. When you create the rule it is the name of the group that you select, not its ID number.

---
Tags: rules, organic-groups
---


title: Turn text or link field in image

text:
# Question
Title: Turn text or link field in image
Users can enter links in separate fields that lead to their facebook, youtube pages.

On output i would like to use images for those fields instead of showing ugly links.

Is there a module to acomplish this ?

# Answer
> 1 votes
The best way to implement this is to implement a custom display formatter for the link field. You can either do it directly in a custom module by implementing `hook_field_formatter_info`.

Or without try out Custom Formatters module if you want to avoid custom code:

> The Custom Formatters module allows users to easily create custom Field Formatters without the need to write a custom module. Custom Formatters can then be exported as CTools Exportables, Features or Drupal API Field Formatters.

# Answer
> 0 votes
Try this modules

1. Image Link Formatter
2. Link Image Field

# Answer
> 0 votes
You can also do the same using CSS. Just set color of link as white, and place background-image for the anchor tag, and set text-indent.

---
Tags: 7, entities, navigation
---


# Question
Title: Error when updating Bootstrap 7.30 to 7.35
Im getting the following error when visting the root of my Drupal 7 project after updating the sites bootstrap theme from 7.30 to 7.35.

```
Notice: Undefined index: element in bootstrap_menu_link() (line 22 of /Users/Chris/Sites/iss-mw/sites/all/themes/bootstrap/templates/menu/menu-link.func.php).
Recoverable fatal error: Argument 3 passed to l() must be of the type array, null given, called in /Users/Chris/Sites/iss-mw/sites/all/themes/bootstrap/templates/menu/menu-link.func.php on line 52 and defined in l() (line 2481 of /Users/Chris/Sites/iss-mw/includes/common.inc).

```

Seems to be some issue with the menu-link.func. Anyone know what this could be?

Cheers!

# Answer
> 0 votes
This is probabbly not related to bootstrap theme itself, because the function `bootstrap_menu_link()` is the same in both versions. As I can see the error is because the `element` key is empty

```
22. $element = $variables['element']

```

So, when the the function try to call the `l()` function, throw an error fatal, because is expecting an array as 3rd argument

```
52. $element['#title'] = l($element['#title'], $element['#href'], $element['#localized_options']);

```

---
Tags: 7, theming
---


# Question
Title: How to switch OG group members in bulk to another group
D7. I have Organic Group (OG) installed. Out of the approximately 150 groups on my website, one is sticky and titled "Welcome New Members." It has about 2,000 members. Recently, a problem developed with that group only and a user gets a 500 error when posting. Another kind of error is "The website encountered a difficulty. Please... blah blah."

The other groups seem to be working fine.

I could be wrong, but it seems to me that the easiest way to fix this is to create another group and transfer all the group members, along with their posts to the new group. Then I could delete the original group and its content.

Looking at the data base table "og\_membership" I see that all members of all groups are mixed together in the same table.

I need to extract those nodes and users that belong to that one group. I guess a dump of selected users and nodes based on the group ID could do the trick. But how do I upload them back into the same table with a different *gid* or *etid* so they also belong to the new group? Or is there a way in the data base to "search and replace" a group ID (gid) with another?

I have tried the following formula but I am being told it is the wrong syntax (`etid` is the entity ID:)

```
update [og_membership] set [etid] = replace([etid],'[776]','[10177]');

```

Any pointer would be greatly appreciated. :)

# Answer
OK. Finally got it right. The easiest way to do this is to do a dump of the og\_membership table into a text file.

Then run a "search and replace" for the *gid*, replacing the old *gid* with the new one. A simple word processor is ideal for this. Any string replacement can be handled this way.

Then importing that text file into the og\_membership table.

Voila! All members have switched to the new group and they don't even know it! :)
> 0 votes

---
Tags: organic-groups
---


# Question
Title: Disable publish and unpublish options in VBO on the main content view for one role
We have a situation where a user that has a role without permissions to administer nodes is able to bypass that restriction and use the VBO widget to mass-publish or -unpublish nodes on the system content view at `/admin/content`.

My thought was to unset the `publish` and `unpublish` values from the select box definition, but after debugging with `hook_form_alter`, I discovered I could not see the element in the form definition.

I next tried to look at the view object with `hook_view_pre_view`, but I don't see it there either?

How can I selective alter the VBO widget? We don't want to get rid of it altogether, but we can't have people without permissions publishing and unpublishing nodes.

**Edit:** I found this question, but it only explains how to delete those operations altogether, for everyone, which is not what we want. We only want them gone for people who don't have permission to publish or unpublish.

# Answer
Views Bulk Operations (VBO) contains a sub module called ACTIONS PERMISSIONS:

> A module called actions\_permissions is included in the package. This module generates a permission for each action, and VBO honors those permissions before showing or executing the corresponding actions. This is useful if you want to provide your VBO to several groups of users with different privileges: the same view will accommodate those different groups, showing to each the actions that they are permitted to see.
> 1 votes

---
Tags: views
---


# Question
Title: Help using hook_theme() on custom module
I've been writing a custom module to spit a content type into 2 pages, with custom fields accessible via a tab. For ease I've built the test case on a fresh d7 install and using the predefined article content type.

My module folder has the following files:

Now, the template file is simply a copy of the bartik themes node.tpl.php file, but for some reason the module will not load it. I've read through the hook\_theme() page and used the examples for developers theming\_example, but I just can't get it to work.

Any help would be greatly appreciated.

-------- UPDATED CODE ----------------

```
    <?php
    /**
     * Implements hook_menu().
     */
    function article_page_menu() {

      $items['node/%/info'] = array(
        'title' => 'Info',
        'page callback' => 'article_page_page_callback',
        'page arguments'   => array(1),
        'access callback' => 'article_page_access_callback',
        'access arguments' => array(1),
        'type' => MENU_LOCAL_TASK, // tab instead of MENU_CALLBACK
        'weight' => '1000', // last tab item
      );

      return $items;
    }

    /**
     *  Page Callback
     */
    function article_page_page_callback($nid) {
      if (is_numeric($nid)) {
        $node = node_load($nid);

        if($node->type == 'article') {
          return theme('article_page_template', array('node' => $node));
        }

        drupal_not_found();
        return;
      }
      return FALSE;
    }

    /**
     *  Create the access callback
     */
    function article_page_access_callback($nid) {
      if (is_numeric($nid)) {
        $node = node_load($nid);
        // only show for article types
        if($node->type != 'article'){
          return FALSE;
        } else {
          return TRUE;
        }
      }
      return FALSE;
    }

    /**
     * Implements hook_theme().
     */
    function article_page_theme($existing, $type, $theme, $path) {
      return array(
        'article_page_template'  => array(
          'template' => 'article_page_template',
        ),
      );
    }

    function theme_article_page_template($variables) {
      $node = $variables['node'];
      $build = node_view($node);
      $output = drupal_render($build);
      return $output;
    }

```

------------ END UPDATED CODE -----------

--------- BELOW IS THE OLD CODE ---------------------

Here is the code from the module file:

```
        <?php
        /**
         * Implements hook_menu().
         */
        function article_page_menu() {

          $items['node/%/info'] = array(
            'title' => 'Info',
            'page callback' => 'article_page_load',
            'page arguments'   => array(1),
            'access callback' => 'article_page_access',
            'access arguments' => array(1),
            'type' => MENU_LOCAL_TASK, // tab instead of MENU_CALLBACK
            'weight' => '1000', // last tab item
          );

          return $items;
        }

        /**
         * Constructs a descriptive page.
         */
        function article_page_load($nid) {
          if (is_numeric($nid)) {
            $node = node_load($nid);

            if($node->type == 'article') {
              // convert object to array
              // else we get an error
              $build = node_view($node);
              $render = drupal_render($build);
              return $render;
            }
            drupal_not_found();
            return;
          }
          return FALSE;
        }

        /**
         *  Create the access callback
         */
        function article_page_access($nid) {
          if (is_numeric($nid)) {
            $node = node_load($nid);
            // only show for article types
            if($node->type != 'article'){
              return FALSE;
            } else {
              return TRUE;
            }
          }
          return FALSE;
        }

        /**
         * Implements hook_theme().
         */
        function article_page_theme($existing, $type, $theme, $path) {
          return array(
            'article_page_template'  => array(
              'template' => 'article_page_template',
            ),
          );
        }

```

# Answer
It seems like there are quite a few elements in your module code that are used incorrectly. For example, your page callback should not be a hook (you are using hook\_load()) and the callback should call theme() and invoke your custom theme function. In addition, your hook\_theme() implementation is incorrect and you will also need to implement hook\_theme\_registry\_alter() in your module to let the theme system know about your template file.

There is a good example of all this that you can base your code off of in this comment in the API for hook\_theme()

Also, you seem to be mixing together the terms 'node' and 'page' so I am unsure whether you are using the terms correctly (i.e. I'm not sure if you're mistakenly using a node template as your basis when you may really want to use a page template, etc.)
> 3 votes

# Answer
You have a quick tutorial for hook\_theme in D8 here if you need: http://westweb-solutions.com/blog/drupal-8-how-use-hooktheme. It's a bit more tricky, but D8 is gaining ground quickly.
> 0 votes

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


# Question
Title: When a link is clicked, a value is retrieved from the table and displayed on a Webform field
I have created a basic page with two buttons, "Yes" and "No". When the "Yes" button is clicked, it is directed to the webform.

Aim: When the webform appears, it displays a value from the table into a field.

**Database**

* Table name: Room
* Field: Room
* Data: Training Room

**The Basic Page**

**The Webform**

I created a module for this functionality:

**test\_presave.info**

```
name = "Test presave"

description = "Retrieving data from table"

core = 7.x

package = Test

```

**test\_presave.module**

```
/*

*Implements hook_node_presave()

*/

function test_presave_node_presave($node)

{

    $accessnode=$node->nid;

    if($accessnode==20)//Lettable Room Booking webform

    {

        $result=$db_query("SELECT Room FROM {Room} WHERE Room =:ln",array(':ln'=>'Training Room'))->fetchCol();

        $node->webform['components'][1]['value']=$result;

    }

}

```

Am I using the correct hook?

Do I have to use the node api or the webform api?

Can you help me with this?

# Answer
> 0 votes
Rather do this:

Alter the button link to include a parameter:

```
<a href="./lettable-room-booking?captured=true">Yes</a>

```

In hook\_form\_alter, check for the parameter and set the default value(s):

```
function test_presave_form_alter(&$form, &$form_state, $form_id) {
    // dpm($form_id); // uncomment to get $form_id
    // dpm($form); // uncomment to get $form
    if ($form_id == 'webform_client_form_2') { // use dpm($form_id) to get your form id
        $param = drupal_get_query_parameters();
        if (isset($param['captured']) && $param['captured'] == "true")
        {
            $result = ...
            if ($result) {
                $form['submitted']['room']['#default_value'] = $result; // use dpm($form) to get your room field
            }
        }
    }
}

```

---
Tags: 7, nodes, database, webforms
---


# Question
Title: How can I display sql query from database?
I'm trying to display sql query on page in drupal 8.2, but I get an error:

> The controller must return a response (Object(Drupal\Core\Render\Markup) given).

How should I change the following code?

```
if ($result = $mysqli->query("SELECT id, discipline, teacher FROM canteach")) {
  $output .= "Select вернул " . $result->num_rows . " строк <br />";
}

$mysqli->close();

$header = array('id', 'Discipline', 'Teacher');
$rows = array();

while ($row = $result->fetch_array(MYSQLI_NUM)) {
  $rows[] = array($row->id, $row->discipline, $row->teacher);
}

$result->close();

$items_array = array(
  '#theme' => 'table',
  '#items' => array('header' => $header, 'rows' => $rows),
);

return render($items_array);

```

# Answer
> 2 votes
From the error, I assume your code is in a controller? In that case, take note that you should return a render array or an object inheriting the Response class, not HTML.

In your case, just do:

```
return $items_array;

```

instead of

```
return render($items_array);

```

**But wait!**

The table render array should be constructed this way:

```
$items_array = array(
  '#theme' => 'table',
  '#header' => $header,
  '#rows' => $rows,
);

```

For a reference of what you can pass in, check out https://api.drupal.org/api/drupal/core%21modules%21system%21templates%21table.html.twig/8.1.x

**Other notes**

The way you are querying data is not wrong per se but definitely not the "Drupal way". To perform queries using Drupal's DBAL, check out https://api.drupal.org/api/drupal/core!lib!Drupal!Core!Database!database.api.php/group/database/8.2.x

---
Tags: 8
---


# Question
Title: Customize Rate module using Cpanel/Hostmonster
I am using rate module(https://www.drupal.org/project/rate) for drupal 6, I want to use it in panels which is hostmonster but I dont know how, I have read the "readme.text" and it says I should put the php script somewhere in drupal. Can you help me on how to do this, most of forums say the same, but some users like me are real newbies, I'd love to use the module, please help me on this, or perhaps you could write a step by step on how to do it.

# Answer
The readme states you should enable the PHP input filter (The PHP module which is part of Drupal core). Then you can choose to use PHP code instead of Full- or Filterend HTML. You should place the code there.

Also be aware that Drupal 6 is officially no longer supported and you are encouraged to update to Drupal 7 or Drupal 8. (See On February 24th 2016, Drupal 6 will reach end of life and no longer be supported.)

From the README:

```
8. Using rate in blocks or panels
--------------------------------------------------------------------------------
You can place the rate widget on a node page in a block or (mini) panel. Add
a custom block with the PHP code input filter or a panel with PHP code and use
the following code:

<?php
if (arg(0) == 'node' && is_numeric(arg(1)) && $node = node_load(arg(1))) {
  node_invoke_nodeapi($node, 'view');
  print $node->rate_NAME['#value'];
}
?>

Replace NAME by the widget's machine readable name.

The display setting for nodes must be set to "Do not add automatically".

```
> 1 votes

---
Tags: rating
---


title: Devel dpq() not working?

text:
# Question
Title: Devel dpq() not working?
I am trying to print the sql generated from the view but its not working. Below is the error message I am getting:-

```
Fatal error: Call to a member function arguments() on a non-object in /var/www/Exaxmple-Site/sites/all/modules/devel/devel.module on line 1834

```

I have seen many of them using this function to print the sql statement but in my case its giving error. Below is the code how I am calling the function.

```
function example_views_query_alter(&$view, &$query) {
    if ($view->name == 'search_jobs'){

        dpq($view->build_info['query']);
    }
}

```

Has anyone experienced this issue before?

# Answer
If you want show sql query you can use code below:

```
function example_views_pre_execute(&$view) {
  if ($view->name == 'search_jobs'){
        dpq($view->build_info['query']);
    }
}

```

In your code function dpq error because variable $view-\>build\_info\['query'\] is **NULL**. The function dpq only run when variable is **An object that implements the SelectQueryInterface interface**.
> 3 votes

---
Tags: 7, debugging
---


# Question
Title: How can I ensure I retain access to a Drupal site after handing it over to a client?
Does Drupal have a mechanism which will allow me to keep control over a site after handing it over to a client?

If things go wrong with the client relationship, I need to be sure I still have control over the website.

# Answer
> 3 votes
Yes, as the developer you can control this:

1. Make sure only you know the (strong) password to the admin (user 1) account.
2. Make sure Drupal core and modules are up-to-date to mitigate possibility of a security hole that may expose the user 1 login.
3. Make sure only you have access to the files/database for the site; that way your client can't change data manually that might give them access, or run PHP scripts to do the same.
4. If you have the PHP filter module enabled, disable it, or at the very least make sure your client can't use it.
5. Install User One to stop users with the "Administer Users" permission from editing user 1's password.
6. Make sure no other user has permission to "Administer Permissions" and "Administer Modules" so they can't grant permissions to them selves, disable User One or other critical modules.

There may be some more steps you can/should take, depending on the nature of your relationship/hosting/etc, but those should cover the basics from a Drupal perspective.

I'd strongly recommend being up-front with your client about this. Call it a 'policy' that you have, to ensure a smooth relationship, and position it that your having access to the site for maintenance/updates is actually the right move for *them*, not just you.

# Answer
> 2 votes
Apart from the Drupal specific actions (as described in the previous answer), you may also want to consider additional approaches that will give you another level of control over a Drupal website, as further detailed below.

# Contract

Put an appropriate phrasing (clause) in your contract with your client about that website. Something like so "*For as long as client 'uses' (which means 'so and so') this website, client agrees that 'I' keep control (which means 'so and so') over this website. Any time Client violates this obligation, a penalty of X $$$ is due (by the client), for each period of 24 hours that Client does not remedy such violation, notwithstanding any additional damages due to this violation to be compensated on top of that.*".

Your client is not going to easily agree to such clause, but after you get it in your contract, you're in pretty good shape. If you can't reach an agreement on that, and you really need that control, then better run away from this client.

# Payment terms

If the background of your question is that you want to be sure that you get payed for the work you did to build the site (as in version 1 of your question ...), then that is something to think about upfront and get it included in your contract. Something that IMO could be a good compromise is like so:

* Split the payment of the total invoice amount in 3 slices (instalments). Receiving the very first payment (slice) is considered as the final approve of the customer to accept your offer to build the site (and only then you start working on it).
* The 2nd payment is due when you first show/demonstrate the newly developed site to the customer (which may include giving the customer limited access to the site also).
* The 3rd (final) payment is considered as the final approve of the customer of the delivered site, in the state the site is in at that very moment. And after that payment is received, you ensure that within a reasonable amount of time (eg 7 days) you "turn over the keys to the kingdom" (aka give all access of the site to the customer).

# Trusted 3rd party

Get a trusted 3rd party involved, such as a "*Software Escrow Agency*". You turn over whatever is needed (eg: passwords, etc) to have full control over the site. The 3rd party only forwards that to your client after all conditions are satisfied (eg after you confirmed you received the payments, if that's what the background of your question is.

And for this to work smoothly, you create a 3 party agreement that all parties agree to upfront, and which includes appropriate details about what exactly the "deposit" is about (password(s), keys, software, etc.), and what the conditions are for the intermediate party to give the client access to what you deposited with that 3rd party.

This approach (which is not cheap, so you may want to include the cost of it in what you charge the client ...) often helps it you're a small company, and your client is a huge organization (that really needs "something" from a tiny niche company, which may even be located in another country).

# Hosted solution

Your question doesn't specify what type of control you want to have/keep, but "a" possible reason might be because you've created a Drupal based website which is using GPL software.

So "if" you want to prevent your client to provide a copy of the typical Drupal components (modules, etc that you are handling over to your client) to some other 3rd party, without your prior approval (whatever that would take, eg some fee?), "then" you might want to try to convince your client to accept a hosted solution (by you, or some 3rd party you have an agreement with). Whereas you ensure that the client receives all the benefits (functions, etc) of the website, possibly exclusively also, but without giving them access to those typical Drupal components.

With this approach, you also have the right (unless your contract with your client stops you from doing so) to reuse these Drupal components for other clients.

# DNS

If "you" have control over the DNS settings used to access the Drupal site (eg because you are the owner of the domain name), then that gives "you" another level of control of the site that the domain name refers to.

---
Tags: security
---


title: Remove language prefix from custom URL

text:
# Question
Title: Remove language prefix from custom URL
Our site exists in several languages. I have installed xmlsitemap module and default link looks like sitename/en/sitemap.xml

I need to remove language prefix just for this link. It seems like there's no settings to disable translation for any specific custom link.

May be I can do it programmatically?

# Answer
Why not just add a redirect in .htaccess or similar, e.g.?

```
RewriteRule ^sitemap.xml$ /en/sitemap.xml [R=301,L,QSA]

```
> 2 votes

# Answer
Hope this will work just add a redirect in .htaccess as

```
RewriteEngine on
RewriteRule ^en/(.*)$ /$1

```
> 0 votes

---
Tags: 7, i18n-l10n, uri
---


# Question
Title: How to make views header sticky while scrolling?
I have created report using drupal views and i used views\_merge\_rows module. Now i wanted to create sticky header of report table. Can any one please help me.

# Answer
> 4 votes
1. Under the format in views select table.
2. Got to settings on table there will find the checkbox named Enable Drupal style "sticky" table headers (Javascript) . Enable it
3. In views preview u can see the sticky headers of the table.

---
Tags: views, theming
---


# Question
Title: how to alter exposed form values before submit for filters in drupal7 view
I want to do left and right trim when end user enters data in textbox for filter list of rows in drupal 7 views

# Answer
> 1 votes
```
function example_form_alter(&$form, &$form_state, $form_id) {
 array_unshift($form['#validate'], 'example_request_validate');
}

function example_request_validate(&$form, &$form_state) {
  if (isset($form_state['values']['text_field']) && !empty($form_state['values']['text_field'])) {
    $request_id = $form_state['values']['field_request_id_value'];
    if (strchr($request_id,''))) {
      $request_id = ltrim(strchr($request_id,''), '');
    }
    form_set_value($form['text_field'], $request_id, $form_state);
  }
}

```

---
Tags: views
---


title: Rename the sub-total line

text:
# Question
Title: Rename the sub-total line
currently on my orders, I have the line "sub-total". How to change the name to "subtotal without promotions" ?

# Answer
> 1 votes
You can do it in a custom module using the `hook_commerce_price_component_type_info_alter` hook.

*Remember to replace HOOK with your module name.*

```
function HOOK_commerce_price_component_type_info_alter(&$component_types) {
  $component_types['base_price']['display_title'] = t('Subtotal without promotions');
}

```

---
Tags: commerce
---


# Question
Title: Commerce add product attribute without adding new product variations
I have found this Commerce manual: Product Attributes & Variations, which explains the differences and connections between fields, attributes and variations, where in the end they assign a different product to each product display.

The situation I am in is as follows. Let's say I sell lunchboxes. The same model is available in 5 colors and the lid is always white. But now I want to add an option to the shop where people can order a lid in the same color as the lunchbox. My SKU's are as follows:

* lunchbox\_red
* lunchbox\_blue
* lunchbox\_...

I was hoping this could become a simple product attribute (a checkbox?), but it seems I will have to add a second version of my 5 products with the extra costs of the lid:

* lunchbox\_red
* lunchbox\_red\_lid\_red
* lunchbox\_blue
* lunchbox\_blue\_lid\_blue
* lunchbox\_...

I initially wanted to let people choose the color of the lid, but that would require me to maintain 25 different products for each box-lid combination!?

* lunchbox\_red
* lunchbox\_red\_lid\_red
* lunchbox\_red\_lid\_blue
* lunchbox\_red\_lid\_...
* lunchbox\_blue
* lunchbox\_blue\_lid\_red
* lunchbox\_blue\_lid\_blue
* lunchbox\_...

Since I don't really care about the photo (I would definitely need a product for each lid combination in that case), I was hoping for a smarter way to implement this.

Can I add a general attribute (with added costs) to all product variations without adding all the products? The price for the coloring of the lid will be a fixed price, not depending on the color used.

# Answer
> 3 votes
It appears I have been looking for Commerce Pricing Attributes. There is one SKU with a base price and I can manage the attributes and add a price modifier for each of them.

This screenshot from the module page explains it all:

# Answer
> 0 votes
You could bundle your products with commerce\_product\_bundle.

> So you only have the lunchboxes and the lids in their variations. and combine them in bundles.

---
Tags: 7, commerce
---


# Question
Title: "drush sql-sync" failing with Illegal string offset 'site' backend.inc:1030
I'm using Drupal 8. I have an installation on my local dev machine as well as one on my remote demo machine. I'm attempting to use drush `sql-sync` so that I can make sure my local dev has the same data as my remote demo.

The command I'm running is:

```
drush sql-sync @remote.demo @local

```

The error is:

> ### Illegal string offset 'site' backend.inc:1030
>
> The command could not be executed successfully (returned: env: drush: No such file or directory, code: 127)
> Error: no database record could be found for source @remote.demo

My aliases file is ~/.drush/aliases.drushrc.php.

```
<?php

$local = '/var/www/drupal/';
$aliases['local'] = [
    'root' => $local,
    'path-aliases' => [
        '%dump-dir' => "{$local}drush.dbdumps",
    ]
];

$remote = '/var/www/drupal/';
$aliases['remote'] = [
    'remote-host' => 'x.x.x.x',
    'remote-user' => 'myUsername'
];

$aliases['remote.demo'] = [
    'parent' => '@remote',
    'root' => $remote,
    'path-aliases' => [
        '%dump-dir' => "{$remote}drush.dbdumps"
    ]
];

?>

```

I know it's being picked up because it shows up in `drush status`.

This is a snippet of backend.inc (the file referred to in the error):

```
1028        if ($proc['output']) {
1029            $values = drush_backend_parse_output($proc['output'], $proc['backend-options'], $proc['outputted']);
1030            $values['site'] = $site;
1031            if (is_array($values)) {

```

It seems to me that `drush_backend_parse_output()` is parsing something incorrectly but I'm unable to figure this one out. Any idea what I'm doing wrong?

**UPDATE** I ran the drush command with the verbose flag:

```
drush -v sql-sync @remote.demo @local

```

The output is long but the relevant output is:

```
ssh -o PasswordAuthentication=no myUsername@x.x.x.x 'env COLUMNS=112 drush --backend=2 --verbose --root=/var/www/drupal/  sql-conf   --all 2>&1' 2>&1                       [notice]
Illegal string offset 'site' backend.inc:1030

```

It seems like the drush command run on the remote machine is generating output that my local drupal is tripping on. Not sure how to resolve this though.

**Note**: `drush --version` gives me `Drush Version : 8.0-dev` on both machines.

# Answer
I had same issue and fixed it by specifying the `%drush-script` path for my remote machine alias. Just ssh into your remote machine and run "drush status" to find the correct "Drush script" path and put it in under `path-aliases` array. So it would look like this:

```
'path-aliases' => array(
  '%drush-script' => '/{your_path}/drush.php',
)

```
> 1 votes

---
Tags: 8, drush
---


title: Creating custom blocks

text:
# Question
Title: Creating custom blocks
I am building a custom block. The content of module\_name/src/Plugin/Block/MyCustomblockName.php is the following.

```
    namespace Drupal\module_name\Plugin\Block;

    use Drupal\block\BlockBase;
    use Drupal\Core\Session\AccountInterface;

    /**
     * Provides a 'Demo' block.
     *
     * @Block(
     *   id = "demo_block",
     *   admin_label = @Translation("Demo block"),
     * )
     */

    class MyCustomblockName extends BlockBase {

      /**
       * {@inheritdoc}
       */
      public function build() {
        return array(
          '#markup' => $this->t('Hello World!'),
        );
      }

      /**
       * {@inheritdoc}
       */

  public function access(AccountInterface $account) {
    return $account->hasPermission('access content');
  }

}

```

It doesn't display the block at all. What could be the reason?

# Answer
1. From the above code replace:

```
use Drupal\block\BlockBase;

```

with:

```
use Drupal\Core\Block\BlockBase;

```

Then *Flush cache* and check.
2. Go to *Structure*, *BlockLayout* and click on *Place block*.
> 5 votes

---
Tags: 8, blocks
---


# Question
Title: How do I see *which user* last updated a node?
In `admin/content`, how might I override this display to list **the User who last updated** a piece of content. We can see the initial author and that's fine. But I'd like a running trail on who touched a node.

### What I've tried

* *Revisions:* However, some Content Types use a field by Jquery Tabs which lose their content when going back to a certain revision.

# Answer
> 3 votes
Use Administration Views module to replace default content page for admins.

Find new View created by that module and add Relationship -

```
Content revision: User

```

Then add field to your View `"User: Name"` and use that relationship on it. It will show you the username of the User who edited content last.

# Answer
> 1 votes
In order for Drupal to be able to save the user that edited the Node, you need to have revisions enabled on the node. So the way to go is to enable revisioning, but prevent users from going back to previous versions.

Drupal comes with the `revert revisions` permission. So just make sure none of the users is able to revert revisions and you should be good.

---
Tags: 7, nodes
---


# Question
Title: How do I change the edit form layout for a custom field type
I created an *Address* custom field type, with two text fields (*street* and *city*).

When I add a new *Address* field on a content type, I get this form inside the edit page.

How can I change the layout of the form above?

For example, I would like to add some space between the *Street* text line and the *City* label, or display both fields on the same line.

This is the code for the `AddressDefaultWidget` class.

```
/**
 * Field type widget implementation.
 *
 * @FieldWidget(
 *   id = "AddressDefaultWidget",
 *   label = @Translation("Address select"),
 *   field_types = {
 *     "Address"
 *   }
 * )
 */
class AddressDefaultWidget extends WidgetBase {

  /**
   * Define the form for the field type.
   */
  public function formElement(
    FieldItemListInterface $items,
    $delta,
    Array $element,
    Array &$form,
    FormStateInterface $formState
  ) {

    // Street

    $element['street'] = [
      '#type' => 'textfield',
      '#title' => t('Street'),
      '#default_value' => isset($items[$delta]->street) ?
          $items[$delta]->street : null,
      '#empty_value' => '',
      '#placeholder' => t('Street'),
    ];

    // City

    $element['city'] = [
      '#title' => t('City'),
      '#type' => 'textfield',
      '#default_value' => isset($items[$delta]->city) ?
          $items[$delta]->city : null,
      '#empty_value' => '',
      '#placeholder' => t('City'),
    ];

    return $element;
  }

}

```

# Answer
> 3 votes
This is off the top of my head, so there might be a few kinks. The way I would do it would be to:

1. Add a new class to each of the form elements that your module produces
2. Create some CSS to pad the top/bottom of elements with this class
3. Tell Drupal to include this CSS file whenever the form elements are on the page

In your Widget file add the following to each element to add an additional class to the form elements.

```
'#attributes' => [
  'class' => 'address_widget_class',
],

```

To add CSS styles to a custom module, you will need to create a few files and directories.

* module/module.libraries.yml
* module/css/style.css

In your CSS file, add the following to add 10 pixels above and below each item.

```
.address_widget_class {
  margin: 10px 0;
}

```

Next, you need to tell Drupal that the CSS file exists. In the module.libraries.yml file, add the following code.

```
style_name:
  version: 1.x
  css:
    component:
      css/style.css: {}

```

Finally, to include the library when the element is used, add the following to your Widget.

```
$element['street']['#attached']['library'][] = 'module/style_name';

```

---
Tags: 8, entities
---


title: Get clean date without any HTML tags

text:
# Question
Title: Get clean date without any HTML tags
I am using the Date module together with a view to display dates, and I need to get the date timestamp. The problem is that `$fields['date_in_timestamp']` content comes wrapped in HTML.

```
<span class="date-display-single"> 1468473300 </span>

```

I need only the value and no HTML.

PS: my field "date\_in\_timestamp" will apply a "U" format for the timestamp.

One possible way I found is described in https://www.drupal.org/node/423870, comment #9. The problem is that this applies to all those who have a certain format, and I don't know how to distinguish them from other similar formats.

Is there any way to get the machine name of the date format?

# Answer
> 0 votes
The solution that worked for me in this case was easier than I thought.

**Solution**:

In the configurations of the view

1.- Select settings Style -\> Customize HTML field -\> None

* Uncheck Add default classes

2.- In Rewrite results -\> Select Strip HTML tags

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


title: How do I render a form as a table?

text:
# Question
Title: How do I render a form as a table?
The default form layout has each form element wrapped in individual div tags, with a label, and input inside. I would like to lay things out neatly, and create a column for the field labels, and another column for the input areas.

I can see this being accomplished in one of two ways: \- I could create a table, using table elements or divs, and separate the labels from the inputs. Would I use Twig for this? \- Alternatively, maybe there's a creative way to use CSS with the default structure to make everything look good. If there is, I can't figure it out.

How should I implement one of these, or another way to accomplish the same thing?

# Answer
I had forgotten about the table-cell and table-row diplay properties. Despite the fact that CSS is off topic, the way to do it given Drupal's form class structure is:

`.form-no-label {
 display: table-cell;
}
label {
 display: table-cell;
}
.container-inline {
 display: table-cell;
}
.label {
 display: table-cell;
}
.form-item {
 display: table-row;
}`
> 4 votes

# Answer
First of all, laying out forms in tables is frowned upon in modern web design, and you should be able to achieve the same effect with CSS. Taking this approach results forms that are better structured for mobile devices and for accessibility requirements such as screen readers. This isn't really a Drupal issue as a general CSS theming one.

A useful module for theming your forms is Form Element Layout, which lets you tweak a number of form aspects, particularly giving separate classes to input fields and their labels: https://www.drupal.org/project/fel (edit: unfortunately this hasn't yet been ported to Drupal 8, so you're probably stuck with the classes you've got, or will have to write your own theming function to add extra classes).

However, if you feel you must use tables, have a look at the #type=table render element (new in Drupal 8). You put the rows of your table as array elements of the table array, and the columns as elements of the row arrays. In your case you would have one row for each form field, and two columns in each row, one for the label and one for the field.
> 2 votes

---
Tags: theming, forms, 8
---


# Question
Title: How should I go about placing the content of a field from a content type into a block?
My case is this: I have a content type called 'Test Type' with 2 fields: Body (text area), Slideshow (Unlimited list of images) When I create an instance of Test Type and it renders, my goal would be to have the content of the Slideshow field go to a different region, let's say the header. First thought was to create a custom block that would hold a reference to the field content, but that does not seem to be an option. Is this possible to do through the UI with certain settings or would I be better off writing a module. The module Field as Block is pretty much exactly what I was looking for but it seems not work right now.

# Answer
this can be possible by using **views** which is now in **core** in **drupal 8**

step 1 :: go to structure-\>views-\>add new views

step 2 :: Add new view ui will be opened

2.1.enter view name

2.2.under view settings select show content of type (the content type whose field you would like to place in an block ex:your required content type)

2. 3.**only check the check box create a block under block settings**

2.3.1.under BLOCK DISPLAY SETTINGS select the display format most likely (unformatted list) of **fields**

2.3.2 now save and edit and you are good to go...

step 3 :: now views ui is opened

3.1.on the top left hand side of the page under title

3.2. under fields select add (an pop up ui will open)

3.3. **select type content** -\>**select the field types of your content you want to display in your block ex-body and so on and so forth as required by you** now apply and save..

3.4. configure field will now open configure as required..you can also rewrite the fields so better follow this link rewrite fields

step 4 :: go to structure-\>blocks-\>place the block as per your required region-\>and find the block(it will be the same name as block name or view name unless changed)

4.1. place the block as per your wish there are many boundaries like selecting content type etc ...but for now **select pages under visibility** leave the check box as default and inside pages type `<front>` \**remember to add less than and greater than sign as well

4.2.now save the block

step 5 :: in the block ui at the bottom also click save blocks and finally **go back to the site**

if all goes right you will see the content of a field from the content type in a block using views
> 2 votes

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


# Question
Title: What exactly is "Overridden", "Needs review" & "Revert component" in Features?
I can see `Overridden`, `Needs review` & `Revert component` in Features.

If I want to get latest updated features always, what I will do?

What `drush fr, drush fu` will do internally?

What I understood is, `overridden` is the state where our current config/settings changed with new features. If we do `revert component`, all the new changes will be reflected. So here what is the drush command shall I use?.

Anyone can explain all these three?

# Answer
> 6 votes
Both **needs review** and **overridden** statuses mean that the feature in the database does not match the feature in code. Running **"drush fr"** (feature revert) will replace the feature in the database with the feature in code.

Now lets see **"Revert" vs "Update"**

**Revert:**(drush fr)

This operation changes your site configuration (living in the database) to match up with the definitions in the feature module code.

**Update / Recreate**:(drush fu)

The update operation will produce a modified version of your feature module, which matches up with the configuration found in the database.

> Remember, revert for Drupal features means copy configuration from code into the database.

If you want to go in detail with simple explanation, then please follow below links

1. Modifying, updating and reverting Features
2. Revert and update a Drupal feature module

# Answer
> 3 votes
# Feature states

**Default**: Everything contained in the feature matches the site's database.

**Overridden**: Something used in the site no longer matches the state of it as contained in the feature.

**Needs review**: This is the same state as **Overridden**, but it means there are more complicated changes and you should review the differences prior to reverting the feature. Remark: use the Features Diff module to simplify the investigation of the changes.

# Feature actions

**Revert**: reverting an overridden feature makes the site settings match those in the feature again. This is equivalent to using drush cmd `drush fr`.

**Update**: updating a feature makes the feature match (in synch with) the site settings. This is equivalent to using drush cmd `drush fu`.

# Video tutorials

---
Tags: features
---


title: Webform draft share link

text:
# Question
Title: Webform draft share link
I would like to create a webform which accepts input from two parties. First party fills out part of a form and share a link with second party to proceed with the rest.

I have found 'save draft' feature useful for this service but only loads pre saved info for the same person. Is there anyway I can share a link (based on sid) so that whenever the URL has a SID parameter, it loads pre saved info?

Thanks

# Answer
I was thinking of creating a custom module that creates **form 1** which saves the info in DB tables with a unique value of SID.

**Form 2**, which has url of `/example/%` the variable % being the sid.

loads info from db using the url parameter.

```
$sid = request_path(); // gets the current page url. ex: example/sid
$sid = str_ireplace('example/','', $sid); // removes the example/ from our variable, so we are left with sid

```

Now that you have the sid inside $sid, you can query the db to grab your fields.

EX:

```
$field1 = db_query("SELECT field1 from {table_name} WHERE sid = :sid LIMIT 1", array(":sid" => $sid))->fetchField();

```

**PS:** In case you are wondering why the mysql query looks the way it does, see Writing secure code and How do I get only one result using db\_query()
> 0 votes

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


# Question
Title: What is the purpose of the config/install directory?
I was trying to use omega theme and found lot of files under omega/config/install. E.g. block.block.omega\_account\_menu.yml, block.block.omega\_branding.yml, omega.layout.omega\_default.yml. I wonder what are the functionalities of these files and how are they being used. Is there any guide to follow? How can I create another one and how can I use it?

# Answer
The config/install directory contains the default configuration of a theme/module. Its purpose is explained in Include default configuration in your Drupal 8 module, which says:

> In Drupal 7 default configuration for modules such as content types, field configuration, views, etc. required custom PHP code to install and keep updated. In Drupal 8, these are stored with the configuration system in plain text YAML files.
>
> For example the configuration management system takes care of creating and managing content types. You can ship a content type with your module by creating a properly named and structured configuration file.

Then, it adds:

> You can include default configuration for other things like block placement, views, text formats, editor configuration, user roles, etc. with your module the same way.

Drupal core itself uses files like block.block.bartik\_powered.yml, or block.block.seven\_messages.yml.

I didn't find a description of the content, but if you look at the content of those files, you can understand what you need to put.

```
langcode: en
status: true
dependencies:
  module:
    - system
  theme:
    - seven
id: seven_messages
theme: seven
region: highlighted
weight: 0
provider: null
plugin: system_messages_block
settings:
  id: system_messages_block
  label: 'Status messages'
  provider: system
  label_display: '0'
visibility: {  }

```

Note that the file declares its dependency from the System module because that is the module implementing the block plugin (`plugin: system_messages_block`).
> 5 votes

---
Tags: 8, theming
---


# Question
Title: Cache remains stale for custom blocks after editing
My Drupal 8 website consists of multiple custom blocks created from the drupal backend user interface.

As I went from dev to production settings and activating `Internal Dynamic Page Cache` (set to 1 minute), the custom block content doesn't change on the actual site after editing (for both anonymous and authenticated users). If I go back to editing mode, the changes are persisted as expected.

The changes are visible when I clear the caches (i.e. drush cache-rebuild). I don't have any issues with my own blocks that implements the Block plugin and has a max-age set. Nodes works works as expected too.

What could be wrong?

# Answer
> 0 votes
hope this works ...

```
<?php
abstract class BlockBase extends PluginBase implements BlockPluginInterface {
  /**
   * Returns generic default configuration for block plugins.
   *
   * @return array
   *   An associative array with the default configuration.
   */
  protected function baseConfigurationDefaults() {
    return array(
      'label' => '',
      'module' => $this->pluginDefinition['module'],
      'label_display' => BlockInterface::BLOCK_LABEL_VISIBLE,
      'cache' => array(
        'max_age' => 0,
      ),
    );
  }
}

```

refer to this link block cache api is removed

The following block cache constants have been replaced with the combination of the cache.max\_age and ::getCacheContexts() return values (or bubbled cache contexts) on blocks:

```
DRUPAL_NO_CACHE (equivalent: cache.max_age = 0)
DRUPAL_CACHE_CUSTOM (equivalent: cache.max_age = 0 + Cache::keyFromQuery())
DRUPAL_CACHE_PER_ROLE (equivalent: cache.max_age >0 + user.roles)
DRUPAL_CACHE_PER_USER (equivalent: cache.max_age >0 + user)
DRUPAL_CACHE_PER_PAGE (equivalent: cache.max_age >0 + url)
DRUPAL_CACHE_GLOBAL (equivalent: cache.max_age >0, no cache contexts)

```

---
Tags: 8, caching
---


title: Similar/related tags block

text:
# Question
Title: Similar/related tags block
There are a lot of ways to build similar content block according to their tags. Is there any way to build similar tags block?

I try to build similar/related tags block.

I want to look at contents and common tags they have. How many times they added to contents together. Something like this:

For example: for first column green is similar for blue. For the third column yellow and blue similar for green.

# Answer
* Create one content views for block
* Relationship \> Taxonomy term: Content with term
* aggregation setting yes
* use count on aggregation setting for the field.

There are other options available over here. https://www.youtube.com/watch?v=w22Utjm-chs
> 0 votes

---
Tags: 7, views, taxonomy-terms
---


# Question
Title: how to force drupal to create tables with ENGINE=MyISAM
this is a popular error in drupal that you guys might have seen this before :

```
PDOException: SQLSTATE[42S02]: Base table or view not found, table .... does not exist.

```

when I'm trying to install drupal7, it reports an error that semaphore table does not exist. I tried to create it manually by this query

```
CREATE TABLE IF NOT EXISTS `semaphore` (
  `name` varchar(255) NOT NULL DEFAULT '' COMMENT 'Primary Key: Unique name.',
  `value` varchar(255) NOT NULL DEFAULT '' COMMENT 'A value for the semaphore.',
  `expire` double NOT NULL COMMENT 'A Unix timestamp with microseconds indicating when the semaphore should expire.',
  PRIMARY KEY (`name`),
  KEY `value` (`value`),
  KEY `expire` (`expire`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='Table for holding semaphores, locks, flags, etc. that...';

```

it reported the same error. I changed `InnoDB` to `myISAM` and it worked!!! I found out that tables with the `InnoDB` engine are not supported in mysql on the server and unfortunately drupal7 creates all the tables with this engine by default. is there any way to change this default to `MyISAM` ?

# Answer
> 3 votes
The schema definitions can take an argument of `'mysql_engine'`, which defaults to 'InnoDB', in createTableSql().

In theory you could thus alter all the defined schemas with a custom module, and change the engine.

It's **highly questionable** to do so though. If you value your site and data, you should **NOT** use MyISAM unless you understand the difference the two engines.

Switch to a provider that supports InnoDB instead. MySQL itself defaults to InnoDB as of 5.5. I would be very suspicious of any provider that didn't support InnoDB.

# Answer
> 0 votes
Try this way: (from here: https://www.drupal.org/node/1089724 )

> In includes\>database\>mysql\>shema.inc, on line 84, I changed 'mysql\_engine' =\> 'InnoDB' to 'mysql\_engine' =\> 'MyISAM'.

It works for me.

# Answer
> 0 votes
Define 'mysql\_engine' =\> 'MyISAM' in your hook\_schima as given below:

```
function hook_schema() {
$schema['table_name'] = array(
'description' => 'Your description.',
'fields' => array(
  'id' => array(
    'description' => 'Auto increment id.',
    'type' => 'serial',
    'unsigned' => TRUE,
    'not null' => TRUE,
  ),
  'old_id' => array(
    'description' => 'The old id.',
    'type' => 'int',
    'unsigned' => TRUE,
    'not null' => TRUE,
  ),
  'Comments' => array(
    'description' => 'Add comment for table.',
    'type' => 'varchar',
    'length' => 200,
    'not null' => FALSE,
  ),
 ),
 'primary key' => array('id'),
 'mysql_engine' => 'MyISAM',
 );
 return $schema;
}

```

---
Tags: 7, database
---


# Question
Title: How to theme the controls of an Openlayer map?
The Openlayers module comes with a default set of maps. It's possible to add layer templates, but it seems that the controls are always the same (see image). The controls exist of images that are located on a CDN such as `http://cdnjs.cloudflare.com/ajax/libs/openlayers/2.13.1/img/zoom-plus-mini.png`

Is there a way to style the controls of Openlayer maps? In other words to apply your own CSS or images to it?

# Answer
The CSS is mostly contained in the js of the module. You can poke around in the openlayers user lists to maybe find a solution.
> 1 votes

# Answer
Have a look at the IP Geolocation Views & Maps module. Partial quote from its project page:

> Despite what the name may suggest, IP Geolocation Views & Maps (IPGV&M) is first and foremost a mapping engine.
>
> The module makes it very easy to create Views-based mapping solutions using the map renderer of your choice (**Google**, **OpenLayers** or **Leaflet**) with any location storage module of your choice, e.g.:
>
> This allows you to bring together modules and feature sets that without IPGV&M you would not be able to combine.
>
> Like beautiful animated marker clustering on Google or Bing or Mapbox ... any of various map providers.
>
> But more importantly IPGV&M adds some features you won't find as conveniently packaged elsewhere.
>
> These include marker differentiation based on field values or ranges (2nd screenshot) with or without font icons, various centering options, super-imposing the current visitor's location, allowing multiple content types to be displayed on the same map, full screen button and mini-map inset (bottom screenshot), polygon support (Geofield), marker tags and tool tips and cross-highlighting of associated content on the page when markers are hovered (and vice versa).

Head over to its (impressive) project page for even more information about it (it would be way too long to include a quote of it all here). That project page also includes various screenshots.
> 0 votes

---
Tags: theming, javascript
---


# Question
Title: Edit weight of block without using drag and drop
I'm attempting to reorder blocks. I understand that it can be done by dragging and dropping on the block structure page, however I have a limitation.

When saving, the order isn't saved. This is most likely because there is a very large number of blocks and the server can't handle that many inputs in one form. So it just reverts to it's original position. I do not have access to the server so I'm unable to make the changes to allow the server to handle that many inputs. I also do not have access to the mySQL database.

I'd like to be able to change the weight manually within the block, but weight is not a field I can edit when attempting to edit that specific block.

Is there a way to add this field? Or is there another possible way to perform this action?

# Answer
This is a very hacky way to do it but I managed to achieve my goal. Through the dev tools on my browser I removed the html of every row of the block table except for the block I wanted to edit. I then changed the weight and submitted.

This worked since only one input was being submitted instead of over 1000
> 0 votes

# Answer
you can do it by using context name in `hook_context_load_alter()` and tweak it.

`/**
 * Implementation of hook_context_load_alter()
 */
function mymodule_context_load_alter(&$context) {
 if ($context->name == 'my_context_name_from_the_ui') {
 $context->reactions['block']['blocks']['my_block_name']['weight'] = -99;
 }
}`
> 1 votes

---
Tags: 7, blocks
---


# Question
Title: Search API: getAutocompleteSuggestions in D8?
How can I use the function **getAutocompleteSuggestions()** in Drupal 8? In Drupal 7 you could do something like this:

```
$query->getIndex()->server()->getAutocompleteSuggestions($query, $this->getSearch(), $incomplete_key, $user_input);

```

Thank you for your help!

# Answer
> 1 votes
I've solved it with Solarium

```
//...
use Solarium\Client;
//...

// $value is the search value from the textfield.
if (!empty($value)) {
    $searchAPIconfig = \Drupal::config('search_api.server.server');
    $searchAPIconfigData = $searchAPIconfig->getRawData();

    $config = array(
    'endpoint' => array(
      'localhost' => array(
        'host' => $searchAPIconfigData['backend_config']['host'],
        'port' => $searchAPIconfigData['backend_config']['port'],
        'path' => $searchAPIconfigData['backend_config']['path'],
      ),
    ),
    );

    $client = new Client($config);

    if ($client !== NULL) {
        $query = $client->createSuggester();
        $query->setQuery($value);
        $query->setDictionary('mySuggester');
        $query->setOnlyMorePopular(TRUE);
        $query->setCount(10);
        $query->setCollate(TRUE);

        $resultset = $client->suggester($query)->getData();
        $results = $resultset['suggest']['mySuggester'][$value]['suggestions'];
        $suggestions = array();
        foreach ($results as $key => $termResult) {
          $suggestions[] = $termResult['term'];
        }

        //...
    }
}

```

---
Tags: 8, search
---


# Question
Title: drupal_mail() sends two emails, second email is empty
I'm using the following code for sending out an email with `drupal_mail()`

```
$module = 'example_module';
$key = 'key';
$language = language_default();
$params = array();
$from = 'email@email.com';
$send = TRUE;
$message = drupal_mail($module, $key, $order->mail, $language, $params, $from, $send);
$message['subject'] = 'Subject';
$message['body'] = $message_body;

// Retrieve the responsible implementation for this message.
$system = drupal_mail_system($module, $key);
// Format the message body.
$message = $system->format($message);
// Send e-mail.
$message['result'] = $system->mail($message);

```

I get two emails after the function that contains this runs, one email is perfect, the other email is completely empty.

The function that contains the code above only runs once, I tested by printing out some text with dsm().

How can I fix this?

Thank you!

# Answer
> 3 votes
The `drupal_mail()` function you call will send an email.

Then when you call `$system->mail($message);` that will send a second email.

Here is an example of how to use `drupal_mail` (taken from here):

```
/**
* Implements hook_entity_insert().
*
*/
function dummy_module_node_insert($node) {
  $module = 'dummy_module';
  $key = 'dummy_key';
  $language = language_default();
  $params = array(
    '@url' => url('node/' . $node->nid, array('absolute' => TRUE)),
    '@title' => $node->title,
  );

  drupal_mail($module, $key, $mail, $language, $params);
}

/**
* Implements hook_mail().
*/
function dummy_module_mail($key, &$message, $params) {
  $message['subject'] = t("@title event registration confirmation", $params);
  $message['body'] = array();
  $message['body'][] = t("Hello", $params);
  $message['body'][] = t("Node has been created @title (@url).", $params);
}

```

The user who posted this code originally labeled it as *"The propper way to use this:"* and I've had success using this code before.

# Answer
> -1 votes
```
$module = 'example_module';
$key = 'key';
$language = language_default();
$params = array();
$from = 'email@email.com';
$send = FALSE; //                               <-- HERE
$message = drupal_mail($module, $key, $order->mail, $language, $params, $from, $send);
$message['subject'] = 'Subject';
$message['body'] = $message_body;

// Retrieve the responsible implementation for this message.
$system = drupal_mail_system($module, $key);
// Format the message body.
$message = $system->format($message);
// Send e-mail.
$message['result'] = $system->mail($message);

```

Just set $send = FALSE; to disable the blank email your code is correct as well

---
Tags: 7, emails
---


# Question
Title: menu_tree_all_data() returns empty arrays for custom menus
This works.

```
$tree = menu_tree_all_data('main-menu');

```

This doesn't work.

```
$tree = menu_tree_all_data('menu-health-center');

```

Why doesn't `menu_tree_all_data()` work for custom menus?

# Answer
> 2 votes
Custom menu machine names always have a prefix of "menu-", e.g.:

```
$tree = menu_tree_all_data('menu-custom-menu');

```

Make sure you're using the right machine name. Edit the menu and look at the URL: The last part of it is the machine name for the menu.

---
Tags: 7
---


# Question
Title: How to change the button name after click on it using ajax
I am a newbie in drupal. I created a form that perform ajax action. How can I change the button name after click by using ajax.

```
function auktion_fav_form($form, &$form_state, $auktion_id) {
  form['add_to_fav'] = array(
    '#type' => 'submit',
    '#id' => 'submit',
    '#value' => t($value),
    '#ajax' => array(
      'callback' => 'auktion_fav_submit',
      'wrapper' => 'submit',
      'method' => 'replace',
      'effect' => 'fade',
    )
  );
  return $form;
}
function auktion_fav_form_submit($form, &$form_state) {
  $form['add_to_fav']['#value'] = "remove from favourite;
  return $form['add_to_fav'];
}

```

# Answer
In hook form alter define your submit value . Below is small piece of code .

```
   $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Calculate'),
     '#prefix' => '<div id="div-example">',
     '#suffix' => '</div>',
    '#ajax' => array(
        'callback' => 'example_ajax_form_callback',
        'wrapper' => 'div-example',
         'method' => 'replace',
      ),
     );

function example_ajax_form_callback($form, &$form_state) {
  $form['submit']['#value'] = 'New value';
    return $form['submit'];
  }

```
> 3 votes

# Answer
you can use hook\_form\_alter

```
 yourmodule_form_alter{

   $form_state['values']['add_to_fav'] = "remove from favourite";

}

```
> 1 votes

# Answer
You can do it by changing your code to

```
function auktion_fav_form_submit($form, &$form_state) {
  $form_state['add_to_fav']['#value'] = "remove from favourite";
  return $form['add_to_fav'];
}

```
> 0 votes

# Answer
**Add this code in your themes js file:**

```
jQuery(document).ready(function(){
  jQuery("#submit").click(function(){
    switch (jQuery(this).val()) {
      case 'Your-button-text-here':       **//this is the text of the button which you want to change now change it with your button name**

        jQuery('#submit').val('remove from favourite');
        break;
    };
  });
});

```
> 0 votes

---
Tags: forms, ajax
---


# Question
Title: Read field value and pass it to section style atributes only for node page
I have a color field in content type -\> page fields. And i want to read the values of this field and pass this value as a background color(bootstrap subtheme) to element for main content ( - from page,tlp.php). And only for node type -\> page.

In my template.php i tried to use function theme\_preprocess\_page. My code:

```
function theme_preprocess_page(&$vars) {

    if (isset($vars['node'])) {

        $vars['theme_hook_suggestions'][] = 'page__' . $vars['node']->type . 'page';

        // check the node type and specific field in not empty
        if (($vars['node']->type = 'page') && (!empty($content['field_color']['#items'][0]['value']))) {

            //read the value of color field
            $bg_color = $content['field_color']['#items'][0]['rgb'];

        }
    }
}

```

but i dont know how to pass the value of color field ($content\['field\_color'\]) to section style attributes. Should i use $vars\['attributes\_array'\]\['style'\] ? and how to pass it to section element style.

Help please.

# Answer
```
 $color = preg_replace("/#/i", "", $bg_color);
$vars['classes_array'][] = $color;
 $vars['style'] = "style='background-color:$bg_color'";

```
> 2 votes

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


# Question
Title: How to data compare the price or, subtotal in Ubercart flat rate shipping quotes
Using Drupal 7.43 and Ubercart 7.3.9 I am trying to set up flat rate shipping for two parameters.

1. For orders with a subtotal above $34.00
2. For orders with a subtotal below $34.00

Unfortunately, there are no options under data comparison for the Subtotal... Only the Order total.

Or, I would like to create a flat rate shipping rates that vary by price ranges.

1. For products with a price above $34.00
2. For products with a price below $34.00

Can't figure that one out either. Any help will be greatly appreciated!

# Answer
> 0 votes
Never mind... I had negate checked! This is how I did it...

Data comparison Parameter: Data to compare: \[order:delivery-address..., Data value: United States

AND

Data comparison Parameter: Data to compare: \[order:order-total\], Operator: is greater than, Data value: 34

---

Data comparison Parameter: Data to compare: \[order:delivery-address..., Data value: United States

AND

Data comparison Parameter: Data to compare: \[order:order-total\], Operator: is less than, Data value: 34

---
Tags: 7, ubercart
---


# Question
Title: Storing a URL from a basic page using a custom module
I created a basic page at http://example.com/\[company\]/\[customer\]?id=2. I want to store this URL in a global variable for string manipulations within a custom module.

I succeeded to retrieve the URL by using `hook_form_alter()` with respect to a **webform** but I don't know how to do the same thing for a **basic page**.

Which hook do I need to use?

# Answer
> 0 votes
In your custom module, try to implement the **hook\_preprocess\_page**

```
function my_module_preprocess_page($vars) {
  print_r(current_path());exit;
}

```

This will retrieve the current URL of the site.

---
Tags: 7, hooks
---


# Question
Title: How to acces gmap markers after map is generated?
I've got a problem with Google map markers and I don't find a way to solve it.

I've got a map page view generated with the GMap module where I show certain nodes. I've got also a view block that show some of the same nodes that appear in the map in an unformatted list. What I need is to relate the nodes on the list with their respective markers in the map (so hovering the list change the marker icon or vice versa).

I could relate the nodes with the markers since I've got the exact coordinates of the node which coincide with the marker coordinates (obviously). My problem is that I don't know how to get a list of the existing markers on the map.

From what I've read I should push the markers in an array when they're generated so later I can acces to the markers using the elements in the array, but I couldn't found where does gmap generate the markers. I've tried creating a global array and pushing the markers in the `gmap_marker.js` inside:

```
obj.bind('addmarker', function (marker) {
  // ... //
    mymarker.push(marker.marker);
}

```

but even I can see any result. I tried counting the markers that are generated with something like `countmarkers += 1;` but the output is also 0.

Anyone has a clue on hou could I achieve this? Any advice would be appreciated.

> Edit: Ok, I solved this problem. It looks like what I did was fine and the problem was in the timing of the process. I called:
>
> ```
> mymarkers.forEach(function(marker) {
>         //funciona OK
>         alert(marker.getPosition().lat() + ' - ' + marker.getPosition().lng());
>     });
>
> ```
>
> inside a `setTimeout(function(){});` with a 10ms delay. By increasing the delay to 5000ms all the markers have enough time to be created and I can finally access the markers array.

# Answer
> 1 votes
Here is a quote from the Comparison of mapping modules:

> GMap is considered a legacy module.

So maybe you want to have a look at the IP Geolocation Views & Maps module. Partial quote from its project page:

> Despite what the name may suggest, IP Geolocation Views & Maps (IPGV&M) is first and foremost a mapping engine.
>
> The module makes it very easy to create Views-based mapping solutions using the map renderer of your choice (**Google**, **OpenLayers** or **Leaflet**) with any location storage module of your choice, e.g.:

> This allows you to bring together modules and feature sets that without IPGV&M you would not be able to combine.
>
> Like beautiful animated marker clustering on Google or Bing or Mapbox ... any of various map providers.
>
> But more importantly IPGV&M adds some features you won't find as conveniently packaged elsewhere.
>
> These include marker differentiation based on field values or ranges (2nd screenshot) with or without font icons, various centering options, super-imposing the current visitor's location, allowing multiple content types to be displayed on the same map, full screen button and mini-map inset (bottom screenshot), polygon support (Geofield), marker tags and tool tips and cross-highlighting of associated content on the page when markers are hovered (and vice versa).

Head over to its (impressive) project page for even more information about it (it would be way too long to include a quote of it all here). That project page also includes various screenshots.

---
Tags: 7, javascript, google-maps
---


# Question
Title: How to track Drupal user login-logout session length and registration activities?
Is there any hook\_function/code in Drupal where I can track user activity, like:

1. User core logged in time / or third party login
2. User log out time
3. Login-Logout session length (active time)
4. registration submit core or / third party submit.

Please share event for these activity.

# Answer
> 3 votes
For standard login, and 3rd-party login modules that are properly integrated with core, you can use:

For 3rd-party login modules that aren't properly integrated with core (i.e. don't fire those hooks), you'll need to approach each on a case-by-case basis, and find out what hooks they provide.

You could measure the duration of the session in `hook_user_logout`, by checking the account object's `login` property against the current time - there's no hook for such a thing as it's not an event, just a value which needs some context to give it meaning.

# Answer
> 1 votes
Have a look at the Event log module (a module also consists of "Drupal code", right?). Some details about it, from its project page:

> This module logs specific events. The events are saved in the database and can be viewed on the page admin/reports/events. Furthermore, a views integration is provided in which you can relate for instance a node to its events. You could use this to display the total number of views, or the number of times that the node has been modified and by which users.
>
> Currently, the following events are supported:
>
> * User authentication (login/logout/request password)
> * Node operations (CRUD)
> * User operations (CRUD)
> * Menu operations (custom menu's and menu items CUD operations)
> * Taxonomy operations (vocabulary and term CUD operations)
>
> The event log can be easily extended with custom events. For more information please have a look at the API documentation and the available sub modules.

You are probably going to be interested in these specific events and facilities of it:

* User authentication.
* User operations (CRUD).
* ... log can be easily extended with custom events.
* Views integration.
* API documentation.
* The available sub modules.

---
Tags: users
---


# Question
Title: How to display a form filled by a VBO-submission?
I'd like to use Privatemsg module to send messages to group of users. For this purpose I plan to use a view with Views Bulk Operations (VBO) and plenty of exposed filters.

I was able to create a custom VBO-action that puts the selected users into the recipient field of the message form:

```
function mymodule_my_custom_action(&$user, $context=array()) {

module_load_include('pages.inc','privatemsg');

$recipients = array();
foreach ($user as $recipient) {
$recipients[] = user_load($recipient->uid);
}

$subject = 'Some subject'

$message_form = drupal_get_form('privatemsg_new', $recipients, $subject);
$message_html = drupal_render($message_form);
}

```

I'm not very experienced in development so I don't know how to display this form together with the view that helps choosing the recipients. A simple `print $message_html;` won't be enough of course. For example would it be possible to use a panel page containing two panes: one for the view of users with VBO and one for the privatemsg form?

Any help would be greatly appreciated!

# Answer
> 2 votes
As per the "*I'm not very experienced in development*", you may want to use an alternative approach which only requires site building skills, as further explained below ...

Use the integration of the Privatemsg module with Rules instead (make sure to checkout this community docu, and its child pages ...), together with the Views Bulk Operations module.

For more details, refer to the video about Using Rules components with VBO. Possibly you also want to look at the 2 prior videos and/or the 2 subsequent videos (all about Views Bulk Operations), i.e.:

In this specific case;

1. use Views bulk operations to create the list of your users to be targeted (so this is just a minor variation of the VBO based view you seem to already have in place).
2. create a Rules Component which uses Rules action "Send a message" (provided by the Privatemsg module). If you'd add 2 "variables" to this Rules Component, named something like "MsgSubject" and "MsgBody", you might want to use those variables as "tokens" for constructing the actual Subject and Body of your message.
3. Within your VBO settings, just execute this Rules Component. If you then use this VBO-view, you can specify the desired values for the variables used to create your Rules Component (like "MsgSubject" and "MsgBody"). So you avoid hardcoding the "***Subject***" and "***Body***" for the "Send a message" action (without those variables it would only allow you to send predefined messages). And this simply by using these variables of your Rules Component (to implement that "Subject" and "Body" of the message). That way, each time you use your VBO to send such messages, you can enter the desired "Subject" and "Body" for each of those messages.

Done, no (custom coding) involved ...

For some other illustrations about using VBO in combination with Rules Components, refer to the answers to these questions:

---
Tags: 7, views, privatemsg, actions
---


# Question
Title: How to implement some type of private messaging to arbitrary groups of users?
I'd like to send private messages (with email notification) to groups of users. These groups can be either pre-defined or ad-hoc selected. Is there any way to implement this feature in a Drupal site?

I found Privatemsg which seemed quite promising since it has Views\- and Rules-integration. But after all it has not meet the requirements: I couldn't find a way to populate the recipients field with multiple users (I thought using a view with exposed filters and VBO would be a handy tool for selecting users).

Is there any solution for this?

# Answer
Using the Forena module, you could start from one of the Sample reports and solutions that come with it. I.e. the **Active Users Email**, which is a ***demo of the ability to send email to all active users of a Drupal site***.

The idea is that those users who have access to it, actually get a FORM to have Drupal send an eMail to all users selected via the query. To do so, you just have to "submit the report".

The easiest way to see the out-of-the-box example at work, is to (temporary) install the module in some dev environment you have available (for obvious reasons this sample report is NOT available to anonymous users in a Forena demo site ...).

Here is what would be needed to transform (clone) this sample to fit your needs:

* Adapt its data block (an SQL query) to list "all persons to be eMailed" (instead of all "active users of a Drupal site").
* Adapt the actual content of the delivered eMail template to fit the actual eMail content (message).
* Optionally you may want to make the "group" to be selected a report parameter.
* Secure "access" so that only authorized users can send such eMails. Depending on how your security is setup, you may want to adapt the Forena permissions accordingly.

The above approach can be used for all sorts of eMails towards any set of users of a Drupal site. Whereas that "set of users" is just a matter of writing some (basic) SQL statement to select the users you want to target. E.g:

1. Users with a selected role or
2. Users who didn't login for X days anymore or
3. Groups of users that are either pre-defined or ad-hoc selected (as in your question), whereas you'd need 'something' to actually indicate that ad-hoc selection that you can retrieve via some SQL query, like:
    * a taxonomy term.
    * some flag (using the Flag module).
    * all members of a group, created using either Group or Organic Groups .
    * etc.
4. ...

And the actual eMail content (message to be delivered) is actually anything you can format as an XHTML document.

Disclosure: I'm a co-maintainer of the Forena module.
> 0 votes

---
Tags: 7, emails, views, privatemsg
---


title: How do I find the correct plugin?

text:
# Question
Title: How do I find the correct plugin?
As an Drupal 7 developer I'm currently trying to get into Drupal 8. I got a problem finding the right plugin.

For example, I simple want to change the text of a node link "**read more**" into "**read more \>**".

Leaving the templates out, I would google for Drupal 7 something like "drupal hook -what I want- alter" and found the correct hook. How can I find the correct plugin?

Especially for this case, there `hook_node_links_alter()`. Should I use this, or is it just for legacy and I should prefer a other way?

# Answer
> 1 votes
In the specific example you make, there aren't plugins involved. The hook in invoked from NodeViewBuilder::renderLinks(), which executes the following code.

```
  $links = array(
    '#theme' => 'links__node',
    '#pre_render' => array('drupal_pre_render_links'),
    '#attributes' => array('class' => array('links', 'inline')),
  );

  if (!$is_in_preview) {
    $entity = Node::load($node_entity_id)->getTranslation($langcode);
    $links['node'] = static::buildLinks($entity, $view_mode);

    // Allow other modules to alter the node links.
    $hook_context = array(
      'view_mode' => $view_mode,
      'langcode' => $langcode,
    );
    \Drupal::moduleHandler()->alter('node_links', $links, $entity, $hook_context);
  }
  return $links;

```

To know if a plugin is involved, you need to read the documentation. Plugin API in Drupal 8 give the general documentation, but then you need to read more specific documentation pages, for example Block API in Drupal 8.
A plugin could be annotated, so in some cases you can find any plugin implemented by Drupal core by looking at the classes annotated with a specific class, which is what happens with form input elements, which are classes annotated with `\Drupal\Core\Render\Annotation\FormElement`. The documentation page gives a list of the classes annotated with that `Annotation` class, so you can find any plugins of that type.

Then, as @CLive said, if you are simply wondering if you should use a hook, just look at the documentation page for that hook: If it has been deprecated, the documentation reports that, and tells you exactly what you should use: a different hook, a plugin, a specific class.
Also, as said from @mradcliffe, change records reports the changes done in Drupal, and for which version. They are helpful if you want to look at the changes that could interest the code you are writing.

---
Tags: 8, plugins
---


# Question
Title: How do I view the string pulled from feeds image importer?
I am importing images from a feed using xPath parser. I think that I have the correct attribute value, `media:content@url`, but I am getting a `Unable to handle the provided embed string or URL.` error. My first instinct is to check that I'm getting the proper string. How do I do this? Is there a way through devel to view the imported string? Devel?

The url string I want to pull is `https://cdn2.orgsync.com/images/os-photos/s5o0zqk8o29mi46_710.jpg`

# Answer
> 0 votes
I haven't solved my problem, but I found the hook needed to spit out the pre-parse data.

```
\**
* Importer testing.
*/
function wpi_events_feeds_after_parse(FeedsSource $source, FeedsParserResult $result) {
dpm($result);
}

```

This spits out the source strings, which is great, because it tells me my xpath selector is wrong.

---
Tags: media, feeds, debugging
---


# Question
Title: Create a View which shows Nodes AND Taxonomy Terms
I am working with Search Autocomplete to create a suggestion list which includes nodes and taxonomy terms. Is there a way to include both entity types within a single view? Thanks for your time.

# Answer
> 0 votes
1. Create a view and select show content of type All
2. Under format in show fields select fields. 3.Create a relationship Content: Taxonomy terms on node
3. Select Content: Title and Taxonomy term: Name fields under Fields
4. Under filter criteria select two fields first one Content: Title and second one Taxonomy term: Name and dont forget to check the Expose this filter to visitors, to allow them to change it

---
Tags: 7, views, taxonomy-terms, ajax
---


# Question
Title: Problem uploading files and images containing spaces in the filename
In Drupal 8 I have fields of type `File` and `Image`, inside Content types and forms. These fields stores files inside the "public" folder.

When I upload files with a name **containing spaces**, for example a file named `"example with spaces.pdf"`, the file is correctly uploaded but once uploaded it is no more available.

The image below is just after uploaded an image containing spaces in the filename. Note that all seems correct:

When I save and publish the content I get this:

And returning back in the edit panel the thumbnail is no more available:

Same problem above trying to upload files inside a field of type `File`.

The file's url becomes something like this:

```
localhost:8888/sites/default/files/2016-05/example%20with%20spaces.jpg

```

But I'm redirected to the home page trying to open such url. Maybe there is a bug in Drupal when translates the url encoded filename in the real one.

If the filename has no spaces, or if the file is uploaded inside the "private" folder, there are no problems.

Any idea about how to solve this problem?

---

**EDIT**

I can reproduce the error with following steps:

1. Download Drupal

```
$ drush pm-download drupal --drupal-project-rename=drupal

```
2. Install Drupal

```
$ cd drupal
$ drush site-install standard \
--db-url='mysql://[db-user]:[db-pass]@localhost:[db-port]/drupal' \
--account-name=admin --account-pass=password \
--site-name="Drupal" \
--site-mail=noreply@example.com

```
3. Start Drupal

```
$ drush runserver

```
4. Create a new 'Article' and upload an image with spaces.

Maybe is there something wrong in steps above? Or a bug in the drush's built-in server?

# Answer
> 1 votes
I found out that it was a problem with `drush runserver`, maybe a bug. Currently I'm using Drush 9.0-dev. Probably will be fixed soon.

Using apache all it works fine.

# Answer
> 1 votes
Just I checked on different types of image files. So it could not reproduce your error. In my opinion, if your problem is in the server settings or the settings of the Drupal 8. Because viewing the forums, the Internet, communicate with colleagues at work, such a mistake, I have not met anybody.

---
Tags: 8, drush, media, files
---


title: Emails are not sent to outside domains

text:
# Question
Title: Emails are not sent to outside domains
I deployed a Drupal 8 website, on a hosting service with cPanel, with domain *mydomain.com*.

If I set this email address on the user profile: *john.smith@**example.com***, that is an email address with a domain different from *mydomain.com*, then I go to:

```
mydomain.com/user/password

```

and I click to "Send" trying to receive the "reset password" email, it give me the error below and I don't receive the email:

> Unable to send e-mail. Contact the site administrator if the problem persists.

Same problem on contact forms.

If I set an email address within my domain, for example *john.smith@**mydomain.com***, all works and the email is correctly sent.

Any idea why this is happening and how to solve this problem?

---

**NOTE**

I tried to create this php script inside the server in order to check if there is some issue on the server configuration:

```
<?php

$to = "john.smith@example.com";
$subject = "Test mail";
$message = "This is a test message.";

$headers = [];

$headers[] = "From: noreply@example.com";
$headers[] = "MIME-Version: 1.0";
$headers[] = "Content-type: text/plain; charset=UTF-8; format=flowed; delsp=yes";
$headers[] = "Content-Transfer-Encoding: 8Bit";
$headers[] = "X-Mailer: Drupal";
$headers[] = "Reply-To: noreply@example.com";

$res = mail($to, $subject, $message, implode("\n", $headers));

echo "Mail Sent. <br/>\n";
echo "Res: " . $res . " <br/>\n";

```

When I run this script it correctly works and sends the email, either if the `$to` property is from my domain or if it is from an external domain.

So I excluded it is a server configuration issue.

# Answer
> 0 votes
I solved the problem.

Taking inspiration from this thread, I figured out that, for some obscure reason, I need to set the email setting under "*Administration \> Configuration \> System \> Basic site settings \> E-mail address*" to an **existing email address** on my hosting service.

So, I created a new email with cPanel, *noreply@mydomain.com*, then I setted this email address in the above configuration.

Now seems that all is working perfectly.

---
Tags: users, 8, emails
---


title: Custom paragraph prefixed with number?

text:
# Question
Title: Custom paragraph prefixed with number?
I am looking at different CMS's and KMS's for suitable software user documentation systems. Im very impressed with Drupal.

I have a user case where I would like to be able to add a series of steps - so a user can read the steps and actions needed to take to complete a task.

I thought this could be achieved using paragraphs. However, I would like to have a sequential number at the beginning of each paragraph, eg:

1. Do step one
2. Add a widget
3. Enable the gadget

How would I do this in Drupal?

Thanks

# Answer
> 1 votes
Do you have control over the CSS? What about a CSS solution?

http://bl.ocks.org/trauber/5163440

```
.paragraph-parent {
    counter-reset: paragraph;
    padding-left: 20px;
}
.paragraph-parent p {
    width: 75%;
}
.paragraph-parent p:before {
    position: absolute;
    margin-left: -20px;
    content: counter(paragraph);
    counter-increment: paragraph;
}

```

---
Tags: views
---


title: Extra empty rows when serving CSV file

text:
# Question
Title: Extra empty rows when serving CSV file
I'm building a CSV file and serving it up as a downloadable file. Pretty straightforward. Thing is, I get 18 leading empty rows in my csv file. Any ideas? I've stripped the code down to just about nothing - should I be looking for problems somewhere else?

```
/**
 * Implementation of hook_menu
 */
  ...
  $items['providers/dashboard/generate-csv/%/%'] = array(
   'title' => t('Export CSV Data'),
   'page callback' => 'generate_csv',
   'page arguments' => array(3, 4),
   'access arguments' => array('administer module_name content'),
   'type' => MENU_CALLBACK
  );
  return $items;
}

/**
 * MENU_CALLBACK function
 */
function generate_csv($source_type, $include_unpublished = FALSE) {

  // start up headers
  $csv_name = $source_type . '-csv_' . date('Y-m-d') . '.csv';
  header('Content-Type: text/x-comma-separated-values');
  header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
  header('Cache-Control: private', false); // required for certain browser
  header('Content-Disposition: attachment; filename="' . $csv_name . '"');

  // write csv data
  $test_output = "test,test,test";
  print $test_output;
}

```

**EDIT** \- Looks like it is an issue with the headers, not the content. If I write the contents of my output to a file, I do not have any extra space at the beginning. Does anyone know:

* What's up with the headers that could be causing the extra spaces? Or..
* How can I ditch any output and start over fresh with my headers?

# Answer
The comments for my question were pretty much the answer, but I'll elaborate here.

The root of the problem was one of the included files had an ending PHP tag. However, it wasn't in my code and I had no idea where else to look.

I ended up using something similar, to the following code.

```
watchdog("Module_name", "Check these files: !files", array("!files" => implode(get_included_files(), ', ')));

```

This gave me a list of all the files that Drupal had included in order to run my code. There were about 140 of them.

The best way to figure out which might have superfluous end tags would be to cycle through each file programmatically, as Luke Redpath suggests on http://www.designerstalk.com/forums/programming/8005-php-finding-occurences-string-file.html.

In my case the file permissions were giving me trouble, so I brute forced it until I found an unrelated (but custom) module that had a bunch of `?>` tags.
> 4 votes

# Answer
Maybe this lines "hang" in an output buffer, that were started some time before. This way you can set headers without the good old "headers already sent"-error, but this content will be send to the browser when flushing the buffer anyway.

Try this one

```
ob_clean();
print $csv_data;

```
> 1 votes

---
Tags: files
---