# Question
Title: How to use node title or path alias instead of node id in node reference contextual filter in views?
I have node A with a node reference to node B.

In a view I show all nodes A that have particular node B referenced (nid: 123, title: node-B-title).

Instead of using the nid in the contextual filter I would like to use the node title. For example, instead of:

```
view-name/123

```

I would like to use

```
view-name/node-B-title

```

How could I do that?

# Answer
> 10 votes
I had a very similar problem and I not just found the solution to it, but also learned new things about how view works. Let me share what I learned and the solution to your problem too.

When you are creating a view with one or more contextual filters, the view must receive values of those filters from somewhere. This can be done by -

1. Picking the context filter value(s) **from the URL**
    * Typically you would have a *page view* for such purposes one that has URL of the form `foo/%/bar` or `foo/bar/%` for single contextual filter OR of the form `foo/%/bar/%` or `foo/bar/%/%` for multiple filters
    * In case you have multiple filters, the url value that appears first is mapped to the first filter, next to the second filter and so on.
2. Views allows you to tell **what to do if** the filter values are **not available in the URL**. This is typically used for *block views*.
    * You can choose from different actions and then configure the choice too. asdfj kajsdf
3. Another thing views allows you is to tell **what to do with** the filter values **if they are found in the URL** as described in #1 above. Typical use cases are - Making dynamic titles based on filter values, Validating filter values etc.
    * When validating filter values, you can change the values too! (That is where our solution lies btw). This is very akin to the way we can change $form values in the drupal form validation callbacks.

**Solution to your specific problem** lies in using a very similar code in the sections pointed to by the arrows in the above image.

This link proved out to be great help to me. Here is an excerpt from it:

```
$np = explode('/', drupal_get_normal_path($argument));
if (!empty($np[1])) {
  $handler->argument = $np[1];
  return TRUE;
} else {
  return FALSE;
}

```

# Answer
> 1 votes
The view argument must be the field reference of content type, then select the option "Provide default argument" and check the option Id Node (something like that).

1) Add argument "X field reference" 2) Check ID node from url (in add default argument) 3) In validation section, check the content type of node, and on setion "Node type" select "Node Id

And is done. :)

# Answer
> 1 votes
This will not work in all circumstances, but one approach to the problem in the question is to use the actual node display of node B (or node type B) and set its path how you want it with the path or pathauto module. Then use views block to add the content relationship and the view you want.

Use a contextual filter on NID and then setting `Provide default value > Content ID from URL`. Then add the views block to your page or set of pages.

If your context allows you to use a views block on the node itself and not a views page this will make it much easier to get the path you want and the views display you want.

# Answer
> 1 votes
I edited the accepted answer, but wanted to add the actual code here:

Use PHP validated option under the validation options in the contextual filter.

```
$np = explode('/', drupal_get_normal_path($argument));
if (!empty($np[1])) {
  $handler->argument = $np[1];
  return TRUE;
} else {
  return FALSE;
}

```

# Answer
> 0 votes
Old question, but found it through Google and figured I'd share my solution for anyone else who finds it in future:

There is now a module named safeword which basically does exactly what Sumeet Pareek suggested: (Automatically) creates a URL friendly field.

# Answer
> 0 votes
I would recommend the Extended Path Aliases (path\_alias\_xt) module. It fixes this problem purely by being installed with no configuration, it's basically magic, apparently. :D Not really, but the excerpt from the module page extolls how you just install it and it fixes this and other problems, but doesn't go into how the module does so behind the scenes... O, well, we could always read the code :D It doesn't specifically mention fixing views paths, but I have used it to do so and it works perfectly.

List of problems it solves, from the module page:

> * Have you ever wondered why, after defining an alias like about-us for, say, node/123, your pages are still riddled with those ugly machine-generated tabs and links like /node/123/edit, node/123/revisions etc.?
> * Likewise for /taxonomy/term/% and /user/% links: did you expect to see /dries/track but got /user/5/track?
> * Do you find that your browser address bar also shows those ugly numbers instead of your aliases?

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


title: Programmatically turn off body summary

text:
# Question
Title: Programmatically turn off body summary
My apologies if this is a duplicate, but I spent two days using my Google-foo to find this information and never did. So, now that I've figured it out, I'll post it here.

# The Question

**How do I turn off the body summary programmatically?**

# Answer
> 0 votes
I placed this code directly after my call to `node_add_body_field('my_node_type')`.

```
  $field_instance = field_info_instance('node', 'body', 'my_node_type');
  $field_instance['settings']['display_summary'] = FALSE;
  field_update_instance($field_instance);

```

## References

# Answer
> 0 votes
Another way to do so is to use hook\_form\_alter like this:

```
/**
 * Implements hook_form_alter().
 */
function my_module_form_alter(&$form, &$form_state, $form_id) {
  if($form_id == 'my_content_type_node_form')  {
    $form['body'][LANGUAGE_NONE][0]['summary']['#access'] = FALSE;
  }
}

```

---
Tags: entities
---


title: Show permission used

text:
# Question
Title: Show permission used
I've on a drupal 6 site a custom module which generate a page, i send in that page a form.

When i try to test my form as an anonymous user, it doesn't work as i get:

> You are not authorized to access this page.

I've a `hook_perm` on my module and permission are activate for anonymous user, but that still doesn't work, even after "cache clear" or "rebuild permission".

So i must have another permission in conflict here that forbid me to show my form to anonymous user (as an admin, i can see it). Is there a way for me to print the "rights" that forbid me to access my form, to get a list of the permission used in a specific page?

# Answer
> 0 votes
I get an solution : Exposed here in : https://drupal.org/node/109157

I had to add '"access callback" =\> TRUE' to my hook menu (TRUE because i want anonymous user get access to the page).

```
function custom_createAccount_menu()
{
  $items["createAccount"] = array(
    "title"=>t('Create an account'),
    "page callback"    => "_custom_createAccount",
    "access callback"  => TRUE,
    "access arguments" => array("access createAccount content"),
  );

  return $items;
}

```

and that works.

@SavaryNicolas

---
Tags: 6, forms, users
---


# Question
Title: How can I show the receiver name in a rules email
I use the rules module in Drupal 7. I use it to send an email to a few receivers with a certain role. How can I get their name or userID? Is there a Replacement Pattern to get the email Receiver details?

edit:

I'm sorry for being unclear. I have made a rule that emails all users with a certain role after new content of a certain type was created. In this email I would like to start with "Hi \[Username\_of\_email\_receiver\]" but it seems I can only use the author username or the current logged in username

# Answer
> 0 votes
You cannot, the message is the same for all users of a certain role in this case. I think you have, first, to get the users of a certain role (php custom code) and then for each user fire an other rule or a custom hook\_mail with the account as argument

# Answer
> 0 votes
Couldn't you do fetch entity (type user) by property and have the property by the role and select that role? Then loop through entity list of users and then you can, i believe, access the fields on each user as you loop through.

---
Tags: rules, emails
---


# Question
Title: How to set Link field value via entity metada wrapper?
I'm using Link field.

I need to populate link field programmatically. Currently I'm using EMW a lot, so I'm wonder if it possible to set Link field value via EMW.

# Answer
> 6 votes
Try this code:

```
$node = node_load(nid);
$wrapper = entity_metadata_wrapper('node', $node);
$link = array(
  'url' => 'url',
  'title' => 'title',
  'attributes' => array()
);
$wrapper->field_link->set($link);
$wrapper->save();

```

Don't missing **$wrapper-\>save();**

# Answer
> 3 votes
If your Link field is multivalue, use this code:

```
  $node = node_load(nid);
  $wrapper = entity_metadata_wrapper('node', $node);
  $wrapper->field_link[] = array(
     'url' => 'url',
     'title' => 'title',
     'attributes' => array()
   );
  $wrapper->save();

```

---
Tags: 7, entities
---


# Question
Title: Where can I download old releases of Drupal?
I'm trying to find a copy of 6.20 to run a diff on a client's Drupal install. I believe there's been changes to core.

How can I get version 6.20? Additionally, how can I download any older Drupal versions?

# Answer
You can get Drupal 6.20 from the Drupal 6.20 released page.

You can also view a list of all current and previous releases on the Releases for Drupal core page, complete with download links. It goes all the way back to Drupal 4.2.0, which I'm now off to install to see what happens!
> 16 votes

# Answer
I know you've already got it answered... but Git wasn't mentioned.

```
git clone http://git.drupal.org/project/drupal.git target_directory
cd target_directory
git checkout -b local 6.20

```

Good option if you just want to cut to the chase and "git" it. Best paired with "Drush", to download, update, backup etc from the command line.
> 3 votes

# Answer
My best bet (to answer "Where can I locate source code of Drupal 1.0 or earlier version?", marked as a duplicate of this question here) would be to try to use the contact form on Drupal.org for **user/1** ... Here is part of what's included in that special profile:

> **Bio**:
>
> * Drupal founder and project lead
> * ...

As the founder of Drupal, this user must have had a pretty early version of (what today is called) Drupal. So that user may have some types of backups hanging around from those very early (pre Drupal 1.0) days. For example something that at that time was used also for running (eg) www.drop.org.

Have a look at the video about History of Drupal aka from Drop 1 0 to Drupal 8 0, and pay special attention to what is shown around 5:02 in it where you can see a timestamp of ***Dec 29, 2000 at 11:00:56 GMT***, together with the historical words "***I think I'll baptize the engine 'drupal'*** ...". If you continue a bit further in that video, you'll notice Jan 15, 2001 as the release date of Drupal 1.0 (with a screenprint of how that looked like around 6:45).

PS: I assume everybody knows the story that "***Drupal***" is the English/American pronunciation of the Dutch (Flemish) word "***Druppel***", whereas ***Druppel*** is the Dutch (Flemish) word for ***Drop***. And also that long time this very same user wanted to register domain name ***dorp.org*** (the Dutch (Flemish) for "***village***"). But made a typo and registered ***drop.org*** instead ... All this to explain why I suggest having a look at (the arcive.org-version of) www.drop.org also ...
> 0 votes

# Answer
My answer is for the question: Where can I locate source code of Drupal 1.0 or earlier version?

Just get the current code from github. The commit msg from commit `6e88265b1f5fd984c7bff8207e214982ec260e3e` reads `- added drupal 1.00 final`.

So it seems it's a good bet that this commit holds the drupal 1.0 code.

Even earlier: the second commit is tagged with *start*. So try to check that out.
> 0 votes

# Answer
I had a presentation about History of Drupal and as part of it I pushed historical releases of Drupal on github

Browse Drupal source code by version:

Drupal 1.0

Drupal 2.0

Drupal 3.0

Drupal 4.0

Drupal 4.1

Drupal 4.2

Drupal 4.3

Drupal 4.4

Drupal 4.5

Drupal 4.6

Drupal 4.7

Drupal 5.0

Drupal 6.0

Download Drupal (tar.gz) per version:

Drupal 1.0

Drupal 2.0

Drupal 3.0

Drupal 4.0

Drupal 4.1

Drupal 4.2

Drupal 4.3

Drupal 4.4

Drupal 4.5

Drupal 4.6

Drupal 4.7

Drupal 5.0

Drupal 6.0
> 0 votes

---
Tags: files
---


# Question
Title: Possible timing issues when using setActiveConnection to an external database under normal Drupal 8 operation
I'm using Drupal 8.0.5. In my settings.php file I have defined an external database:

```
$databases['notificationsdb']['default'] = array (
  'database' => 'NotificationsDB',
  'username' => 'my_user_name',
  'password' => 'my_password',
  'prefix' => '',
  'host' => '127.0.0.1',
  'port' => '3306',
  'namespace' => 'Drupal\\Core\\Database\\Driver\\mysql',
  'driver' => 'mysql',
);

```

I have then created a custom form where I need values from the NotificationsDB database to populate a form fields. In my custom form class in the \__constructor I created an instance of my Notification Client class:

```
public function __construct() {
        $this->_notificationClient = new NotificationsClient();
}

```

In my NotificationsClient class I have the following code:

```
public function __construct() {
        // Set the active database to notificationsdb
        \Drupal\Core\Database\Database::setActiveConnection('notificationsdb');
        $this->_db = \Drupal\Core\Database\Database::getConnection();
    }
public function __destruct() {
        // Set the active database back to the default
        \Drupal\Core\Database\Database::setActiveConnection('default');
        // https://api.drupal.org/api/drupal/core!lib!Drupal!Core!Database!Database.php/function/Database%3A%3AsetActiveConnection/8
}

```

When I go to view my form I get the following error:

Drupal\Core\Database\DatabaseExceptionWrapper: SQLSTATE\[42S02\]: Base table or view not found: 1146 Table 'notificationsdb.shortcut\_set\_users' doesn't exist: SELECT ssu.set\_name AS set\_name FROM {shortcut\_set\_users} ssu WHERE (ssu.uid = :db\_condition\_placeholder\_0); Array ( \[:db\_condition\_placeholder\_0\] =\> 1 ) in Drupal\shortcut\ShortcutSetStorage-\>getAssignedToUser() (line 103 of core/modules/shortcut/src/ShortcutSetStorage.php).

From what I can tell the Shortcuts module is trying to run some queries against the NotificationsDB. I'm guessing this is a timing issue. I'm also concerned with how Drupal handles multiple database connections.

# Answer
In looking at the getConnections method closer you can pass it the $target and $key parameters directly and it will return a handle to the specified database.

```
$this->_db = \Drupal\Core\Database\Database::getConnection('default', 'notificationsdb');

```

This way you don't have to mess around with setting the active database.
> 1 votes

---
Tags: database
---


title: How do I get the login link?

text:
# Question
Title: How do I get the login link?
I have a backup of a Drupal 7 website with its database. Is there any solution to get the login path? I have tried many options: /?q=user/login, /login, /user, and /user/login.

# Answer
> 3 votes
use drush command to login, it will print the login URL.

```
drush uli;

```

---
Tags: 7, users
---


# Question
Title: Display 3 items by default in a multivalue field?
I have a field collection which is a multivalue field with unlimited values.

when I opens the form, the field collection has a set of fields with "`add another item`" button. When I click the button, it adds one more set and so on.

Is it possible to have 3 sets by default and when the "`add another item`" button clicked, one more set is being added and so on?

# Answer
> 0 votes
You can do it by jQuery, when page loads simulate the click event on the add more button using **onClick()**

---
Tags: 7, entities
---


title: Set global data like $user

text:
# Question
Title: Set global data like $user
On my project, I have a custom table for some custom permissions for users. I want all permissions for a user loaded on each page like `$user`. I created a custom module and set the global variable `$cperms` in `hook_init()` which contains all custom permissions for current logged in user.

These values are available on site pages but I am not sure it is good to use `hook_init()` to set global data. Is there any proper method?

# Answer
It sounds like you're reinventing the wheel here; as @burnsjeremy mentions, there's already an effective system built into Drupal for storing permissions.

`hook_permission()` allows any module to define its own custom permissions that can be set per-role. Once implemented, `user_access()` can be called to check a user for custom permissions.

If you need some data that is more granular (i.e. at the per-user level), the global `$user` object has an array property called `data`. `$user->data` is loaded/saved with the user object and should always be available to you.
> 0 votes

# Answer
from a custom module you can add global variables by prefixing the variable name with **global** keyword.

```
global $my_global_var;

```

another way to use the variables from anywhere is by using the **variable\_get()** and **variable\_set()** functions.
> 0 votes

---
Tags: 7, hooks
---


# Question
Title: Tags not rendering in the correct location
I have tags after body in article but its not rendering in the correct place. Instead it displays at the end.

I have included the screenshot below.

# Answer
> 0 votes
I had the same issue before, try rearranging the fields then save. after that rearrange again to the original order of fields, save then clear all caches.

---
Tags: 7, nodes, taxonomy-terms
---


# Question
Title: LDAP SSO - User not redirecting to user/login/sso to login the visitor
I have implemented LDAP - Single Sign On (SSO) on my Drupal project. All the settings (testing, connecting with server) is working perfectly fine.

The problem is that when I visit my site, the site doesn't authenticate the user.

Upon testing every option regressively, I realized that my site is not redirecting to **http://www.theurl.com/user/login/sso**, which authenticates and sign in the visitor.

When I manually went to **http://www.theurl.com/user/login/sso**, the site authenticated and logged in the user perfectly.

Is there anything I can do to mitigate it?

Thanks a lot

# Answer
> 1 votes
You can use a rule to redirect them to the /user/login/sso. You can make a rule, if user has not logged in auto send them to /user/login/sso. If the user is already logged in send them to the home page.

---
Tags: authentication-authorization
---


# Question
Title: Moving PayPal Payment iFrame to Checkout page
**The Problem**

Hi, I'm trying to move the payment iframe from its own page to the main checkout page so that I just have a one page form for checkout. I followed the directions here but wasn't able to get it to work (ie. I moved the 'review' section to 'disabled' and move the 'payment' section to 'checkout' in configuration).

**The Current Status of My Situation**

I'm using the Drupal Payflow Link module, and I have all my items in my checkout pane in store configuration. However, when a user goes to the checkout page they fill out all their information and also choose what payment method they want to use, but the actual entering of the payment information (credit card for example) still happens on the 'next' page. I want everything on ONE page.

**Question**

Anyone know how to make this happen with PayPal Advanced Payments/PayFlow Link so that entering the credit card details also appears on the main checkout page?

# Answer
This actually just isn't possible. The iframe depends on having a completed order object, which you can't possibly have (or know for certain) if it's on the same page as fields placed to collect user input to complete that order. The same is true for all redirect, tokenized, or iframe based payment solutions.
> 2 votes

---
Tags: commerce, payment-gateways
---


# Question
Title: Exclude node referenced from Related Views
I have a view which show 4 related nodes based on category. Issue is that there is an entity reference product\_group, in the node, and I want to show only those nodes which are not in product\_group reference field.

This only involves one content type.

# Answer
THis things might be solved in many ways, but the 2 solutions which we can use is.

1. We can add entity reference filter in Filter section of view. Entity Reference Filter is a view of type entity reference, and it should return node id based on arguments, and in our parent view, we can apply condition, that `is not one of`.
2. We can add a contextual filter of NID, with option of provide default value \>\> fixed value, and under more section, we can check exclude checkbox. After that we can use `hook_views_pre_view`, to set the argument, if it is first contextual filter, then using $arg\[0\], if it is second contextual filter, then using $arg\[1\].
> 0 votes

---
Tags: views, entities
---


# Question
Title: How to use Rules to perform a simple anti-spam validation using specific keywords?
My site is under repeated attacks by spammers who create accounts manually with nonsense email addresses and "fake" IP addresses (no way to block them).

I came up with the idea of blocking node creation with the Rules module, using data comparison, but it does not work. Here is a summary of the rule I have:

> Event : Before saving content
>
> Conditions: text comparison : Parameter: Text: \[node:body:value\], Matching text: lexapro, etc. \[how to make the list of words/expression? One per line?\]
>
> Actions : page redirect

**Update**: starting from the rule in this answer, I created a rule which will redirect to a page and unpublish the node, but only if the words are both in the title and in the body. I've tried to put an *OR* in the rule, but it didn't work.

```
{ "rules_simple_antispam" :
  {
    "LABEL" : "Simple antispam",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "node_presave" : [] },
    "IF" : [
      { "text_matches" : { "text" : [ "node:title" ], "match" : "lexapro" } },
      { "text_matches" : { "text" : [ "node:body:value" ], "match" : "lexapro" } }
    ],
    "DO" : [
      { "redirect" : { "url" : "death-spam" } },
      { "node_unpublish" : { "node" : [ "node" ] } }
    ]
  }
}

```

What do I need to change in my rule to make it work?

PS: I'm not a coder.

# Answer
> 1 votes
IMO you should use a captcha, such as:

## reCAPTCHA

> Uses the Google reCAPTCHA web service to improve the CAPTCHA system and protect email addresses.

OR

## Draggable Captcha

Here is an instruction video on how to set it up Drupal 7 Draggable Captcha - a more friendly way to prevent Spam

If spam still happening, which means they are indeed human and not bots, you could implement a point system. Where users need to gain points by doing something (login x amount of days or comment x amount of times etc..) To create nodes, users need to have x amount of points.

In addition, you could also implement spam flags, where users can flag content as spam and have the content be auto deleted if x amount of flags are raised.

# Answer
> 0 votes
Have a look at this rule (in Rules export format):

```
{ "rules_block_specific_words_in_node_body" : {
    "LABEL" : "Block specific words in node body",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "node_presave" : [] },
    "IF" : [
      { "user_has_role" : {
          "account" : [ "site:current-user" ],
          "roles" : { "value" : { "2" : "2" } }
        }
      },
      { "OR" : [
          { "text_matches" : { "text" : [ "node:title" ], "match" : "lexapro" } },
          { "text_matches" : { "text" : [ "node:body:value" ], "match" : "lexapro" } },
          { "text_matches" : {
              "text" : [ "node:title" ],
              "match" : "ANotAllowedTextStringInTitle",
              "operation" : "regex"
            }
          },
          { "text_matches" : {
              "text" : [ "node:body:value" ],
              "match" : "ANotAllowedTextStringInBody",
              "operation" : "regex"
            }
          }
        ]
      }
    ],
    "DO" : [
      { "redirect" : { "url" : "no_spammers_allowed" } },
      { "node_unpublish" : { "node" : [ "node" ] } }
    ]
  }
}

```

Just import it in your own site (using the Rules UI) to experiment with it, and make it fit your needs.

Some more details about the logic included in the above sample:

* It only applies to authenticated users (adapt and/or remove that Rules condition as needed).
* It includes 4 verifications about the title or the actual body text (at least 1 one of these 4 Rules Conditions must be satisfied, **as per the "OR" in these Rules conditions**), ie:
    + an exact match (equal to) of either the title or the content of the body which is (just) "lexapro".
    + using a regular expression (regex) related to the string (in the title) `ANotAllowedTextStringInTitle` or (in the body) `ANotAllowedTextStringInBody` (use any regex that may fit your needs).
* If the combination of Rules conditions is satisfied (ie the role matches AND at least 1 of the 4 of the text comparisons are satisfied), then these 2 Rules Actions are triggered:
    + issue a redirect "before saving the content" (which is the Rules Event) to a page with a path like `no_spammers_allowed`.
    + the node is unpublished.

**Note**: to make a list of words, the most straight forward way to do so is via the RegEx expressions (in which you could also use the "lexapro" word of course, which would make the first 2 Rules Conditions obsolete).

---
Tags: 7, rules, advertising
---


title: Need help with Views and Glossary

text:
# Question
Title: Need help with Views and Glossary
I'm following along on the blog post "Use Views to Create an Alphabetical List of Taxonomy Terms" by Kristin Brinner http://getlevelten.com/blog/kristin-brinner/drupal-tutorial-use-views-create-alphabetical-list-taxonomy-terms and my sample does not produce the results as she shows.

Part 1 & 2: I successfully created a new view selecting taxonomy terms (create as Grid), then grouped terms alphabetically (add Taxonomy term: Name, label it "Grouping", exclude from display, rewrite to max length = 1), then under Grid-Settings use "Grouping"

Part 3, Create a Views page for each letter of the alphabet: I can't see these results, but I presume I did this correctly, using contextual filters, (Glossary, Character limit 1)

Part 4, Create A-Z list (create a block that will display the list of first letters in a cute list above the grouping grids) isn't working. Here is what the tutorial says should be the result:

I followed along exactly with the tutorial except When the filter value IS available, the tutorial says Specify validation criteria, Basic Validation, Hide View and I do not have Hide View available.

I don't have an option to Apply, only Save. My content continues to look the same as it did previously in the exercise, i.e. like this (graphic omitted because I don't have enough clearance on this site)

However when I put "S" into the Preview with contextual filters, I get (graphic omitted because I don't have enough clearance on this site)

So, it looks like it's almost working. Ideas? TIA

# Answer
You can find validation in Contextual Filter. I am attaching screen shot for the same.

However you can also use the glossary view which is provided by Drupal.
> 0 votes

---
Tags: blocks, views
---


# Question
Title: Can Forena Reports be used with Organic Groups to create a report with a "page" for each member?
I would like a link in each of my organic groups where Forena would replicate some of my views and create a pdf document with a page per OG user.

I've looked through the documentation and module but my SQL knowledge is quite primitive and I don't see anything related to using the current NID in queries.

I think the Views Show Query module would allow me to copy the relevant queries into Forena while I learn the SQL.

So my question is, does the above sound possible and would copying the SQL queries that views produces be enough to get me started?

Below is a view using field collections and a screenshot of the views\_show\_query pasted into Heidi. There are two arguments given to the view. "1422" and "1243".

```
SELECT field_sts_grades_fc_field_collection_item.nid AS field_sts_grades_fc_field_collection_item_nid, field_collection_item.item_id AS item_id, field_sts_grades_fc_field_collection_item.title AS field_sts_grades_fc_field_collection_item_title, field_sts_grades_fc_field_collection_item__field_data_field_exam_class_reference.field_exam_class_reference_target_id AS field_sts_grades_fc_field_collection_item__field_data_field_, field_sts_grades_fc_field_collection_item__field_data_field_grade_date.field_grade_date_value AS field_sts_grades_fc_field_collection_item__field_data_field__1, field_sts_grades_fc_field_collection_item.created AS field_sts_grades_fc_field_collection_item_created, users_field_data_field_sts_grades_ref__realname.realname AS users_field_data_field_sts_grades_ref__realname_realname, 'node' AS field_data_field_grade_date_node_entity_type, 'field_collection_item' AS field_data_field_sts_grades_ref_field_collection_item_entity, 'field_collection_item' AS field_data_field_grade_decimal_field_collection_item_entity_, 'node' AS field_data_field_exam_class_reference_node_entity_type
FROM
field_collection_item field_collection_item
LEFT JOIN field_data_field_sts_grades_fc field_data_field_sts_grades_fc ON field_collection_item.item_id = field_data_field_sts_grades_fc.field_sts_grades_fc_value
LEFT JOIN node field_sts_grades_fc_field_collection_item ON field_data_field_sts_grades_fc.entity_id = field_sts_grades_fc_field_collection_item.nid
LEFT JOIN field_data_field_admin_students_class_ref field_sts_grades_fc_field_collection_item__field_data_field_admin_students_class_ref ON field_sts_grades_fc_field_collection_item.nid = field_sts_grades_fc_field_collection_item__field_data_field_admin_students_class_ref.field_admin_students_class_ref_target_id AND (field_sts_grades_fc_field_collection_item__field_data_field_admin_students_class_ref.entity_type = 'entityform' AND field_sts_grades_fc_field_collection_item__field_data_field_admin_students_class_ref.deleted = '0')
LEFT JOIN entityform field_admin_students_class_ref_node ON field_sts_grades_fc_field_collection_item__field_data_field_admin_students_class_ref.entity_id = field_admin_students_class_ref_node.entityform_id
LEFT JOIN field_data_field_sts_grades_ref field_data_field_sts_grades_ref ON field_collection_item.item_id = field_data_field_sts_grades_ref.entity_id AND (field_data_field_sts_grades_ref.entity_type = 'field_collection_item' AND field_data_field_sts_grades_ref.deleted = '0')
LEFT JOIN users users_field_data_field_sts_grades_ref ON field_data_field_sts_grades_ref.field_sts_grades_ref_target_id = users_field_data_field_sts_grades_ref.uid
LEFT JOIN field_data_field_grades_exam_set field_sts_grades_fc_field_collection_item__field_data_field_grades_exam_set ON field_sts_grades_fc_field_collection_item.nid = field_sts_grades_fc_field_collection_item__field_data_field_grades_exam_set.entity_id AND (field_sts_grades_fc_field_collection_item__field_data_field_grades_exam_set.entity_type = 'node' AND field_sts_grades_fc_field_collection_item__field_data_field_grades_exam_set.deleted = '0')
LEFT JOIN field_data_field_exam_class_reference field_sts_grades_fc_field_collection_item__field_data_field_exam_class_reference ON field_sts_grades_fc_field_collection_item.nid = field_sts_grades_fc_field_collection_item__field_data_field_exam_class_reference.entity_id AND (field_sts_grades_fc_field_collection_item__field_data_field_exam_class_reference.entity_type = 'node' AND field_sts_grades_fc_field_collection_item__field_data_field_exam_class_reference.deleted = '0')
LEFT JOIN field_data_field_grade_date field_sts_grades_fc_field_collection_item__field_data_field_grade_date ON field_sts_grades_fc_field_collection_item.nid = field_sts_grades_fc_field_collection_item__field_data_field_grade_date.entity_id AND (field_sts_grades_fc_field_collection_item__field_data_field_grade_date.entity_type = 'node' AND field_sts_grades_fc_field_collection_item__field_data_field_grade_date.deleted = '0')
LEFT JOIN realname users_field_data_field_sts_grades_ref__realname ON users_field_data_field_sts_grades_ref.uid = users_field_data_field_sts_grades_ref__realname.uid
WHERE (( (field_sts_grades_fc_field_collection_item__field_data_field_grades_exam_set.field_grades_exam_set_target_id = '1422') AND (field_sts_grades_fc_field_collection_item__field_data_field_exam_class_reference.field_exam_class_reference_target_id = '1243') ))
ORDER BY field_sts_grades_fc_field_collection_item__field_data_field_ ASC, field_sts_grades_fc_field_collection_item__field_data_field__1 ASC, field_sts_grades_fc_field_collection_item_created ASC, users_field_data_field_sts_grades_ref__realname_realname ASC, field_data_field_sts_grades_ref.field_sts_grades_ref_target_id ASC

```

# Answer
IMO the approach to use the Views Show Query module as you wrote is definitely a valid approach to get you started. Even though I've not (yet) used this module to produce such queries, this part from the module's project page may need an extra hint about how to further "massage" your query (to further improve it):

> ... the module adds 'User ID to show final query' field in views preview form. You must enter numeric user ID in this field to view the real SQL query.

More specifically, I would try to transform that "user id" in that query in a "query parameter" to be used by Forena, similar to what you can already see in this SQL query that comes with the Forena samples (note the `(:state)` in this sample query):

```
select * from user_distribution WHERE
  state in (:state)
  order by city, state

```

In your own site where you have Forena installed, you can find this query at relative path `admin/structure/forena/data/sampledb.distribution/edit`.

And to see the power of this query with Forena parameters, go have a look at the Users in cities in state Illinois sample, which in your own site you can find via relative path `/reports/sample.user_distribution_simple?state=IL`.

The interesting/relevant part here is the `?state=IL` at the end of it: change it to any other (valid) state like CA, FL, etc, and see what happens (answer: similar report, for the state you asked for).

With that, I think your question (challenge) is reduced to finding a way to find a way to use these kinds of relative paths (with the query strings to indicate report parameter values, and use those parameters in your query parameters also.

Ps: If you refine your question with more specific paths, a samples SQL, the parms you have in mind etc, I might be able to further refiine my answer about also.
> 2 votes

---
Tags: 7, organic-groups, log-messages, forena
---


title: Body field not saving it's summary data

text:
# Question
Title: Body field not saving it's summary data
I've inherited a Drupal 7 site that was built in 2014. We've noticed that the body field (on any content type) has a summary textarea, but it does not save data upon submission.

Also, in comparing with other D7 sites that we have, I find it odd that on this site the Body field is assigned a 'Long text' field type whereas normally the body field uses a 'Long text and summary' field type.

Also of note, the 'Summary input' check-box on the content type setting page (/admin/structure/types/manage/page/fields/body) does not exist.

Any ideas on how to debug this issue?

# Answer
> 0 votes
Change the body field widget to **Long text and summary**

# Answer
> 0 votes
Just a hunch: this could be a form alter hook implementation. It would explain why the summary (or a summary) field appears even though the configuration is only for a long text.

Try looking at the site's custom modules for a hook\_form\_alter implementation.

Cheers

---
Tags: 7, entities
---


title: Filter node indexes by current domain

text:
# Question
Title: Filter node indexes by current domain
I'm building a D7 site using domain access. What I need now is to make a nodes list for each domain. The list would make use of the Facet API. And the list would only display the nodes on that specific domain.

I used to think adding a NODE INDEX view page, with "avaliable on current domain" filter would do the trick. But then I found there is no "avaliable on current domain" when views is selecting Node Indexes from the database !

What sould be done to restrict the results to current domain?

FYI, the site is using database search, not apache solr

# Answer
For showing nodes of particular domain on a particular domain, you dont need `avaliable on current domain`. First you have to see, if you are able to see the list of nodes on a particular node without applying the filter on a normal view.

If you cant see the content, then you will have to change some settings by going to link.

```
admin/structure/domain/settings

```

Under Advanced Settings, in Search Settings, check `Search content for the current domain only`

Under Domain Specific Settings \>\> Domain Settings Behaviour \>\> `Use the active domain`
> 1 votes

---
Tags: views, search, domain-access
---


# Question
Title: jQuery wrapper function when using Drupal behaviours
I have been trying unsuccessfully to add Drupal behaviors to an existing and workding JS script file that is wrapped in :

```
jQuery(document).ready(function($){
  // some JS here
  Drupal.behaviors.ios = {
    attach: function (context, settings) {

        // Code to be run on page load, and
        // on ajax load added here

    }
  };
});

```

I cannot get my behaviours to work.

However I have changed the wrapper to :

```
(function($){
  // some JS here
  Drupal.behaviors.ios = {
    attach: function (context, settings) {

        // Code to be run on page load, and
        // on ajax load added here

    }
  };
})(jQuery);

```

and now the behaviours work.

What is the difference between the wrappers and can I expect the existing Javascript to continue functioning if I make this change ?

# Answer
> 1 votes
Drupal attaches behaviours on DOM ready - by waiting until the DOM is ready yourself to actually inform Drupal of your custom behaviour, it's too late (unless you call Drupal.attachBehaviors manually afterwards, which would be less than efficient).

Your 2nd example is both logically correct, and the recommended way to use behaviours with jquery in Drupal 7.

Unless you have a very good reason not to, always using that approach would be a good idea.

---
Tags: 7, javascript
---


# Question
Title: Problems with Views Load More module loading via AJAX
I tried to add the Views Load More module to my semantic view but it doesn't load all of the view fields (e.g. image, etc.) when I use it with ajax. Can someone give me a hint why?

Here you can see the view:

http://www.mustxhave.com/testing

The site runs Drupal 7.43 and Views Load More v1.5. The view output is standard, no .tpl theming for this view.

# Answer
Your problem is the image path not the load more module.

I inspected the image in your view and found that it is being requested from this URL: http://www.mustxhave.com/**mustxhave**/sites/all/themes/simpnews/images/xyz-300x500.jpg which is wrong.

Removing **musthave** from the URL will fix the image path. http://www.mustxhave.com/sites/all/themes/simpnews/images/xyz-300x500.jpg

This may be caused by one of these:

* Check the view settings for the image field.
* Check settings.php file for base\_url variable value.
* Check if have Rewrite Base in the .htaccess file.
> 2 votes

# Answer
I think issue in your case is of jQuery, as you are getting the error of `jQuery is not Defined`. Please see my attached screenshot.

Try to remove jQuery `(jQuery)` from addThis js file, there is also one extra semicolon in end of file.
> 0 votes

---
Tags: views
---


# Question
Title: How to use the view_mode in hook_preprocess_flag?
I'm using Drupal 7 and Flag.

I try to modify the output of my flags according to the view mode with preprocess\_flag :

```
function mytheme_preprocess_flag(&$variables) {
  $variables['full'] = $variables['view_mode'] == 'full';
  if ($variables['full']) {
...
  }
}

```

But i have an error : `Notice : Undefined index: view_mode dans publiu_preprocess_flag()`.

Do you know how to use the view\_mode in hook\_preprocess\_flag ?

# Answer
> 2 votes
view\_mode key is not in variables object, which you get as argument. You can check for the same, by printing variables object.

```
print '<pre>';
print_r($variables);
print '</pre>';

```

However if u still want to get view mode, you can use somewhat like below.

```
function bartik_preprocess_flag(&$variables) {
  $arg_1 = arg(1);
  if( isset($arg_1) && !empty($arg_1) ) {
    $menu_obj = menu_get_object();
    $menu_obj_content = $menu_obj['content'];
    foreach($menu_obj_content as $menu_key=>$menu_val) {
      $node_view_mode = $menu_val['#view_mode'];
      break;
    }
    print $node_view_mode;
  }
}

```

Here node\_view\_mode will return "View Mode" of current node.

---
Tags: 7, theming, flags
---


# Question
Title: Drupal 7 Rules - Set value of multiple value reference field (user reference)
I have a cck content type with a multi value reference field. Using rules, I am trying to populate these reference fields when users create a different content type (for example an event and I want to keep adding user references for people that view the event -- this is an example.)

My issue right now is that I can fetch the entity to set the user reference (using a loop of users), but I can only set the first field. How do I move to the next field of the fetched entity and set it to the next user in the loop list?

I imagined that as long as I was in the loop, for each item in the loop, a set data value on the reference field would move to the next field but it simply overwrites the first one.

I see that the particular reference field I'm trying to set values for is an array (fetched-entity:field-blah:0 etc). Since I cannot pick for example item \[0\], I thought fetched-entity:field-blah without the delta would keep shifting to the next. It does not.

I'm thinking there is a way for me to loop through the deltas in the fetched entity as I loop through the list?

Any help appreciated.

# Answer
1. Install next modules:
2. Create a rule for "Content is viewed".
3. Set conditions , like "content is type"
4. Create a loop and set its name, in the data selector choose the field(not the deltas) like `[node:field-alumnos-curso]`
5. Create an action inside the loop(do not "set data value"), just select "add item to the list" and the value will be the list name or loop name.
6. Remember create a action "Save an entity".
> 2 votes

# Answer
Its long since the question asked. Currently this can be done very easily.

1. Load a list of entity objects. I used a VBO View.
2. Set a data value. Parameter: Data: \[node:field-your-user-ref-field\], Value: \[entity-list-you-loaded\]
3. Save the entity

Its as simple as this. I am using this very successfully.
> 0 votes

---
Tags: 7, rules, nodes, entities
---


title: Product page on brands block

text:
# Question
Title: Product page on brands block
I created pages for brands that I sell on my shop. Each product is associated with a brand taxonomy term. I created a view block that displays pages of brands. The block is displayed throughout the store and displays the entire list of brands. How to display only those brands related to product pages?

I know we need to use contextual filters, but I do not know how to configure.

# Answer
You can do this with the following:

* Create a new View to display the Taxonomy Terms for Brand
* In the **Views UI**, add a new **Relationship Taxonomy term: Content with term**, and uncheck *"require this relationship"*.
* Add a new Contextual filter : **Content: Nid** and choose the just-created relationship as the relationship. Provide default value \> **Content ID From URL** under When the filter value is **NOT** available.
> 0 votes

# Answer
There are certain steps which you can follow.

1. I have created a vocabulary Brand, which contains all brand.
2. I added a field in Article Content Type, field\_brand, which is term reference type.
3. After that, I create a view of type Taxonomy Term, which show terms of Brand Vocab.
4. Add Relationship for field\_brand (Taxonomy term: Content using Brand).
5. Add Contextual Filter, field\_brand ( Content: Brand (field\_brand)), which uses above relationship.
6. Under `WHEN THE FILTER VALUE IS NOT AVAILABLE,` Click on Radio Button `Provide Default Value`, Choose from drop down, `Taxonomy Term ID from URL`, `uncheck` checkbox `Load default filter from term page`, and `check` checkbox, `Load default filter from node page`, that's, check `Limit terms by vocabulary`, select your vocabulary, in my case it was `Brand`, under `Multiple View Handling`, check radio box, `Filter to items that share all terms`.

I have attached screenshot for the last step settings.
> 0 votes

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


# Question
Title: Applying a condition/reaction context to all themes
I use Drupal 7.43 with Context to hide the sidebar regions in certain content-types so that their nodes will have full-width (at least in desktop mode).

This is a good way to hide sidebars programmaitcaly, and not by CSS (which may cause clashes with other CSS rules and maybe also JavaScript).

## My problem:

If I change **my theme**, I need to reapply each condition-reaction I've created to regions in the new theme. For example, I need to pick the existing name of my sidebar region each time anew.

Do you think there's a better approach to auto-hide **ANY** sidebar region on certain Pages or Nodes?

# Answer
You could do this through a very simple custom module. This way hiding the region will work with any theme, as long as it has the same name of the region you are trying to hide.

Here's the code that would go into your `sample.info` file:

```
name = Module name
description = Module description
package = Custom
core = 7.x
version = 7.x-1.0

```

Create `sample.module` file and add the following code:

```
function sample_page_alter(&$page) {
  // Fetch the node object.
  $node = menu_get_object();
  // Perform some checks to make sure this is the page we want to alter.
  if (
    // We are on node page.
    $node &&
    // Check if the node if of type you want to have 100% wide layout.
    $node->type == 'page' &&
    // This will exclude local node tasks, such as edit, delete and revision.
    !arg(2)
  ) {
    // Unset the region you want to hide.
    unset($page['sidebar_first']);
  }
}

```

### Update

You asked for a wildcard that would work across multiple themes.

First off - the `sidebar_first` and `sidebar_second` are somewhat standard names for left/right sidebars in Drupal themes. Most of the themes will name sidebars the same way.

However, for the sake of answering the question, here's how you'd "scan" for all regions that contain for example the word "sidebar":

```
function sample_page_alter(&$page) {
  // Fetch the node object.
  $node = menu_get_object();
  // Perform some checks to make sure this is the page we want to alter.
  if (
    // We are on node page.
    $node &&
    // Check if the node if of type you want to have 100% wide layout.
    $node->type == 'page' &&
    // This will exclude local node tasks, such as edit, delete and revision.
    !arg(2)
  ) {
    // Unset the sidebar regions.
    //
    // We will loop through the elements and check if they are set and contain
    // the word "sidebar".
    foreach (element_children($page) as $region_name) {
      if (strpos($region_name, 'sidebar') !== FALSE && !empty($page[$region_name])) {
        unset($page[$region_name]);
      }
    }
  }
}

```

### Notes

1. Do take into consideration that the above approach will just prevent the region from being printed on the screen. This means that if you have complex blocks, they will still be rendered and take server resources.
2. You can replace all instances of `sample` with whatever else you want to call your module.

For more information, check out the following:

Hope this helps.
> 1 votes

---
Tags: 7, nodes
---


# Question
Title: Commerce Shipping - Calculate the shipping cost as a percentage
I am looking to calculate the shipping cost as a percentage of each item in the order.

In addition to that I would like there to be an extra shipping option which is a flat rate that can be added on as well.

So the shipping rate is always a percentage of the order total, and then also an additional flat rate charge can be added on.

# Answer
> 0 votes
there's also this tutorial for anyone who runs into this. Sorry for just posting the link. https://www.youtube.com/watch?v=0A1Yyam3Ico

# Answer
> 0 votes
Commerce shipping + commerce flat rate can give you the flat rate part of your shipping.

For the % based you can add it with tax module and make a shipping "tax". You can add a condition that the order has the selected flat rate for it to apply.

This is a pretty easy solution but won't display the correct price in selection. If you need that you would need to code it yourself.

---
Tags: rules, commerce
---


# Question
Title: Why is the third level not showing in my superfish menu?
I'm having a super fish menu wih three layers of menu points but my second layer links do not seem to be expanding even tho "Show as expanded" is checked for the individual menu points (2nd level) that is selected as "Parent item" for the 3rd level page.

Some links:
menu point with submenus: http://www.lslib.ca/content/skwlax-daycare
Third level page(hidden from the menu): http://www.lslib.ca/content/admin

How can I get the third level to display?

**EDIT 1**

I don't exaxctly know how Superfish binds into the configration either.
Maybe a link to the page would help: http://www.lslib.ca/
Under Blocks, I only see Content assigned to a Region. I'm officially confused here... :o

**EDIT 2**

The name of the theme is `Nexus Theme`, under `admin/appearance` it says: `Nexus Theme is a premium Drupal 7 theme. Developed by Devsaran.com.`

In `page.tpl.php` I have the following:

```
<nav id="navigation" role="navigation">
  <div id="main-menu">
    <?php
      if (module_exists('i18n_menu')) {
        $main_menu_tree = i18n_menu_translated_tree(variable_get('menu_main_links_source', 'main-menu'));
      } else {
        $main_menu_tree = menu_tree(variable_get('menu_main_links_source', 'main-menu'));
      }
      print drupal_render($main_menu_tree);
    ?>
  </div>
</nav>

```

# Answer
> 1 votes
I would give this a try:

> In the drupal bloc configuration just disable "Slide-in effect"

Quoting the last comment from this thread: https://github.com/joeldbirch/superfish/issues/30

Hope you get lucky with this, that whole github thread could be also interesting/relevant to your issue.

Update: This is apparently a theme specific superfish implementation, the respective theme being (most probably) Nexus

In order to deactive the effects that could be causing the error, you should edit the file sites/all/themes/nexus/js/custom.js at about line 7, commenting out the animation options:

```
//  animation:   { opacity:'show',height:'show'},   // fade-in and slide-down animation

```

Hope this does the trick!

---
Tags: 7, navigation
---


title: drupal_add_js within AJAX callback

text:
# Question
Title: drupal_add_js within AJAX callback
How can i add some data to drupal setting object using drupal\_add\_js withing some ajax callback?

For example I have ajaxified flag link on my page, and have implemented hook\_flag in my module, how can I add JS within this hook?

```
function hook_flag($action, $flag, $content_id, $account) {
...
  drupal_add_js(array(
      'my_module' => array('color' => 'green')
    ),
    'setting'
  );
...
}

```

# Answer
> 5 votes
`drupal_add_js` is designed to work when you are rendering a page, it doesn't really work for AJAX callbacks and it doesn't need to. If you want to modify the `Drupal.settings` data, you should do so within the JavaScript invoking the ajax call. It could look like this:

```
$.ajax({
  url: "mydomain.com/url",
  type: "POST",
  dataType: "json",
  data: $.param( $("Element or Expression") ),

  success: function(json) {
    Drupal.settings.data = json.data;
  },

});

```

# Answer
> 6 votes
drupal\_add\_js doesn't work properly in an AJAX callback. If you need to execute a JavaScript function within an AJAX callback, here's a way :

First, in your form, you have to create (you can just import it) the JavaScript function :

```
function my_module_form($form, &$form_state) {
// [...]
  drupal_add_js(
    'Drupal.ajax.prototype.commands.myFunction = function(ajax, response, status) {
      // Whatever you want to do.
    }',
    'inline'
  );
// [...]
  return $form;
}

```

Then, in your AJAX callback, you need to call this function you created :

```
function my_module_my_ajax_callback($form, &$form_state) {
// [...]
  $commands[] = array("command" => 'myFunction',);
// [...]
  return array('#type' => 'ajax', '#commands' => $commands);
}

```

Hope it helps !

# Answer
> 1 votes
If you want the updated values of your variables `Drupal.settings.my_module`, you can use response data at `ajaxComplete`

```
(function($){
  $( document ).ajaxComplete(function( event,response, settings ) {
    console.log(JSON.parse(response.responseText)[0].settings.my_module));
  });
})(jQuery);

```

---
Tags: 7, ajax, flags
---


# Question
Title: Allow registered users and anonymous users to add node with Password - "Password node"
I've just installed version 7.x-1.x-dev of the protected node module on a drupal 7 site. As administrator, i can manage averything as desired. That mean can set password on node. But my problem is: i want all other users including anonymous and registered users to be able to add a node and set a password on their own. Maybe i'm just missing a detail, but i counld not find any whay to do this in permission without allowing the user to bypass password. Any idea?

# Answer
For adding password for Anonymous User, you have to give them permission of editing and adding any node, and in permission section, you have to set permissions:

```
Access protected node password form
Edit any protected node password
Edit <CONTENT TYPE> password

```
> 1 votes

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


# Question
Title: Newly Inserted Record was not Queried, Immediately after Insertion
I have a form element below:

```
//Calls a function that contains the html for templates table.
$form['myid_templates_editor_table_wrapper'] = array(
    '#type' => 'item',
    '#markup' => myid_create_templates_table(),
);

```

The function below, populates the element above with the HTML of a table.

```
function myid_create_templates_table(){

    //Retrieve list of templates in the database
    $query = db_select('studidtemplates', 't1',array('target' => 'import'));

    $result = $query
        ->fields('t1', array('template_id', 'template_name', 'date_created', 'user_name'))
        ->orderBY('template_id', 'DESC')
        ->execute();

    $table_header = array(
        'template_id' => array('data' => 'Template ID' , 'field' => 'template_id','sort' => 'asc'),
        'template_name' => array('data' => t('Template Name'), 'field' => 'template_name','sort' => 'asc'),
        'date_created' => array('data' => 'Date Created' , 'field' => 'date_created','sort' => 'asc'),
        'user_name' => array('data' => t('Created by'), 'field' => 'user_name','sort' => 'asc'),
    );

    foreach ($result as $record) {
        $table_rows[] = array(l(t($record->template_id), $record->template_id, array('attributes' => array('class' => 'use-ajax'))), $record->template_name, $record->date_created, $record->user_name);
    }
    return '<div id="myid_templates_editor_table_wrapper">' . theme('table', array('header' => $table_header, 'rows' => $table_rows)) . '</div>';
}

```

It looks like the image below:

Whenever a new record is inserted to the table, the function below renders the `$form['myid_templates_editor_table_wrapper']` element to update it's table display.

```
function myid_save_templates_editor($form, &$form_state){
    global $user;

    $save = db_insert('studidtemplates',array('target' => 'import'))
        ->fields(array(
            'template_name' => 'WEW',
            'date_created' => date("Y-m-d H:i:s", time()),
            'user_name' => $user->name
        ))
        ->execute();

    return array(
        '#type' => 'ajax',
        '#commands' => array(
            ajax_command_replace('#myid_templates_editor_table_wrapper', render($form['myid_templates_editor_table_wrapper'])),

        )
    );
}

```

I notice something weird about it. When my actual record in the database is 1, the table displays 0 records. When my actual record is 2, my table displays 1 record. When my actual record is 3, it displays 2 records in my table and so on and so forth.

I was suspecting that my `$form['myid_templates_editor_table_wrapper']` element was being rendered, even if `db_insert` has not yet successfully inserted a record in my database.

Now, the question is : How will I execute the rendering of my form element after `db_insert` had successfully inserted a record in my table?

UPDATE 1:

I tried **Shabir A.** 's suggestion:

```
$save = db_insert('studidtemplates',array('target' => 'import'))
    ->fields(array(
        'template_name' => 'WEW',
        'date_created' => date("Y-m-d H:i:s", time()),
        'user_name' => $user->name
    ))
    ->execute();

watchdog('myid', $save);

if($save){
    return array(
        '#type' => 'ajax',
        '#commands' => array(
            ajax_command_replace('#myid_templates_editor_table_wrapper', render($form['myid_templates_editor_table_wrapper'])),
        )
    );
}

```

But the problem still occurs, When I view my `watchdog` table, the `$save` variable has a value of `371`. That means it was inserted successfully, as what `Shabir A.` said, but the table display was not updated. Is there anything wrong with my query? Where am I missing?

# Answer
> 0 votes
I have fixed your issue locally. Actually Issue is that, you have to render the tablemarkup, instead of the form element.

```
$markup_table = demo_pane_get_markup_table();
ajax_command_replace('#myid_templates_editor_table_wrapper', render($markup_table))

```

I am attaching the whole solution, I have created a form, with 2 fields (markup and submit button), on clicking of submit, markup of table refreshes up.

```
function demo_pane_form($form, &$form_state) {
  $form['myid_templates_editor_table_wrapper'] = array(
    '#type' => 'item',
    '#markup' => demo_pane_get_markup_table(),
  );

  $form['custom_submit'] = array(
    '#type' => 'submit',
    '#value' => 'Click',
    '#ajax' => array(
      'callback' => 'demo_pane_ajax_insert_row',
      'method' => 'replace',
      'effect' => 'fade',
    ),
  );

  return $form;
}

function demo_pane_ajax_insert_row($form, &$form_state) {
  $tags_state = variable_get('tags_state', '');
  if(empty($tags_state)) {
    variable_set('tags_state', 4);
    $state = 4;
  } else {
    $state = $tags_state + 1;
    variable_set('tags_state', $state);
  }
  $save = db_insert('field_data_field_tags')
          ->fields(array(
            'entity_type' => 'node',
            'bundle' => 'article',
            'deleted' => 0,
            'entity_id' => $state,
            'revision_id' => $state,
            'language' => 'und',
            'delta' => 0,
            'field_tags_tid' => 1,
          ))
          ->execute();

  watchdog('Table Entry', print_r($save, TRUE));

  if($save) {

    $markup_table = demo_pane_get_markup_table();
    watchdog('Table Entry', print_r($markup_table, TRUE));

    return array(
        '#type' => 'ajax',
        '#commands' => array(
            ajax_command_replace('#myid_templates_editor_table_wrapper', render($markup_table)),
      )
    );
  }
}

function demo_pane_get_markup_table() {
  $query = db_select('field_data_field_tags', 't1');
  $result = $query
            ->fields('t1', array('entity_type', 'bundle', 'entity_id', 'field_tags_tid'))
            ->orderBY('field_tags_tid', 'DESC')
            ->execute();
  $table_header = array(
        'entity_type' => array('data' => 'Entity Type' , 'field' => 'entity_type','sort' => 'asc'),
        'bundle' => array('data' => 'Bundle', 'field' => 'bundle','sort' => 'asc'),
        'entity_id' => array('data' => 'Entity ID', 'field' => 'entity_id','sort' => 'asc'),
        'field_tags_tid' => array('data' => 'Tags TID', 'field' => 'field_tags_tid','sort' => 'asc'),
    );

    foreach ($result as $record) {

      $table_rows[] = array(
        l(
          t($record->entity_type),
          'node/'.$record->entity_id,
          array('attributes' => array('class' => 'use-ajax'))
        ),
        $record->bundle,
        $record->entity_id,
        $record->field_tags_tid
      );

    }
    return '<div id="myid_templates_editor_table_wrapper">' . theme('table', array('header' => $table_header, 'rows' => $table_rows)) . '</div>';
}

```

Tell me if you have any query for the same.

# Answer
> 0 votes
You can simply check against inserted id. If insert successful means you get inserted id only then you render the data otherwise do nothing

```
$inserted_id = db_insert('studidtemplates',array('target' => 'import'))
        ->fields(array(
            'template_name' => 'WEW',
            'date_created' => date("Y-m-d H:i:s", time()),
            'user_name' => $user->name
        ))
        ->execute();
if($inserted_id) {
   return array(
    '#type' => 'ajax',
    '#commands' => array(
        ajax_command_replace('#myid_templates_editor_table_wrapper',     render($form['myid_templates_editor_table_wrapper'])),

    )
);
}

```

# Answer
> 0 votes
Check if an offset of 1 is being set in the table. I do not know how to check it technically but it could be somewhere in the theme() function that you are using.

May be its considering the 1st row of data as the table header due to some missing setting.

Hope it throws some light on the way to solution.

Regards,

Supriya Rajgopal

# Answer
> 0 votes
You're creating a new record and then querying for it, so one possibility is that either the page cache, or other caching that you may have configured is showing you stale information.

---
Tags: 7, database, ajax, forms
---


# Question
Title: composer-install of Drupal8 creates a tmp####/ folder. How to manage & clean it?
I'm working with Drupal, with v8, using Composer to install & manage it.

I create a new Drupal8 project using the 'drupal-composer/drupal-project' template,

```
composer create-project --keep-vcs --stability dev --no-interaction drupal-composer/drupal-project:8.x-dev mysite

```

That installs

```
tree mysite  -L 1
    mysite
    ├── composer.json
    ├── composer.lock
    ├── drush
    ├── LICENSE
    ├── phpunit.xml.dist
    ├── README.md
    ├── scripts
    ├── tmp12972441691459034756
    ├── vendor
    └── web

```

If you look inside that 'tmp#' folder

```
tree mysite/tmp12972441691459034756 -L 2
    mysite/tmp12972441691459034756
    └── drupal-8.0.5
        ├── autoload.php
        ├── composer.json
        ├── composer.lock
        ├── core
        ├── example.gitignore
        ├── index.php
        ├── LICENSE.txt
        ├── modules
        ├── profiles
        ├── README.txt
        ├── robots.txt
        ├── sites
        ├── themes
        ├── update.php
        ├── vendor
        └── web.config

```

it looks like a complete copy of the source.

Afaict, it's used only on the first install, and doesn't ever seem to get cleaned up or deleted (by cron etc).

Do I need to keep those files around for some reason? Or is it safe to just delete that folder?

Is there a Drupal8 maintenance task, maybe cron, that should be cleaning it out?

I've read older comments on this, and there's references to old versions' "/tmp" usage, but this is not that I guess, and this has a hash. Anyway, I don't see the Drupal8-specific usage instructions anywhere.

# Answer
> 1 votes
You shouldn't keep the tmp folder. The scaffolding plugin should delete tmp folder after it copied the necessary files into the web folder. Not sure what went wrong on your machine.

Fixed in https://github.com/drupal-composer/drupal-scaffold/issues/33

---
Tags: installation, configuration, composer, files
---


title: I want to import content

text:
# Question
Title: I want to import content
I have 2 sites running Drupal 8; the first one is a Drupal 8 beta 10 site, while the second one is a Drupal 8.0.5 site.

I made many changes to content types, but almost all the fields are identical (such as body, date, entity reference).

How can I import all the content from the first to the second one? In Drupal 7, I could use node\_import, which doesn't exist in Drupal 8.

# Answer
In time Drupal will have Drupal 8 -\> Drupal 8 migration, but it will be a while since migration from D6 and D7 is more important. Right now there aren't any easy solutions for this.

The most sound solution would be to create a service on the beta site that exposes the data on the beta site and create a script that fetches this.

You can use RELAXed Web Services to help creating webservice on the beta site.
> 0 votes

---
Tags: nodes, 8
---


# Question
Title: How can I affect a custom block to a custom page/view in Drupal 8?
I know I can choose the page were the block Will be displayed but for a big website I Will have hundred block on same région on same admin menu, it Will be hard to handle this. Is there a way to separate the custom block or create a new space for région, because if I place a custom block in a region, this custom block Will be automatically display on all page , ans I dont want that.

Thanks.

( for drupal 8 )

# Answer
> 0 votes
Of course that you can restrict on which pages you want to show block. When you edit block you can select specific pages where block will show up. But if you want more control you should consider to use Panels module. I recommend you to check that module and see if that will help you.

---
Tags: views, blocks, theming
---


# Question
Title: Warning: call_user_func_array() expects parameter 1 to be a valid callback
I have two custom modules: 1. oldmpp 2. newmpp (copying from oldmpp but modifying some parts). This method works for my other custom modules. But this time, it gave me this error:

```
warning: call_user_func_array() expects parameter 1 to be a valid callback, function ' filterrekkor_mppnew' not found or invalid function name in D:\d6\includes\form.inc on line 378.

```

In old modules, this function named "filterrekkor\_mpp". So, in new module, I rename to "filterrekkor\_mppnew"

I've already tried to rename function to: "mppnew\_filtrek", but the error still the same.

What should I do? Thanks for your help...

# Answer
Damn, it was caused by name of function. I renamed to " filterrekkor\_mppnew" (white space in the beginning) :X

Solved after 5 days just to realize for white space! OMG!
> 1 votes

---
Tags: 6
---


title: Drush affected by El Capitan?

text:
# Question
Title: Drush affected by El Capitan?
After updating my Mac from Yosemite to El Capitan, I am noticing drush does not run properly on any of my sites. Doing a simple:

```
drush status-report

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

```

This is now happening on all my Drupal sites locally, and yes, I am at the root of the Drupal install directory where this command would normally work. I've updated Composer and made sure that stable Drush 7.0.0 is running. Has anyone else come across this behaviour?

Fortunately, I made a full bootable backup of Yosemite so I will 'simply' roll my Mac back to how it was setup prior to the so-called upgrade of El Capitan. Normally I wait at least a month or two before upgrading to Apple's latest release but I got reckless and now this is the price. Sometimes I just want to switch to Ubuntu full time and say goodbye to the Mac OS.

Using:

* Mac OS 10.11
* MAMP PRO 3.2.1
* Little Snitch 3.6 (mentioning this because of this thread)
* Composer version 1.0-dev
* Drush 7.0.0

**2015-10-17 - Update #################################**

First off, thank you for the folks who commented on the original issue. I have decided for better or worse to try again. I updated Yosemite, where Drush, Mamp and everything was working fine, to El Capitan.

I removed drush by editing the .json file for composer by removing the lines for drush and then running `composer global update` which then finished the job by removing the actual drush files. Composer is up to date, and then drush7 was installed successfully with

`composer global require drush/drush:7.0.0`

However, once I navigate to a directory with a Drupal install, I am told after running some commands that 'No drupal site was found' and yet, the commands seem to complete regardless. Here are some examples:

`drush cron` results in the following:

```
 No Drupal site found, only 'drush' cache was cleared.
 'all' cache was cleared.

```

`drush updb` results in the following:

```
 No database updates required
 No Drupal site found, only 'drush' cache was cleared.
 'all' cache was cleared.

```

`drush dl hacked` results in the following:

```
 Project hacked (7.x-2.0-beta5) downloaded to
 /Users/[me]/Sites/[path]/drupal/sites/all/modules/contrib/hacked

```

Note there was no 'drupal not found' message on the last command. So, my concern is why the 'No Drupal site found' message is showing up. Here is what my .bash\_profile looks like:

```
export PATH="/Applications/MAMP/bin/php/php5.4.42/bin:$HOME/.composer/vendor/bin:$PATH"
export PATH

export DRUSH_PHP='/Applications/MAMP/bin/php/php5.4.42/bin/php'

export PATH=/usr/local/bin:$PATH

```

None of these settings were changed from how it was in Yosemite. If anyone can shed some light on these issues, I'd really appreciate it. Thanks again.

# Answer
### Homebrew

Install Drush by Homebrew:

```
brew install drush

```

### via Phar binary

```
sudo wget -O /usr/local/bin/drush http://files.drush.org/drush.phar
sudo chmod +x /usr/local/bin/drush

```
> 1 votes

# Answer
Add this to your .bash\_profile file (found here: ~/.bash\_profile)

```
export PATH="/usr/local/lib/drush:$PATH"

```

If you already have an 'export PATH=", add it like this (colon separated):

```
export PATH="/other/path:/usr/local/lib/drush:$PATH"

```
> 0 votes

# Answer
I think I found the answer! I added `/Applications/MAMP/Library/bin:` to my PATH, so that it went from this:

```
    export PATH="/Applications/MAMP/bin/php/php5.4.42/bin:$HOME/.composer/vendor/bin:$PATH"

```

To this:

```
    export PATH="/Applications/MAMP/bin/php/php5.4.42/bin:$HOME/.composer/vendor/bin:/Applications/MAMP/Library/bin:$PATH"

```

And now I am *not* getting any messages about 'No Drupal site found'. Hope this helps out others.
> 0 votes

# Answer
To make it simpler, you may also install `drush` via:

```
COMPOSER_BIN_DIR=/usr/local/bin composer global require drush/drush:7

```

which would automatically install `drush` binary into `/usr/local/bin`, so you don't have to add `vendor/bin` dir into your `PATH`.

However still you need to add path to your `php` binary.

If you've installed `php` via `brew`, add this line into your `~/.bashrc`:

```
which brew && brew --prefix homebrew/php/php56 > /dev/null && export PATH="$(brew --prefix homebrew/php/php56)/bin:$PATH"

```

However since you're using MAMP, this can help:

```
PHP_VER="5.4.42"
export PATH="$PATH:/Applications/MAMP/Library/bin:/Applications/MAMP/bin/php/php$PHP_VER/bin"

```

Then make sure you configured your mysql socket correctly by linking into it:

```
ln -vs /Applications/MAMP/tmp/mysql/mysql.sock /var/mysql/mysql.sock

```

or adding into your `php.ini` (`pdo_mysql.default_socket`) or in `settings.php` (`unix_socket`).
> 0 votes

# Answer
$ brew install homebrew/php/drush

this worked for me, on MacBook Pro - mama - el capitan I installed brew first, then the above command which installed composer as well.
> 0 votes

---
Tags: drush
---


title: Exposed filter list by tags

text:
# Question
Title: Exposed filter list by tags
I have a view, which is listing nodes. I like to exposed filter it by tags (what is a taxonomy). But I like to show tags, what is relevant (has nodes) for the current view. How can I make it?

# Answer
> 0 votes
You need to add a field in view with name **Content: All taxonomy terms Display all taxonomy terms associated with a node from specified vocabularies.** That will display all terms associated with a node

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


# Question
Title: How to change images without removing and re-uploading via GUI back end?
I have some images I need to change in batches on the website.

For example, I want to replace all color header images with grayscale images.

What I did was subsitute the old images with the new ones in folder:

```
C:\patch\sites\default\files\styles\slideshow_1920_x_700_scale\public

```

Now the problem is that after doing this, even if I restart the computer(using aquia dev desktop), clear all caches ect...

The color images still show up on the website, even if the grayscale ones are in the folder.

The only way to get the grayscale images to show is to go in the content item, remove the image, and reload the identical grayscale one.

Is there a way to batch do this WITHOUT having to manually remove and re-upload?

What if I had to change 1000 images...?

# Answer
Derivative images (the files that result from using Image Styles) are auto-generated; you need to replace the *original* image file, then flush the images already created for the style(s) you're interested in, so the derivatives be re-generated next time they're requested.

For the example path you've given, the originals will be in the root of the public file system (/sites/default/files), so just replace those with the new images, and flush the styles that use them.

Probably the easiest way to do the last part is to install the Image style flush module.
> 1 votes

---
Tags: media, batch-operations
---


title: How to render field HTML from tpl file

text:
# Question
Title: How to render field HTML from tpl file
I am trying to create a custom field widget and change the HTML of the field through a .tpl file or a theme function. The idea is my field will store some integer value (it will be updated by another form) and show the value in the from of a progresbar. My question is how can I change the HTML of the field. Same question is asked here also. Please help if anyone have any clue.

# Answer
> 0 votes
After a long research I got the answer how to do this.

```
/**
 * Implements hook_theme().
 */
function mymodule_theme() {

return array(
'my_field' => array(
  'render element' => 'element',
  //  'template' => 'field--field-progress',
  //  'variables' => array('element' => NULL, 'field' => NULL),
   ),
  );
 }

```

Than render the field as below\_

```
function theme_progressbar_field($vars){
  $element = $vars['element'];
  $output = '';
  $output .= '<div class="link-field-subrow12 clearfix">';
  $output .=' <a href="#">';
  $output .='<div class="clearfix  progress-percentage">';
  $output .='<span class="pull-right">'.$element['myfield']['#value'].'%     </span>';
  $output .='</div>';
  $output .='<div class="progress ui-progressbar">';
  $output .='<div class="progress-bar" style="width:'.$element['myfield']   ['#value'].'%"></div>';
  $output .='</div>';
  $output .='</a>' ;
  $output .= '</div>';
  return $output;
}

```

---
Tags: entities
---


# Question
Title: Once function not preventing behavior executing on AJAX update
I am attempting to disable 2 inputs within the Views exposed filter form upon initial page load. However I don't want this to happen after the filter form is autosubmitted. I have the following code, but it runs every time the filters are autosubmitted.

```
(function ($){

Drupal.behaviors.ios2 = {
    attach: function (context, settings) {

        $('#edit-arrival-date-datepicker-popup-1, #edit-departure-date-datepicker-popup-1', context).once('disable-dates', function(){
            console.info('Disable em once');
            $(this).attr('disabled', true);
        });
    }
};

})(jQuery);

```

After the initial page load I can see the disable-dates-processed class on the input in question, but the filter autosubmit causes the attribute change to run again.

What is it that I'm getting wrong ?

# Answer
> 1 votes
The `once` method is a simple beast - it checks for a class of `NAME-processed` on the element (`NAME` being the string arg you pass it). If it doesn't find that class, it assumes this is the first execution; it runs the function, and adds the class to the element. When the code executes again, the class is there, so it doesn't run the function.

When your behaviour executes first time, there's no `-processed` class on the elements, so it gets added and your function executes. Everything's happy...

Then an AJAX call happens, and the textfields get replaced; they no longer have the `-processed` class on them, since they're new elements received from the from builder function, and `once` has no option but to start from scratch again, running the function and adding the class to the new elements.

2 ways you could solve this:

1. Keep using behaviours, and use your own flag:

```
(function ($) {
  var processed = false;

  Drupal.behaviors.ios2 = {
    attach: function (context, settings) {
      if (!processed) {
        $('#edit-arrival-date-datepicker-popup-1, #edit-departure-date-datepicker-popup-1', context).attr('disabled', true);
        processed = true;
    }
  };

})(jQuery);

```
2. Conclude that behaviours aren't appropriate for this particular op, and stick with `jQuery.ready`

---
Tags: views, javascript
---


# Question
Title: Drupal's .htaccess does not deny access to nodes
D7, .htaccess woes. I'm trying to deal with referer spam in my Statistics module and block the most notorious referers. I edited my .htaccess file like this:

```
# Follow symbolic links in this directory.
Options +FollowSymLinks

# ... some options ....

# Various rewrite rules.
<IfModule mod_rewrite.c>
    RewriteEngine on

    # ... some more options ....

    # Block referer spam
    RewriteCond %{HTTP_REFERER} spamhost1\.com [NC,OR]
    RewriteCond %{HTTP_REFERER} spamhost2\.com
    RewriteRule .* - [F]
</IfModule>

```

When I went on to test this setup, I found out that it works correctly only if I try to access my site's main page. This request results in a correct 403 response:

```
GET http://www.example.com/ HTTP/1.1
referer: http://spamhost1.com/
Host: www.example.com

```

But any request to a node page produces 200 OK and loads the page which I'm trying to block:

```
GET http://www.example.com/node/1 HTTP/1.1
referer: http://spamhost1.com/
Host: www.example.com

```

Is it a matter of the Apache configuration in my server? How do I deny access to node pages?

# Answer
In your settings.php file you can add the following lines and upon recognition of an HTTP\_REFERER Drupal will not deliver any page data.

```
if ($_SERVER['HTTP_REFERER'] == 'http://spamhost1.com') {
  exit;
}

```

You should consider looking into existing modules that block spam though. Trying to manage this one URL at a time seems like a lot of work.
> 0 votes

---
Tags: 7, .htaccess
---


title: Insert form fields into form

text:
# Question
Title: Insert form fields into form
i have a form inside an .inc file. That form i'm calling it inside a new form i'm making, using form\_load\_include, so far is working but its rendering the external form outside the new form. this is the code that does that:

```
<?php
// start form to create projects
function project_creator_form($form, &$form_state) {
    global $user;
    $uuid = $user->uid;

  form_load_include($form_state, 'inc', 'lc_core', 'location'); //here i call the form
  $renderable = drupal_get_form('location_form', $form_state);
  $location = render($renderable);
  print $location; //here i print the included form

  $form['u_id'] = array(
    '#type' => 'textfield',
    '#title' => t('Identificador de Usuario'),
    '#size' => '6',
    '#attributes' => array('readonly' => 'readonly'),
    '#default_value' => $uuid,
    '#description' => "Este es su identificador de usuario, (no se puede modificar)",
    );

    $form['p_name'] = array(
    '#type' => 'textfield',
    '#title' => t('Nombre de Proyecto'),
    '#required' => TRUE,
    '#description' => "Introduzca el nombre del proyecto.",
    );

    $form['p_type'] = array(
    '#type' => 'select',
    '#title' => t('Seleccione tipo de proyecto'),
    '#options' => array(
      'Obra Nueva' => t('Obra Nueva'),
      'Adecuación' => t('Adecuación'),
      'Remodelacion' => t('Remodelación'),
      'Ampliación' => t('Ampliación'),
      'Refuerzo estructural' => t('Refuerzo estructural'),
      'Mantenimientos' => t('Mantenimientos'),
  ),
    '#required' => TRUE,
    '#description' => t('Seleccione el tipo de intervención a relizar.'),
    );

    $form['p_area'] = array(
    '#type' => 'textfield',
    '#title' => t('Area del proyecto (m2)'),
    '#required' => TRUE,
    '#description' => "Ingrese la cantidad de metros cuadrados (m2) del proyecto.",
    '#size' => '6',
    );

  $form['p_desc'] = array(
    '#type' => 'textarea',
    '#title' => t('Descripción'),
    '#description' => "Describa de que se trata el proyecto a ejecutar, puede especificar algunos detalles e información que considere necesaria.",
    '#rows' =>4,
    '#resizable' => FALSE,
    '#required' => TRUE,
    );

    $form['buttons'] = array(
    '#type' => 'submit',
    '#value' => t('Guardar proyecto'),
    );
  return $form;

}

function project_creator_form_submit($form, &$form_state) {

    db_set_active('civilproconstru'); //OPEN alter DATABASE.
    db_insert('project_info')
        ->fields(array(
        'u_id' => $form_state['values']['u_id'],
        'p_name' => $form_state['values']['p_name'],
        'p_type' => $form_state['values']['p_type'],
        'p_area' => $form_state['values']['p_area'],
        'p_ctry' => $form_state['values']['p_ctry'],
        'p_dept' => $form_state['values']['p_dept'],
        'p_city' => $form_state['values']['p_city'],
        'p_desc' => $form_state['values']['p_desc'],

        ))->execute();
$p_name=$form_state['values']['p_name'];
$loglink = l("Ver Proyectos", 'admin/lista_de_proyectos');
$msg= "El proyecto $p_name ha sido indexado, continue ingresando información del proyecto en $loglink o puede seguir indexando nuevos proyectos.";
drupal_set_message($msg);

db_set_active(); //CLOSE alter DATABASE.
}

```

And this is the output i'm getting:

Despite i'm printing inside the function that is creating the form drupal it's rendering outside of it...

HOW CAN I FIX THIS???? thanks for the help!...

# Answer
> 1 votes
Instead of printing the form when you load it, create a new form item of type markup and add your subform there as markup.

```
$form['subform'] = array(
  '#type' => 'markup',
  '#markup' => $location,
);

```

This would fix the display order but your submit handler will need to handle the extra items.

---
Tags: forms
---


# Question
Title: How to use rules to take a user from a group content page to the group page the content belongs to?
I'm using Organic groups (7.x-1.5) and wonder how to write a rule that would take the user from a group content page to the group page the content belongs to?

The event could be triggered by a button on the group content.

For example: I am viewing the page of the University of Berkeley and if I click on the button there, I am taken to the California universities page (University of Berkeley page is group content, California universities page is group.)

Notice I did not say "back" to the group since the user can land on the group content page without first landing on the group page.

Any suggestions?

# Answer
Many approaches available here. You can use the rules link module to do this. It can fetch the parent node and redirect to it when the link is clicked. https://www.drupal.org/project/rules\_link

However, check if organic groups provides tokens that you could use to build the link in html. Or a php snippet to grab the nid of the parent if it exists and print it as part of a link.

The other option is crumbs, the breadcrumbs module that automatically outputs the subgroup hierarchy. https://www.drupal.org/project/crumbs

If you are using panels, I'm pretty sure there's a replacement pattern for the parent if you create custom content.
> 2 votes

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


# Question
Title: Why are DIVs in the wrong order in Zen theme
I'm guessing (hoping) there is a good reason that the DIVs in the Zen theme are in reverse order.

In "Main", the natural order should be Banner, Navigation, Content. Instead the template is rendering them backwards and then using CSS to re-order them in the correct position.

Why? It is causing me massive grief.

I should point out that the "Banner" DIV is my own customization of the theme. It actually shows up in the correct natural order. So - really the issue is why is ***Content*** rendered BEFORE ***Navigation***? Doesn't make logical sense; is there a technical reason?

# Answer
I'd guess it has mainly to do with SEO.

From SEO Tutorial:

> In the HTML code for the page, the body text should be as close to the beginning of the code as possible, because there is a limit to how far down into a page a search engine spider will go to try to find text. So make sure your text comes before some really long JavaScript menu in the code for the page, or else the search engine won't make it far enough into the page to index the text. The search engine spider may never see the text if it is buried way down at the end of the code.

From 27 Quick Tips to Top Search Engine Rankings:

> 22. If you have a persistent (on most or all of your pages) navigation bar at the side of each page, your table is almost certainly set up in such a way that it pushes your page's body text down the HTML document. Search engines give prominence to keywords nearer the beginning of a HTML document. So, design your HTML table so that the navigation bar is placed after your main body text.
> 2 votes

---
Tags: theming
---


# Question
Title: How to override the H1 element from module?
I am trying to override the h1 element on a node view for a content type. I do not want to change the meta tags or anything else. Any tips how I could achieve this?

I have been trying something like this, but it has no effect

```
function xxx_preprocess_node(&$vars) {
    dpm($vars);
    if ($vars["type"] == 'mycontenttype') {
        $custom_title = $vars["title"] . " TESTING";
        $vars['title'] = $custom_title;
        dpm($vars);
    }
}

```

# Answer
> 1 votes
This is the sample code that will overwrite the title page of Drupal, you have to locate within the `template.php` file of the active theme Drupal website.

```
function YOUR_THEME_NAME_preprocess_page(&$vars) {
  $node = menu_get_object();
  if (isset($node->nid) && $node->type == 'your-content-type-name') {
    $custom_title= "My custom title on node: ". $node->title;
    $vars['title'] = $custom_title;
  }
}

```

---
Tags: 7
---


# Question
Title: How to create regular (monthly) reports from users?
There are several users with a customized role - Sales managers, who need to provide monthly reports on sales. A Content Type - Sales Report was configured in the system.

The users will need to login and if the report is not yet provided for the last month, they need to have an option to create a new one and submit it, if the report was provided - they need to have the option to edit the report.

After the report is submited, a user with the role Department Manager will have to approve the report or send it back to Sales managers to be update.

How do I organize/configure this with Drupal?

# Answer
> 0 votes
This seems like a perfect usecase for the Forena module. Forena is built of the idea of using SQL to get data out of a database and use XHTML and CSS to format it into web reports (and/or charts). Visit the Forena HowTos page for some links (near the bottom) to some live demo / showcase links, and experiment a bit with some of its demo samples.

Have a look at the "Northwind database" demo videos, which is similar to what you're looking for. Such as these videos:

Below are some more suggestions to map the various features you're asking for to Forena equivalents ...

> There are several users with a customized role - Sales managers, who need to provide monthly reports on sales.

Forena comes with various types of permissions, such as:

* Who is allowed to *build the SQL statements* (data blocks) that will be used in the reports that visualize these data?
* Who can browse specific reports?

Especially for "sensitive data" (commissions, salaries, ...) this is important.

> A Content Type - Sales Report was configured in the system.

Forena doesn't really need a content type to show its reports/graphs. And using the BEAN integration of it you can also create blocks that display Forena reports. For the actual look-and-feel of the report, anything that can be expressed in XHTML is supported by Forena.

> The users will need to login and if the report is not yet provided for the last month, they need to have an option to create a new one and submit it.

That sounds like anonymous users are to be excluded from Forena reports (a matter of permissions). If the site somewhere shows a menu item or some link to "a" (monthly?) report, these users just have to use that link. And specifying the actual month for which the report is to be shown, is typically implemented as a "*report parameter*", typically a pull down selection list near the top of the report.

Because of all the options that Forena offers to specify report parameters, there are various ways you could implement the selection of the actual month to be reported about.

> If the report was provided - they need to have the option to edit the report.

That's what you typically do using the WYSIWYG report editor. Though somebody who's familiar with XHTML might rather want to directly edit the (so called) .frx files.

> After the report is submited, a user with the role Department Manager will have to approve the report or send it back to Sales managers to be update.

That sounds like a workflow issue. Not sure if it is the only (or most elegant) way to implement this, but here is a possible approach:

1. Somebody authorized to do so, should create a report for the "new" month, by cloning the report from the "prior" month. Probably only changing the parameter list (by adding the new month to it).
2. Grant access to this new report to (only) role Department Manager, so that such users can look at the new report.
3. Continue improving the "new" report (as in step 1.) until it gets approved by the Department Manager.
4. After the "new" report is approved, grant access to anybody else who is now also allowed to browse it.
5. Build a special Forena report that can be used (by an authorized user ...) to send a notification eMail to all users that might be interested in being notified that the "new" report is available. To do so, you just build a report of such users, and enable "eMail" as on of the allowed "document formats" (= formats that a report can be exported to, such as CSV, XLS, PDF, eMail, etc).

> How do I organize/configure this with Drupal?

As detailed above: there's a module for it, i.e. Forena

PS: nowhere in your questions it says anything about "Charts" (sales people often "need" them also) ... But creating charts is a bonus that comes with Forena also ...

Disclosure: I'm a co-maintainer of Forena.

---
Tags: nodes
---


# Question
Title: How to use FULL Jquery.com files in Drupal content item?
I can use JS Injector and link to JS files through the info file, but what if the script is quite complicated with a lot of files and dependencies?

This accordion script has over 20 files...how to link all this and make it work?

Script is over here:

Download Builder

# Answer
All you need is to enable the jQuery Update module, which provides support for all jQuery UI versions for Drupal 7 to jQuery 1.5.x, 1.7.x, 1.8.x, 1.9.x, 1.10.x, 2.1.x and jQuery UI 1.10.2.
> 0 votes

---
Tags: javascript
---


# Question
Title: Is it possible to use Rules to make an action to entities that refers to other with entity reference
I have type Article that refers one user with entity reference.

article1 refers to user1 article2 refers to user1

I want a Rule to show a message on user profile with all the articles that refer to this user. Is it possible without coding?

# Answer
Finaly i found the solution to this problem using module Views Rules.

I create a view of users, i pass the nid as an integer and set a content referencing to the user.

I don't know if there's a better way but this works fine.
> 2 votes

# Answer
Yes, it is possible to perform an action on referenced entities via the drill down syntax `entity:uid:entity`.

However you are asking to display all the articles referenced by a user and that isn't an action. It is context.

What you are looking for is a views list.
> 0 votes

# Answer
Yes, it's an action called "fetch by property" where you select the entity reference field and provide the uid. That return a list for rules to loop over. You could then display these with a site message.

I think you're looking for views here though. I can't see much benefit from using rules.
> 0 votes

---
Tags: rules, entities
---


title: Reference with content types

text:
# Question
Title: Reference with content types
I want to show one content type content in another content type. Like one content type have Title, text field 1, text field 2, picture and i want to be able show in another content type. Is this possible? Thanks.

# Answer
Two module you can use to accomplish your requirement (1) entity reference and (2) node reference. Both directly added field to your content type as field which would be reference to another content type.

Select "entity reference" or "reference" in data type select of cck field.
> 1 votes

---
Tags: nodes
---


title: scale image in Drupal

text:
# Question
Title: scale image in Drupal
I need to scale image in Drupal 7. IF the width is greater than the height, THEN scale the image to 200px height. IF the height is greater than the width, THEN scale the image to 200px width. and if the width and height are the same, scale to 200x200. Please help me out.

# Answer
> 2 votes
I believe this module will do the trick:

ImageCache Actions

> **Effects provided**
>
> ...
>
> * Aspect Switcher - lets you perform different actions or use different dimensions based on whether the image is 'landscape' or 'portrait'

# Answer
> 0 votes
You can use Image style Configuration » Media » Image styles. Add new image style and add scale property to it. Apply that image style to image field.

---
Tags: 7, media
---


# Question
Title: AJAX callback function has to be defined in the same file?
I have defined a textfield that includes an AJAX callback. In another separate file, I have the AJAX callback function defined.

Will this work or does the callback function need to appear in the same file the textfield was defined in?

This is the code I would use.

```
'associated_element' => array(
  '#type' => 'textfield',
  '#title' => t('Destination Data Element'),
  '#description' => t('Some text.'),
  '#ajax' => array(
      'event'=>'change',
      'wrapper' => 'linked_form_elements',
      'callback' => 'form_editor_linked_form_ajax',
    ),
  ),
);

```

# Answer
> 2 votes
use form\_load\_include() in your form definition function. I put this just above the `return $form;` line.

```
form_load_include($form_state, 'file_extension', 'your_module', 'your_file_name_without_extension');

```

# Answer
> 0 votes
It doesn't matter where your file locates, it depends on your module includes that file or not.. Your ajax callback is just a PHP function and it needs to be loaded before calling. You can define ajax callback in different file, but need to load that file before calling callback function. There are multiple ways that you can include files in Drupal, for ex, in `.info` file (if you want file be loaded globally), with `module_load_include()` function, or PHP's built-in `require` or `include` functions...

---
Tags: 7, forms, ajax
---