# Question
Title: Modal window open once when user visits website
I'm trying to build simple modal window using jquery ui implementation in my custom module. I want to show this modal once when user visit my website. I choose implementation with cookie. How to make this modal appears once to user when he visit my website? should I use hook\_init?

this is my codes:

mymodule.module

```
/* menu callback */
function mymodule_menu() {
    $items['mymodule-popup'] = array(
        'title' => 'Join Club',
        'page callback' => 'mymodule_ajax_register',
        'page arguments' => array(1),
        'access callback' => TRUE,
        'type' => MENU_CALLBACK
    );

    return $items;
}

function mymodule_ajax_register() {
    $path = drupal_get_path('module', 'mymodule');
    drupal_add_library('system', 'ui.dialog', false);
    drupal_add_library('system', 'ui.draggable', false);
    drupal_add_js($path.'/mymodule.js');

    $output = '';
    $webform_nid = 30;
    $node = node_load($webform_nid);
    $submission = (object) array();
    $webform = drupal_get_form('webform_client_form_'.$webform_nid, $node, $submission);
    $output .= '<div id="popup">';
    $output .= drupal_render($webform);
    $output .= '</div>';

    return $output;
}

```

mymodule.js

```
(function ($) {
$(document).ready(function(){
    $('#popup').dialog({
        height: 'auto',
        width: 700,
        autoOpen: false,
        modal: true,
    resizable: false
    });

    $('a').click(function(){
        var status = false;
        if(this.className !== 'lightbox-processed'){
            if(!getCookie('newspopup')){
                setCookie('newspopup', 'true', 1);
                $('#popup').dialog('open');
            }else{status = true;}
            if(this.className === 'ui-dialog-titlebar-close ui-corner-all ui-state-hover'){
                $('#popup').dialog('close');
                status = true;
            }else{
            }
        }
        if(this.id === 'bottomNavClose'){
            $('#popup').dialog('close');
        }
        return status;
    });

    function setCookie(name,value,days) {
        if (days) {
            var date = new Date();
            date.setTime(date.getTime()+(days*60*60*1000));
            var expires = "; expires="+date.toGMTString();
        }
        else var expires = "";
        document.cookie = name+"="+value+expires+"; path=/";
    }

    function getCookie(name) {
        var nameEQ = name + "=";
        var ca = document.cookie.split(';');
        for(var i=0;i < ca.length;i++) {
            var c = ca[i];
            while (c.charAt(0)===' ') c = c.substring(1,c.length);
            if (c.indexOf(nameEQ) === 0) return c.substring(nameEQ.length,c.length);
        }
        return null;
    }

    function deleteCookie(name) {
        setCookie(name,"",-1);
    }
});
})(jQuery);

```

with those codes, when user visit myweb.com/mymodule-popup then click any link/url, modal window (pop up window) will appears.

How to make modal window appears once every time user visit my website?

I need advise from you guys, Thanks before.

# Answer
> 2 votes
Why invent a new module while there are existing, well-supported ones?

Two existing modules:

* The popup\_message does what you want and has a lot of features and a large installed base.
* popup\_announcement \- this is a relatively new module with full html support, but with only a few downloads.

# Answer
> 0 votes
The way I did it was as follows:

1. In `.module` file I provided a HTML output for my modal window.
2. In `.info`, CSS and JS files was added.
3. CSS defined overlay and window, so all I needed to do to switch it visible / invisible was to change one element's class, add or remove `.modal_visible` (name of the class does not really matters but that's what I used)
4. In JS I created behavior, and algorithm as follows:
    1. If the context was not right (IE new elements added instead of page load), end.
    2. If the cookie "already seen" is set, end.
    3. Set "already seen" cookie
    4. Attach function to close button's `onclick`, to remove `.modal_visible` from overlay
    5. Add `.modal_visible` to overlay

I sold copyright to code, but algorithm should be simple enough to reuse.

---
Tags: 7, javascript
---


title: What's the purpose of each directory?

text:
# Question
Title: What's the purpose of each directory?
What's the purpose of the directories used from Drupal?

# Answer
> 25 votes
I haven't seen one, so let's start a list right here. In Drupal 5, 6 and 7 the structure looks like this:

* includes - include files with php functions and classes that make up the Drupal API
* misc - miscellaneous assets like javascript files and images
* modules - Drupal core modules (not meant for contrib and custom modules)
* profiles - installation profiles
* scripts - shell scripts for developers and administrators
* sites - all files that are added by a developer to create a site

+ sites/all/libraries - 3rd party libraries, eg. a wysiwyg editor
    + sites/all/modules - contributed and custom modules
    + sites/all/themes - contributed and custom (sub)themes
    + sites/default - contains the default settings.php
    + sites/default/files - the default directory for user-uploaded files
    + sites/example.com/modules - the site-specific modules directory in a multisite structure
    + sites/example.com/themes - the site-specific themes directory in a multisite structure
    + sites/example.com/files - the site-specific directory for user-uploaded files in a multisite structure
* themes - Drupal core themes

# Answer
> 2 votes
The accepted answer is good. This is just my two cents to expand other answers, as a site developer on Drupal 7. It is easier to navigate when upgrading many custom modules, few features, and parent/custom sub-themes.

* sites/all
    + /modules
        - /contrib
        - /custom
        - /features
    + /libraries
    + /themes
* sites/example.com
    + same as sites/all/\* with site-instance specific needs when appropriate

---
Tags: 7
---


# Question
Title: How to programmatically add a user to a group in Drupal 7
I am trying to programmatically create a group node and add a user to that group in Drupal 7. The group node is being created just fine but the user is not being added to the group and I am not getting any errors. I am guessing I am using the og\_group function incorrectly but I am not sure. What am I doing wrong?

```
function MYMODULE_form_submit($form_id, $form_values) {
    global $user;

    $node = new stdClass();

    $node->type     = "group";
    $node->uid      = $user->uid;
    $node->title        = t("Group Node Title");
    $node->body     = t("Group Node Body");
    $node->status       = 1;
    $node->promote      = 0;
    $node->comment      = 1;

    $node->og_description   = t("OG Description");
    $node->og_register  = 0;
    $node->og_directory = 0;
    $node->og_private   = 1;
    $node->og_selective = 3;

    $node = node_submit($node);
    node_save($node);

    $account = user_load(2);

    og_group($node->nid, array(
                "entity type"       => "user",
                "entity"        => $account,
                "membership type"   => "OG_MEMBERSHIP_TYPE_DEFAULT",
            ));

    drupal_set_message(t("Finished"));
}

```

# Answer
> 13 votes
I figured it out. It ended up not working because the group ID is NOT the same as the node ID for that organic group. Here is the working version:

```
function MYMODULE_page_form_submit($form_id, $form_values) {
    global $user;

    $node = new stdClass();

    $node->type     = "group";
    $node->uid      = $user->uid;
    $node->title        = t("Group Node Title");
    $node->body     = t("Group Node Body");
    $node->status       = 1; //(1 or 0): published or not
    $node->promote      = 0; //(1 or 0): promoted to front page
    $node->comment      = 1; //2 = comments on, 1 = comments off

    $node->og_description   = t("OD Description");
    $node->og_register  = 0;
    $node->og_directory = 0;
    $node->og_private   = 1;
    $node->og_selective = 3;

    $node = node_submit($node);
    node_save($node);

    // Get the group ID from the node ID
    $group = og_get_group("node", $node->nid);

    // Load the user we want to add to the group (ID #2 was my test user)
    $account = user_load(2);

    // Add the user to the group
    og_group($group->gid, array(
                "entity type"       => "user",
                "entity"        => $account,
                "membership type"   => OG_MEMBERSHIP_TYPE_DEFAULT,
            ));

    // Changes the users role in the group (1 = non-member, 2 = member, 3 = administrator member)
    og_role_grant($group->gid, $account->uid, 3);

    drupal_set_message(t("Finished"));
}

```

# Answer
> 13 votes
Since OG7-2.x the node ID == group ID, there is no need to use og\_get\_group(). And in og\_group() and og\_role\_grant() your group type is the first argument. So here is the same code for OG 7.x-2.x

```
function MYMODULE_page_form_submit($form_id, $form_values) {
global $user;

$node = new stdClass();

$node->type     = "group";
$node->uid      = $user->uid;
$node->title        = t("Group Node Title");
$node->body     = t("Group Node Body");
$node->status       = 1; //(1 or 0): published or not
$node->promote      = 0; //(1 or 0): promoted to front page
$node->comment      = 1; //2 = comments on, 1 = comments off

$node->og_description   = t("OD Description");
$node->og_register  = 0;
$node->og_directory = 0;
$node->og_private   = 1;
$node->og_selective = 3;

$node = node_submit($node);
node_save($node);

// Load the user we want to add to the group (ID #2 was my test user)
$account = user_load(2);

// Add the user to the group
og_group('node', $node->nid, array(
            "entity type"       => "user",
            "entity"        => $account,
            "membership type"   => OG_MEMBERSHIP_TYPE_DEFAULT,
        ));

// Changes the users role in the group (1 = non-member, 2 = member, 3 = administrator member)
og_role_grant('node', $node->nid, $account->uid, 3);

drupal_set_message(t("Finished"));

```

}

# Answer
> 1 votes
```
Adding programmatically Group  content:
$node->type     = "group_post";
$node->uid      = $user->uid;
$node->title        = t("Group postNode Title");
$node->body     = t("Group Node Body");
$node->status       = 1; //(1 or 0): published or not
$node->promote      = 0; //(1 or 0): promoted to front page
$node->comment      = 1; //2 = comments on, 1 = comments off

$node->og_group_ref['und'][] = array('target_id' => $gid);

$node = node_submit($node);
node_save($node);

```

---
Tags: organic-groups
---


# Question
Title: Why does the files directory ignore system wide umask?
I have a Debian test system running Nginx and PHP-FPM, and have set a system wide umask of 027 which translates to default permissions of U=RWX G=RX O= for directors and U=RWX G=R O= for new folders and files, respectively.

After running the Drupal installer and reviewing directory structure, I notice that the installer generated files directory has default permissions of U=RWX G=RWX O=RX. Any files uploaded to this directory also receive similar permissions. Why is this so? Is it hard coded into the software to provide such permissions?

It would seem that if any new folders of files created in the files directory will receive hard coded permissions, that you would need to regularly update those permissions to something of your choosing.

# Answer
> 0 votes
Yes, if Drupal has permission to write to your doc root then it will certainly create the files folder on your behalf during installation, and attempt to set sensible permissions on it (775 seems perfectly reasonable to me considering the web server itself is creating the folder). This all happens in the /includes/install.inc file.

If your server is secured correctly, though, this should not be able to happen. The web server user should not be able to write to the doc root, only to the public/private filesystems. So you would create the files folder manually, and whatever permissions you decide to grant become part of *that* process.

See Securing file permissions and ownership for a full set of instructions on properly securing a Drupal site.

---
Tags: files
---


# Question
Title: PHP Fatal error: Cannot call overloaded function for non-object in /var/www/html/includes/database/query.inc on line 331
We have a Drupal 7.12 Setup in production.

Recently we upgraded PHP to 5.4.10 and we are getting the following error,

> PHP Fatal error: Cannot call overloaded function for non-object in /var/www/html/includes/database/query.inc on line 331

What can be the possible reason for it and how do can we solve it?

If the above information is not good enough to know about the root cause, how can some more data be logged about the error?

# Answer
You have to configure apache correctly, edit apache config file:

```
vi httpd.conf

```

Add this line in config file:

```
CoreDumpDirectory /tmp/apache2-gdb-dump

```

Create the folder and set permissions:

```
mkdir -p /tmp/apache2-gdb-dump
chown httpd.httpd /tmp/apache2-gdb-dump
chmod 0777 /tmp/apache2-gdb-dump

```

Then restart apache

```
/etc/init.d/httpd restart

```
> 1 votes

# Answer
On the requirements page there is a "Version specific notes on PHP requirements" section that gives information on supported PHP versions.

Notice that it doesn't mention PHP 5.4 anywhere. I take this to mean that Drupal 7 is not guaranteed to work with PHP 5.4.

In addition to this there is no hard requirement for any contributed modules to support PHP 5.4 yet. Some modules will work and some will have problems. Some modules have already had these problems fixed and I have seen in some cases, maintainers saying they will not support 5.4 if the fix causes problems for older versions, because php 5.2 & 5.3 are the main target versions of Drupal 7.

I would recommend if possible to not use PHP 5.4, and if you do you will quite probably be having to debug more of these issues as you encounter them.

Also, your version of drupal is 10 versions (more than a year) old. If you want to use the cutting edge version of PHP you have to also use the latest versions of all modules as this will give you the best chance of these kinds of issues having been fixed.

Not to mention that there have been some security fixes since 7.12 that you would benefit from having.

Is it an option for you to stay on PHP 5.3?
> 1 votes

---
Tags: 7, database
---


# Question
Title: How to add a tooltip to a Form API field?
I have a field defined like that:

```
'name' => array(
  '#title' => t('Name'),
  '#type' => 'textfield',
  '#size' => 30,
  '#maxlength' => 45,
  '#default_value' => $item->Name,
  '#description' => t("Item's name, no longer than 45 characters."),
),

```

How can I turn the description into a tooltip that will appear when user keeps mouse cursor over form element?

# Answer
Solution is to use `#attributes` attribute to provide form element with HTML title attribute, like that:

```
'name' => array(
  '#title' => t('Name'),
  '#type' => 'textfield',
  '#size' => 30,
  '#maxlength' => 45,
  '#default_value' => $item->Name,
  // '#description' => t("Item's name, no longer than 45 characters."),
  '#attributes' => array(
    'title' => t("Item's name, no longer than 45 characters."),
  )
),

```
> 6 votes

---
Tags: forms
---


title: Views Contextual Filter on date range

text:
# Question
Title: Views Contextual Filter on date range
Drupal 7.23, Views 7.x-3.7
I have a Calendar Event content type, with a date field.
In my view, I need to pass a date range as a contextual filter such that if the event's date falls within the specified range, the events is returned.
In other words, something like /events-calendar/2013-09-04/2013-09-30 should return any events happening for the rest of this month. So far I'm only able to match a single date, not a range.
Any ideas appreciated.

# Answer
Assuming that you have set up your contextual filters properly, all you need to do is change the format of the date you pass.

```
/events-calendar/20130904--20130930

```

That above format should do the trick.
> 5 votes

# Answer
If you are looking for ranges in general within the contextual filters then you should consider using the Views Contextual Range Filter module. Some more details about it:

> Views Contextual Range Filter is a simple plugin for Views that adds the option to contextually filter not just by a single value, but also by range.
>
> Numeric, alphabetical and list ranges are all supported. Node ids, user ids and even taxonomy term ids are all special cases of numbers so will work also. Range-filtering on dates is also supported. For this you may use either the absolute date format as dictated by Views, YYYYMMDD, or the relative format, which supports natural language phrases like six months ago, today noon and even first Tuesday of November.
>
> Please be aware that contextual filters are different from exposed filters. This module is about contextual filters only.
>
> You may use the OR operator (i.e. +) and the negate operator. You negate by ticking the "Exclude" box on the Views Contextual filter configuration panel, in the "More" section.
> 2 votes

---
Tags: views
---


# Question
Title: How do I filter a view with a contextual filters on a custom date field?
I am using the Quicktabs module to filter out posted that have a field value that in the date range specified. If you have a better solution in mind, please let me know. I am running Views 3.5 and Drupal 7.16

QuickTabs layout
I should be able to pass arguments to it to generate the new date sorted views using a contextual filter on the view.
Contextual Filters
I was able to query with the other contextual filters just fine but the date doesn't want to work at all.
What I would like to do is have a tab 4 date ranges (see first image) and clicking on the tab would load the content items with a that take place in a the range of specified dates. How can I get this to work? Is there a url query that I can pass as the argument for the start date field?

# Answer
> 0 votes
In the arguments follow the pattern

```
20130904--20130930

```

for date range between 4th September and the rest of the month.

---
Tags: views
---


# Question
Title: Drupal Commons add automation using Workflow modules to solve the problem of Wiki/Article Publishing for End users
I have a Drupal Commons Profile and I have setting up the following modules to my drupal commons site.

**Workbench**

1. Workbench Access
2. Workbench Moderator

Configure the **Taxonomy** and set it to "**Section**"

**My Workflow**

1. Content Creators
2. Content Publishers

Article Content Type: Publishing Options: Disabled Enabled Moderator Options to "Drafts"

**Created two Roles**

* Content Creator ( Content Creators )
* Channel Manager ( Content Publishers )

**Set permissions to Each Role**

First I logged in as Content Creator

```
My Workbench->Create Content->Article->Add New Article
Set Moderator: "Needs Review"

```

and `Save article`.

**Issues:**

After logged in as *Publishers account*. Go to

```
My Workbench->Needs Review

```

But there is no any content will be appear.

***But If i logged in as Administrator I will show the same there?***

Can anyone let me know what was the issue I am facing. any suggestion will be helpful.

# Answer
your subject is quite different than the question you ask. If its just a permission issue then you need to check under roles and permission. Sometime we cannot give all rights required to for mod or data entry access, so best is to copy administrator role and remove all critical permission and assign only what you want to give (to specific piece of content).

Btw, workbench is only used for permissions and not for the work flow. Its a like creating a working space for certain set of people (work bench) with adequate permissions, that's it.

If your question is regarding your subject of how to create workflow, then look at maestro module https://drupal.org/project/maestro to create GUI based logical workflow with great level of approvals, check point and notification options.

I researched Maestro week back for my friend and worked for a short while.
> 1 votes

---
Tags: 7, workbench
---


# Question
Title: Conditional checkbox fields if checked show a related textfield
So I want to create an Order form for my products list in Drupal 7, I'm using Entity form module, I have a prepopulated checkbox list widget to show all my product's node title as checkbox. What I want is if anyone checks a checkbox a textfield shows up to add the amount he wants to offer. I tried Conditional fields module too but it kind of doesn't work for my case because there will be more products added to the list and I cant add textfield to it manually and it will be a massive waste of time to do that.

I appreciate any suggestions and approaches or any other modules you might recommend.

# Answer
If you need to show a field when something gets checkked, you could just use JS to display a hidden field.

My approach would be to make custom table form that has the required input field as hidden. Then add javascript event listener to checkboxes that show the input at that row.

Then just do the normal validation and submit callbacks to update entities based on rows which are checked.
> 1 votes

---
Tags: forms, entities
---


# Question
Title: feeds importer tamper double importing image
Using feeds import with tamper to split up images at a | our database has thousands of products and only some of them have an image and then some have a second image (a room view of the product) and the images arent tracked in the data.

anyways the build of the url to retrieve the image is: `http://domain.tld/imgs/flooring/Manufacturer/IemNumber.jpg|http://domain.tld/imgs/flooring/Manufacturer/IemNumber-room-view.jpg`

when importing displays with a second image it works fine along with displays with no images however when importing displays with only one image it puts in two of the same image instead of ignoring the second image that it cant find as I would expect it to

# Answer
> 0 votes
I was having a similar problem using the standard feed tamper modules, so in the end I installed the Feed Tamper PHP module alongside it. Here's some example code I've used to split a string and import multiple values into a field using the Feed Tamper PHP module.

```
if (is_array($field)) {
  $value = implode($field);
}
else {
  $value = $field;
}

$field = explode('|', $value);

foreach ($field as $key => $value) {
  $field[$key] = trim($value);
}

return $field;

```

---
Tags: 7, feeds, importing-exporting
---


title: duplicate entry for username

text:
# Question
Title: duplicate entry for username
I am creating a user account programmatically with the following code.

```
$fields = array(
  'name' => $first_name,
  'mail' => $mail,
  'pass' => $password,
  'status' => 1,
  'init' => $mail,
);

$account = user_save('', $fields);

```

When I am trying with same name again, it throws an error, but by default it updates the name.

How do I update the name if already exist?

# Answer
Something very simple like this, using `user_load_by_name()`, would be an option:

```
$original_username = $username = 'something';
$count = 1;
while (user_load_by_name($username)) {
  $username = $original_username . $count++;
}

$fields = array(
  'name' => $username,
  ...

```

That will keep on trying 'something', 'something1', 'something2', 'something3', etc. until it finds a unique name.
> 6 votes

# Answer
A quick solution can be:

* Add this function to return unique user name

```
function _mymodule_unique_username($name, $uid = 0) {
  // Strip illegal characters.
  $name = preg_replace('/[^\x{80}-\x{F7} a-zA-Z0-9@_.\'-]/', '', $name);

  // Strip leading and trailing spaces.
  $name = trim($name);

  // Convert any other series of spaces to a single underscore.
  $name = preg_replace('/ +/', '_', $name);

  // If there's nothing left use a default.
  $name = ('' === $name) ? t('user') : $name;

  // Truncate to reasonable size.
  $name = (drupal_strlen($name) > (USERNAME_MAX_LENGTH - 10)) ? drupal_substr($name, 0, USERNAME_MAX_LENGTH - 11) : $name;

  // Iterate until we find a unique name.
  $i = 0;

  do {
   $new_name = empty($i) ? $name : $name . '_' . $i;
   $found = db_query_range("SELECT uid from {users} WHERE uid <> :uid AND name = :name", 0, 1, array(':uid' => $uid, ':name' => $new_name))->fetchAssoc();
   $i++;
  } while (!empty($found));

  return $new_name;
}

```
* Call it

```
// Get the updated name.
$name = _mymodule_unique_username($first_name);
$language = LANGUAGE_NONE;

// Set up the user fields.
$fields = array(
  'name' => $name,
  'mail' => $mail,
  'pass' => $password,
  'status' => 1,
  'init' => $mail,
);

$account = user_save('', $fields);

```
> 1 votes

# Answer
You may try Real name module for your users. or this snippet of code may help you

```
if ((bool) db_query("SELECT 1 FROM {users} WHERE uid <> :uid AND LOWER(name) = LOWER(:new_name)", array(
      ':uid' => $account->uid,
      ':new_name' => $new_name
    ))->fetchField()
    ) {
      $name_idx = db_query_range("SELECT SUBSTRING_INDEX(name,'_',-1) FROM {users} WHERE name REGEXP :search ORDER BY CAST(SUBSTRING_INDEX(name,'_',-1) AS UNSIGNED) DESC", 0, 1, array(':search' => '^' . $new_name . '_[0-9]+$'))->fetchField();
      $new_name .= '_' . ($name_idx + 1);
    }

```
> 0 votes

---
Tags: users
---


# Question
Title: Using integer with multiple values in Form API
I have an integer field on a node which can take two values. The nodes are created by the users by submitting a form. I can't work out how to do this for a multiple field text value.

How do I set-up a textfield form element to take multiple values?
How do I then submit it into the node using an entity wrapper?

This is the form element.

```
function createnode_form($form, &$form_state){
    $form['field_student_age'] = array(
      '#type' => 'textfield',
      '#title' => t('test'),
    ); .....

```

This is the code that creates the new node.

```
function postajob_form_submit($form, &$form_state) {

  $entity = entity_create('node', $values);
  $ewrapper = entity_metadata_wrapper('node', $entity);

  $ewrapper->field_salary->set($form_state['values']['field_salary']);

```

There is no multiple property for textfields. Do I need to open up a different path in the form variable (e.g. `$form['field_student_age']['value1']`)? I've tried various options but I can't work out what the path would be.

If I do that, can I then just submit it in the wrapper with the extended path?

# Answer
> 0 votes
I got the solution from Save a new value with entity\_metadata\_wrapper to an entity field which is an array.

I created two separate form fields.

```
function createnode_form($form, &$form_state){
  $form['field_student_age'] = array(
    '#type' => 'textfield',
    '#title' => t('test'),
  );

  $form['field_student_age2'] = array(
    '#type' => 'textfield',
    '#title' => t('test2'),
  );

```

Then I stored them using the first method in the post quoted above.

```
$ewrapper->field_student_age[] = $form_state['values']['field_student_age'];
$ewrapper->field_student_age[] = $form_state['values']['field_student_age2'];

```

Rather than using `set` as I'd done with single values, I created a new entry for each value using `[] =`.

---
Tags: 7, nodes, forms, entities
---


# Question
Title: $base_url and the mystery of broken feed images
I recently upgrade my Drupal6 site to Drupal7 and migrated to getpantheon platform, I am hand-coding absolute image url's in nodes like this :

```
<div align="center">
<img src="http://www.megaleecher.net/sites/default/files/images/sneaksy.jpg"
style="max-width:100%;height:auto" alt="sneaksy" />
</div>

```

Despite using full absolute url's, images in feedburner are getting broken : `http://feeds.feedburner.com/TheBestInternetNews` as it's source `http://www.megaleecher.net/rss.xml` is outputting relative images.

Strangly, using `$base_url = 'http://megaleecher.net';` (without www) in settings.php fixes the issue but using `$base_url = 'http://www.megaleecher.net';` (with www) makes them relative again.

I have hired two drupal dev's from oDesk (https://www.odesk.com/o/jobs/job/Fixing-relative-image-paths-Drupal-rss-feed\_~~0c48e61824bc3263/) and also asked for support from getpantheon but no solution.

# Answer
Module Pathologic might help your problem, if you haven't tried that. Here is a quote about it (from the module's project page):

> ... is an input filter which can correct paths in links and images in your Drupal content in situations which would otherwise cause them to “break;” for example, if the URL of the site changes, or the content was moved to a different server. Pathologic can also solve the problem of missing images and broken links in your site’s RSS feeds.
>
> Pathologic is designed to be a simple, set-it-and-forget-it utility. You don't need to enter any special “tags,” path prefixes, or other non-content noise into your content to trigger Pathologic to work; it finds paths it can manage in your content automatically.
> 1 votes

# Answer
Disabling CDN module did the trick, even when not enabled for images the module still made image path's relative resulting in broken images for feeds. Posting the issue on CDN module issue queue.
> 1 votes

---
Tags: feeds, uri, configuration
---


# Question
Title: How can I make someone else group manager of a group I've created?
I created a few groups and populated them with users. I also selected an admin per group. I don't want to appear on the OG members view of the group anymore, therefore I want to remove myself from the group. I find this impossible. Probably, because I'm the group manager. How can I change the group manager to that admin?

# Answer
> 1 votes
Change the author of the group node. Make it someone else than yourself.

---
Tags: 7, organic-groups, users
---


title: Access the blog from the main menu

text:
# Question
Title: Access the blog from the main menu
I want to add a link in the main menu to Blog a whole, ie the blog you go all blog entries of all users. I use the blog module and yes I can insert the access to different users blogs, but not the general blog. I do not know what is the link to the blog generic.

thanks

# Answer
> 3 votes
You can create a menu pointing to http://yoursite.com/blog. The page showing all the blogs posts uses blog as path. (See blog\_menu().)

```
  $items['blog'] = array(
    'title' => 'Blogs',
    'page callback' => 'blog_page_last',
    'access arguments' => array('access content'),
    'type' => MENU_SUGGESTED_ITEM,
    'file' => 'blog.pages.inc',
  );

```

---
Tags: routes, nodes
---


# Question
Title: Domain Access and mother website arguments
I am thinking of creating a series of websites based on one mother website using the Domain Access module, like this:

www.domain1.com linking to www.motherwebsite.com/argument1

www.domain2.com linking to www.motherwebsite.com/argument2

www.domain3.com linking to www.motherwebsite.com/argument3

etc. Each child domain will show the content associated with this domain (but created on the mother website) depending on argumentN.

So, my question is how can I capture the argumentN data to deliver the corresponding content (in Views, Blocks, Panels etc)? I guess I won't be able to use the URL for that as the argument data will not be part of the child domain's URL...

Thank you

# Answer
If you have installed the Domain Access module, you will have the Domain Access Views module available. First thing you want to do is enable that module if you haven't already.

Once you've done that, you can use the current domain as a filter:

1. Under Filter Criteria, add "Domain Access: Domain ID"
2. "Operator" is one of "Current Domain"

Now the view will only return nodes for the domain that the block/page is loaded from.
> 2 votes

---
Tags: domain-access
---


# Question
Title: use block_load to load the same block with parameters?
I have defined a "userinfo\_Block" block to show special user's info. I have a userlist.tpl.php template file.

What I want to do on this page is using `block_load()` to display each user's info, but I don't know how to send the userid to the block.

How can I achieve this?

# Answer
> 2 votes
Based on what you've explained above, a custom module is required (I called mine MODULE) and you will have your hook\_block info() which will declare the block:

```
function MODULE_block_info()
{
    $blocks = array();

    $blocks["userinfo_Block"] = array(
        "info" => t("User Info Block"),
    );

    return $blocks;
}

```

And hook\_block\_view() which will define the block. Below I have set the block content to the return value of the function userinfo\_Block():

```
function MODULE_block_view($delta = "")
{
    $block = array();

    switch ($delta)
    {
        case "userinfo_Block":
            $block["content"] = userinfo_Block();
            break;
    }

    return $block;
}

```

Now, the function that creates the block:

```
function userinfo_Block()
{
    global $user;
//print out user, remember to check for no user
print_r($user);
}

```

---
Tags: 7, blocks
---


# Question
Title: Can I use ajax to target multiple form elements from one input?
I'm trying to use ajax to update two different parts of a drupal form from just one form input blur.

I have the standard ajax stuff on my input:

```
$my_form['my_input']['#ajax'] = array(
  'callback' => 'my_callback',
  'wrapper' => 'my_target_div',
  'event' => 'blur',
);

```

This is working well, swapping out my div when the input is updated ... **however** I also want to update another form input elsewhere in the form with different code as a result of the blur on my original input.

Is this possible, any ideas?

Edit: For clarity, here's my real world example:

* Content type 'movie'
* Added field 'primary\_title'
* When 'primary\_title' is updated my ajax callback checks for similar strings and returns html.
* The html from the callback is inserted into an empty div.

That part is working great!

I'm trying to also modify the standard node 'title' input, giving it the value of 'primary\_title' after I have done some regex to tidy up the string (removing "The" or "A" from the start etc) The result will be two title fields, one with the complete title 'primary\_title' and one trimmed 'title' that will be useful for sorting and displaying records.

# Answer
> 13 votes
It appears that you can target different parts of a form using ajax commands, however you must choose to return **only one** of either:

* HTML or
* A renderable array or
* An array of AJAX commands

In the situation I originally wrote about, I was trying to return both an array of AJAX commands **and** a renderable array, which doesn't seem possible.

Code in the examples module demonstrates targeting different parts of a form using an array of AJAX commands:

```
function ajax_example_advanced_commands_html_callback($form, $form_state) {
  $text = $form_state['values']['html_command_example'];

  $commands = array();
  $commands[] = ajax_command_html('#html_div', $text);
  $commands[] = ajax_command_replace("#html_status", "<div id='html_status'>Updated html_command_example with text=$text;  " . date('r') . "</div>");
  return array('#type' => 'ajax', '#commands' => $commands);
}

```

In this code sample, #html\_div is getting $text, and separately #html\_status is getting "Updated html\_command\_example with text=$text; " . date('r') . ""

Two different locations on a form with two different pieces of information from the one ajax callback!

Looking again at what I was working on, I realized that I didn't need to return the node title field at all. It will only be a utility field, used for sorting data in lists.

I have hidden the field on the node form and it is populated the second time my form is built when my original ajax callback is triggered.

# Answer
> 0 votes
I am quite new to Drupal but so far i found the Ajax framework rather unflexible. It works great as long as you use it as it was intended to. So in your instance if you know some JS the best would definilty be to make that script your self it should be very light.

Good luck!

# Answer
> 0 votes
Another option, from drupal.org:

> You can easily replace the entire form if that is easiest. Just add a #prefix and #suffix to the entire form array, then set that as the #ajax\['wrapper'\]. (This will allow you to change multiple form elements via a single ajax call.) The only reason not to do this is that the process is faster if less information is transferred.

Your callback funciton could be as simple as:

```
function _callback($form, $form_state) {
  return $form;
}

```

That should be called from an `#ajax` array on a form element (`field_whatever` for the example below) defined in a `hook_form_FORM_ID_alter()` (or some kind of form alter hook) where you also test for `$form_state` and make alterations to the `$form` array, like:

```
 if (isset($form_state['values']['field_whatever'])){
     $form['field_something']['#disabled'] = TRUE;
     $form['field_something_else']['#disabled'] = FALSE;
 } else {
     $form['field_something']['#disabled'] = FALSE;
     $form['field_something_else']['#disabled'] = TRUE;
 }

```

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


# Question
Title: How to set automatically meta tag from node content?
I use the Nodewords module and in the Readme file it talks about ability to automatically create metatag from node content but I don't find how to do.

> 5. Each content type should be configured to control whether certain meta tags should be automatically generated, e.g. the "description" tag can be automatically taken from the node teaser.

Do someone know? Do I need additional module?

# Answer
Log into your Drupal 6 backend and go to sitename.com/admin/content/types

Edit content type you wish to set auto generation of meta tags.

In this example I am editing Basic Page so I hit edit and ended up at

sitename.com/admin/content/node-type/page

Select "Meta tags settings" and on that page you can set various meta tag generation options.

One you probably want to set is:

* Generate meta tag content when the meta tag content is empty (default)

AND

* Generate meta tags content from the node teaser (default)

Both of these are default so they should be working out of the box.
> 1 votes

---
Tags: 6, meta-tags
---


title: Multisite: Other link color (css)

text:
# Question
Title: Multisite: Other link color (css)
When using the same theme on multisites, what would be the easiest sollution to give each domain another link color?

# Answer
I would suggest you try Domain CSS module if you are already using Domain Access module. ( https://drupal.org/project/domain\_css )

This will give you ability to add additional css per domain so you can keep everything clean and organized.

Another alternative is to write a custom module and get $\_SERVER\['HTTP\_HOST'\]; which you can run into switch statment to load css.

Similar question: Load domain-specific CSS file on a multisite
> 1 votes

---
Tags: 7, theming, multi-sites
---


title: drupal multisite

text:
# Question
Title: drupal multisite
I already have a Drupal 7 website. I want to extend it to a second one. The first one is stored in a subfolder. I want to create a second subfolder to store the second one. At the base I will have an intro page which will redirect to either the 1st or the 2nd one. I do not care for different domain names. I just want different content (different menus) and slightly different template. Also same users same admin. But I would like the search to be site related.

What is the easiest way to do this? Should I create a 2nd databale or use the Domain Access module? If I create a 2nd database how can I have shared logged users? If I have the same database how will the admin be able to update each one separately (assign nodes to sitesa) and should I override the search module to only query site-related content?

# Answer
> 1 votes
There are a number of different ways to setup a drupal multisite.

Domain Access works well as its one code base, one database and one user base. Content can also be shared easily between each of the sites.

Domain Access is only one of the easiest to deploy and create any number of sub sites. Any node can be associated with as many sites as you have and node edits apply across all domains. You can also set different themes for each site to give them a different look and feel.

However in your case as previous poster pointed out it might be an overkill.

I would suggest you use Context module (https://drupal.org/project/context) to have ability to load different content and menu's. This would give you different "landing pages" while keeping single instance of Drupal and single user base.

# Answer
> 1 votes
I don't think you need multisite for you needs. In fact it may work against you.

Cant you have

```
 / = intro page
 /sitea/ = menu and templates for site a
 /siteb/ = menu and templates for site b

```

# Answer
> -1 votes
Try the Single Sign-On module. I am not sure about the name, but it shares user table across Multiple sites.

> Single Sign-On (SSO) means that if you are logged onto the master site, you will automatically be logged into any slave site that you visit.

---
Tags: 7, theming, database, search, multi-sites
---


# Question
Title: Extended default form inside block, possible?
Ok. So I have a content type, let's say "My favorite places". So naturally Drupal has a form to create new "favorite place" at node/add/my-favorite-places which appears as a page. I managed to create a customized template for this form my\_favorite\_places-node-form.tpl.php following this very helpful thread. How do you theme a content type's create/edit form in Drupal 7?

I'd like to use this form in several pages on my site. So I was thinking to make it into a block. In below mockups, My favorite places = Content Type A.

However...... I had some experiences customizing front page for anonymous users showing login & register form at the same time, which doesn't run properly with a block (messaging issue). An expert mentioned that form rendering calls should never be fired from inside blocks.

So, I was wondering whether this is a good idea. And if so, how should I do that, if possible without installing another contrib module.

Please advise. Thanks.

# Answer
You can definitely use forms inside blocks but its always best to run them through Drupal's form API to benefit from their security layers. Alejandro's suggestion to use drupal\_get\_form is right but you might find it easier to use the Advanced Form Block module which does exactly what you are asking, including creating multiple form blocks of the same content type. You create a block through their interface, chosing the content-type you want to create, and its then available to place through blocks admin or context, etc.
> 0 votes

# Answer
Using php inside blocks or simply pouring your database with php used to be bad practice.

Said that, the function toy are looking for is drupal get form:

https://api.drupal.org/api/drupal/includes%21form.inc/function/drupal\_get\_form/7
> 0 votes

---
Tags: 7, forms
---


title: Drush command to show aliases?

text:
# Question
Title: Drush command to show aliases?
Is there a `drush` command to show existing aliases? Some Googling didn't turn up anything.

# Answer
> 50 votes
You can use this in the terminal

```
drush sa

```

For example on my dev server:

```
- drush sa
@8080
@commons_3_dev
@none
@w2

```

The aliases are set in file called aliases.drushrc.php. For me this is located in /usr/local/share/drush/. Depending on how you installed Drush and on which distro you're on this may differ.

You can set up aliases in this fashion inside that file

```
$aliases['8080'] = array(
'uri'=>'server.com:8080',
'root'=>'/var/www/html_webtest2',
);

$aliases['w2'] = array(
'uri'=>'webtest2.server.com.edu',
'root'=>'/var/www/html_webtest2',
);

$aliases['commons_3_dev'] = array(
'uri'=>'yourserver.com/c3d7/',
'root'=>'/var/www/html_commons_3_dev',
);

```

For more fun, you can chain these together for server wide backups. For example, I do a big back up to all aliased sites like this

```
 drush sa | egrep "(@|default)" | egrep -v "(@none|@self) | xargs -L1 drush arb

```

Taken individually

```
 drush sa  # list site aliases
 | egrep "(@|default)"  # include default and any line containing a @ mark
 | egrep -v "(@none|@self)" # remove any lines with @none or @self
 | xargs -L1 drush arb # with each line run drush archive-backup

```

To find path and other info, use a bit o' pipping:

```
drush sa | xargs -I {}  sh -c "echo {}; drush {} st"

```

To narrow it down to finding paths:

```
    drush sa | xargs -I {}  sh -c "echo {}; drush {} st" | egrep "(@|path)"
@8080
 Site path                     :  sites/8080.webtest2
 File directory path           :  sites/8080.webtest2/files
 Private file directory path   :  /var/www/drupal_private_files
@commons_3_dev
 Site path              :  sites/default
 File directory path    :  sites/default/files
@none
@w2
 Site path              :  sites/default
 File directory path    :  sites/default/files

```

**update**

A bit late but I wanted to say don't forget about `drush @sites st`. I believe the `@sites` parameter will act on everything found under the sites folder. Think

```
drush @sites cron -y # runs cron on each root/sites/site
drush @sites rf

```

# Answer
> 2 votes
If you're like me you want all the details too…

Try `drush site-alias --table` or the shortcut `drush sa --table`.

Check GitHub or `drush topic aliases` for further info.

---
Tags: drush
---


title: View only works for root user

text:
# Question
Title: View only works for root user
I have a really strange issue occurring within a view I've created. I have the same code base on two servers, one is a stage server one is on a Vagrant instance on my local machine.

The view displays messages for a user (the UID is retrieved from the currently logged in user via a contextual filter). If I pass the UID of a user I know has messages into the contextual filter preview box in the Views admin panel while logged in as root then the view returns a record. If I try the same with another user it does not even though I am specifying the same UID, and the other user has the "administration" role checked in their profile so they should have the same permissions.

Does anybody have any ideas as to what may be causing this? I have a feeling it's something to do with configuration as like I said, the code base is mirrored yet works on one site but not the other.

# Answer
Views hardcodes RIDs in when you export or featurize a view. That means that if the role has a different RID on one site than on the other, you'll have issues with Views giving permissions to the wrong users.

One way I've gotten around this is to hack the exported view, and where it would say something like

```
$handler->display->display_options['access']['role'] = array(
  4 => 4,
);

```

I have

```
$rid = ($role = user_role_load_by_name('administrator'));
$handler->display->display_options['access']['role'] = array(
  $rid => $rid,
);

```
> 0 votes

---
Tags: 7, views
---


title: MYSQL date in views not working

text:
# Question
Title: MYSQL date in views not working
I am connecting views to an external database and everything works fine if my views handler is a string but not as a date, here is my view definition:

```
$data['Punches']['Punch_Date'] = array(
   'title' => t('Punch Date'),
    'help' => t('Employees Punch Date'),
    'field' => array(
      'handler' => 'views_handler_field_date',
      'click sortable' => TRUE,
    ),
    'sort' => array(
      'handler' => 'views_handler_sort_date',
    ),
    'filter' => array(
      'handler' => 'views_handler_filter_date',
    ),
    'argument' => array(
      'handler' => 'views_handler_argument_date',
    ),
  );

```

If I change views\_handler\_field\_date to views\_handler\_field I can see the records in my view. The date coming from mysql looks like

```
2013-08-27

```

I would also like to format that date to look like

```
08-27-2013

```

The biggest problem is that I want to be able to filter between dates, thanks for any help that can be given.

# Answer
To set the date format used when dates are displayed on your site, navigate to `Home » Administration » Configuration » Regional and language`, and set date format.
> 0 votes

---
Tags: views, 7
---


# Question
Title: Is it possible to create a Nodequeue of Nodequeues?
I have a number of node queues that serve as collections of nodes. I want the user to be able to take those collections (node queues) and add them to a queue, essentially allowing the user to have a node queue of node queues. Is this possible? If not, are there ay recommendations on how I might implement something like this?

also, I'm using drupal 7

# Answer
> 2 votes
Nodequeue supports Smartqueues.

> Smartqueue API
>
> Nodequeue provides a robust API that allows other modules to define smartqueues, which are associated with external data. For example, the included taxonomy smartqueue creates subqueues for a given queue for every term in the chosen vocabulary. Nodes are then only eligible for subqueues whose term matches the nodes terms. This makes it very easy to have queues for each category without cluttering the management page.

If the default smartqueue's dont meet your needs you could leverage the API to write your own smartqueue that uses the queue's you've made for your users.

**EDIT:**

Perhaps see Smartqueue for Content Types.

> This module provides a smartqueues based on avaliable content types. It adds a subqueue per node of selected content type to hold an ordered queue for nodes of another types. Any of these types can be used for smartqueues as well to hold additional levels of nodes grouping. So you can build very complex informational structures powered by handy Nodequeue's features and integration.

# Answer
> 0 votes
This is not exactly what you are looking for, but I did this on my site by having a node (a new content type called "Collections") that is associated with each queue. I needed this so I could have an author, description, date, and other metadata for each collection.

Then I made one more queue that can only contain nodes of type = collection. This is only worth it if you want the benefit of the collection nodes, of course. You can see it in action at http://hastac.org/collections

---
Tags: 7, nodes, queue
---


# Question
Title: Views Contextual filter using two terms, one assigned to node and one not
I have a view which uses TID from a single vocabulary as a contextual filter to create a dynamic slideshow.

This slideshow is displayed on nodes of a specific content type ("Landing Page"). The images for the slideshow are loaded from another content type ("Slideshow"). Both are tagged with terms from a common vocabulary with only one level.

The slideshow then displays all images tagged with the same term as the current landing page. This bit is working as intended.

However, I also want all slideshows to include images tagged with another term from the same vocabulary. This term has not been assigned to the landing page.

So, I'm looking for a way to achieve something like this:

Show all images tagged with the TID from the current node AND all images tagged with term 58.

Term 58 is static and will not change.

I've tried all manner of configurations with no luck. I figure I could use some PHP code in the contextual filter but haven't been able to find anything similar that would help. Worse case scenario is I create a separate display in the view for each term but that just seems inefficient.

Thanks

David

# Answer
> 0 votes
You can use relationship settings to add in the taxonomy, and then add field to also add items tagged with that Term into the slideshow.

Something like this:

Edit your view and add a relationship (3rd column on right) for Content: Taxonomy terms on node

Then under your filters add:

"Taxonomy term: Term" and Select the term that is 58

I just did a test with a sample view and results were as expected, it showed me all the items for that node plus the specific term.

---
Tags: views
---


title: Open search results in new tab

text:
# Question
Title: Open search results in new tab
I am using Apache Solr Search on my site, and would like links on the search results page to open in a new window/tab. How can I accomplish this?

# Answer
You should install Custom Search module as it does provide an option to open results in new tab or lightbox.

https://drupal.org/project/custom\_search

Otherwise you can always look into using custom functions or js to achieve the same in your search template.

**Updated Answer**

Since you are using solr and search-result.tpl.php you should have a line like:

```
<a href="<?php print $url; ?>"><?php print $title; ?></a>

```

change it by adding target value like:

```
<a href="<?php print $url; ?> target='_blank'><?php print $title; ?></a>

```
> 0 votes

---
Tags: search
---


# Question
Title: Restrict access to a section of the site implemented by a custom module
I have a site with two different type of users: clients and anonymous users.

I'm currently building custom modules to handle a "client administration" section of the site, where clients are able to change their profiles, modify custom settings, etc. There is a section of the site "client" users are able to access, but regular users are not.

How can I restrict access to that section to only a particular class of user?

# Answer
If you implement hook\_permission in your custom module, you can control the access of your client administration section.

1. Set up roles. You've done this already with the client role.
2. Implement hook\_permission():

```
function MODULE_permission()
{
    return array(
        'access client administration' => array(
            'title'       => t('Access Client Administration'),
            'description' => t('Allow users to access client administration'),
        ),
    );
}

```
3. When you define hook\_menu(), make sure you set the permissions accordingly:

```
function MODULE_menu()
{
    $items['client_administration'] = array(
        'title' => 'Client Administration Page',
...
        'access arguments' => array('access client administration'),
    );

    return $items;
}

```
4. Go to admin/people/permissions and set the permissions for 'Access Client Administration' to your client role.
> 5 votes

# Answer
Use `hook_permission()` in your custom module to define a new permission (e.g. "use module foo") and then assign that permission to the appropriate roles. Then check permissions with `user_access()` wherever necessary in your module.
> 1 votes

---
Tags: 7, users
---


# Question
Title: How to append a new form element to a form via AJAX not triggered inside the form?
Suppose I have a form only with a submit button. After an AJAX response (not an `#ajax` form callback) I need to insert/append a new form element into this form.(it's not declared in the form-building function)

How will I initialize this new form element in the PHP callback function, in order to populate it with the data i am getting through ajax?

I could have initialize the form with a dummy element and copy its array to a new one?How will I hide this dummy element in the initial state of the form (before ajax)?

In the "Add more" examples out there, the initial form carries the first of these elements from the beginning... what if there is not from the beginning in the form?

In other words how can I get anywhere in the code a fresh-empty form element ready to be rendered?

# Answer
You can add some custom value to the `form_state` and use it to determine whether to build a new form element or not. Please try the following example:

```
/**
 * An example form.
 */
function example_form($form, &$form_state) {

  $form['#tree'] = TRUE;

  // Use this value to determine whether to build a new form element or not.
  if (empty($form_state['add_new_item'])) {
    $form_state['add_new_item'] = FALSE;
  }

  $form['example_fieldset'] = array(
    '#type' => 'fieldset',
    '#title' => t('Example form'),
    // Set up the wrapper so that AJAX will be able to replace the fieldset.
    '#prefix' => '<div id="example-fieldset-wrapper">',
    '#suffix' => '</div>',
  );

  $form['example_fieldset']['name'] = array(
    '#type' => 'textfield',
    '#title' => t('Name'),
    '#required' => FALSE,
  );

  $form['actions'] = array(
    '#type' => 'actions'
  );

  // add field button.
  $form['actions']['add_field'] = array(
    '#type' => 'submit',
    '#value' => t('Add new form item'),
    '#submit' => array('field_add_one'),
    '#ajax' => array(
      'callback' => 'example_form_callback',
      'wrapper' => 'example-fieldset-wrapper',
    ),
    // hide this form element
    '#attributes' => array(
      'class' => array('element-invisible')
    )
  );

  // submit button.
  $form['actions']['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Submit')
  );

  $form['#attached']['js'] = array(
    array(
      'type'  => 'file',
      'data' => drupal_get_path('module', 'YOUR_MODULE') . '/js/add_field.js',
    ),
  );

  // append a new form element (after ajax)
  if ($form_state['add_new_item'] == TRUE) {
    $form['example_fieldset']['new_item'] = array(
      '#type' => 'textfield',
      '#title' => 'My new item',
    );
  }

  return $form;
}

/**
 * Submit handler for the "add-field" button.
 *
 * - set the $form_state['add_new_item'] as TRUE.
 * - rebuild the form.
 */
function field_add_one($form, &$form_state) {
  $form_state['add_new_item'] = TRUE;
  $form_state['rebuild'] = TRUE;
}

/**
 * Ajax callback.
 *
 * Returns the fieldset with all values in it.
 */
function example_form_callback($form, &$form_state) {

  return $form['example_fieldset'];
}

/**
 * Final submit handler.
 *
 * Reports what values were finally set.
 */
function example_form_submit($form, &$form_state) {
  $output = $form_state['values']['example_fieldset'];
  drupal_set_message('<pre>' . print_r($output, true) . '</pre>');
}

```

**add\_field.js**

```
(function($) {
  Drupal.behaviors.your_module_name = {
    attach:function() {

      var form = $('#example-form');

      // the 'add-field' form element
      // this form element is invisible. It will be triggered by the custom link (not form element).
      var addField = $('#edit-actions-add-field');

      // add an example link
      $('#my-custom-link').remove(); // prevent from adding the custom link more than once
      form.after("<span id='my-custom-link'><a href='#'>ADD FIELD</a></span>"); // add custom link

      // Attach mousedown() to the custom link in order to activate ajax.
      // Notice: You can attach click() to a normal submit form element (without ajax)
      // but it has to be mousedown() if the form element has an ajax attribute.
      $('#my-custom-link').click(function() {
        addField.mousedown();
      });
    }
  };
}(jQuery));

```
> 2 votes

# Answer
In your callback function you should be able to return a new form element like:

```
function YOURMODULE_your_callback($form, &$form_state) {
  $form['new_item'] = array(
    '#type' => 'textfield',
    '#title' => 'My new item',
  );
  return $form['new_item'];
}

```

Doesn't that work?
> 0 votes

---
Tags: forms, ajax
---


title: Autologin feature killing my website

text:
# Question
Title: Autologin feature killing my website
I have a drupal 7 site.

Running a auto login feature when people click on my newsletter.

A hook is fired when they visit the site to check for the cookie. my setup : Background info : I am already using Memcache, APC, Varnish,

2 Varnish Servers (8 GB)
1 Db percona server (32 GB)
1 HaProxy 4
Webservers, 16 GB

my question is, Performance wise. I can see that my server cannot handle 8000 users logging in.

Is there any way to make this impact on the server more "soft" in terms of performance. So my DB doesnt go down. when 8000 request auto login at the same time.

Example 1.

Ex: 1 request to auto login, causing 3-4 query to DB via the core Drupal API if so if I get 1000 users at the same time I got 3000 queries to DB -\> DB cannot handle the load. What to do ?!

Best regards

Victor

# Answer
You could cache the content and displaying it cached would ideally take stress off your database. Check out module "Boost" it can help.

Ideally optimization of the site is what is needed along with better hardware and maybe Varnish.

If you are using views consider using views built in cache with time based expiration to take stress off database.

**Update**

If you already have Varnish, APC and memcache then the only other think you can really do is get some better hardware.

We have servers that get about double what you have and they run on a quad core processor with 32GB of RAM.

We also split Web and DB server so we can utilize APC for Web Server and memcache for DB server.

Have you checked your APC stats? Varnish probably won't do much unless you configure it to cache Authenticated traffic which by default bypasses Varnish.

What are your server stats?
> 0 votes

---
Tags: performance, users
---


# Question
Title: Renaming the label of the Title textfield
Adding new fields allows you to specify the label of the field but the Title field does not. In fact, it just sits there on top acting all high and mighty. I just want to change the label of Title to something like `Your name` but retain the machine name. Does anyone have an idea how to do it?

# Answer
Go to Content type, you will have a list of content types of your site. Under Operations click on edit for the content type you want to change the title. Under `Submission form settings` you can change the "Title field label"
> 17 votes

# Answer
Use **themename\_preprocess\_field** in template.php file in theme folder.

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

    if($element['#field_name'] == 'field_xyz') {
      $variables['label'] = "your label name";
    }

}

```
> 4 votes

---
Tags: entities
---


title: need help with drupal arrays

text:
# Question
Title: need help with drupal arrays
my array for $var gave me the following $var dump

```
stdClass Object

    (
        [vid] => 71
        [uid] => 1
        [title] => dr1
        [log] =>
        [status] => 1
        [comment] => 1
        [promote] => 1
        [sticky] => 0
        [nid] => 71
        [type] => doc_upload
        [language] => und
        [created] => 1378359025
        [changed] => 1378359025
        [tnid] => 0
        [translate] => 0
        [revision_timestamp] => 1378359025
        [revision_uid] => 1
        [body] => Array
            (
            )

        [field_upload] => Array
            (
                [und] => Array
                    (
                        [0] => Array
                            (
                                [fid] => 59
                                [display] => 1
                                [description] =>
                                [uid] => 1
                                [filename] => drupal-7.23.zip
                                [uri] => public://documents/drupal-7.23.zip
                                [filemime] => application/zip
                                [filesize] => 3646168
                                [status] => 1
                                [timestamp] => 1378359025
                            )

                    )

            )

```

i need to take the value of **\[uri\]...** (indicated above) in a variable. Plz help

# Answer
> 2 votes
$uri = $var-\>field\_upload\[und\]\[0\]\[uri\];

For object you need to use the notation '-\>' for tracing the object and $var is the variable which gave you the array .

---
Tags: theming
---


# Question
Title: How can build a website for multiple organization?
I am going to build a Drupal 7 website with this structure.

* Drupal admin create organizations, the organization is separated.
* In each organization, it will be have an organization admin who is assigned by Drupal admin.
* Each organization will have their own taxonomy. The taxonomy are created on one vocabulary.
* Organization admin is able to create Project.
* Organization can create users (called organization user) in their organization and assign what project users can working on.
* Organization users can create some nodes and those nodes are separated in each project they are working on.

My questions are: 1) How I can do like that? and 2) What modules can be used to do it?

# Answer
> 2 votes
This is pretty much exactly what the OG (Organic Groups) module is for.

# Answer
> 1 votes
I agree that Organic Groups is great for this.

But also Open Atrium. The it is a Drupal distribution that has everything you request.

See also separate website: OpenAtrium.com

# Answer
> 1 votes
Open Atrium will be good.Interestingly surfing around for alternate options I found project management module.I guess its worth having a look.

---
Tags: 7
---


# Question
Title: Where should one add the js file (D7) to be attached to the custom theme's template.php file
I have js file which needs to be attached to template.php file.
Can I directly add the js file in template.php file ?
I am using drupal\_add\_js() but
should I add it inside the functions of template.php
or
should I add it directly into template.php file
I have the code in d6 which has added the drupal\_add\_js() in template.php file
without including it in any of the functions?

# Answer
Hope this will help you.

In Drupal 7, you can achieve it by

* Using preproccess function(theme\_preprocess\_page)

```
function MYTHEME_preprocess_page(&$variables) {
    //check your condition and add js here
    drupal_add_js(drupal_get_path('theme', 'MYTHEME') .'/mytheme.js', 'file'); //if js file is in theme folder
    drupal_add_js(drupal_get_path('module', 'MODULE_NAME') .'/js/myscript.js', 'file'); //if js file is in module folder
}
```
> 0 votes

# Answer
Quick example of use in your theme's template.php

```
function MYTHEME_preprocess_page(&$variables) {
    drupal_add_js(drupal_get_path('theme', 'MYTHEME') .'/mytheme.js', 'file');
}

```

Reference : https://api.drupal.org/comment/14344#comment-14344
> 0 votes

---
Tags: 7, theming
---


# Question
Title: Why is Pressflow not listed under Drupal.org's List of distributions?
I'm curious why it isn't listed under distributions. Is it because they have made modifications to the drupal core?

# Answer
Press-flow generally takes the established features of the next version of Drupal and back-ports it to the current version.

For example Pressflow-6 Takes the features(enhancements and performance improvements) from Drupal-7 and back-ports it Drupal-6. These changes generally include changing the core to considerable amount.

The only reason I think of why it is not included is that

> Since it makes changes to the core it doesn't make sense to host it on the Drupal.org under project.
> 2 votes

---
Tags: community-official-site
---


# Question
Title: getting error when clear cache in drupal
Following Error occure when i clear cache from admin in drupal:

> PDOException: SQLSTATE\[23000\]: Integrity constraint violation: 1062 Duplicate entry 'seven-views-retailers\_view-block' for key 'tmd': INSERT INTO {block} (module, delta, theme, status, weight, region, pages, cache) VALUES (:db\_insert\_placeholder\_0, :db\_insert\_placeholder\_1, :db\_insert\_placeholder\_2, :db\_insert\_placeholder\_3, :db\_insert\_placeholder\_4, :db\_insert\_placeholder\_5, :db\_insert\_placeholder\_6, :db\_insert\_placeholder\_7); Array ( \[:db\_insert\_placeholder\_0\] =\> views \[:db\_insert\_placeholder\_1\] =\> retailers\_view-block \[:db\_insert\_placeholder\_2\] =\> seven \[:db\_insert\_placeholder\_3\] =\> 0 \[:db\_insert\_placeholder\_4\] =\> 0 \[:db\_insert\_placeholder\_5\] =\> -1 \[:db\_insert\_placeholder\_6\] =\> \[:db\_insert\_placeholder\_7\] =\> -1 ) in drupal\_write\_record() (line 7106 of /home/nxsol/webdata/latestspecialsonline.co.za/includes/common.inc).

# Answer
Consider using db\_merge if you want to write when the record doesn't exist and update if the record exists. In fact at the business logic level you should check if a record exists or not before making an insert or update. That way you will have more control.

And regarding the problem you are facing only when you clear cache, it can be that somewhere in your code when you have an entry in cache you are not making an insert. But when there is no entry in the cache, you are making an insert. So every time you clear the cache an insert is being attempted with the same key which might be causing the problem.
> 2 votes

---
Tags: theming
---


# Question
Title: How to display time with different field in calendar?
How to display time on calendar if time is different field created usin CCK Time Module.

# Answer
> 1 votes
Solved this by adding field group in calendar style display.

Added time field in views and edit the settings of calendar style plugin. There is a option to group field by hour. I selected my field.

# Answer
> 0 votes
Given that you use the module Calendar you can edit the Calendar View and then switch the date field in all it's instances (at least look under contextual filters also).

Another way to do it could be to change the widget for the ordinary date field so that it uses CCK Time input widget, that way you don't have to change the Calendar view.

---
Tags: 7, datetime
---


title: Subscribe user to list

text:
# Question
Title: Subscribe user to list
I have a forum site and I **need sign up user list** (on profile page). So every user should sign up for new forum posts. Basically, I need a user group which I can attach in rules and send them email with new thread details.

**Is there a module for this or do I need create a custom module?** If I need my own module is this a good solution - Create content type "user\_list" and attach users to nodes via user reference field. Then in Rules settings I will attach this user\_list and send email to all users(via user refernce) in this node. Or is there a better alternative?

Thank you for response

# Answer
> 0 votes
Have you already tried to use Organic Groups and Notifications ? There is also *Organic groups e-mail blast* module I didn't try.

# Answer
> 0 votes
If you want it to be light-weight your should consider using https://drupal.org/project/userqueue

You can add users to a queue (similar to the nodequeue) and then use this user-queue along with views, and VBO

I am not sure if it has integration with Rules. If it has, it should make your work much easier.

---
Tags: 7, rules
---


# Question
Title: xpath XML parser is not parsing anything, neither does give any debug info
Mappings: https://www.evernote.com/shard/s61/sh/3e900019-a2c7-4a10-bc1c-0868341c4d9d/a735396d74047a86da8668c34c7a9f7d

Source feed: https://www.monosnap.com/image/BmKv9p9ao4hua1wvWpRh2pl85

For some reason I can't get it to import anything. What am I missing?

Tried also context: //channel/item.

Feed path: http://poliisi.fi/poliisi/kanta-hame/home.nsf/feedrss.xml

This is very simple and basic feed which is giving me a major headache currently. Maybe a fresh pair of eyes is smarter than mine.

# Answer
> 0 votes
Solved. Module had some odd bug. Cloning earlier working importer and changing it identical to above worked.

---
Tags: feeds
---


# Question
Title: Turning a query string into an array after using parse_url
Okay, I am afraid this might be a 'duh!' question, but I am just having one of those days! Well, the problem is, I am getting the following error every time I have a query string in my url **(https://www.google.com/?q=hello)**:

Recoverable fatal error: Argument 1 passed to drupal\_http\_build\_query() must be an array, string given

I am modifying a custom module that someone else wrote and this is the code that is problematic.

```
$pieces = parse_url($href);
$pieces['html'] = TRUE;
$pieces['path'] = isset($pieces['path']) ? $pieces['path'] : '';
if (isset($pieces['scheme'])) {
  $pieces['path'] = $pieces['scheme'] . '://' . $pieces['host'] . $pieces['path'];
}

return l($image, $pieces['path'], $pieces);

```

This is what $pieces looks like:

```
scheme (String, 5 characters ) https
host (String, 13 characters ) www.google.com
path (String, 22 characters ) https://www.google.com/
query (String, 6 characters ) q=hello
html (Boolean) TRUE

```

Obviously, the problem is due to $query not being an array. I am wondering how best to rewrite the above code so that I can properly call the l() function with the query string and any other attributes that a user might put in there. Any and all help would be greatly appreciated. Thanks.

# Answer
> 1 votes
This is the re-worked drupally way to turn the query string into an array. The function drupal\_get\_query\_array does the work for us:

```
$pieces = parse_url($href);
$pieces['html'] = TRUE;
$pieces['path'] = isset($pieces['path']) ? $pieces['path'] : '';
if (isset($pieces['scheme'])) {
  $pieces['path'] = $pieces['scheme'] . '://' . $pieces['host'] . $pieces['path'];
}

// We need to convert the query to an associative array before we pass it
// to the l() function.
if (isset($pieces['query'])) {
  $pieces['query'] = drupal_get_query_array($pieces['query']);
}

return l($image, $pieces['path'], $pieces);

```

# Answer
> 2 votes
You need to use an associative array, e.g.

```
$pieces['query'] = array('q' => 'hello');

```

The arguments for `l()` are in no way related to, or compatible with, the return from `parse_url()`. To avoid confusion it'd be better to build up a separate options array to pass as the 3rd argument to `l()`.

# Answer
> 0 votes
I would rather use the following code.

```
  $query = array();
  $url = parse_url($href);

  if (!empty($url[query])) {
    foreach(explode('&', html_entity_decode($url[query])) as $val) {
      $token = explode('=', $val);
      $query[$token[0]] = $token[1];
    }
  }

  $options = array(
    'fragment' => !empty($url['fragment']) ? $url['fragment'],
    'query' => $query,
    'absolute' => TRUE,
    'html' => TRUE,
  );

  return l($image, $url['path'], $options);

```

I assume the URL contained in `$href` is for the site running Drupal. Differently, the following code should be used.

```
  $query = array();
  $url = parse_url($href);

  $path = !empty($url['path']) ? $url['path'] : '';

  if (!empty($url['scheme'])) {
    $path = $url['scheme'] . '://' . (!empty($url['host']) ? $url['host'] : '') . $path;
  }

  if (!empty($url[query])) {
    foreach(explode('&', html_entity_decode($url[query])) as $val) {
      $token = explode('=', $val);
      $query[$token[0]] = $token[1];
    }
  }

  $options = array(
    'fragment' => !empty($url['fragment']) ? $url['fragment'],
    'query' => $query,
    'absolute' => TRUE,
    'html' => TRUE,
  );

  return l($image, $url['path'], $options);

```

I would avoid using the array returned from `parse_url()` since it could contain array elements that conflict with the ones used by modules that implement hook\_url\_outbound\_alter().

---
Tags: theming
---


# Question
Title: How to add profile fields on Ubercart 3 checkout page?
I used to use the uc\_profile module to add user profile fields to the D6/Ubercart 2 checkout page, but I cannot find a suitable solution for that same functionality in D7/UC3. Can anyone guide me toward an alternative solution? I need to add things like "birthday" and "shoe size" to the checkout page, and I need those items to be displayed on the users' profiles.

Thanks!

# Answer
You can try out the Extra Fields Checkout Pane module.

> This modules allows an administrator to define additional (billing and shipping) address fields (i.e. VAT) as well as custom order fields in Ubercart e-commerce suite. These fields will be available during checkout process and in order handling pages.
> 0 votes

---
Tags: 7, users, ubercart
---


# Question
Title: Get the name of file from file field before node is saved
There is a file upload field(which uploads zip files) . I want to get the name of file in `node_presave` , How do I do it?

# Answer
try some thing like

```
function module_node_presave($node)
{
   if($node->type=='article'){

       $file = file_load($node->field_zip['und'][0]['fid']);
       dpm($file->filename);
   }
}

```
> 1 votes

---
Tags: files
---


title: Problem by creating nodes in loop

text:
# Question
Title: Problem by creating nodes in loop
i am new to drupal and trying to migrate same pages to drupal. I am able to create one node via druapals API, but when trying to create more nodes in a loop it doesn't work...

This is the working code:

```
    define('DRUPAL_ROOT','/var/www');
    require '/var/www/includes/bootstrap.inc';
    drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);

    #construct the new node object
    $node = new stdClass();

    #specify node properties
    $node->uid = 1;
    $node->title = "new node";
    $node->log ="";
    $node->status = 1;
    $node->comment = 1;
    $node->promote = 0;
    $node->sticky = 0;
    $node->type = 'veranstaltung';
    $node->language = 'und';
    $node->created = time();
    $node->changed = $node->created;
    $node->tnid=0;
    $node->translate=0;
    $node->body['und'][0]['value']="<h1>content</h1>";
    $node->body['und'][0]['format']="filtered_html";
    $node->body['und'][0]['safe_value']="<h1>content</h1>";

    #save node
    node_save($node)

```

If i put this in a for-loop and change the body and title each iteration it doesn't work.. The code is inside an external php script. Even copy the code and paste behind it again with other body and title does not work.

Thanks a lot

# Answer
Objects are passed by reference in PHP; therefore `$node->nid` is being set after your first go around the for loop. If `$node->nid` is set, no new node is created, so, I'd `unset($node->nid)` after each `node_save()` and give it another try.
> 1 votes

# Answer
Try function node\_object\_prepare()

```
$node = new stdClass();
$node->type = 'thing';
node_object_prepare($node);
$node->title = 'Test thing';
// ...more node properties...
node_save($node);
$nid = $node->nid;
print 'nid of the node I just created: ' . $nid;

```

You can also include your code in a custom module in a hook\_init() or a hook\_cron(), you'll not need to boostrap drupal
> 1 votes

---
Tags: nodes, bootstrapping
---


title: Dropdown menu to filter view

text:
# Question
Title: Dropdown menu to filter view
I am creating a document library. I've made a custom content type of "document" and a taxonomy for document categories. I've added the categories as a field in the document view. I want to display the document list, and at the top, have a dropdown menu where you can choose a category, and then have the view update to show you just the documents in that category.

I know that you can create a filter and then "expose" that filter to the user, but when I do that with this example, it makes a text entry box, not a dropdown box.

# Answer
You can give drop down menu using **Filter Criteria** option.

In **Filter Criteria** in the field which you added for filtering Check the **checkbox** called

> Expose this filter to visitors, to allow them to change it
> 1 votes

# Answer
I would recommend that you give a try to OM Maximenu. It is a very flexible dropdown menu that basically works with any types of blocks. So you can build any View (block) or Taxonomy block or whatever and have it available for inclusion in OM Maximenu. THe toughest part seems to be skinning and styling and providing the right kind of markup.
> 0 votes

# Answer
Start using Views 3. For taxonomies you have the following option.
> 0 votes

---
Tags: views
---


# Question
Title: Display the Group Title after the content in Views Grouped By
I've got a View which displays a grid of content. The nodes are of type Photo Gallery and I'm showing a grid of thumbnails, each thumbnail representing one node. I'm grouping the content by Post Date so it appears like this:

There are two galleries posted on 09/04/2013, 1 gallery on 09/01 and 3 galleries on 08/28 and this is all well and good. However, my client would like the group title to appear below the content. So it should show `Rome 2` and `Rome 2013` and then below that should show `Post date: 09/04/2013`.

Is there any way I can make the group title render after the content instead of before?

# Answer
You should override the `views-view-grid.tpl.php` for your views. Otherwise, it will be effect all grid layout into your site.

The correct template suggestions for views be `views-view-grid--[views_name].tpl.php` or `views-view-grid--[views_name]--[display_id].tpl.php`.

To know more template suggestions for views, you can follow below step.

* Go to Administration » Structure » Views
* Edit your views
* Open the correct display of the views.
* Click on information link for theme under Advanced tab.
* A popup be display for all template suggestions for a particular views.
> 2 votes

# Answer
I found a way to do it. There is a views template which I could copy into my theme and override. Since I was displaying my content as a Grid, I copied the `views-view-grid.tpl.php` into my theme, changed it, flushed my cache and viola!
> 1 votes

---
Tags: 7, views
---


title: Custom module block holding DB calls

text:
# Question
Title: Custom module block holding DB calls
I am working on a project where I first was only designing the theme. However, I now need to create 5 already made custom pages or blocks in a page, which will be available as soon as theme is enabled.

Each page should hold its own code for grabbing information from external database. Now I am having a huge dilemma on deciding how to create those pages. Since there are DB calls made on each of them, I was suggested to create a custom module, which would display a block with the printed content from database. I tried creating "pvpstats.module" and "pvpstats.info" as normal for custom modules, and displaying it in sidebar\_first. After I enable the module, nothing happens. The block is just not visible. I used the code below.

```
function pvpstats_block_info() {
  $blocks['pvpblock'] = array(
    'info' => t('Example Block'),
    'status' => TRUE,
    'region' => 'sidebar_first',
    'weight' => 0,
    'visibility' => 0,
    'pages' => 'admin*
coder*
node/add*
node/*/edit
node/*/devel
',
  );

  return $blocks;
}

/**
  * Implements hook_block_view().
  */
function pvpstats_block_view($delta = '') {
  $block = array();

  switch ($delta) {
    case 'pvpblock':
      $block['subject'] = t('Block Name');
      $block['content'] = theblock_contents();
      break;
  }

  return $block;
}

function theblock_contents() {
  return '
    $dbserver="serveradress";
    $dblogin="username";
    $dbpass="dbpassword";
    $dbname="databaseserver";

                mysql_connect($dbserver, $dblogin, $dbpass);
                mysql_select_db($dbname);
                mysql_query("SET NAMES 'utf8'");

                $vypis =  mysql_query("SELECT * FROM characters WHERE (accesslevel < '1') AND (pvpkills > '0') order by pvpkills desc LIMIT 20");
                echo '<table><tr><td><center>Nick</center></td><td></td><td>Kills</td></tr>';
         while($row = mysql_fetch_array($vypis))
                    {
                echo '<tr><td><font color="green">';
                echo $row["char_name"];
                echo '</font></td><td>  </td><td><font color="blue">';
                echo $row["pvpkills"];
                echo '</font></td></tr>';

                    }
    echo '</table>';
    ?>

```

The main point is that I need those blocks later included in my theme so that they are visible immediately after enabling the theme, if that is somehow possible.

# Answer
In `theblock_contents` you are trying to return php code. Don't. Do not echo or print in it. If anything, build a string. It should look about like that:

```
/**
* custom html block
* @return string
*/
function theblock_contents() {
  $dbserver="serveradress";
  $dblogin="username";
  $dbpass="dbpassword";
  $dbname="databaseserver";

  $result = '';

  mysql_connect($dbserver, $dblogin, $dbpass);
                mysql_select_db($dbname);
                mysql_query("SET NAMES 'utf8'");

  $vypis =  mysql_query("SELECT * FROM characters WHERE (accesslevel < '1') AND (pvpkills > '0') order by pvpkills desc LIMIT 20");
  $result .= '<table><tr><td><center>Nick</center></td><td></td><td>Kills</td></tr>';
  while($row = mysql_fetch_array($vypis))
  {
    $result .= '<tr><td><font color="green">';
    $result .= $row["char_name"];
    $result .= '</font></td><td>  </td><td><font color="blue">';
    $result .= $row["pvpkills"];
    $result .= '</font></td></tr>';
  }
  $result .= '</table>';
  return $result;
}

```

It's worth to mention that your code was plainly invalid PHP, no matter if it was supposed to run in Drupal or not. You can't simply `return` PHP code as string and hope it'll be executed. Only the part about not using `echo` in hooks is really Drupal dependent.

**Important note:** if you want your modules to work stable, please don't use PHP SQL functions directly. Use `db_select` to obtain data. Connecting to multiple databases is pretty well documented too.
> 1 votes

# Answer
You can associate a block automaticly with a theme's region. (I've done it in a module.install file.) By default a block in not visible; you have to choose manually a theme's region, or you can use code similar to the following one to add it programmatically.

```
  $default_theme = variable_get('theme_default', 'bartik');
  $values = array(
    array(
      'module' => 'block',
      'delta' => 'pvpblock',
      'theme' => $default_theme,
      'status' => 1,
      'weight' => 1,
      'region' => 'sidebar_first',
      'pages' => '',
      'cache' => -1,
    ),
  );

  $query = db_insert('block')->fields(array('module', 'delta', 'theme', 'status', 'weight', 'region', 'pages', 'cache'));
  foreach ($values as $record) {
    $query->values($record);
  }
  $query->execute();

```
> 0 votes

---
Tags: blocks
---


# Question
Title: Updating field in external Drupal database
I'm working on a project where I have 2 Drupal installations which occasionally need to interact with eachothers database.

So far, I've been able to set up all interactions using db\_set\_active and db\_select/db\_query/db\_update statements (example below):

```
db_set_active(.....);
db_select(.....);
db_set_active;

```

Simple select queries don't pose any problem. And while update queries are being propagated correctly, they have an inherit issue: they don't call the save hooks in the target Drupal installation...

My use case: I'm database updating a boolean CCK field (in Drupal B) from 0 to 1 (through a module script at Drupal A) and Rules (at Drupal B) should trigger on this. Moreover, the field caches aren't cleared so probably going directly through the database isn't a very good way to update the field...

Any other ideas how to update fields from within external scripts? Or maybe how to execute Rules while keeping the database operations?

Thanks

# Answer
> 0 votes
I have achieved the similar functionality with following code. I worked on Drupal 6. But, hopefully it worked for you.

I have two same drupal installation and when creating new node in one installation, I need to create node into another Drupal installation also. So, I customize the node form and added a submit function to node form.

Custom Submit function

```
function custom_node_export_form_submit($form, $form_state) {

  //Creating node object
  $node = new stdClass;

  foreach ($form_state['values'] as $key => $value) {
    $node->$key = $value;
  }

  db_set_active('domain');

  node_save($node);

  db_set_active('default');

}

```

---
Tags: database
---


# Question
Title: Reduce installation time and increase the installation speed using drush command "site-install"
Can anyone tell me how to increase the installation speed and reduce installation time using drush command "site-install".

or

Is there any alternate way to install the distribution via drush with minimal time.

Because, I am trying to install the larger size distribution via drush using "site-install" command. It takes more time to complete the installation and even some of the distributions are broken during installation after 10min time.

Is there any min requirement in-terms of hardware to install the distribution via drush. Or does it require any additional configuration in php.ini or httpd.conf config file.

We already tried to changing the config in php.ini file for the following attributes.

max\_execution\_time memory\_limit max\_input\_time

Regards Arun

# Answer
> 2 votes
> Is there any min requirement in-terms of hardware to install the distribution via drush

No, there aren't any minimum hardware requirements. If your machine can run the software that Drush relies on, Drush can run.

> does it require any additional configuration in php.ini or httpd.conf config file

It depends on your environment - the project page has all the information you'll need.

> Is there any alternate way to install the distribution via drush with minimal time

I don't see how there would be. The Drush guys aren't going to have made that process intentionally slow, so it'll probably be as quick as it can be.

> Can anyone tell me how to increase the installation speed and reduce installation time using drush command "site-install"

That's down to the specs of your machine; the obvious (if slightly patronising) answer is simply to buy better hardware if yours isn't up to the task you want to use it for.

Bottom line, if you're installing a "larger size distribution" you can expect it take more resources. If that amount of resources is more than you have to give, it's time to look at buying better hardware.

---
Tags: drush
---


# Question
Title: Using PHP ImageMagick with ImageCache Custom actions - Returning image
I'm trying to composite some images using ImageMagick - I know imagemagick via PHP, i'm trying to return the image via PHP but it seems to overwrite the original source file - not ideal as it can apply the filter over and over.

Ideally, I'd like to write the original file with \_thumb after it, then call this file via Drupal for display, where it would copy to the appropriate imagecache directory and display from there. Anyone with ImageMagick experience, would be appreciated if you can help.

```
$location = $image->source;

$newImage = new Imagick($_SERVER['DOCUMENT_ROOT'].'/'.$image->source);

$distort = array( 0.0, 0.0, 0.16, 1.0  );
$newImage->distortImage( Imagick::DISTORTION_BARREL, $distort, TRUE );
$newImage->resizeImage(1600, 1600, Imagick::FILTER_CATROM, 1);
$newImage->cropImage(1500, 1500,60, 50);

$extension_pos = strrpos($fileName, '.'); // find position of the last dot, so where the extension starts
$thumb = substr($fileName, 0, $extension_pos) . '_thumb' . substr($fileName, $extension_pos);
$newImage->writeImage($thumb);

return $thumb;

```

# Answer
Someone might find this useful as Documentation is very sparse for this (this took me over a day to figure out). The problem was I was writing to a seperate file - Works, but ImageCache will delete it, also defeats the point of using ImageCache.

The solution is as follows, to use $image-\>ops\[\] and ImageMagick CMD's. (This is entered in the custom actions of imagecache. Distort image, apply mask, and apply overlay. This is used for creating product images for a Shop with just normal images supplied. I'll probably make a blog post in more depth at some point.

```
$image->ops[] = "-distort Barrel '0.0 0.0 0.16 1.0'";
$image->ops[] = "-resize 1600x1600";
$image->ops[] = "-crop 1500x1500+60+50";
$image->ops[] = "'sites/default/files/coushin-bg.png' -compose Dst_In  -gravity center -alpha Set -composite -format png -quality 90 ";
$image->ops[] = "'sites/default/files/Blank-Cushion.png' -compose Multiply  -composite -format png -quality 90 ";
return $image;

```
> 2 votes

---
Tags: media
---


title: How to modify body of a node

text:
# Question
Title: How to modify body of a node
I have to add some data to body of my content type, how do I add it in hook\_node\_save. I tried adding it like shown below but it's not getting saved.

```
function mymodule_node_save($node) {
$node->body = 'test string';
}

```

Also when I do `dsm($node)` in the above function, the `$node->body` doesn't contain the string I added.

# Answer
There's no such hook as `hook_node_save()`, you're probably looking for `hook_node_presave()`

> Act on a node being inserted or updated.

Also, the nody body is a field so you have to treat it as such when assigning values:

```
function mymodule_node_presave($node) {
  $node->body[LANGUAGE_NONE][0]['value'] = 'test string';
}

```
> 3 votes

---
Tags: nodes, hooks
---


# Question
Title: Show taxonomy children terms when searching parent term
I have a question about taxonomy term search and I hope someone can help. What I need to do is be able to perform parent taxonomy term search and pull all children terms so that the resulting page shows content tagged with children terms to the searched parent term. There might be already a solution out there but I can’t seem to find it, so if someone knows where to get to it, please let me know. I have already created a vocabulary, which contains about 100 terms; some terms have with sub-terms (children terms). When I search for a parent term, I don’t get the content tagged with its children terms related to the parent. When I click the parent term the only thing I get is: “There is currently no content classified with this term”. Thanks for help.

# Answer
> Add these helper functions to your module \- Call function get\_all\_nodes\_belong\_to\_taxonomy\_hierarchy(), with argument as parent term id, to get all nodes related to parent term and child terms both

```
/**
 * function to get all term ids inside a vocab in a flat array
 * No matter if vocab consists of hierarichal order of terms,you will get all term ids in a flat array.
 * @param
 *   $vocab_machine_name takes vocabulary machine name as parameter.
 * @return
 *   $tids return array of tids in a flat array format
 */
function get_taxonomy_term_ids_inside_vocab($vocab_machine_name) {
  $vocab = taxonomy_vocabulary_machine_name_load($vocab_machine_name);
  if (is_object($vocab)) {
    $term_tree = taxonomy_get_tree($vocab->vid);
    if (is_array($term_tree) && !empty($term_tree)) {
      foreach ($term_tree as $key => $value) {
        $tids[] = $value->tid;
      }
    } if (empty($term_tree)) {
      $tids = array();
    }
  } else
    return "No Vocab Found with the given name";

  return ($tids);
}

/**
 * function to get all the node ids directly mapped to the given taxonomy terms.
 * Returns Flat array of node ids belong to the given term ids.
 * @param
 *   $tid takes term id can be a single term or array of terms.
 * @return
 *   $nid/$nids returns node ids array or sinly node id directly mapped to the given taxonomy term.
 */
function get_nodes_directly_mapped_to_term($tid) {
  if (is_array($tid) && !empty($tid)) {
    foreach ($tid as $key => $value) {
      $nids[] = taxonomy_select_nodes($value);
      $flat_nids = multitosingle($nids);
    }
    return $flat_nids;
  }
  else {
    $nid = taxonomy_select_nodes($tid);
    return $nid;
  }
}

/**
 * function to convert mutlidimension arrays to flat arrays.
 * Returns Flat arrays.
 * @param
 *   $input takes input array as multudimension array.
 *   $output takes output array as paramter in the recursive call.
 * @return
 *   $output return flat array format for the input multidimenional array
 */
function multitosingle($input, $output = array()) {
  ksort($input);
  foreach ($input as $value) {
    $key = count($output);
    if (is_array($value)) {
      $output = multitosingle($value, $output);
    }
    else {
      $output[$key] = $value;
    }
  }
  return $output;
}

/**
 * function to get array/single nids which are attached with any of the taxonomy term of the given vocab.
 * Returns Flat array of nids.
 * @param
 *   $vocab_machine_name takes the machine name for the vocabulary.
 * @return
 *   $nids_inside_vocab returns array of nids/single nid attached to any taxonomy term under the given vocab.
 */
function get_nodes_belong_to_vocab($vocab_machine_name) {
  $vocab_tids = get_taxonomy_term_ids_inside_vocab($vocab_machine_name);
  if (is_array($vocab_tids) && count($vocab_tids) > 0) {
    $nids_inside_vocab = get_nodes_directly_mapped_to_term($vocab_tids);
    return $nids_inside_vocab;
  }
  elseif (is_array($vocab_tids) && count($vocab_tids) == 0) {
    return array();
  }
  else {
    return "There is no vocab found with the given machine name";
  }
}

/**
 * function to get array/single nids inside a single taxonomy term/array of taxonomy terms
 * function to get all node ids recursively inside a taxonomy term.
 * if parent term is passed as parameter then the function returns nid belongs to the parent term and nids related to its child terms.
 * Returns Flat array of nids.
 * @param
 *   $tids takes array/single tids for which you need nids recursively.
 * @return
 *   $nids flat array of nids
 */
function get_all_nodes_belong_to_taxonomy_hierarchy($tids) {
  if (is_array($tids)) {
    foreach ($tids as $key => $value) {
      if ($value <= 0) {
        return "Please Enter a valid taxonomy term id set";
      }
    }
  }
  if (is_array($tids) && !empty($tids)) {
    foreach ($tids as $key => $value) {
      $term = taxonomy_term_load($value);
      $hierarchical_terms_object[] = taxonomy_get_tree($term->vid, $term->tid);
    }
    $flat_terms_object = multitosingle($hierarchical_terms_object);
    if (is_array($flat_terms_object) && !empty($flat_terms_object)) {
      foreach ($flat_terms_object as $key => $value) {
        $flat_tids[] = $value->tid;
      }
      $flat_tids[] = $tids;
      return array_unique(get_nodes_directly_mapped_to_term($flat_tids));
    }
    else {
      $flat_tids = $tids;
      return array_unique(get_nodes_directly_mapped_to_term($flat_tids));
    }
  }
  elseif (!is_array($tids) && $tids > 0) {
    $flat_tids = $tids;
    get_all_nodes_belong_to_taxonomy_hierarchy(array($flat_tids));
  }
  else {
    return "Please Enter a valid term id";
  }
}

```
> 1 votes

# Answer
The reason being when a tag is attached to a content the parent tag does not get attached by default. The parent lineage is not saved by default. I would suggest you use something like hierarchical select.

> Hierarchical Select has the ability to save the entire lineage of a selection or only the "deepest" selection. You can configure it to force the user to make a selection as deep as possible in the tree, or allow the user to select an item anywhere in the tree.
> 0 votes

---
Tags: taxonomy-terms
---