# Question
Title: Query Database to Fill Dropdown Form API #states
I am trying to develop a pretty complicated form. Essentially the user selects from Education, health, or water quality. Then using states the correct follow up questions are asked before all this data is submitted.

However, whenever I try to populate with a db query it acts funny. For example. Health and Education but have a dropdown select for years. Each should load the years available from the database and populate accordingly. However, the health dropdown select for year (which comes after the education) populates its self with the education's years. If I do a dpm to see what year the health year query gets, it is right, but it does not display on the dropdown.

I hope that makes sense. To sum it up: I have two queries to populate two different year forms. However, both populate themselves with the first query, even though the second one returns the right variables.

Here is the code:

```
$form['data_set'] = array(
    '#type' => 'select',
    '#title' => t('Please Select a Topic'),
    '#options' => array(
        'education' =>t('Education'),
        'health'    =>t('Health'),
        'water'     =>t('Water'),
    ),
    '#required' => TRUE,
);
// If User Selects Education
$form['education'] = array (
    '#type' => 'fieldset',
    '#title' => t('What Education Information are you looking for?'),
    '#states' => array(
        'visible' => array(
            ':input[name="data_set"]' => array('value' => 'education'),
        ),
    ),
);

    //Query DB for Rows
    $query = db_select('hp_education_years');
    $query->fields('hp_education_years', array('id', 'years',));
    $query->orderBy('years', 'ASC');
    $results = $query->execute();

    //define rows
    $options = array();
    foreach ($results as $result) {
        $options[$result->id] = array(
            $result->years,
        );
    }
    $form['education']['year'] = array(
        '#type' => 'select',
        '#title' => t('Year'),
        '#options' => $options,
        '#states' => array(
            'visible' => array(
                ':input[name="data_set"]' => array('value' => 'education'),
            ),
        ),
    );
    $form['education']['level'] = array(
        '#type' => 'select',
        '#title' => t('Level'),
        '#options' => array(
            'primary' => 'Primary',
            'jhs' => 'JHS',
            'shs' => 'SHS',
        ),
    );
    $form['education']['sector'] = array(
        '#type' => 'checkboxes',
        '#title' => t('Sector'),
        '#options' => array(
            'public' => t('Public'),
            'private' => t('Private'),
        ),
    );

//if user selects health
$form['health'] = array (
    '#type' => 'fieldset',
    '#title' => t('What Health Information are you looking for?'),
    '#states' => array(
        'visible' => array(
            ':input[name="data_set"]' => array('value' => 'health'),
        ),
    ),
);

    //Query DB for Rows
    $query1 = db_select('hp_health_years');
    $query1->fields('hp_health_years', array('id', 'year',));
    $query1->orderBy('year', 'ASC');
    $results1 = $query1->execute();

    //define rows
    $options1 = array();
    foreach ($results1 as $result1) {
        $options1[$result1->id] = array(
            $result1->year,
        );
    }
dpm($result1->year);
    $form['health']['year'] = array(
        '#type' => 'select',
        '#title' => t('Year'),
        '#options' => $options,
    );

```

# Answer
> 1 votes
You have the same variable ($options) for both fields. Use $options for $form\['education'\]\['year'\] and $options1 for $form\['health'\]\['year'\].

---
Tags: forms, database
---


title: Show a popup after saving a new node

text:
# Question
Title: Show a popup after saving a new node
How do I create a popup which can use the node variables after saving a new node? For example, I want to show a popup with the social media share button. Should I use `node_save()`?

# Answer
When a node is saved, the user is normally redirected to the page showing the node, which is not a form. In that case, `hook_form_alter()` doesn't help. I said the user is normally redirected to the page showing the node, as that is what Drupal does, but there could be a module that redirects the user to a different page, such as the one showing the node edit form to add a new node.

To show the popup when the node is viewed, you can use hook\_node\_view(), which can be used to add HTML tags to the node view page.

The example shown in the documentations shows how to add markup to the node view page.

```
function mymodule_node_view($node, $view_mode, $langcode) {
  $additional_markup = 'Markup to add to the page';

  $node->content['my_additional_markup'] = array(
    '#markup' => $additional_markup,
    '#weight' => 10,
  );
}

```

As for showing the popup right after the node has been saved, you could implement `hook_form_alter()` to add a form submission handler to the "Save" button; that submission handler would add a session variable that is the checked from your implementation of `hook_node_view()`. Its code should then be similar to the following one.

```
function mymodule_node_view($node, $view_mode, $langcode) {
  if (isset($_SESSION['nid']) && isset($_SESSION['timestamp']) && $_SESSION['nid'] == $node->nid && mymodule_check_timestamp($_SESSION['timestamp'])) {
    $additional_markup = 'Markup to add to the page';

    $node->content['my_additional_markup'] = array(
      '#markup' => $additional_markup,
      '#weight' => 10,
    );
  }
}

```

The values in `$_SESSION` are the ones set by the form submission handler. `mymodule_check_timestamp()` should return `TRUE` when `$_SESSION['timestamp']` doesn't contain a value too past in time; this would help in the case there is a module that redirect the user to a different page, and then the user visit the node page to review the node s/he saved. For example, it could return `TRUE` when `$_SESSION['timestamp']` is a timestamp 5 seconds earlier. It is up to you to decide how much delay should be acceptable between when the node is saved, and when the node is viewed from the same user who edited it.

You can change the weight used in `hook_node_view()`; that changes where in the node view page your markup is added.
> 0 votes

# Answer
drupal\_add\_js inside a hook\_form\_alter, like so:

```
function yourmodule_form_alter(&$form, &$form_state, $form_id)
{
  if ([your logic to pick out the node form])
    {
      drupal_add_js([your javascript]);
    }
}

```

Or you could probably do it with Rules calling some custom code.
> -1 votes

---
Tags: 7, nodes, javascript
---


# Question
Title: how to pass variables from one module to another module?
I wanted to use apachesolr module along with a field module that is custom written.

The field module gives the input to 'apachesolr' module instead of the normal search bar. The output is passed through the field module. The output is printed as the field output.

Will module\_invoke() be helpful in these cases?

I want to pass variables from one module to another module like the input and output.

# Answer
As alternative, you can use also drupal\_static() if the value you pass from a module to the other doesn't need to be saved past the page request. When both the modules pass to `drupal_static()` the same value for the first parameter, they get the same static value.

In the case you use `drupal_static()`, you must be sure the module that is setting the static variable is executed before the module that reads that value.
> 1 votes

# Answer
According to the API, module\_invoke() seems to do the job if you plan on passing the data as arguments to a hook the specified module. If you just want another module to have access to the variables, you can always use variable\_set() and variable\_get().
> 0 votes

---
Tags: 7, search
---


# Question
Title: Huge delay on first request due to many slow SQL queries
> **Possible Duplicate:**
> Performance Problem: Delay on first request

The first page of my site takes up to 15 secs to load and then the site become responsive. If I leave the site for 20 min or so, the first request is very long again.

Following recommendations found on this similar question, I checked the Devel query logs and there is a whole bunch of queries related to `field_sql_storage_field_storage_load` taking more than 250ms. I am not sure it is purely related to `field_sql_storage_field_storage_load` though as there is another `language_list` query with a simple `SELECT * FROM languages ORDER BY weight ASC, name ASC` taking 186ms.

My questions are: why do I encounter such delays and how can I reduce them?

# Answer
> 1 votes
So this is how I fixed the problem. It is not a real solution as I could not nail the exact source of the problem (if there is one).

1) Aggregate CSS (cache settings). This reduced the latency by half 2) Set cron to never (and run it externally) 3) Set up a cron job that calls the home page with Lynx every 30 minutes

---
Tags: performance, debugging
---


# Question
Title: Views Display output in tpl file not working
I'm making use of views 2.xx and pressflow 6.xx and i'v a little issue when it comes to the views Display output template file, it just won't show the rows when i tried to print them like this:

```
      <?php print $fields["field_genre_value"]->content; ?>
      <?php print $rows["field_genre_value"]->content; ?>

```

Non of them work....

# Answer
While not a direct answer, the best thing I've found to do in cases like these is to put a

```
<?php drupal_set_message('<pre>' . print_r($rows, TRUE) . '</pre>'); ?>

```

in the template to see what you have to work with. But if you are talking about the Display template, I am pretty sure by that point the `$rows` variable has been populated with HTML so you may need to look at another template if you want to get fancier with the output.
> 1 votes

---
Tags: views, theming
---


title: QR Codes with the Barcode module

text:
# Question
Title: QR Codes with the Barcode module
I am interested in creating barcodes from field data on-the-fly using the http://drupal.org/project/barcode module. As a rookie, could somebody explain to us how generally this is done and what is the best approach. For my working project example, I've already installed the said module and integrated a field into a Field Collection, but don't really want to spend more hours 'experimenting' to result on nothing. One idea I would like to explore is a QR barcode dynamically appearing on say a user home page (created via Views/Panels). Since my other interests are in music, a working example maybe a link to a band's website (i.e I create a 'Link' field in a Field Collection about a rock band, a visitor views the rock bands 'Homepage' on a D7 site, the link is dynamically shown as a QR code). This example is probably very common and portable across other content sites (trades, places of interest, 'Buy Now' links etc), but a decent 'how to/work through' or generalisation would be most welcome. Again, possibly it is something that can be done in Views or a case of backend PHP in a custom module (in which case I've a lot to learn). Thanks in advance.

# Answer
> 2 votes
It looks like a barcode is just a piece of encoded text from the .module file:

```
/**
 * Implements hook_field_info().
 */
function barcode_field_info() {
  return array(
    'barcode_field' => array(
      'label' => t('Barcode'),
      'description' => t('This field stores a barcode in the database.'),
      'default_widget' => 'barcode_textfield',
      'enable_tokens' => 1,
      'default_formatter' => 'barcode_default',
    ),
  );
}

```

So what you likely want to do is creating link fields that upon form submission pass their values onto the barcode field(s) as well. Then, you will show the barcode field(s) on any pages you want and hide the raw link field from the users view (unless their editing the entry).

You could look at the Rules module to automate this for you if you don't want to write a module (for example, when a new piece of content of type Foo, if field link is blah, copy field value to field my\_barcode value). Look into the Form API to hide (with `#access`)the field\_barcode values in the edit form (as they are dynamic end-user stuff).

The only thing that the Link field gives you over putting the raw url link in the bar\_code field itself is extra form validation for free (for example, check it is a valid URL).

---
Tags: navigation
---


# Question
Title: Is there a hook or sth after file is uploaded via file field?
I have drupal 7 installation with file field + video field(and media module). I can change where to upload files in video field setting(default: videos/original). I'm trying to do stuff to videos after file is uploaded and node is saved. Is there a hook I can use to achieve this?

What I want Exactly: Make a copy of the videos to 2 different servers via ftp and some transcode codes. First file needs to be uploaded to drupal folder and after that I need my code to run. sometimes videos need to be converted using ffmpeg(move to videos/converted) and then I run my code.

I've found these hooks but none of theme get called after uploading files or even after saving the node:

hook\_file\_copy($file, $source)

hook\_file\_move($file, $source)

how about this one?

hook\_field\_insert or hook\_node\_insert

# Answer
`hook_node_insert()` and/or `hook_node_update()` would probably be the right place to do this. Your code might look something like this:

```
function MYMODULE_node_insert($node) {
  // See if a file has been added
  if ($file_items = field_get_items('node', $node, 'field_file')) {
    // Get the first file item
    $file_item = array_shift($file_items);

    // Load the file object from the cache/database
    $file = file_load($file_item['fid']);

    // The path to the file is in $file->uri
    do_something_with($file->uri);
  }
}

```
> 2 votes

---
Tags: 7, entities, hooks, files
---


# Question
Title: entityFIeldQuery on user table, how can I add a condition for $user->data
I have tried extending EntitiyFieldQuery to add a condition that would be able to match on a `$user->data["somevar"]`, but to no avail. I am not sure this is even possible, as `$user->data` is serialised.

I have just the base class working, returing users with status set to 1:

```
class SubscriberEntityFieldQuery extends EntityFieldQuery {
  // define some defaults for the class
  public function __construct() {
    // now we don't need to define these over and over anymore
    $this
      ->entityCondition('entity_type', 'user')
      ->propertyCondition('status', 1);
  }
}

```

Would anyone have an idea if this is even possible? Or would I need to resort to using db\_query for a case like this?

# Answer
> 4 votes
The `data` column contains a serialized PHP string, which MySQL doesn't understand. As far as MySQL is concerned the data is just a string like any other.

Because of that you won't be able to query the properties of the serialized objects in that column without doing some seriously nasty work with `SUBSTRING`/regex/insert-other-unreliable-method-here.

If possible you should add a field to the user entity instead that represents the same data, and use the `EntityFieldQuery` with that field. It might not be ideal but it's probably the easiest solution.

# Answer
> 1 votes
May be you need `fieldCondition` like the one below

```
class SubscriberEntityFieldQuery extends EntityFieldQuery {
  // define some defaults for the class
  public function __construct() {
    // now we don't need to define these over and over anymore
    $this
      ->entityCondition('entity_type', 'user')
      ->propertyCondition('status', 1)
      ->fieldCondition('field_data_field_yourcustomuserfield', 'value', 'whatever-value-you-are-looking-for', '=')
  }
}

```

---
Tags: 7, entities
---


# Question
Title: I get "You are not authorized to access this page" when I try to load a view with Ajax
I am trying to load a view with Ajax, showing it in a specific `<div>`. I always get the Ajax message, "You are not authorized to access this page." My code is the following one:

```
/**
* Implementation of hook_menu().
*/
function custom_api_menu() {
  $items['ajaxgettip/nojs/%'] = array(
    'page callback' => 'custom_api_test_ajax',
    'type' => MENU_CALLBACK,
    'access callback'   => TRUE,

      );
  $items['ajaxgettip/ajax/%'] = array(
     'delivery callback' => 'ajax_deliver',
     'access callback'   => TRUE,
  );
  return $items;
}

function custom_api_test_ajax($nid) {

   $viewName = 'tip';
   $args = array($nid);
   $displayId = 'block_1';
   $view = views_embed_view($viewName, $displayId, $args);
   //return drupal_json(array('test'=>$res));
   ajax_deliver($view);
}

```

I am creating a link as follows:

```
<?php
    $link = array(
        '#type' => 'link',
        '#title' => t('something'),
        '#href' => 'ajaxgettip/ajax/114', #Hard coded nid at the end of path, just for testing
        '#ajax' => array(
            'wrapper' => 'ajax-response-goes-here',
            'method' => 'replace',
            'effect' => 'fade',
        ),
    );

$output = "<div id='ajax-response-goes-here'>Some HTML and stuff</div>" . drupal_render($link);
print $output;
?>

```

I don't have an idea about what I did wrong, and I have read a whole lot of documentation. Who can help me?

# Answer
> 1 votes
Try with `page arguments` in hook\_menu:

```
function custom_api_menu() {
  $items['ajaxgettip/nojs/%'] = array(
      'page callback' => 'custom_api_test_ajax',
      'page arguments' => array(2),
      'type' => MENU_CALLBACK,
      'access callback' => TRUE,
  );
  $items['ajaxgettip/ajax/%'] = array(
      'delivery callback' => 'ajax_deliver',
      'page arguments' => array(2),
      'access callback' => TRUE,
  );
  return $items;
}

```

# Answer
> 0 votes
I don't think you need `access callback` if you're returning `true`. It should be a string function name or don't specify it at all. Also check if $nid is being passed to the delivery callback function.

Edit: Sorry for bad answer, according to the comments this answer received, you do need to specify `access callback` as a function or `true`.

# Answer
> 0 votes
According to the docs you are correct

"access callback": A function returning TRUE if the user has access rights to this menu item, and FALSE if not. It can also be a boolean constant instead of a function

UPDATE: clearing the cache did it for me. (Now I've got to figure-out why I didn't think of that before)

# Answer
> 0 votes
```
/**
* Implementation of hook_menu().
*/
function custom_api_menu() {
  $items['ajaxgettip/nojs/%'] = array(
    'page callback' => 'custom_api_test_ajax',
    'page argument' => array(1,2),
    'type' => MENU_CALLBACK,
    'access callback'   => TRUE,

      );
  $items['ajaxgettip/ajax/%'] = array(
     'delivery callback' => 'ajax_deliver',
      ) +  $items['ajaxgettip/nojs/%'];
  return $items;
}

function custom_api_test_ajax($ajax, $nid) {

   $ajax_true = $ajax === 'ajax';

   $viewName = 'tip';
   $args = array($nid);
   $displayId = 'block_1';
   $view = views_embed_view($viewName, $displayId, $args);

if ($ajax_true) {
    $commands = array();

    $commands[] = ajax_command_append('#ajax-response-goes-here', '<div>' . $view. '</div>');

    return array(
      '#type' => 'ajax',
      '#commands' => $commands,
    );
  }
  else {
    // Else show the page when nojs page is accessed instead.
  }

}

```

---
Tags: views, hooks, ajax
---


# Question
Title: Add headers to each grouped section in a view
I've got some content (Employees) and I've got a View that is showing the content in a grid grouped by Department (i.e. it shows the title "Customer Support" and then a grid of Employees and then the title "Sales" and a grid of Employees, etc.)

I would like to include a paragraph of text before each section, preferably from a content node so that my users can modify the description before each section.

I've seen something online (although I'm having trouble finding it again) about being able to attach a view above another view. Is it possible to somehow display a DepartmentDescription node before each section of my grouped view?

# Answer
You certainly can, if you use a Views relationship to load in those other Department nodes, add a field using that relationship showing the Department node body, set it to "exclude from display" (so it doesn't appear twice) and in Format: Settings set Grouping to use that specific field.

The key question then is - how does each Employee node know which is the Department node that corresponds to it? I'd suggest you use one of the node relationship/reference modules to link them together - I can vouch for relation which is good, powerful and (since a few months ago) works well with views. It isn't so easy to use and doesn't have a great interface yet, but learning to use it is time well spent, especially for the sort of site you seem to describe. If you think Relation is overkill (it is for many very simple sites), here's a guide which covers the many simpler alternatives.

With Relation, a step-by-step could be:

1. Create the relation type (say, "is in department" source\>target, "has employee" target\>source, valid source: employee, valid target: department)
2. Create a relation for each employee, linking it to its department
3. In the view, create a node-node Relation relationship using "is in department" from the 'source' endpoint
4. Add a content:body field, using this relationship. Set it to exclude from view
5. In View Format: Settings, choose this body field to group the view
> 1 votes

---
Tags: 7, views
---


title: Using ftp wrapper in file_copy

text:
# Question
Title: Using ftp wrapper in file_copy
Can I use php ftp wrappers using `file_copy` or `file_move`. like this:

```
file_copy($file, 'ftp://user:pass@site.com/file.flv', FILE_EXISTS_RENAME);

```

Or is this limited to drupal default wrappers?

And if I can't, do I have to use drupal built-in ftp hanlder(FileTransferFTP Class) or I'm allowed to use my own php ftp functions(`ftp_put`)?

Which one's better?

# Answer
I don't know what type of file are you trying to copy over the FTP server, but I did something like that once. This is what I did (it might give you an idea):

1. I created a content type where I added all the fields for the data I was collecting (like 10 fields)
2. Then I created an small module that will query the database and will create a CSV file from the data entered on the content type (I applied some logic to the data as well needed for my project)
3. I use the Drupal default file functions to name the file, placed on the define directory and avoid been overwritten by following exports.
4. Then on the same small module I created an small function that will read the directory content where the CSV file was and upload it to and FTP server.
5. When all this was done I use the "hook\_cron" to create an small function that will do all that for me.

**Note:** in my project I created an small admin interfaced where I entered a couple of settings like the name and location of the local directory where the CSV files will be stored as well as the FTP credentials (the client wanted to have there as well) and the location on the FTP server as well.

**Note 2:** I know this module is good with moving media files: http://drupal.org/project/media\_mover/

Thank you.
> 1 votes

---
Tags: 7, stream-wrappers, files
---


# Question
Title: Number items in a grouped view, resetting counter with each group
I've got a view (D7, Views3) that is grouped by a relationship-based title field (set in `Format: settings`), and I'm using a `Global: View result counter` to give each item a number. This is how output currently looks:

---

**Some group**

**1**...An item

**2**...Another item

**Another group**

**3**...More items

**4**...Still more items

**5**...Even more items

---

It's counting rows regardless of position in groups. I want it to reset the counter with each group, to look like this:

---

**Some group**

**1**...An item

**2**...Another item

**Another group**

**1**...More items

**2**...Still more items

**3**...Even more items

---

Seems like a simple enough task - but I can't find any options relevant to this. I don't mind writing some code to achieve this, but Views is so dense I have no idea where to start.

Can this be done without coding up some hooks? If so how?

If not, where and how in the thicket of data that is a views object could I identify where within a grouping each `Global: View result counter` field row is?

EDIT: looking at the very simplistic code in `views/handlers/views_handler_field_counter.inc`, it looks like a custom module based on this code would be the best option, creating a new global field that uses groups instead of the pager. This would need to find data about each group (probably in `$this->view` somewhere?), and would identify its own row's position in the appropriate group. Is this possible? Again, not really sure where to start.

EDIT 2: No sign of useful grouping data in the view object that I can see, but this thread suggests that maybe it's sorting data that should be used for this?

# Answer
> 5 votes
You can use the *HTML List* format. In the settings of this format, you can set the grouping field and then set the list to an ordered list.
By doing this, you won't need any global counter.

See in the following screenshot how the list would be rendered.

>

---
Tags: views
---


title: TinyMCE buttons by content type

text:
# Question
Title: TinyMCE buttons by content type
I installed tinyMCE with IMCE in my Drupal 7 site. I'm finding a way to show different buttons in tinyMCE editor by each content type. For example, the image button is displayed for the Article content type, but it will not be displayed for my custom content type.
Is there a way to set this up with the existing module?

# Answer
You need 2 text-formats. Allow "Image" in tinyMCE profile of one text-format and not allow it for the other.

To set fixed text-format to each text-area field, you can use Better Formats module. Download from http://drupal.org/project/better\_formats and install it.

In "Managed Field" page of your text-area field, check "Filtered text (user selects text format)" and "Limit text format". You will see all your defined text-formats with leading check-boxes.

Click the check-box of a text-format and save. In your "Add Content" page, you will see your text-area is assigned with respective tinyMCE editor.
> 1 votes

---
Tags: nodes, wysiwyg, files
---


title: Views of Grandchildren

text:
# Question
Title: Views of Grandchildren
I need to create a view with contextual filters that displays all nodes below the specified term.

Examle:

* Colors
    + Blue
        - **Cerulean**
        - **Slate**
    + Yellow
        - Bright
            * **Hi-liter**
            * **Pastel Yellow**
        - Not so bright
        - **Mustard**

(Bold represents nodes)

So "Colors" would list Cerulean, Slate, Hi-liter, Pastel Yellow, and Mustard.

"Yellow" would list Hi-liter, Pastel Yellow, and Mustard.

"Bright" would list Hi-liter and Pastel Yellow.

etc.

How can I create a contextually-filtered view of nodes by taxonomy term that takes the entire lineage into account?

# Answer
> 1 votes
You can do this in Views as you said with Contextual Filters.

In your view click "add" next to Contextual Filters and in the modal check "Content: Has taxonomy term ID (with depth)". Then click "Add and Configure" and you will see the "Depth" option. In the case of your color example above your depth would be 2 and when passing "Colors" to the view it would return all the nodes you bolded.

If you want the whole depth if it has great grandchildren and so on you would need to set the depth higher to account for the number of levels of your taxonomy hierarchy. For your example and passing "Colors" as the argument, a depth of 0 would return no nodes, 1 would return "Cerulean, Slate and Mustard", and 2 would return all of the nodes as mentioned above.

Passing the other Colors as arguments would behave in the way you desire.

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


title: Ubercart Recurring fees

text:
# Question
Title: Ubercart Recurring fees
I'm using uc\_recurring module in Drupal 6. Added these options to the Recurring orders:

0 day|Every this one...

1 week|Every week

2 week|Every other week

3 week|Every third week

4 week|Every four week

Added recurring fee for fortnight from Product Features.

"add a fee for $2.00 charged first after 0 days and every 2 weeks after that unlimited times".

1) It's working in the cart page.(Recurring order options are showing up), and at the end it's not counting 2$. 2$ is not playing any role, how does it work?

2) On the whole how are recurring orders and recurring fee connected?

# Answer
Be sure that you added the sell price of product and after that in product feature add recurring fee ammount of 2$.
> 1 votes

---
Tags: ubercart
---


# Question
Title: Validate function not working in ajax form
I used Ajax in a form so that submission of form does not lead to reload of the page.It is working . But the problem is **'The Validation code is not working'**. This is the code I have used in the form.

This is the code for submit button.

```
$form['submit'] = array(
  '#type' => 'submit',
  '#ajax' => array(
    'callback' => 'submit_driven_callback',
    'wrapper' => 'myform',
    'method' => 'replace',
    'effect' => 'fade',
  ),
  '#value' => t('Submit'),
);

```

I have put the validation part in the following function.

```
function formname_validate($form, &$form_state) {
  // Validation code
}

```

Am I doing it the wrong way? Should I put the validation part somewhere else?

# Answer
> 1 votes
You can try the following code.

```
$form['submit']['#validate'] = array('YOUR_VALIDATE_FUNCTION_NAME');

```

# Answer
> 1 votes
I am working with AJAX code nowadays, and as far as I can see, if the form builder is `formname()`, then `formname_validate()` should work as form validation handler.

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


title: RSS feed is downloading

text:
# Question
Title: RSS feed is downloading
I just noticed today that my rss feed is not working properly. When I click it, it prompts me to download it.

My site is http://www.sourcecodester.com/

The rss feed url is: http://www.sourcecodester.com/feed

Can anybody tell me what's wrong?

# Answer
I can see one empty line in beginning. This might be due to a empty line in any one of your modules. In PHP blank lines before `<?php` tag causes a lot of problems remove it and check again. have a look at other site XML (Source Code) for proper format.
> 1 votes

---
Tags: feeds
---


# Question
Title: Updating my very first install of Drupal
I'm getting emails to update my very first install. How should I go about updating? Should I download the file and drag and drop using Filezilla, or should I use command prompt on my server? http://drupal.org/project/drush/

# Answer
> 2 votes
If you can use Drush, do. It makes life very easy. If memory serves it's as simple as issuing a `drush up drupal` command, and following the prompts.

If you can't use Drush then copying the core Drupal files over the top of the old ones is the way to go, but make sure you don't replace the `/sites` folder. On most production servers the `/.htaccess` file will also have been modified so make sure you don't overwrite it if there have been changes made.

Either way, make sure you take a backup of the code and database before upgrading so you can easily rollback if something goes wrong.

You may find the Update your Drupal site from one minor 7.x version to another minor 7.x version page a particularly useful read before getting started.

Also, as Kalabro points out in the comments, never run an update on a production server without having tested it on your dev/staging environment first.

---
Tags: updating
---


# Question
Title: Using paragraphs tag instead of div in fields?
I have a node type with a body, that I want to display in a custom node template. When I use code like

```
print render($content['body']);

```

I get a mess of div tags like

```
<div class="field field-name-body field-type-text-with-summary field-label-hidden">
    <div class="field-items">
        <div class="field-item even">Here is my body content</div>
    </div>
</div>

```

I appreciate Drupal's rich markup, but I just want

```
 <p>Here is my body content</p>

```

According to http://api.drupal.org/api/drupal/modules!field!field.module/function/field\_view\_field/7 I **should** be using render(), but it render() doesn't seem to be giving me the control I want. Is there a best-practice way to do this?

# Answer
> 3 votes
The extra junk is added by the field.tpl.php file from core. But hey you can customize it.

Create a new file in your theme's templates folder. (For available variables, see here)

File name: `field--body.tpl.php` (See http://drupal.org/node/1089656 for template file suggestions) Contents:

Now, when you use render() in your node.tpl.php files, you will see the p tag wrapped content instead of the extra junk.

Update: I have forgotten that the $item comes from $items array. Updated the code above. If the body field has multiple instances, each one will be shown in individual p tags.

# Answer
> 1 votes
I'd recommend using Display Suite with the Extras sub-module enabled, which gives a fair amount of control over each field. The screenshot shows the expert settings, but it also provides a full reset template, a minimal template, and allows you to use the default if you want.

# Answer
> 0 votes
If in your template file you do this:

```
<?php
print_r($node);
?>

```

**Note:** you can remove the code mention above when you are done getting your information.

You will see all the parts of the node object and from there you can just pick:

```
$node->body['und'][0]['value']

```

But to avoid issues with the language or translations I recommend you us it like this:

```
$node->body[$node->language][0]['value']

```

so at the end if you just want the content wrap in paragraph tags it will be something like this:

```
<p><?php print $node->body[$node->language][0]['value']; ?></p>

```

Thank you.

---
Tags: entities, theming
---


title: Remove dates from rss

text:
# Question
Title: Remove dates from rss
can someone help me on how to remove or manually edit the post dates displayed on my drupal feeds? No I am not using views to create it.

# Answer
Go to your content type you feed and click on "Manage Display". There you have different possibilities to change the way how your content looks in different view modes. You probably need to activate the view mode for RSS Feeds to change anything.
> 0 votes

---
Tags: feeds
---


title: Browse only mode for Drupal 6

text:
# Question
Title: Browse only mode for Drupal 6
While we do some server maintenance, how might be prohibit our users from editing or adding content but not put the site in offline mode. That is, we'd like to have content browseable but temporarily prohibit content from changing.

# Answer
> 5 votes
I have never used this module, but seems to do what you want: Read only mode.

# Answer
> 1 votes
This will take some effort to accomplish what you are asking for, but as a high level overview, you could use CTools' panel variants for `user/%user/edit` and `node/%node/edit` or whatever is equivalent in D6. And then you selection criteria as php code and then write some logic.

Not done this myself, but it should be possible this way.

# Answer
> 1 votes
I haven't done this (seems to be the common thread here!) but Boost has a feature for running entirely without the database. It also has a crawler to ensure pages are cached. Note the warning!

---
Tags: 6, maintenance-mode
---


# Question
Title: How do I get a custom script to run when using hook_cron in my custom module?
I am brand new to module development, fresh off the D7 tutorial boat. What I want to do cannot be that hard.

I have created my first module called get\_weather, with get\_weather.info and get\_weather.module properly installed and drupal recognized.

I created another simple script that has one function, which I want to run when cron runs. 'update\_weather' the ONLY thing this does is return the temperature for that time and store it in the database.

There is nothing to display, there are no blocks to render. However, this does not work:

```
function get_weather_cron() { update_weather(); }

```

What's going on here? I get no errors, but nothing happens at all? How do I get my module to run my custom function when cron runs?

Note that my custom function works fine if I run it from a script outside of a Drupal module environment.

Here is code based on comments feedback:

```
include('weather.php');
function get_weather_cron(){
    watchdog('get_weather_debug', 'Cron function triggered');
    update_weather();
}

```

Also here is update\_weather, which is included in the weather.php include file:

```
function update_weather() {
    $page['weather'] = scrape_weather();
    //insert into db code here;
}

```

Again, when I simply run this php normally outside of the drupal enviroment, everything works fine. All I want to do is run this same script when cron runs so this is done automatically. No function in my entire library for this functionality has anything to do with Drupal. I am simply trying to activate it by using cron.

# Answer
> 1 votes
Welcome to drupal! One of the first things that will learn is that Drupal keeps an internal cache of *all* hooks implemented on the site. Just because you implement hook\_cron() in your custom module, and then run cron, does not mean it will work.

Steps I would suggest to help fix

1. Install drush (this is Drupal's Swiss Army knife)
2. run `drush cc all`
3. run `drush cron`

Hopefully it will all be resolved

To check if your module is installed and enabled correctly you can

* `drush pml | grep get_weather` (or alternatively look at the modules list in the UI)

Or to check if there is something wrong with your function `update_weather();`, you can run it in the context of drupal (i.e. alter a full drupal bootstrap with all modules loaded)

* `drush php-eval "print update_weather();"` \- you can also place additional logging or printing in your function to see what is going on.

Of course, don't forget to define all you functions that you want to execute in the .module file, as every enabled module, has it's .module file included on every request. On a side note, why don't you do away with calling another function from hook cron?

```
function get_weather_cron() { update_weather(); }

```

Simply use something similar to the following one.

```
function get_weather_cron() {
  // more actual weather getting code here
  variable_set('get_weather_temp', 23);
}

```

It should be easier to read for the next person too.

---
Tags: 7, cron
---


title: Add class to column in a table

text:
# Question
Title: Add class to column in a table
I have a table in a form such as the 'user\_admin\_account' form. In one of the TD's I want to add a class, how do I do this the most convenient way?

This is what I currently have, it doesn't seem to work

```
$row = array(
  'title' => array(
    'data' => array(
      '#title' => $name . ' ' . $surname,
      '#attributes' => array(
        'class' => array(
          'myClass',
        ),
      ),
    ),
  ),
  'date' => date('Y-m-d', $account->created),
  'name' => $name . ' ' . $surname,
);

```

# Answer
The variables for `theme_table()` are structured differently to a standard render array, so you need to format your array slightly differently:

```
$row = array(
  'title' => array(
    'data' => $name . ' ' . $surname,
    'class' => array('myClass')
  ),
  'date' => date('Y-m-d', $account->created),
  'name' => $name . ' ' . $surname,
);

```

The above produces:

```
<table>
  <tbody>
    <tr class="odd">
      <td class="myClass"> </td>
      <td>1970-01-01</td>
      <td> </td>
    </tr>
  </tbody>
</table>

```

The first and last column are only empty as my test environment doesn't have the same variables defined as in your code.
> 6 votes

# Answer
The documentation for theme\_table() describes what the function is expecting in `$variables['rows']`, and it says:

> **rows**: An array of table rows. Every row is an array of cells, or an associative array with the following keys:
>
> * "**data**": an array of cells
> * Any HTML attributes, such as "**class**", to apply to the table row.
> * "**no\_striping**": a boolean indicating that the row should receive no 'even / odd' styling. Defaults to FALSE.

The example present in that page is the following one:

```
$rows = array(
  // Simple row
    array('Cell 1', 'Cell 2', 'Cell 3'),
    // Row with attributes on the row and some of its cells.
    array(
      'data' => array('Cell 1', array('data' => 'Cell 2', 'colspan' => 2)), 'class' => array('funky'))
    );

```

In that example, "funky" is the CSS class applied to the second row, which contains two cells; the second cell takes the room of two cells (because the `'colspan' => 2` part).
> 1 votes

---
Tags: 7, theming
---


title: Simple AJAX callback

text:
# Question
Title: Simple AJAX callback
I'm looking to a way to make a call to a PHP function in my Drupal 6 module, and return the result asynchronously to the page.

I'm familiar with jQuery AJAX, but I don't understand how to post to a function using it. Does anyone have experience on doing this?

# Answer
> 4 votes
Disclaimer: I've never done this with Drupal 6.

You want to use a menu callback: You create a menu item (which is just a path associated to a PHP function), and point your query request at that path.

---
Tags: hooks, ajax
---


# Question
Title: What is the D7 equivalent of CCK "content_instance_tablename" in db_query?
I am porting a D6 module to D7 which deals with controlling field access of CCK fields. I can now successfully enable my port without any errors but receive a fatal error when trying to create new content.

The issue is the the "content\_table\_instance" in db\_query which as far as I understand no longer exists in D7 due to the CCK --\> Fields move. I am having a lot of trouble finding exactly what the alternative of "content\_table\_instance" is in D7. Any suggestions?

Here is the section of the code:

```
$result = db_query("SELECT nfi.field_name, nfi.label
  FROM {" . content_instance_tablename() . "} nfi
    INNER JOIN {" . content_field_tablename() . "} nf ON nfi.field_name = nf.field_name
  WHERE nfi.type_name = '%s' AND nf.active = 1 AND nf.locked = 0", $type_name);

```

# Answer
Both functions in your code (`content_field_tablename()` and `content_instance_tablename()`) just return a string based on the version number of the CCK module.

The Drupal 7 equivalents would be the `field_config` and `field_config_instance` tables respectively, as defined in `field_schema`.

Remember fields can be attached to any entity in Drupal 7 (not just nodes) so you'll need to change your code accordingly.

If you're using this query to get information about the field metadata you might want to use one of the Field Info API functions instead, e.g.

```
$all_field_instance_data = field_info_instances();

```

or

```
$single_field_instance_data = field_info_instance('node', 'field_some_field', 'article');

```
> 0 votes

---
Tags: entities
---


# Question
Title: Best way to add a search function to user profiles
So my client would like to have a search function added to user profiles, because the number is growing rapidly and filtering based on role, etc, isn't working for them.

How do I add a search to the user profile page? This is under User Management \> Users \> List

# Answer
You could code up a form\_alter() in a custom module that could put search in that admin page. Or, you could just use `www.yourhost.com/search/user` to search user accounts. And if you have advanced search and are using content profiles, you could also restrict your regular node search to that content type, eg `type:profile terms to search for` in those nodes.
> 0 votes

---
Tags: 6, users
---


# Question
Title: How to manage placement of blog articles in omega regions
I want to be able to control which omega region blog entries (individual blog articles) are placed. They appear to be in the content-zone, but I have not seen how to control which actual region they are contained within.

# Answer
All content ends up in the **Content** region. If you need something different, then I think g you have two options.

One, you can try to use a process function to move the content to a different region withing the zone. The function would be `function mytheme_alpha_process_zone (&$variables)` and you would place it in "process/process-zone.inc". I have no idea if this would actually work, but it is worth a shot.

Two, you could use one of the various techniques for changing layout based on content type. Personally, I am a fan of Panels, but you could also try Delta (which plays nicely with Omega).
> 0 votes

---
Tags: theming, nodes
---


# Question
Title: Can I by pass the one time login page that forces a use to click "log in"?
I'd like to send a user to a specific page on their one time login. I'd also like to not force them through presentation of the page that says :

```
This is a one-time login for USER and will expire on DATE.
Click on this button to log in to the site and change your password.
This login can only be used once.
Log In

```

I understand the redirection I want to do can be done on a form submission override on the Login button form. link

I'd like to achieve the redirection AND by pass the one time login page.

My intial though is that the onetime login page is essencial to the one time login process. Is that true?

Thanks in advance.

# Answer
If you look at this: http://drupal.org/node/350634

You could try setting your own function for user\_pass\_reset: http://api.drupal.org/api/drupal/modules!user!user.pages.inc/function/user\_pass\_reset/7
> 2 votes

---
Tags: users, forms
---


title: Raw (unlinked) ouput of $name variable

text:
# Question
Title: Raw (unlinked) ouput of $name variable
I'm using `<?php print $name; ?>` in node--front.tpl.php for an exceptional case, where I can't use Views and the output goodies Views has to offer. By default $name output is themed to link to author profile.

Is there anyway to output the author name in raw text, without going throught a preprocess function?

# Answer
The entire node object is available as `$node` so you should be able to do something like:

```
$author=user_load($node->uid);
print check_plain($author->name); // reasonably safe given the 'Spaces are allowed; punctuation is not allowed except for periods, hyphens, apostrophes, and underscores.' validation upon registration but let's check_plain() it anyway

```

or

```
$author=user_load($node->uid);
print check_plain(format_username($author));

```

if you have modules installed that modify the display of the user name.
> 4 votes

---
Tags: theming
---


title: Drush core files location

text:
# Question
Title: Drush core files location
I don't want to add some commands I don't want to know where drush configuration file is I am simply looking for a file which contains drush command functions.

I am running drush on Ubuntu.

# Answer
The commands are in a folder called 'commands' in the root of the Drush folder.

If you don't know where that folder is on your machine, running `locate drush.php` in terminal should help you find it pretty quickly.

In fact, running `locate drush/commands` should give you a list of all the individual include files related to commands, but it depends if your Drush files live in a folder with that name.
> 4 votes

---
Tags: drush
---


# Question
Title: Sum of integer vaules of a multi value field using Computed Field Module
I have a field that is configured to have unlimited values. (field\_a)

How can i use Computed field to add all of the integer values of A?

A: 10, 5, 2

The computed field would then spit out 17

This code will add the last values of field\_a and field\_b together:

```
$entity_field[0]['value'] = array_pop(array_pop(field_get_items($entity_type, $entity, 'field_calories'))) + array_pop(array_pop(field_get_items($entity_type, $entity, 'field_calories')));

```

I just need to add all the values of A together. Anyone know how?

# Answer
> 2 votes
I don't have computed field installed anywhere so I can't test this, but the logic should be something along the lines of:

```
$field_items = field_get_items($entity_type, $entity, 'field_calories');

$total = 0;
foreach ($field_items as $item) {
  $total += $item['value'];
}

$entity_field[0]['value'] = $total;

```

Or if you absolutely need a one-liner:

```
$entity_field[0]['value'] = array_sum(array_map(function($a) { return $a['value']; }, field_get_items($entity_type, $entity, 'field_calories')));

```

---
Tags: 7, entities
---


# Question
Title: "View recent blog entries" only showing on admin's page but other users have blogs
"View recent blog entries" only showing on admin's page:

http://www.effectiveanimalactivism.org/user/1

But other users also have blogs: user/5 and /user/10

that don't show up on their user pages.

# Answer
In the permissions page (under 'People' in Drupal 7), 'create new content' has to be checked for the users.
> 0 votes

---
Tags: nodes
---


title: Bulk enable/disable modules

text:
# Question
Title: Bulk enable/disable modules
I have just begun development on a Drupal 7 site in a team of three and I am trying to determine the best practice for versioning. This is causing me a bit of a headache because much of the work on a Drupal site is made in the database as well as the code.

I have installed the 'Features' module which allows for exporting views, content types, rules, ect. into an XML file which can them be included in the checkin, but we need to ensure that whenever we add a new module it is enabled on our machines before a feature is imported in case there are dependency issues.

When modules are added to our local machines, both code is added and the module is enabled in the database, so checking in the code to our git repo takes care of half of the problem, but we are left with the possibility of crashing each other's site if we fail to contact each team member notifying them of the manual changes to be made.

I have searched but I have failed to find a module or any other solution to this problem. Ideally there would exist a module that would create an XML file of which modules are enabled on one machine, then after checkin a second machine would be able to read this file and ensure that the two sites were in sync.

Has anyone found an elegant solution to this problem?

# Answer
> 3 votes
This is how we are working:

1. Keep as much as possible in code. Features strongarm and other modules are helpfull here. Often we figure out the configuration variables of the modules and put them into settings.php by hand.
2. Things like enabled modules are left to the DB. We maintain a central copy of our db in GIT. If someone adds a new module, he is responsible for taking this DB, adding the module and pushing a new copy to git together with the new module code. The backup & migrate module is very handy here.

An other alternative would be to develope against a single central DB. The disadvantage of this is that you will likely face situations where one developer trashes the DB and therfore the work of his colegues as well. You could set up a cron job taking a DB dumps at regular times to make sure you don't loose to much in such a situation.

---
Tags: features, version-control
---


title: Content profile vs profile

text:
# Question
Title: Content profile vs profile
I am confused as whether there is even a need for me to enable content profile, I mean you can use profile of drupal that has the ability to enable extra fields and all.Whileas content profile only has one field, Name, Bio ....

# Answer
With the core user profile you can have just one profile.

Profile2 gives you the permission to create different profile type and with the permission you can relate it to the role. Every profile can have different fields. Quick example:

Let's say you have a football website, so you have different profiles for different role player like goalkeeper wing, midfilder etc...

You create one profile per each role with different fields with Profile2 goalkeeper: height, gloves size etc...

Wing: first foot, side, speed etc...

You go to people-\>permission-\>role and you create a role per each role player and then you give the permission to a role for the related Profile so user with wing role can use the wing profile.

In the core user account you can create a field "Role player" (a radio button in this case is better)

Goal Keeper | Wing etc...

Then you will use "Rules" to create the rule

**React on event** = After saving a new user account

**Condition** = data comparision (you should look for you field "role player" in core user account)

**Action** = Add user role (you can select the relative role)

Automatically the role is assigned.
> 4 votes

---
Tags: nodes, users
---


# Question
Title: How to print the value of an array instead of the key?
I have the code below in a form builder for Drupal 7:

```
$form['color'] = array(
  '#type' => 'select',
  '#required' => TRUE,
  '#title' => t('Color:'),
  '#options' => array(
    0 => t('Blue'),
    1 => t('Yellow'),
  )
);

```

I need to print the selected value in hook\_mail but I only get the key when I write:

```
function color_mail($key, &$message, $params) {
  global $user;
  $message['subject'] = 'Selected color is: ' . $params['color']
}

```

While what would make sense here would be to print the value, not the key. I tried `$params['color']['#options'];` too but it didn't work.

Any tip on how to make this work? I'm sure it's something simple I don't yet know about.

# Answer
> 2 votes
The form submission process will only actually keep hold of the array key (which is the value for the select element), so it won't be available to you in `$params`.

The usual method to handle this sort of thing is to provide a function to return the options:

```
function MYMODULE_colour_options() {
  return array(
    0 => t('Blue'),
    1 => t('Yellow'),
  );
}

```

Then in your form function you would use:

```
$form['color'] = array(
  '#type' => 'select',
  '#required' => TRUE,
  '#title' => t('Color:'),
  '#options' => MYMODULE_colour_options()
);

```

And in the message hook:

```
$colour_options = MYMODULE_colour_options();

$colour_string = 'Unknown';
if (isset($colour_options[$params['color']])) {
  $colour_string = $colour_options[$params['color']];
}

$message['subject'] = 'Selected color is: ' . $colour_string;

```

---
Tags: forms
---


title: Profile2, url rewrite

text:
# Question
Title: Profile2, url rewrite
How do I create a path like this `www.example.com/PROFILE_NAME/FULL_NAME`

FULL\_NAME is a Profile2 field.

With pathauto you cannot modify profile2 entity.

# Answer
> 1 votes
There's a "quick dirty workaround" to making profile2 entities work with tokens/pathauto properly if you're interested.

It doesn't work for bulk generation, but does for individual saves of an entity.

It seems there is an ongoing effort to get this solved (http://drupal.org/node/1330546), but nothing's been added in a couple of months. It might be worth checking the issue queue/recent release notes to see if you can find out where they are with this.

---
Tags: 7, path-aliases, users, uri
---


# Question
Title: How to create a view of all the nodes sorted by date width header per each year
I need to create a view like this:

2012

node/1, node/2

---

2011

node/3, node/4

---

2010

node/5, node/6

---

The nodes have to be grouped by date and add the header with the year.

I don't want to create one view per each year but just one view. Shall i do it using taxonomy?

# Answer
> 0 votes
I'VE FOUND THE SOLUTION:

I created a view with fields, i added the field date, under "format -\> setting" i used the option Grouping by and I selected the date field and here we go!

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


# Question
Title: Add condition group in Views filter handler
I have a Views filter handler, which does

```
$this->query->add_where(
  $this->options['group'],
  $this->real_field,
  vms_get_current_mlid(),
  $this->operator = ($this->operator == '=') ? 'IN' : 'NOT IN'
);

```

Which initially looks fine, but fails with "NOT IN", when the field value is NULL, as `NOT IN (100)` does not return TRUE for a NULL value, which is what I would like.

When the operator is 'NOT IN', I need to add a "OR IS NULL" operator as well, but still keep it within the same group.

If the filters are

> Node is "page" AND NID\_REFERENCE NOT IN (100, 101, 102)

I would like that to become

> Node is "page" AND (NID\_REFERENCE NOT IN (100, 101, 102) OR NID\_REFERENCE IS NOT NULL)

How do I do that?

# Answer
> 1 votes
The answer turns out to be that `add_where()` also accepts a `DatabaseCondition` argument, meaning I could do

```
$this->query->add_where(
  $group,
  db_or()
    ->condition($table, $vms_target, 'NOT IN')
    ->condition($table, $vms_target, 'IS NULL')
)

```

# Answer
> 0 votes
I couldn't quite wrap my head around those queries in your last comment, but instead I tried exploring how Views does between operations. Check out `db_or()` which is used by views\_handler\_filter\_numeric::op\_between() \- I think that will do it.

---
Tags: views
---


# Question
Title: Alternative to libraries_get_path() to get a JavaScript file path
I was crafting the following code in order to alter the path to a JavaScript file.

```
function MY_MODULE_js_alter(&$javascript) {
      $sm_path = libraries_get_path('soundmanager2'). '/script/soundmanager2.js';
      $javascript['sites/all/libraries/soundmanager2/script/soundmanager2-nodebug-jsmin.js']['data'] = $sm_path;
      }

```

It works fine, but the only thing that bothers me is that `libraries_get_path()` is provided by the Libraries API module. Is there an internal Drupal 7 function to act the same way?

# Answer
You can get the same data using `drupal_get_library()`, but it's not in a friendly format so you'll have to dig into the array yourself. For example, the following code will get the same path as your current code but in a much less less satisfying manner (in my opinion anyway):

```
$lib = drupal_get_library('soundmanager2', 'soundmanager2_debug');
$sm_path = array_shift(array_keys($lib['js']));

```

As I understand it this is actually the *reason* there's a need for the Libraries API to exist...so this sort of thing can be managed in a structured manner.
> 4 votes

# Answer
drupal\_get\_library() returns a library that is between those libraries a module defines in its hook\_library() implementation. If there isn't a module that defines that JavaScript library with `hook_library()`, then `drupal_get_library()` is not a valid alternative to `libraries_get_path()`.

If you just want to look for a library, without requiring the Libraries module as dependency for your module, you can use libraries\_get\_path(), and libraries\_get\_libraries() code to write your own function.
I would rather make a module dependent from the Libraries module for the simple fact you don't need to maintain that code. It is up to you to decide if creating a dependency from the Libraries module is worth being done, in your case.

The alternative to make the Library module a dependency for your module, and copying the code used from the Libraries module is to hardcode the location where your module is looking for the JavaScript library. Considering that users are already used to the Libraries module, and considering that more than one module could use the same JavaScript library your code is using, I think the Libraries module is still the valid solution to your case.
> 2 votes

---
Tags: javascript
---


# Question
Title: how to set and unset javascript files for specifc path aliases in Drupal 7?
I am trying to set particular javascript files for a specific node page by getting the path alias. like this:

```
$path=drupal_get_path_alias();
if($path == 'about-us')
  drupal_add_js(drupal_get_path('theme', 'mytheme') . "/page-download.js");

```

which it doesnt work. But when i add the particular javascript file to my .info file it works. Also in other pages i will have to unset some of the javascript files if the above does not work but still unsetting javascripts does not work.

```
unset($vars['js']['all']['page-download.js']);

```

# Answer
As far as adding the JS file goes it probably depends where you're calling that code from. If you're calling it directly in a template file it's probably happening too late in the page build.

A `hook_preprocess_page()` implementation would probably be a good place for it (as would `hook_init()` and probably a bunch of others). You can also use `request_uri()` to check the current path without incurring a lookup for the alias.

```
function MYMOUDLE_preprocess_page(&$vars) {
  if (request_uri() == '/about-us') {
    drupal_add_js(drupal_get_path('theme', 'mytheme') . "/page-download.js");
  }
}

```

If for whatever reason you can't get that to work, you can remove a JS file by implementing `hook_js_alter()`:

```
function MYMODULE_js_alter(&$js) {
  if ($some_condition) {
    $js_path = drupal_get_path('theme', 'mytheme') . "/page-download.js";
    if (isset($js[$js_path])) {
      unset($js[$js_path]);
    }
  }
}

```
> 4 votes

---
Tags: 7, javascript
---


# Question
Title: Performance Problem: Delay on first request
I put together a D7 site with a Minelli subtheme. Along the way I experimented a lot with different themes, different modules. Somewhere along the way I developed an odd performance issue, and now I don't really know what theme/module/config caused it.

The problem is that when I first visit the site, it takes about 15 seconds before the first page shows. I can then move around the site and it is very responsive. If I leave it for an hour or so, then come back to it, the first request is again very slow.

I have cleared the cache's so that shouldn't be the problem. Also, I have disabled themes and modules which I am not using. I moved the site to new infrastructure but the problem followed it!

Where do I go next?

# Answer
There are three things that I would check.

One, if you are on a production site and not editing PHP files, then you should ensure that APC is enabled, has enough memory, and has a long TTL (you could go with a day or never expire if you wanted). You can also consider setting `apc.stat=0`. The APC docs have all of the information you need for setting the TTL. For choosing the amount of memory, you should stick the apc.php file somewhere protected and monitor the memory usage and churn statistics. Adjust the APC memory so that your miss rate is very low. Initial slowness could be because APC is full and emptying out (IIRC, APC dumps the entire cache when it is full instead of employing LRU or more advanced cache strategies).

Second, make sure you have MySQL tuned appropriately. You can use mysqltuner to adjust your buffer sizes. Your initial slowness could be because of loading tables from disk and/or query cache misses. While not perfect, mysqltuner does get you going in the right direction.

Third, make sure you have a real Drupal cron strategy. Personally, I would disable automagic cron on "admin/config/system/cron" and set up a crontab to run every night. You can also try out Elysia Cron if you really do need finer grained control over things. This way you can the necessary tasks run as often as you need, but have the normal ones run overnight. Your initial slowness could be from cron runs happening every hour. You can confirm this by looking at when cron runs on "admin/reports/dblog" and trying to match up with your slowness.
> 16 votes

# Answer
Ivanhoe123 is probably right: Drupal 7 comes with 'poor mans cron' enabled by default. In short, it means that (once in a while) cron is run before Drupal renders the page, delaying everything.

Always try to use a real cron job on production sites. For more technical details see http://drupal.org/cron, or talk to your hosting company.

To disable it, go to admin/config/system/cron and select 'Never'.
> 9 votes

# Answer
The Devel module offers database logging to check whether you have any long running queries.

If this doesn't help take either XHProf or XDebug and find the guilty code. XHProf (a profiler) draws you a nice map of all the functions that are being executed on the server, and it tells you which ones are consuming the most execution time. On the other hand, when XDebug (a debugger) is configured with an IDE such as Eclipse (see video) it allows you drill down into every function being executed LIVE. The profiler will give you an idea of **what** is being executed; while the debugger will show you **why** is it being executed.
> 8 votes

# Answer
Just from the flavor of the question, I immediately think of three(3) things

* MySQL Storage Engine/CPU
* Database Caching
* Table Locking

# **MySQL Storage Engine**

If you are not using any FULLTEXT searching/indexing, I strongly recommend you convert all your MyISAM data into InnoDB. MyISAM is not designed to take advantage of multiple CPUs and multiple cores. InnoDB has been greatly enhanced for multiple CPU usage as well as read/write hyperthreading.

Here are some posts I made about this in the DBA StackExchange and in this site with regard to tuning MySQL for InnoDB Performance

# **Database Caching**

Another strong argument for converting all MyISAM data to InnoDB is how MySQL caches data/indexes. **The MyISAM Storage Engine only caches indexes. InnoDB caches data and indexes**. In light of this, you can allocate enough memory for the InnoDB Buffer Pool to accommodate one of the following (whichever is smaller)

* All InnoDB Data and Indexes (Ideal if you have enough RAM for it as well for the OS; eliminates subsequent delays)
* 75% of Installed RAM (in case you have more InnoDB data/indexes that RAM ; minimizes delays)

If you are using MySQL 5.1, you could set **innodb\_max\_dirty\_pages\_pct** = 0. This will slightly increase disk I/O, but the InnoDB Buffer Pool will be cleared enough to allow old data and index pages to rotate out without disk I/O surges. MySQL 5.5 and MySQL 5.1's InnoDB Plugin do not need this adjustment since it has a better default Buffer Pool flushing mechanism.

If using InnoDB is out of the question, you may need to go with memcached or varnish. This allows the developer to dictate how long cached data will reside in server RAM. Naturally, this will require developmental enhancement to make your application memcached/varnish-aware.

# **Table Locking**

# **Epilogue**

You cannot avoid an initial delay after a MySQL Restart. Yet, once you enhance MySQL using the aforementioned suggestions/information, you should no longer experience subsequent delays.
> 6 votes

# Answer
I would use tools like YSlow or Firebug etc. to determine exactly what is happening when you load said page and when you load said page immediately after. Check if it's a caching issue and furthermore, check how it functions when you access the page as an anonymous user and then as an authenticated user. Compare this to your performance settings within Drupal.

If it's not a caching issue, then use Devel's query log as well as MySQL's logs to see what's happening w.r.t. the database. Additionally, if you have opcode or similar performance-enhancing caches on the server, try getting some numbers with them off and then back on.
> 5 votes

# Answer
Sounds like the cron is running.

Check your settings here: admin/config/system/cron
> 4 votes

# Answer
I nearly dropped Drupal for my last project because of this.

There must me more than one cause though. I have yet to find a 'fix all' solution that works every time this issue creeps up.

**Syslog and Ubuntu/Debain**

The first time I ran across the intermittent 15 second load time was while running drupal on (Dedicated, non-shared) Debian/Ubuntu based systems. Disabling the Syslog module was the solution for me.

As @BetaRide said, using xDebug or some other PHP profiler is extremely enlightening.

---

**Still A Problem - A Workaround**

As for my other installs, I'm still at a loss.

This issue is more noticeable on my development server and my low traffic Drupal installs.

As a workaround I've setup a cron job to load the sites home page every 60 seconds as well as Drupal's cron script every 300 seconds. This is obviously not optimal, but I would rather wget or curl experience the 15 second load time instead of a human visitor.
> 3 votes

# Answer
Many people suggest this issue could be related to **blocking synchronous background processes**, particularly related to **heavy cron jobs**.

If true, there exists a great pair of modules under active development by gielfeldt* that might cut this issue right out, or at least, could offer some clues and help site builders diagnose and treat specific culprits in their cases. Both replace blocking synchonous processes with non-blocking asynchronous HTTP or commands, and both offer relevant reports that can identify troublesome processes:

* Background process and its bundled modules allow for Drupal's background processes queue to be processed asynchronously, so they don't block. This could stop the problem. Also, with the bundled Background Process Apache Server module in the latest dev, there is a basic but improving UI report with features to oversee, unlock and inspect start times and progress of these processes. This could identify the problem process.
* Ultimate Cron builds on Background Process to allow cron-triggered tasks to have their own seperate asynchronous scehdules, each of which can be monitored and stopped in a UI. As well as being great for seperating heavy duty performance-sapping tasks from regular low-overhead cleanup, it also gives you a report with convenient information such as the running duration of each individual cron-triggered task, when they last run, current status, etc. This could also remove the blocking from, and/or identify, problem processes.

Both are very useful modules anyway; for this problem, they can be used to test the (very plausible sounding) theory that the blockages are caused by synchronous blocking processes or cron runs. Potentially, they could solve the issue by running these asynchronously instead of synchronously, and they could also potentially offer clues as to which specific processes were causing the hold up. *(be warned that their documentation is very much a work in progress...*

If, however, they can't be configured to help at all, that suggests there's more to the problem than just synchronous background processes. FWIW, I've never had this particular issue on a site since getting these modules to work properly (yet - touch wood) - but I have seen it on my sites before, as well as on live Drupal sites in the wild.

Also be aware of other related plug-in modules currently in development - e.g. in complex high-intensity cases, Ultimate Cron Queue Scaler, which allows threshold-based throttling, might help reduce cron-related performance problems.

---

**no affiliation, I'm just a highly impressed user of their work*
> 3 votes

# Answer
Since this is hitting me once more I startet do investigate the problem. I can definitely confirm that

1. a call to `drupal_cron_run()` triggered by poorman's cron of core adds ~5s to the request time on my dev machine. This can be tested by uncommenting the tests around the call to `drupal_cron_run()` in `modules/system/system.module` in `system_run_automated_cron()`
2. clearing all caches adds ~2s to the request time on my dev machine. This can be tested by doing a `drush cc all` and reloading the page again.

This means that setting cron to never and adding a call to cron via crontab makes the situation a lot better. Hitting some often used pages right afterwards to refill the cache would again improove the user experience.

I'm not sure though about the caching. I haven't touched the default cache settings for this site. I think that drupal is rebuilding all caches from time to time perhaps triggered by cron, but I'm not sure how this is done. But a 7s delay is pretty much what I see when I hit the page after some hours.
> 2 votes

# Answer
Issues like this can drive you nuts and when I had been in similar situations helps to figure out what is causing the issue going one step at the time and then test it as an anonymous and logged user. (onion layer method)

You mention you start noticing the issue after playing with a couple of theme and custom coding your own. I don't know how complex is your site nor the logic behind it, but the following steps will help you find the issue:

1. In your server create a folder or another account (this might be better) where you are going to do a clean Drupal install with the same version your are using on your site. Then without adding any module or theme test the time it take for the site to respond the first request and the following request. If all works well you can ignore server configurations issues, if it is behaving the same as your current the you have a configuration error either with your web server or database.
2. If the results from step 1 are good and the server is responding fast and following requests are as fast, then install only the theme from your current site into the clean install site and test it again. If everything still respond fast, then your theme is not the problem and you should continue to step 3 otherwise you have to start debugging your theme \*1.
3. If after the tests on step 2 the site still fast start bringing over the modules in your current site and make sure to test the response time after adding and enabling each module \*2.
4. If after adding the theme and modules the site still responding fast start adding the configuration, create content types, import views, setup menus, etc. Don't forget to test the site response after adding each one.
5. Setup and configuration ready and the site still fast, well now bring the data over. Import nodes, taxonomy terms, comments, etc. I know I must sound like a broken record, but always test after completing each step.

***1 Testing themes:** this process can be tricky in a super elaborated theme, here are a couple of pointers:

1. If you link to any external js or css library, try to use a local copy of the same.
2. In your template.php file check for function that might have longer or endless loops as well as preprocess function and/or hook theme functions.
3. Check other template file (page.tpl.php, etc) and look for raw PHP processing of arrays and objects.
4. If using "Views" and views template files, then check then as well.
5. Always double check the paths, optimize images, js and css files. Sometimes js files can have some heavy height when use multiple snippets of code in a single file.

***2 Testing modules:** testing modules is a little different because the use of heavy manipulation with PHP is allowed. Here are some pointers:

1. Community supported modules (CCK, Views, etc) have issues queue on drupal.org check them to see if there is any existing issue about your problem and if there is chances are that there might be a patch to fix it.
2. Own custom coded module, well if you coded you have to fix it, right?. Double check your coding and check the functions usage against api.drupal.org, you might be using an overkilling function instead of a hook.
3. Internet shared custom code module, do as in step 2, but this time you can also contact the original module writer and let him/her know about the problem.
4. If your site is an upgrade ( D5 -\> D6 -\> D7 ) check the migration or upgrade scripts (usually in module.install file) you might need an extra "index" on the new table configuration to make the slow SQL query X faster.
5. If you feel you have tunnel vision about the problem, step out for a bit and do some other activity completely un-related and then come back later to revisit the issue.
6. If you ping point the issue on a section of code, but can not make heads or tails about how to fix it, try explaining what that section is suppost to do to a person that has no idea how to program or how Drupal work and be ready to be surprise.

**Note:** Don't be alarm if after re-building your site all start to work like a charm that is one of best features computers have.
> 1 votes

# Answer
Double check that you haven't deleted any modules without uninstalling them. This causes a delay because Drupal tries to find the files but they aren't there anymore.

Delete references in the variables table if the modules aren't existing anymore.
> 1 votes

# Answer
A Web APM such as newrelic is the best tool for tracking down performance issues. I've had sites calling one or two lines of code that did wonky things, loaded unnecessary arrays at weird times, and did other things that were pretty invisible until we tracked them down with an APM.
> 1 votes

# Answer
Someone mentioned that GoDaddy will be slow. Many cloud-based hosting companies will also have this initial delay because services like AWS have it. It's cheaper to have servers deprioritized automatically, and those servers will require a second or two to 'wake up.'

For instance, Pagodabox has 3-4 seconds for first byte, until the server is happily awake. Pagodabox has in fact monetized keeping the server awake, and so you can pay extra to 'caffienate' your site.

Also, a CDN can help you out. Your web/db sever won't be loaded down with serving cached pages or images. A good tutorial here: http://wimleers.com/article/easy-drupal-cdn-integration-for-fun-and-profit

And... WebPageTest makes me happy. http://www.webpagetest.org/ Compare load times around the planet and with different web browsers for free. Use this to get real-world results for whatever changes you're making.
> 1 votes

# Answer
the problem could be anywhere.

1. Make sure you have not turned on debug mode on any theme or module. For example, in many themes there is an option to regenerate theme registry.
2. If you are running on shared hosting like Godaddy, then 15 sec for the first time request is normal.
3. Convert your site or front page to codebase using Drush CTools Export module. This will eliminate any database call and your site will run entirely from php.
4. If you still get problems, use Devel settings by turning on `query log` and `page timer` options at `admin/config/development/devel`. See which of the two takes more time to generate entire page.
5. Restart your server if nothing works.
6. Worst case install XHProf to see where things are going wrong.
> 0 votes

# Answer
So this is how I fixed the problem for my install. It is not a real solution as I could not nail the exact source of the problem (if there is one), but it is a good fix

1) Aggregate CSS (cache settings). This reduced the latency by half

2) Set cron to never (and run it externally) - Note: I had"attempting to start cron while it is already running" errors. I think it was trying to start cron at every launch but since it failed, the cron page was not mentioning the latest attempt, but rather the latest success.

3) Set up a cron job that calls the home page with Lynx every 30 minutes

All this on a shared hosting server. It is not optimal but it works
> 0 votes

# Answer
I'd suggest using a front-end cache along the lines of the Boost module (assuming you're on shared hosting) or Varnish. This will work best if your site accesses are primarily anonymous and page content is, for the most part, non-dynamic (i.e. the pages don't change much).

These solutions save the rendered pages on first access and then serve the pre-rendered html instead of going through the full Drupal bootstrap, page building, and theming processes, saving a LOT of time, especially on busy sites but also on sites such as you describe which "go to sleep" and take too long to wake up.

The only real drawback is that (at least for Boost) you'll need to clear cache when site content changes. If you want to make sure the site is fully cached with current content, you can run drush cc all and then curl or wget against the full site periodically via cron.
> 0 votes

---
Tags: performance
---


# Question
Title: Is there any security or operational problems if I do not have any .htaccess file in drupal root?
I realise that having the .htaccess file in the root of my installation is probably the way the program is designed to run, but I was having some difficulties accessing the site, and then fixed the problem by deleting the .htaccess file in the root. But then it made me wonder if this was a good idea to leave my Drupal 7 installation without a .htaccess file in the root at all.

Is there any security or operational problems if I do not have any .htaccess file in drupal root? I imagine that I would have to put it back in order to enable clean URLs.

# Answer
> 5 votes
You may have some problems, depending on how Apache is configured.

People may be able to browse directly to some hidden files. Look at lines 6 and 73 in the .htaccess to see what it restricts.

People may be able to browse directories directly. See line 10.

The site *may* not work right if you accidentally put a file called index.html in the root. Line 20 makes index.php the primary file.

Clean URLs won't work. I am not 100% sure if image cache will, either.

There may be some PHP security issue, but the `php_flag` directives have been standard settings in php.ini for a several years now.

Are you on shared hosting? If so, the problem with the .htaccess could be the `Options` lines. Some hosts restrict these. Everything else should be feature checked the the `<IfModule>` directives.

It is possible to not have a .htaccess in the DOCROOT by placing the contents into the Apache config for the site, or in an include. On high volume sites, there are some performance gains from doing this (.htaccess is read each request, where Apache config is read once when it starts).

# Answer
> 3 votes
Adding to what MPD said, I think there are other two important parts in the .htacess file provided by Drupal:

* File caching Drupal says to the browser which files must be cached and how long.

```
# Requires mod_expires to be enabled.
<IfModule mod_expires.c>
  # Enable expirations.
  ExpiresActive On

  # Cache all files for 2 weeks after access (A).
  ExpiresDefault A1209600

  <FilesMatch \.php$>
    # Do not allow PHP scripts to be cached unless they explicitly send cache
    # headers themselves. Otherwise all scripts would have to overwrite the
    # headers set by mod_expires if they want another caching behavior. This may
    # fail if an error occurs early in the bootstrap process, and it may cause
    # problems if a non-Drupal PHP file is installed in a subdirectory.
    ExpiresActive Off
  </FilesMatch>
</IfModule>

```
* Serving compressed JavaScript, and CSS files
Drupal is able to return to the browser compressed files.

```
# Rules to correctly serve gzip compressed CSS and JS files.
# Requires both mod_rewrite and mod_headers to be enabled.
<IfModule mod_headers.c>
  # Serve gzip compressed CSS files if they exist and the client accepts gzip.
  RewriteCond %{HTTP:Accept-encoding} gzip
  RewriteCond %{REQUEST_FILENAME}\.gz -s
  RewriteRule ^(.*)\.css $1\.css\.gz [QSA]

  # Serve gzip compressed JS files if they exist and the client accepts gzip.
  RewriteCond %{HTTP:Accept-encoding} gzip
  RewriteCond %{REQUEST_FILENAME}\.gz -s
  RewriteRule ^(.*)\.js $1\.js\.gz [QSA]

  # Serve correct content types, and prevent mod_deflate double gzip.
  RewriteRule \.css\.gz$ - [T=text/css,E=no-gzip:1]
  RewriteRule \.js\.gz$ - [T=text/javascript,E=no-gzip:1]

  <FilesMatch "(\.js\.gz|\.css\.gz)$">
    # Serve correct encoding type.
    Header set Content-Encoding gzip
    # Force proxies to cache gzipped & non-gzipped css/js files separately.
    Header append Vary Accept-Encoding
  </FilesMatch>
</IfModule>

```

Those directives don't protect from security issues, but they increase the performance of the web site.
You can put those directives in a configuration file read from http.conf, if you have access to those files.

Generally speaking, removing the .htaccess file from the Drupal root directory is not a good idea, except when you can move those directive in another file.

---
Tags: security, .htaccess
---


title: Combine 2 fields into select

text:
# Question
Title: Combine 2 fields into select
I'm looking for a way of mergin 2 fields into html select item. First field is links to other nodes within drupal, second field is links to another external content. Now I would like to merge these fields into html, which I could program "onChange" to follow selected link. Any ideas? Should I override both .tpl.php for that field, then with jQuery build one select? Or maybe this could be done easier, before rendering? Or maybe views might be enough? View, type of entity, added to certain node.. but then I have problems finding way of displaying those fields at the same time. Any advices?

# Answer
> 0 votes
Ok, that was simpler than I thought. Creating view, context filter for NID, fields I want, then I use it as entity for content type I want. Then in my module I use hook\_views\_post\_render and attach JS where I detect if view I attach has any items. If it does, I fetch them and build select list from it, then hide original view and attach created select instead.

# Answer
> 1 votes
I'm not sure what exactly you want to achieve. Maybe this two modules are helpfull for you:

---
Tags: 7, views, entities
---


# Question
Title: Ubercart 3 check the stock before adding to the cart
When a user enters in a quantity to add to their cart, I am trying to check that quantity against the stock level of that product, and when the stock is less than their quantity, it returns and error. This is as far as I have gotten, and I am stuck. Got any ideas?

```
function uc_check_stock_form_alter(&$form,&$form_state,$form_id) {
  if ($form_id == 'uc_product_add_to_cart_form_') {
    $form['#validate'][] = 'uc_check_stock_form_validate';
  }
  return $form;
}

function uc_check_stock_form_validate($form, &$form_state) {

  $stock = db_result(db_query("SELECT `stock` FROM `uc_product_stock` WHERE `nid` = '%d'", $form_state['values']['node']->nid));
  if (is_numeric($stock) && $stock < $form_state['values']['qty']) {
  form_set_error('qty', t('Quantity is greater than our available stock. Please adjust your quantity for the this item.'));
  }
}

```

# Answer
Someone created a module for that already, needs some fixing IMHO, maybe you can play with that and make something better, I'll definitely be very thankful...
> 1 votes

---
Tags: 7, ubercart
---


# Question
Title: Ubercart/Securepages site breaks overnight!? Can't POST (login/add to cart)
This site seemingly broke overnight without any changes being made to the configuration.. this is a production site:

https://www.skinnyboyswagclub.com/cardigan

Add an item to your cart and watch the network activity.. It redirects through a 302. Is this secure pages switching to https? (even though it's submitting from https?)

Nothing gets added, no errors.

Can't login either. Logging in with the correct password (guest/guestpass) doesn't work either.

I did add another dns record the other day to point ".dev." at another server. Could that have broken the production site at www.?

I removed the record just now, in case..

Since this is an issue on a production site and I can't even log in, I'm BEGGING for help! :|

# Answer
> 0 votes
I had a similar issue. You can look at this and this to get a bit more insight as to what my problem ended up being. Here are somethings you may want to try;

* Enable your cookies via your settings.php file. (This is something that helps with securepages).
* Enable secure pages across all your pages. This will test if its the issue with securepages losing its session values. If it works, then you need to wait till secure pages gets fixed OR just make every page on your site HTTPS.
* Turn caching off. For some reason, this was conflicting with my current setup. It wasn't until I did this that ALL my problems went away.

Good luck and I hope this helps.

---
Tags: 7, ubercart, users, http-request
---


title: How to change layout of profile2 page?

text:
# Question
Title: How to change layout of profile2 page?
I have no experience with php and I've been trying for hours to alter the HTML of a profile 2 (module which extends core profile functionality) page. How can I do this?

Ideally I'd like it so I can just alter the page and add things like:

```
<div>
    <?php print $name ?>
</div>

```

Thanks

# Answer
You need to enable the **Profile2 Page** module in the modules list page.

Then you go to `modules/profile2` and copy `profile2.tpl.php`, paste it into your template folder and there you can customize as you want using...

```
print render($content['YOUR_FIELD']);

```

...or other variables you want.
> 2 votes

---
Tags: hooks, users, theming
---


# Question
Title: Slideshow with images of a gallery ,at the end of the gallery next gallery images should start
I have several modules to show the images in slideshow, but i need to show the images of a gallery with slide counter.

At the end of the last image in that slide there must a next gallery navigation,to start the next gallery images with slide counter.

It will continue as for next galleries.

Anyone say how to do this using views or by modules ? am in urgent need of this, to update

Thanks in advance.

# Answer
There are a couple of things that you need to think about.

First, what do you mean by the "next" gallery? You will need that value to populate the link to the next gallery.

The slideshow can take an argument of the gallery ID, which will limit the images displayed to one gallery. You can then create another view which takes that argument and displays a field (which is a link to the "next" gallery).

You can filter by node type, order by whatever you want to order by, limit to display only one node (of type gallery), and, finally, filter by the same thing you are ordering by, but use the filter to limit the list to what is appropriate, ie, do not display nodes with node id greater than (or less than) or equal to that of the argument, so you don't get a duplicate.

Then you attach that view to the gallery view, and you have a link to the next gallery. You may be able to do something with an Ajax module if you don't want the page refresh.

I'm actually having a similar problem. The issue I'm having is that I want to display the latest gallery (my galleries have a CCK date field). I can do that, but I want to limit by gallery id. However, I won't have the gallery ID because I'm displaying the "latest" gallery, so I can't just do a simple filter by gallery id. I can sort by the date, but I can't seem to limit the results to the same parent gallery without the gallery id argument. Any ideas would be greatly appreciated.
> 0 votes

---
Tags: views, media
---


# Question
Title: It is it difficult/time consuming to set up a Drupal site that users pay to subscribe to?
I have never implemented a payment system in Drupal but it looks like I will have to do it in the very near future. I have plenty of Drupal experience, including writing custom modules, but I know nothing about payment systems.

I know of the Ubercart and Drupal Commerce modules and presume this is the standard way to go when setting up payment system for a Drupal website.

Basically I need to let users pay for monthly subscriptions for the site, and then money will be automatically taken from users' accounts on a monthly basis, until they cancel the subscription or it runs out.

Is this difficult/time consuming to set up? Will it take a weeks to implement for someone like myself with no prior experience in this area? How long rougly would I be looking at to get this set up?

# Answer
> 2 votes
I've just finished writing a multi-tiered subscription system for an online business directory, using Commerce. Without going into too many details (the clients might be watching ;) it took a fair bit longer than a week to complete and sufficiently test the subscription/payment element of the system, and I'm pretty familiar with how payment processors and Drupal Commerce work under-the-hood.

FWIW I took most of my inspiration from the Commerce subscription products PayPal module, which:

> integrates the PayPal Recurring Billing functionality into the Commerce subscription product module.

It's a feature module so you can just chuck it into a site and see what it does (sets up a product type of 'subscription', adds fields to the user and order entities for tracking subscriptions, handles the recurring IPN notification from Paypal, etc.)

If you read through that module code you'll get a good idea of what's required to set up a subscription system using Commerce. If you also need to write a payment processor from scratch then it'd be a good idea to look at the Commerce Paypal module at the same time so you can get a good overview of what needs to be done.

I'm afraid I can't comment on the UC Recurring Payments options as I've never used it.

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


# Question
Title: External login should set custom properties in user object
I have a Drupal website and a Symfony based API. I have configured Drupal to use my API for logging in. The users are stored in Symfony.

When logging in, Drupal will store a user in the database to create a user object. On this user object, I want to set some custom properties. For example an `id` which is a reference back to my Symfony user so that I can load the users settings, etc. later on.

I have not managed to figure out how to do this. I hope someone has an example on how to do this or can point me in the right direction.

Below is the code I use for logging the user in. First I check if the entered username matches an administrator that Drupal knows of. If it does, I will use the default Drupal login validation. If not, I will login through the API.

```
/**
 *  Validates the login. Uses either the default Drupal validation or a custom validation.
 */
function myy_authenticate_validate($form, &$form_state)
{
    // Retrieve name and password.
    $name = $form_state["values"]["name"];
    $pass = $form_state["values"]["pass"];

    // Check if the user exists in the Drupal users
    if ($user = db_query("SELECT * FROM {users} u WHERE name = :name", array(':name' => $name))->fetch())
    {
        // A user exists. Loads the user information.
        $user = user_load($user->uid);

        // If the user is an administator, log him in using the Drupal validator.
        if (in_array("administrator", $user->roles))
            return user_login_authenticate_validate($form, $form_state);
    }

    // The user didn't exist in the Drupal users. Now, try to authenciate using the custom validation.
    $authenticated = myy_symfony_auth($name, $pass);

    // Check if we did authenciate
    if ($authenticated)
    {
        // This sets up the external user with Drupal by creating a local entry. If they don't exist they are added.
        user_external_login_register($name, "myy");

        // We must set the "uid" to pass back. This looks up the logged in user and sets the Drupal UID.
        $user = user_external_load($name, $pass);
        $form_state["uid"] = $user->uid;
    }
    else
    {
        // Do nothing. Drupal will handle the errors.
    }
}

```

`myy_symfony_auth` is a method which returns whether or not we were able to login using the API.

Does anyone have an idea how I can add custom properties to the `user` object when a login succeeds? It is only relevant to do this when the login was performed using the API (meaning that it was not an administrator who logged in).

# Answer
I've done the same thing in D7. I see you're using the user-login-form directly and skipping over UID = 1 .... thats ok.

What you want todo is essentially copy the PHP logic of user\_external\_login\_register into your own function, you're already calling your own \*_authenticate() function to process the login page.

So you would change your:

```
// This sets up the external user with Drupal by creating a local entry.
// If they don't exist they are added.
user_external_login_register($name, "myy");

```

To like:

```
// This sets up the external user with Drupal by creating a local entry.
// If they don't exist they are added.
MYMODULE_user_external_login_register($name, "myy", $external_data);

```

and define the necessary function that mimics the D7 login logic AND adds you're own fields for the user upon creation (I mean literally copy the D7 function body into your function body and tweak as needed) -- I've added additional fields using the Field UI found at /admin/people to my User accounts as seen below.

So I have this function to do that:

```
function MYMODULE_auth_idstaff_user_external_login_register($name, $module, $external_ldap_details) {
  $account = user_external_load($name);
  if (!$account) {
    // Register this new user.
    $roles = user_roles();
    $userinfo = array(
      'name' => $name,
      'pass' => user_password(),
      'init' => $name,
      'status' => 1,
      'access' => REQUEST_TIME,
      // This is where we are different from the default function and add our fields.
      'roles'        => array(array_search('staff', $roles) => 1),
      'mail' => $external_ldap_details['mail'],
      'field_first_name'   => array(LANGUAGE_NONE => array( 0 => array('value' => $external_ldap_details['first_name']))),
      'field_last_name'    => array(LANGUAGE_NONE => array( 0 => array('value' => $external_ldap_details['last_name']))),
    );
    $account = user_save(drupal_anonymous_user(), $userinfo);
    // Terminate if an error occurred during user_save().
    if (!$account) {
      drupal_set_message(t("Error saving user account."), 'error');
      return;
    }
    user_set_authmaps($account, array("authname_$module" => $name));
  }

  // Log user in.
  $form_state['uid'] = $account->uid;
  user_login_submit(array(), $form_state);
}

```

I've actually done the same exact thing in Symfony 1.4.x a few years ago ... except it was all object oriented lol (because Symfony's forms are Objects).
> 1 votes

---
Tags: hooks, users
---