# Question
Title: Rewrite labels on fields rendered via php
So I'm designing a specific node page where I'm manually inserting every field (to ensure I can customize it as the client wants) and I'm having a bit of trouble with certain areas.

Essentially I'm curious if there's a way to rewrite the label of a field while I'm including/rendering it.. see the code below for what I'm currently using:

```
<?php print render($content['field_product_reference']); ?>

```

I should also mention that I'm using Drupal 7 & the DisplaySuite module.

**UPDATE: Is it possible to make it display HTML in the title area?**

# Answer
> 1 votes
The label is usually in the `#title` key in each content member of the array, so something like

```
$content['field_product_reference']['#title'] = t('Something new');
print render($content['field_product_reference']);

```

should update it.

If not, try installing the Devel module and running `dpm($content['field_product_reference']);` to see whereabouts in the array the label value is.

---
Tags: 7, entities, display-suite
---


title: Content Type with tabs

text:
# Question
Title: Content Type with tabs
I am new Drupal user working on a Drupal 7 site. We have a content type that allows us to add related content in tabs that are aligned down the left side of the page. How do I duplicate (clone?) this content type and make slight modifications?

# Answer
Look at the Bundle Copy module. It'll let you clone a content type.
> 0 votes

---
Tags: nodes
---


# Question
Title: How to filter view based on a parent node
On my website, i have some **products** and some **master products**.

Each **products** depend on a **master product**, which can have multiple products under itself. There are 2 different content type.

In the product content type, **master product** is an **Entity Reference**.

I'm trying to filter my view to get all *similar products* : basically, i need a view to get all products that have the same **tint** has the current product.

The tricky part is that the **tint** is a field of the master product.

Does anyone has any part of an answer?

Thanks!

# Answer
> 0 votes
If you are displaying all similar products on another node page - load the master node by adding an entity reference relationship to your view. I don't think you can compare values of two different nodes in a view. So, Use the view PHP module to write a filter script that can compare both the fields from the nodes.

Check out this 'Question' on using the view PHP module

---
Tags: views, entities
---


title: Change the Solr Operator to OR

text:
# Question
Title: Change the Solr Operator to OR
Am working with drupal search api solr module am trying to get it to work with the OR Operator so if i do a search for "David Smith" it should show results for both "David" and "Smith" does anyone have ideas on how to achieve this

# Answer
> 1 votes
By default, the apachesolr Drupal module is set to do an AND search. However, you can change that in one of two ways:

* Implement a custom module that alters the queries sent to apachesolr. All you'd need is to implement the apachesolr\_query\_alter hook.

```
 <?php
 function HOOK_apachesolr_query_alter($query) {
   // Force an OR keyword search.
   $params['mm'] = '100%';
 }
 ?>

```

More details can be found on this drupal.org documentation page: http://drupal.org/node/1159424

* The second thing you can do is modify the deafaultOperator from "AND" to "OR" in apachesolr's schema.xml file. You should be able to find that in your modules/apachesolr/solr-conf folder. That setting should be towards the end of the file

```
<!-- SolrQueryParser configuration: defaultOperator="AND|OR" -->
<solrQueryParser defaultOperator="AND"/>   // change to OR here

```

With this second one, just be careful. You don't want to make this change to your schema file and then forget and have it replaced later when you update your module or something like that. Just by searching now, I can see there is this rather unstable module that exposes some of the configuration options of the schema file in the User Interface: http://drupal.org/project/apachesolr\_confgen, but I'm not sure I'd choose to use that...

Hope one of these helps!

---
Tags: search
---


# Question
Title: How to theme field for many views in drupal 7?
I want to theme `field--uc-product-image.tpl.php` for two views. How to do this?

Is Drupal have theme like `view1-field--uc-product-image.tpl.php` ?

# Answer
> 1 votes
If you want to use template file, you can do that with:
**views-view--\[view name\]--\[display\].tpl.php**

If your view name is "**My product Image**" and display is "**block**"

view mashine name will be: "**my\_product\_image**"

and your template file will be:

**views-view--my-product-image--block.tpl.php**

in this file you can get your fields in that way:

```
$fields = $view->style_plugin->rendered_fields; // fields array

```

and then customize fields with the foreach loop.

**Example:**

```
<?php foreach ($fields as $delta => $item): ?>
    <?php if ($item['uri']) : ?>
        <img src="<?php print $item['uri']; ?>" alt="" class="pull-left">
    <?php endif; ?>
<?php endforeach; ?>

```

Of course there are several ways to custom your image field. In this example I assuming that you need to do that in view template file.

---
Tags: views, entities, theming
---


# Question
Title: How can I upload a Drupal Website into Wampserver
Someone built me a website a year ago. I want to upload this website into a local wampserver so I can make changes before going live. I need step by step instructions on how to upload the files.

Thank you.

# Answer
1. install wamp
2. create folder for your site in wamp/www and upload all files there
3. go to phpmyadmin (`http://localhost/phpmyadmin`) and create database
4. import the sql dump to your db
5. go to wamp/www/your\_site/sites/default and change db settings in settings.php , set db name, db user, password and host(localhost)
6. you can see your site here `http://localhost/your_site`
> 1 votes

---
Tags: database
---


# Question
Title: Variations price adjust based on previous variation
Using Drupal Commerce, is there a way to adjust the variation price base on the first or second variation selected?

For example I have 3 variations: size, material, color. If I choose Small (that costs $5) and material that costs $10 ($15 total), then when I choose Large at $12, the material should cost $20.

I guess I should use rules. Has anyone done this?

# Answer
http://www.drupalcommerce.org/user-guide/product-attributes-variations \- here you can read about product variations, don't forget to enable field as an attribute field that can change the Add to Cart form

After that you need to create products for all variations with right prices. You can use http://drupal.org/project/commerce\_bpc
> 0 votes

---
Tags: commerce
---


# Question
Title: How can I filter a view to show recent items but only one item per user?
I am using the Message module to produce a user activity feed for my site.

I want to make a view for the front page that shows the latest user activity (the 10 most recent actions for which I have messages configured) like this:

* Bill updated his profile.
* Ted updated his profile.
* Wayne added a picture.
* Garth sent a message.

Making a view that shows this activity was fairly simple. However, if one user is very active, the results will look like this:

* Wayne updated his profile.
* Wayne added a picture.
* Wayne sent a message.

This doesn't look very good on the front page, and I have many hyperactive users, so what I would like to do is "show the 10 most recent activity messages **for 10 unique users**." I experimented with the grouping feature of views, but I haven't figured out how to create a combination that allows me to achieve this.

# Answer
A dull ax approach would be to create a View that returns 100 of the latest messages, and then using a views\_pre\_render() hook, go through and grab the messages uniquely per user, eg, something like this:

```
function YOURMODULE_views_pre_render(&$view) {

  if ($view->name=='THIS_VIEW') {

    $new_result=array();
    $unique_users=array();

    foreach ($view->result as $row) {
      if (!in_array($row->USER_FIELD_IN_VIEW, $unique_users)) {
        $new_result[]=$row
        $unique_users[]=$row->USER_FIELD_IN_VIEW;
        if (count($new_result)==10) {
          break;
        }
      }
    }

    $view->result=$new_result;

  }

  // any other pre_render()ings go here

}

```

where USER\_FIELD\_IN\_VIEW is the field in your View corresponding to the uid of the owner of the message. A `print_r()` of `$row` or `$view->result` should give you that information. The other kicker is picking a small enough number of messages to give you those 10 users. I just pulled out 100 out as 10 users and 10 messages per "hyperactive" user to make sure you got at least 10 users without getting too many that you just throw away at the end.

EDIT/ADDITION: there were some variable name typos in my code that I've corrected :)
> 2 votes

---
Tags: views
---


title: Workflow for redesigning a drupal site

text:
# Question
Title: Workflow for redesigning a drupal site
I'm relatively new drupal user, that always get nervous when taking a site live.

I need to redesign our current website as well as add some modules and node types etc.

What i plan to do is just grab the drupal files and the database, change them up locally and then replace the files and database on the live site.

Is this the best method for doing this?

Looks like a relatively simple task, but i just don't wanna be spending 3 days of headache again working out how to take a site live.

# Answer
If you can guarantee that no content will change on the live site while you do the work then that is fine.

This doesn't just include content creation, but also things like users signing up, users commenting or submitting webforms (unless you don't need to keep the webform submissions on your site), users flagging things, or rating things or subscribing to things.

Basically anything an user, admin or not, can do that might change the database in some way. Or even things that change without user action, like time based events (this is probably less likely).

If you can't be sure of that and you can't afford to lose any data there are other options. Whether these options are suitable for you also depends on your specific project and what you are actually changing.

1. You can try keeping a record of any database changes you make and make them again to the live site when deploying your changes. This method is very error prone and can cause you grief if you are not extremely careful. - Things like views & contexts (and many other things) can be exported and imported, making certain tasks very easy to deploy in this manner. Other things require manually reproducing all the changes. There are other import/export type modules around for things like content types, users, taxonomy, menus etc. that are useful to varying degrees depending on your requirements.
2. You can try using modules like features or configuration management, for deploying your database config.

In the end, an exact answer cannot be given for a question like this as it depends on your requirements.
> 0 votes

---
Tags: workflows
---


title: Best way to organise content

text:
# Question
Title: Best way to organise content
I am making a site which will deal with various micro-topics about a subject.

Each subject will have the following:

* A backgrounder (one-time)
* A news blog (obviously recurring)
* FAQs (basically static)
* Set of links/documents (static too, but it can simply be updated)

My problem is organizing the content.

I could set every topic as taxonomy term and create four content types (*Backgrounder*, *Blog*, *Faq*, and *Link*). Soon, I'll run into probably a few thousand topics. Since each term page will have to serve as the homepage for that topic, I have no clue how to organize such a page.

I could also set each topic as a node with additional fields (*Backgrounder*, *Blog*, *Faq*, and *Link*). This would probably look awful, when the content of a field becomes long. Managing this might become difficult. Since most of the content would be node fields, the actual node area might not have any content. Search indexing becomes a hassle.

Right now I am quite clueless.

Any advice towards the right direction would be of great help.

# Answer
> 0 votes
First off, this isn't really a question that has a single correct answer.

It is really up to the site builder as to how they want it to work and it depends greatly on the use cases of the site and any business rules related to the content.

As such, it isn't the best question for a site like this, however I will say a couple of things:

1. Having thousands of taxonomy terms is ok if your content requires it. You might have a thousands of taxonomy terms and tens or hundreds of thousands of nodes. That's fine.
2. The second option you mention doesn't sound like a good idea. Mainly the use of fields as blogs etc. doesn't sound right conceptually. Plus handling revisions, permissions, comments for blog posts etc. is going to be a hassle to say the least.
3. The first option mentioned doesn't necessarily have to have the term page as the topic homepage. It could be done other ways, like having the backgrounder node as the topic homepage or using a views page with arguments to be the homepage.
4. Another possible solution is to have the backgrounder node be the home page and link everything to that via an entity reference field, removing the need for taxonomy at all.
5. As for laying out the home pages, consider using the panels or context modules combined with views.

These are not nearly all the possibilities, there are a bunch of other ways things could be done, so you can see you will not be able to get someone to give you a definitive answer.

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


title: Adding memory to themed pager?

text:
# Question
Title: Adding memory to themed pager?
I have a content type called as People that lists all users on the site.

Next i have a view PeopleList that lists the content type People in a list form and has a pager.

I have customized the pager to look like a Load More button that adds the next set of People and the list grows on the same page. Now when i view a node and hit browser's back button the pager comes to first state only that is on first page .

For example- If i have 30 people listed and i hit load more next 30 add up and now if i view node say number 51 and hit browser's back button the pager comes to its default state that is first 30 people listing only.

How to solve this issue. What should i need to incorporate to get this sorted. Please guide.

# Answer
It sounds like you wrote most of this yourself, or with some heavy work in Views maybe -- either way Good job! :)

You can solve your problem by saving the `pager` value into the users `$_SESSION` data. Every time they the pager page adds a key the querystring `http://www.yoursite.com/page&page=2` you can check the querystring for the `page` key and save its value to the users session. Eg,

```
if (isset($_GET['page']) && intval($_GET['page'], 10)) {
  $_SESSION['your_custom_pager_index'] = $_GET['page'];
} else {
  $_SESSION['your_custom_pager_index'] = 1;
}

```

Then you can check for `$_SESSION['your_custom_pager_index']` in your list form pager code to offset by whatever amount based on your index value.
> 1 votes

# Answer
The simplest way to solve this issue is probably to abandon your home-made content type "People" and customized pager, and to use the **Views** module to produce the list of users. The **Views** module UI lets you add a pager to the module that works the way one expects a pager to work.

You can still customize the *look* of the pager etc. by overriding the template(s) involved. However, I think this problem is best solved by relying on the built-in functionality of **Views** listing the built-in user object.
> 0 votes

---
Tags: views, 7, theming, paging
---


title: arg(1) changed when doing AJAX

text:
# Question
Title: arg(1) changed when doing AJAX
I created a custom module named my\_module.

In `hook_menu()` I define the following path.

```
$items['my-module/item'] = array(
  'title' => 'Item',
  'page callback' => 'drupal_get_form',
  'page arguments' => array('my_module_item_form'),
  'access arguments' => array('access item content'),
);

```

This is the code for `my_module_item_form()`.

```
$arg = arg(1); // Problem here! Should return "item", right?
...
// $form[...] = array('#ajax' => ...);

$form['arg'] = array(
  '#type' => 'hidden',
  '#value' => $arg,
  // I also tried '#default_value'
)

// Submit field

```

Basically, I really need to obtain `item` in `arg(1)` and nothing else.

When I edit fields (not fields with ajax) and click submit, I can obtain the correct `arg(1)` in my `hook_submit` which is `"item"`. Now, when I edit fields with ajax and click submit, `arg(1)` returns `"ajax"` which I do not like.

How should I obtain `"item"` in `arg(1)` in in the form submission handler during an ajax call in my form?

# Answer
When implementing AJAX in a form, it will send a callback to system/ajax, if you didn't set your path in the AJAX properties. So, when you use `arg(1)` in your code, it will return *ajax*, which is the value assigned to the hidden form field.
> 2 votes

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


# Question
Title: resizing the dimensions of the an image field
I need to re-size all the thumbnails of my article images to fit the dimensions of the redesign.

Is there a easy way to do this?

# Answer
I hope you attach an image field to the content type. In that case, you can define the image styles at admin/config/media/image-styles. It is the core continuation of the Imagecache module.

Create a new style and set the dimension for the images; then, go to admin/structure/types, click "Manage display" in "Article", and click the icon under format of image field; choose the image style you created.
> 2 votes

---
Tags: media
---


# Question
Title: How do you change what a function in a core module does?
I am trying to change certain Drupal behavior. I have traced this behavior back to a function in RDF core module, and would like to change what it does. The function in question is `rdf_preprocess_node()`.

Getting what I want would seem as simple as removing one or two blocks of code from this function. So that's exactly what I tried doing: I copied the function into my theme's template.php, made the changes, renamed the function from `rdf_preprocess_node` to `THEMENAME_rdf_preprocess_node`. This did not work, Devel Themer did not list my `THEMENAME_rdf_preprocess_node` among the preprocess functions used.

I do not understand why this didn't work. Only other option that I know is to try and dig through what the function affected and undo it, which sounds horrible.

*What's a practical way to change what a function from another module does?*

# Answer
This is actually pretty easy.

All you have to do is implement your own `template_preprocess_node()`. Then inside, it update the `$variables` that the RDF module made. If you want to update the header additions that it did, then implement a `hook_html_head_alter()`, and update those elements.

If you do this from your theme, then these will run after the RDF module. If you do it from a module, then you need to set the weight to be higher than the RDF module.
> 1 votes

---
Tags: hooks
---


# Question
Title: How to uninstall the Service links module?
I had a hard time with the Service links module (version 7.x-2.1) in Drupal 7. All the harder that links showed for some articles and not others. So while testing and trying to figure out how to configure, it took some time before I realized there were some issues in it.

Anyway, icons are poors, and I replaced it by the Easy Social module, which is quite fine for me and such a pleasure to configure as it is so easy and *understandable*.

The issue I have now is to remove the Service links module: I could disable it, and it remains listed as part of the modules (actually there is quite a bunch of modules in Service links). But then when I go to the *uninstall* tab, it does not show up.

I tried the module widgets on top of Service links to see if I could better configure the display of the links, but it didn't help. And I can't remove it either. My install is quite new and clean.

Any suggestions about how to uninstall the Service links module?

# Answer
> 1 votes
As far as I can see, Service Links 7.x-2.1 does not create tables of its own and the uninstall hook only deletes some configuration variables.

If you can't see the module in the uninstall tabs then you have probably deleted the module's folder before uninstalling. If this is the case, you can restore the module's folder and then uninstall the module (no need to enable it again).

Or you can run `DELETE FROM variable WHERE name LIKE 'service_links_%'` to your database.

---
Tags: installation
---


# Question
Title: How to show a RSS feed button for aggregator node page
I use the Aggregator module to display RSS contents. I want to have a RSS button along with the aggregator node, how can I enable or add the button to page?

# Answer
The RSS icon should already appear automatically on the page. If not, check your theme's `page.tpl.php` file and make sure it has this line on it:

```
<?php print $feed_icons ?>

```
> 1 votes

---
Tags: feeds
---


# Question
Title: How can I limit a views_pre_render() to a specific display of a view?
I have a views\_pre\_render() hook that I want to limit to a specific views display.

So far, based on this code, I have this:

```
function MYMODULE_views_pre_render(&$view) {
  if ($view->name=='VIEWNAME') {
    // ...
  }
}

```

However, I want to limit execution not to a specific view but to a specific display within that view. I know the machine name of the display, but how do I incorporate that into the if statement?

# Answer
> 5 votes
Like so:

```
/**
 * Implements hook_views_pre_render().
 */
function MYMODULE_views_pre_render(&$view) {
  if ($view->name == 'VIEWNAME' && $view->current_display == 'DISPLAY_NAME') {
    // Do your thing here.
  }
}

```

---
Tags: views, hooks
---


# Question
Title: Check for field values to be unique when storing into the DB
I have a content type "Research assignment" which has several fields including the field "field\_user" and "field\_project".

I want to remove any old research assignments having the same user and project fields as newly stored research assignment, before storing a new assignment in the DB.

This could be happily implemented by an UNIQUE SQL constraint, but it seems that the Drupal way is to use fields, not direct access to DB. What could you advise: to do this with fields or to revert to plain SQL?

Also, could you show how to use transactions in this case? I don't want anyone to see a research assignment deleted just before it is inserted again with probably other fields.

# Answer
> 0 votes
When you use *fields* GUI to add fields to a content type, it is correct that the GUI do not let you set the `UNIQUE` constraint.

However, the fields created in this way is stored in the SQL database. They're in a table named `field_data_` followed by the machine name of the field. So it is *possible* to add the `UNIQUE` constraint to any field *after* it has been created by means of an SQL `ALTER TABLE` statement, e.g.:

```
ALTER TABLE `field_data_field_user` ADD UNIQUE (
  `field_user_value`
)

```

As long as you only do this to fields that you've created yourself, I do not see any problems.

However, it is also possible to create the content type yourself as an entity, using the Drupal Schema API. If you've business logic that isn't part of the *fields* repertoire (such as deletion of an old research assignment before inserting a new one), it is probably better to use the Schema API istead of *fields* to create the content type. This is still not plain SQL (the Schema API expects you to declare the database tables in a structured array, and Drupal DB API is using PDO-like objects to interact with the database), but it has the same power and flexibility as plain SQL.

Note that declaring the *user* and *project* fields unique will not get the old assignment automatically deleted before the new is inserted. All this constraint does is to reject operations that does not satisfy the contraint.

To use transactions in Drupal, you just call `$txn = db_transaction();` in your own module. The transaction will remain open for as long as the variable `$txn` remains in scope. When `$txn` is destroyed, the transaction will be committed.

---
Tags: entities, database
---


# Question
Title: How do I test that a text field in $form_state has been populated by the user?
At the moment I am using the following code.

```
if (!empty($form_state['values']['my-field']) {
  // ...
}

```

If the user has entered 0 (a valid input in my case) my test will return `FALSE`. My guess is that I need to test for an empty string '', but I'm not sure.

# Answer
That is how `empty()` behaves; `empty($value)` returns `FALSE` when `$value` is:

* `NULL`
* 0
* A variable that has not been initialized to any value
* An empty string
* A string containing `"0"`

Since the content of a text field is always a string, you can use the following code, if you are expecting an integer.

```
if (!is_numeric($form_state['values']['my-field'])) {
  // Error: The user didn't enter a number.
}

```

That is the code that Drupal uses to check the user input is a number.
Notice there isn't the need of first passing the user input to `trim()`: `is_numeric("")` or `is_numeric(" ")` returns `FALSE`, while `is_numeric(" 2")` returns `TRUE` and the value of `(integer)" 2"` is 2.

Since is\_numeric() accepts also floating point values, to be sure to get only integer values you should use the following code.

```
$value = $form_state['values']['my-field'];

if (is_numeric($value) && ((string)(float)$value) != ((string)(integer)(float)$value)) {
  // It is an integer.
}

```

I would rather use just `is_numeric()` as in the first snippet, though. As long as the user is said to enter an integer, the fact an input like 2e2 is changed to 2 should not matter.

If you want to allow the users to enter a integer as 2e3 (which is 2000, when written without exponential part), when getting the integer entered from the user you should use `(integer)(float)$form_state['values']['my-field']` instead of `(integer)$form_state['values']['my-field']`.
> 0 votes

# Answer
This depends on the field in question and what values could possibly be entered into it.

In most cases an empty string would mean that the field has had no value set. If zero is a valid value then check like this:

```
if ($form_state['values']['my-field'] !== '')

```

That will check that the value is an empty string, whereas != '' would also match zero and false etc.

Also, depending on your set-up and requirements, if the field has a default value you have to decide what happens in the case the the value in form state equals the default value, because in that case you don't know if the user has left the field default on purpose or not.
> 0 votes

---
Tags: forms
---


# Question
Title: Creating user alert node on User Alert module
The steps for using the User Alert module are the following:

> 1. Enable User Alerts
> 2. Set the appropriate permissions for selected roles
> 3. Set the User Alert block in the appropriate region of your theme.
> 4. Create a user alert node.

How can you create a user alert node in Step 4?

# Answer
The module defines a "User Alert" content type; when you go to http://example.com/node/add/user\_alert (replace example.com with the domain name of your site), you are going to create a node of that content type, if you have the permission to create nodes of that content type.

```
/**
 * Implements hook_node_info().
 */
function user_alert_node_info() {
  return array(
    'user_alert' => array(
      'name' => t('User Alert'),
      'base' => 'user_alert',
      'description' => t('A User Alert is a short Twitter like message displayed at the top of the site, alerting users to critical information like an online sale, new blog post, or breaking news. After viewing it, they can click and close the message.'),
      'has_title' => TRUE,
      'title_label' => t('Title'),
      'disabled' => FALSE,
    )
  );
}

```

Check on admin/people/permissions you have at least the "User Alert: Create new content" permission; that is the permission to create nodes of that type. Then, you need the "User Alert: Edit own content" permission to edit the nodes you created.
> 1 votes

---
Tags: 7
---


# Question
Title: Form Builder module not working in Drupal 7
Can someone confirm if Form Builder module is working on your end. I review the `.module` and seems like the paths are still using Drupal 6 format.

# Answer
> 1 votes
I was finally able to activate it. If you read well the requirements to install formbuilder you will find one of the options is to install Options Element. Please refer to this link http://drupal.org/project/form\_builder and see the requirements.

---
Tags: forms, 7
---


# Question
Title: How can I remove the space between fields show in a view that are output with a custom template?
I have a view that has two fields, A and B. Both of these fields are modified using a `views-view-field--myfield.tpl.php` file.

In my output, I want the fields to be displayed as:

> AB (no space in between the values)

However, no matter what I do, it seems that Views puts a space between the two fields. I am using an *Unformatted list* and under *Settings* I have unchecked **Add views row classes** as well as **Add striping (odd/even) rows classes**. This has no effect on the spacing.

Under *Settings* for *Fields*, I have unchecked **Provide default field wrapper elements**. Again, the spacing remains.

I tried rewriting the results of the fields by inputting `[field_fieldA][field_fieldB]` under **Rewrite the output of this field**, but, while this output is shown in the preview in the Views admin interface, it is overwritten by the `views-view-field--myfield.tpl.php` file for the relevant field.

How can I output two values, both of which are output via template files, without a space between them?

# Answer
> 2 votes
I just created a quick View here that had three fields:

```
1.  Node title.
2.  Node type.
3.  Global Custom Text Area

```

I changed the HTML Element and Wrapper HTML Elements to SPANs for the first two fields and also set them both to be excluded from display.

For the Global Custom Text Area, I rewrote its output to be `[title][type]` and got the titles smashed right up next to the node types without a space.

ADDITION:

You could also copy `views-view-field.tpl.php` to `views-view-fields--smashed.tpl.php` (or whatever your Views name is :) and then remove all the whitespace from there, eg, this template looks nice like this:

```
 <?php something ?>
   <?php something else ?>
   <?php something else again ?>
 <?php yadda yadda ?>

```

and each of those lines and indents puts in the whitespace that is causing your grief.

If instead this is saved as

```
 <?php something ?><?php something else ?><?php yadda yadda ?><?php one really big long line of code without any intervening tabs or new lines or spaces ?>

```

and your view will be created with the `<divs>` or `<spans>` smashed right up next to each other in the row. Then CSS it up the way you want.

---
Tags: views, theming
---


# Question
Title: Form element title is not displaying translation
I have got my own module providing a form and there is one element called "Estimated time" defined like this:

```
$form['informacie_o_incidente']['field_incident_doba'] = array(
  '#title' => t('Estimated time'),
  '#markup' => '<div class="control-group form-item"><label class="control-label">Estimated time:</label><div id="field_incident_doba_wrapper" class="controls">'.$doba.'</div></div>',
);

```

I have translated the text "Estimated field" via translation interface, cleared cache several times (both GUI and with drush cc all command). However, when I run this drush command:

```
drush ev "print t('Estimated time');"

```

I am getting correctly translated string. So why not on the form?

# Answer
I think you need add `t()` in `#markup` and translate the string `'Estimated time:'`

```
$form['informacie_o_incidente']['field_incident_doba'] = array(
  '#title' => t('Estimated time'),
  '#markup' => '<div class="control-group form-item"><label class="control-label">'.t('Estimated time:').'</label><div id="field_incident_doba_wrapper" class="controls">'.$doba.'</div></div>',
);

```
> 2 votes

---
Tags: forms, i18n-l10n
---


title: List all users using Drupal Views

text:
# Question
Title: List all users using Drupal Views
I am new to Drupal and Views. I need to list all the authors(users) in my drupal 7 page? Do I need to add relationships for this ?

# Answer
> 2 votes
No.

When you add a new View, in the first screen there is a GUI with menus that let you create a view to;

```
Show users sorted by newest first

```

And that is all there is to it!

You can obviously refine the View to enhance the presentation, change the sorting, add a pager, etc. - but just to list the users, the above is what is required.

---
Tags: entities, views
---


# Question
Title: Omega theme, global css and the lack of grid at global.css
It seems that I misunderstood one major feature of the Omega theme. From what I see, the mobile-first basic css file - global.css - ignores the grid layout altogether and stacks elements one over another. Am I correct, or am I missing something? Does that mean that all the zones and regions will be rendered in a top-down manner with no width control?

I feel that my question is quite vague; I'd be most grateful links towards some relevant documentation and how-tos regarding the pure global.css design. I feel that most of the docs concentrate on structure of the zones& regions, while there's little sugestions as to how to make global.css work good by itself. Thanks for your attention

# Answer
Omega is designed as a mobile-first, breakpoint responsive theme.

global.css is the mobile first sheet, so the grid system doesn't apply. The grid kicks in with the mytheme-alpha-default.css.

The answer for What's the difference between global.css and default.css files in Omega theme? goes into detail about the stylesheet convention. In summary:

> 1. How does my site need to look on **mobile**? Make global.css
> 2. How do things change when the grid system kicks in? Make mytheme-alpha-default.css
> 3. How does my site look when I am viewing it in **portrait mode on a tablet**? Make mytheme-alpha-narrow.css
> 4. How do things change when I am on a **normal desktop**? Make mytheme-alpha-normal.css
> 5. How do things change when I am on a **widescreen monitor**? Make mytheme-alpha-wide.css
> 4 votes

---
Tags: theming
---


# Question
Title: How to aggregate results of search engines using drupal
I want to develop a site with Drupal 7 that lists the search results of some popular search engines. Is there any module or I should develop a custom module for this purpose?

# Answer
> 0 votes
If you have links to RSS feeds, you can use the Aggregator module that comes with Drupal; the alternative is the Feeds module.
Otherwise, if you want to import the content as nodes, you can use the Feed Import module.

---
Tags: search
---


title: How to deploy a site with open source?

text:
# Question
Title: How to deploy a site with open source?
I created a Drupal 7 site on my localhost. I installed some modules, created some content types and fields, changed some preferences, etc. and also entered some real test data. (I want this data to be preserved when I will copy the site to the production server.)

When the first alpha release will be ready I am going to copy the site to a production server in Internet.

I like the idea to make the software behind my site open source. This way I could be able to receive patches from other developers. (And also the possibility exists that somebody may use my engine for his other site.)

How to manage development of my site?

If it would be a framework, I would be able to do it with SVN or Git for all files + database change scripts. But Drupal also has an admin interface, which I don't know how to put under version control.

Also, how to release an open source package? I need include there some database creation script. Should I just export my DB? (only structure no data?) and put some SQL script into my .tar.gz?

Detailed description of deployment of an open source package for Drupal would be welcome.

Also: Could anyone explain how to use "Features" package in this situation?

# Answer
> 1 votes
To migrate your database (including the configuration of the admin interface) from the staging to production server, check out the Backup and Migrate module.

RE: your question about "Open source":

Unless your configuration is something really special, with a specific target audience and use case, it may not be worth your while making your configuration, etc. available for others, but YMMV.

*If* you want to do this, you should create a Drupal Distribution and release it on *Drupal.org/project/distributions* along with the 600 or so distributions already available there. Like all other Drupal projects, you use *git* to interact with the repository, and you also need to be a git-vetted user if you want to create a non-sandbox distribution.

You build a distribution by first exporting its features (including custom cck, templates and Views using the Features module. Then turn this into a distribution using the Profiler library to create an install profile. Finally, you package the distribution with the Drush Make packager (part of *Drush*).

# Answer
> 0 votes
> I like the idea to make the software behind my site open source. This way I could be able to receive patches from other developers. (And also the possibility exists that somebody may use my engine for his other site.)

You can simply create some modules that implement the functionalities present in your site, and make the code available in a git repository. That is what is done for the custom code necessary to run Drupal.org, which is part of the Drupal.org customizations project hosted on Drupal.org. If those modules can be helpful for other users, you can host them on Drupal.org; otherwise, any git that is publicly accessible is fine too.

---
Tags: features, installation, deployment
---


# Question
Title: How do you view a log of previous visited visitors showing their IP in Drupal 7?
Where do you view a log of previous visitors showing their IP address in Drupal 7?

# Answer
You can find visitors IP-adresses in both the `session`table (field `hostname`) or, if you have the core **statistics** module enabled, in the `accesslog` table (field `hostname`).

You can view these logs in a tool that let you examine your database (I use *phpMyAdmin*), or you can write a small custom module that displays them for you.
> 3 votes

# Answer
If you look at admin/reports/dblog, you filter the messages by type, and set the type to user, the list will show which users logged in; when you click on the link shown under "Message," you will get the IP of each user.
> 1 votes

---
Tags: nodes
---


# Question
Title: view inside a view with different arguments
I try to create a view with NID argument and embedd inside as a field another view with totally ditfferent argument. I used module called views\_field\_view but it seems that parent view is passing arguments to child view, which cause to break arguments on child view- that is what I do not want. Is it possible to do such combination? Thank you

What I try to do: I try for days to come up with some decent solution to this problem: On each node there is a multivalue field (field\_ref) for referrencing 2 nodes (can be left empty as well). Also each node contains another field for (field\_par) referrencing parent node. Moreover, each node has taxonomy term.
Now, on current node NID I need to display referenced nodes from field\_ref. If the field is empty I need to display the values from the same field - but this time from a node that is referrenced in field\_par on current node. If this field is empty, it should display values of the same field but from field\_par of the parent node etc. until the node with top term is reached.
My solution was fairly simple - Argument - Content: Has taxonomy term ID (with depth) set to minus values so I get all terms all the way up. Add relationship to field\_ref and connect it with fields - for example title. This way I get all results coming from parent nodes with higher taxonomy terms. Then I restrict results only to 2 results and add sorting according to custom integer field that I created on taxonomy terms according their depth (currently there is no other way to sort terms according to their depth) And that is it.
Problem with this solution is that I am not able to get inside current node values because adding another argument like NID breaks functionality of taxonomy argument.
I was also proposed another solution: to add NID as main argument and to get values from parent nodes using combined relationship : Content: Taxonomy terms on node + Taxonomy term: Parent term + Taxonomy term: Content with term. Which works ok but this view is static.
Finally what came to my mind was to combine view with my solution as a field inside a view with NID argument. So that the main view would display current node fields and if empty, it would display the field with embeded view refults. But maybe the solution can be much simpler and I am overcomplicating it:)

# Answer
> 0 votes
I can't immediately think of a simple solution to this problem, but I also don't have VFV installed anywhere, so I can't play around with it at the moment.

What I would probably have done, is created a ctools content type, called both of the views, and manually rendered through a specific template afterwards. This solution however is non-trivial, so perhaps you will need to search for a different one.

See What are Ctools plugin (content type, access, etc), and how does one create them? for info on implementing ctools content types.

Example of adding a specific template on top: Correct way to render a modules output through a template?

# Answer
> 0 votes
Finally I decided to go slightly different route - there is a setting in advanced tab in views - no results behaviour, which allows you to embed an existing view with it's own arguments.

---
Tags: 7, views
---


# Question
Title: How to render a user register form for a Profile2 type
Since all of the Profile2 registration forms have the same id 'user\_register\_form' (even when using Profile2\_RegPath module) how can I specify a Profile2 type when calling:

```
print(drupal_render(drupal_get_form('user_register_form')));

```

I need to be able to let the user create an account without having him leave the page. I'm able to print the Register and The Profile Fields to be edited, but they each have their own Action button which is what I do not want.

# Answer
> 7 votes
After looking through the Profile2 Git repository viewer for v1.3. I believe you want to do something like the following using profile2\_attach\_form. The \`profile2\_attach\_form has the following API comment and function signature:

```
 /**
 * Attaches the profile forms of the profiles set in
 * $form_state['profiles'].
 *
 * Modules may alter the profile2 entity form regardless to which form it is
 * attached by making use of hook_form_profile2_form_alter().
 *
 * @param $form
 *   The form to which to attach the profile2 form. For each profile the form
 *   is added to @code $form['profile_' . $profile->type] @endcode. This helper
 *   also adds in a validation and a submit handler caring for the attached
 *   profile forms.
 *
 * @see hook_form_profile2_form_alter()
 * @see profile2_form_validate_handler()
 * @see profile2_form_submit_handler()
 */
function profile2_attach_form(&$form, &$form_state) { /* ... */ }

```

So, you could use it as follows by slightly modifying your code:

```
$user_register_form = drupal_get_form('user_register_form');
$form_state['profiles'] = array(
    'CUSTOM_PROFILE_TYPE_NAME' => profile2_get_types('CUSTOM_PROFILE_TYPE_NAME')
);
profile2_attach_form($user_register_form, $form_state);
print(drupal_render($user_register_form));

```

If you need to tweak any profile entity form displayed in some of your registration page(s), you may want to implement the specific FORM\_ID version of hook\_form alter, `hook_form_profile2_form_alter()`.

**EDIT 01/15/2015**

minor API clarification and code cleanup from comments.

# Answer
> 2 votes
It sounds like you want to use the Profile2\_RegPath module. It lets you define custom registration paths for each profile type. It will load all of the profile fields & the normal user registration fields.

If you really want to do this programmatically take a look at their module for how they attach the profile fields to the user\_register form. The function profile2\_regpath\_attach\_profile\_fields around line 438 is what does the bulk of the work.

# Answer
> 0 votes
This used to be done using the Webform Register module in D6, which integrated with Content Profile, the predecessor of Profile 2. You might look at the D6 module and see if you can upgrade it to D7. (Thay are looking for co-maintainers). The module seems to be stalled at D6 (check this issue).

---
Tags: users
---


# Question
Title: How do I hide some fields to registered users?
This is my use case:

* If an **anonymous user** completes an order, the order shows profile type A. When user completes that order, the system creates a new user, and fulfill his profile with the profile2 type A order information.
* If a **registered user** completes an order, it does not show any profile2 information.

I want to make my checkout process shorter for already registered users, and I want for the anonymous users to have a profile filled with the order information. I get the first part of the use case working (the anonymous user workflow) with the excellent Commerce Order Profile2 Checkout Panes module, but I have no idea on what to do to avoid it appears for registered users. The problem is that the fiels in question are profile fields, so I need to grant registered users permission to view/edit them, and I can't hide them there with field permissions or CSS styles because they wouldn't be available to anonymous users too.

What could I do?

# Answer
Though I haven't used profile2 for any commerce site, but the mechanism behind the checkout process for asking profile info for anonymous user is to create account for him on site. If some information in the profile is mandatory then it will be asked on the time of checkout..& register user won't get those fields at time of checkout.

I use address-field for collecting address for shipping as well as billing, which always keep the old address and its possible to make some address default...so that registered user doesn't find it irritating..

If you must have to use profile2 field then please check whether its required field & if it is...then why some registered users profile is not filled with those information...
> 1 votes

---
Tags: entities, commerce
---


# Question
Title: Need advise to link a cck field with several values to another cck field
I am going to try to explain what I need to do. I have a content type called Goals. This content type has a cck text field. This field can has several values in order to write a goal in each value of the field.

What I want is when a user write a new goal (each goal is a value in the same cck field), he has a list tex field to point if he completed the goal.

How can i do this? What is the best option I have?

After I would like to create I view to show the goals completed and incompleted, so the goal and completed-incompleted must be linked in certain way.

Thanks a lot!

# Answer
> 0 votes
As per your requirement I think you have need to create something like project & the task related to the project. I have done something like this.

For this you will have to create a main content type to hold the project, which will have TITLE & BODY without any other fields.

Create one another content type with reference to first content type. User can add as many task as needed below the first content if permission is given. Add a field named STATUS in 2nd content type, which will hold this COMPLETED or NOT-COMPLETED status of the task.

You can make views of it below the first content type by adding relation between first & second content type & adding the fields by help of the relation.

Let me know if it works in your scenario..

---
Tags: entities
---


# Question
Title: How can I put form elements into a table and have a submit at the bottom?
I'm working on this module and I want it displays a page as follows.

What I am doing to get that is just displaying a table through `theme()` and typing out the HTML for the upload. I want the whole page to be seen as a form; the only element that will need changing is the image that's uploaded. I want also a submit button on the bottom to save changes.

One way to solve this would be to put an edit button and have it go to a new page that is just a form and that would work, but I'd prefer to have it on one page.

What is the best way to do this? Every site I read on is just confusing me more because they are all doing it different; it's not the result I am looking for because not all that is displaying is going to be a form element.

# Answer
You should use theme\_table. It will help you. :)
> 0 votes

---
Tags: forms
---


# Question
Title: Is it possible to count sub-items in view in Drupal 7?
I want to count nodes in sub-categories (taxonomy terms using) and view result to category field. how to do this in views?

Example:

category with counter http://3.reshleon.z8.ru/catalog/bytovaya-tehnika

items in category, needs to count them http://3.reshleon.z8.ru/catalog/42

# Answer
In views, there is an one field called global counter. Render it and it will give you the count. If you wish you could also hide it via display setting.
> 1 votes

---
Tags: views, ubercart
---


# Question
Title: Trying to make changes to page (post/article) text just before they are rendered
I have a module that works fine but I cannot seem to get node\_view hook to work - seems to never be called. As a test, I tried adding this to the dennis.module in sites/all/modules/dennis, but nothing happens (Drupal 7).

```
function dennis_node_view($node, $view_mode, $langcode) {

  echo "AAAAAAAAAA";

  $node->content['body'] = array(
    '#markup' => "bonjour!"
  );

  $node->content['body'][0]['#markup']="hello";
}

```

Ultimately I need to find keywords in the content and replace with other text. So easy in WordPress and Joomla but after days of trying I have got nowhere with Drupal. Please help!

# Answer
I can't help with the code, but could you use the String Overrides module for this?

> **Features:**
>
> * Easily replace anything that's passed through t()
> * Locale support, allowing you to override strings in any language
> * Ability to import/export \*.po files, for easy migration from the Locale module
> * Note that this is not a replacement to Locale as having thousands of overrides can cause more pain then benefit. Use this only if you need a few easy text changes.
> 0 votes

# Answer
you can do this by jQuery also :

```
$('body').html($('body').html().replace('Original Text','New Text'));

```
> 0 votes

---
Tags: views, nodes
---


# Question
Title: How to get children and parent book pages
I have nid of a book page. I need the nid of the parent and nid of all direct and indirect childs.

How to retrieve the parent and child IDs?

# Answer
> 3 votes
This is for Drupal 6 but might also apply to Drupal 7. The hierarchy of a book is created with a menu. When you have the node object in `$node` you'll get the menu link id of the parent in `$node->book['plid']`. You can then load the corresonding node with `menu_link_load()`.

As for the children you have to get the menu that represents the hierarchy of your book with `menu_tree_all_data($node->book['menu_name'])` and then go through that menu to fetch the links you need.

---
Tags: nodes
---


# Question
Title: Cart page content in simple block in ubercart 3
Can i use http://www.mysite.com/cart page content in simple block using ubercart 3 in drupal 7? I want same http://www.mysite.com/cart page content area ("cart form") in a simple block for show cart content in any region to authenticated user.

Thanks

# Answer
> 1 votes
There is a module Ubercart pictured cart block which will display the content of the cart page into a block. It will provide all functionality which are cart page. You can set the block in a region from block administration page in admin.

---
Tags: ubercart
---


# Question
Title: Drupal 7 skip loading the template for ajax requests
I am trying to upload an image in my template page, using jquery ajax-form submit.

And i am returning just the image name after it is uploaded in the module function. However, i am getting the entire html as response.

In my theme's template.php, i have used the following code:

```
function my_theme_preprocess_page(&$vars) {
  if ( isset($_GET['ajax']) && $_GET['ajax'] == 1 ) {
        $vars['template_file'] = 'page-ajax';
  }
}

```

I have this code in my theme's **page-ajax.tpl.php**: `<?php print $content; ?>`

And i am passing the 'ajax=1' parameter to the module hook menu function that handles the image upload. How can i just output the image name in ajax response, instead of the entire html.tpl.php?

# Answer
> 1 votes
How are you generating the ajax response?

If you simply want to return a string eg a file name you can just return it as plain text or as JSON using hook\_menu and a callback function eg:

```
function mymodule_menu() {
    $items['my/custom/path'] = array(
      'page callback' => 'mymodule_callback',
    );
    return $items;
}
function mymodule_callback() {
  //Do stuff like get filename from DB.
  print 'filename.jpg';

  //to return JSON use drupal_json
  //drupal_json(array('filename' => 'filename.jpg'))
}

```

---
Tags: 7, theming, ajax
---


title: Add html class to body

text:
# Question
Title: Add html class to body
I've got a block created with views, which displaying a slider. The slider is created as an unpublished content type with two field collections:

**Settings**\[one value\]:

* selectors type: thumbs or bullets
* slider class: fixed position, faded etc.

**Slider content**\[multiple values\]:

* slide class
* content class
* Image
* content

I do not use views slideshow module
I'm using views-view--slider-block.tpl.php file to customize the output

All works, but I have stuck with one specific setting "fixed position" - this setting should add to html a special class, which I guess can be added only by preprocess\_html function:

```
function MYTHEME_preprocess_html(&$variables) {
    if ( SLIDER HAS "fixed" SETTING ){
        $variables['classes_array'][] = 'slider_fixed';
    }
}

```

the problem is:

1. how to compose the if statement?
2. Did I have to load $view object which allows me to check what setting is used?

I'm looking for the solution which has the lowest influence on the performance.

any suggestions?

# Answer
> 3 votes
The Context API allow to pass a variable from view.tpl to template.php file

**Example:**

In view.tpl file :

context\_set('slider\_settings', 'slider\_class', 'fixed\_position');

In theme template file :

function MYTHEME\_preprocess\_html(&$variables) {

```
$slider_class = context_get('slider_settings', 'slider_class');
if ($slider_class == 'fixed_position'){
    $variables['classes_array'][] = 'slider_fixed';
}

```

}

It is an aswer for my own question, because I found a solution by myself, and it might be useful for someone I think..

---
Tags: views, theming, entities
---


# Question
Title: jQuery Draggable plugin integration with Views 3
I want draggable and sortable contents by admin. So, installed jQuery UI and put this code in my main.js:

```
$(function() {
    $( ".panels-flexible-region" ).sortable({
      revert: true
    });
    $( "#makyaj .views-row" ).draggable({
      connectToSortable: ".panels-flexible-region",
      helper: "clone",
      revert: "invalid"
    });
    $( "ul, li" ).disableSelection();
  });

```

Yes, it works. But i want use this option only admin user. Whether View Sort Type: Jquery Draggable and qhat sets the admin users so they can see it.

Is it possible? Can i integration Views and jQuery UI Draggable?

# Answer
You can do something along these lines in a custom module...

```
function mymodule_init() {
  global $user;

  if ($user->uid==1) { // super/admin user, add role based logic if needed or desired
    drupal_add_js('path/to/admin-only.js');
  }
}

```

...where 'path/to/admin-only.js' is a file containing JS you want added only for your admin/super user. Look into drupal\_add\_js() for more information.
> 1 votes

# Answer
I know this isn't exactly what you asked for, but have you considered using the draggable views module? It does what you aim to do without you having to code anything.
> 1 votes

---
Tags: views, javascript, users
---


title: How to drush up multisite?

text:
# Question
Title: How to drush up multisite?
I am not clear after reading another question on same topic how this is done.

At the moment I go to my root drupal install and drushup then updatedb so if I then go to the folder of a multisite and try to drushup it says nothing to update.

If all the modules are in the root drupal install is that sufficient? Could you not make sure they are all placed in there so you would need to only drushup the root folder?

How then do you update individual databases?

# Answer
> 2 votes
There is Aegir, which is a system that helps you with doing that.

I personally have no experience with it, but I attended a talk on it a few weeks ago and it totally does the job.

In general, it gives you an admin interface of all your sites on that drupal installation while letting you update each one individually. It automatically rolls back if something fails.

Go have a look: http://www.aegirproject.org/

It probably is overkill with just two or three sites, but it seems to help a lot with bigger sites.

# Answer
> 2 votes
pm-updatecode updates the code of your installation. In a multisite install, all sites share the same code, so if you run pm-updatecode on one site, you have updated the code for all of the sites.

After you update the code for a site, you must update the database. This is done with the updatedb command. If you run pm-update, it will first run pm-updatecode, and then will run updatedb. However, this will update the database for only one of your sites. You will then need to run updatedb on all of the other sites in the multisite install.

Note that between the time you run pm-updatecode and the time you run updatedb, your site might not behave correctly; it is therefore advisable to take a site offline when updating it.

In a multisite install, then, all of the sites must be updated at the same time. It is therefore better to stick with single-site installs, so that you can handle updates on each site one at a time.

---
Tags: drush, multi-sites
---


# Question
Title: Per-song play counts with SoundManager2 module
When I am using the SoundManager2 module, is there a way I can get per-song play counts for display on pages?

# Answer
The way I solved your issue was by creating a statistic table with 2 foreign keys columns and count column.

```
nid   int
fid   int
count int

```

Create a custom module and call it *mysound*.

To create the database, add the following code to mysound.install.

```
/**
 * Implements hook_schema().
 */
function mysound_schema() {
  $schema = array();

  $schema['soundmanager2'] = array(
    'description' => 'Table soundmanager2',
    'fields' => array(
      'nid' => array(
        'type' => 'int',
        'unsigned' => TRUE,
        'not null' => FALSE,
        'default' => 0,
        'description' => 'Primary Key: {node}.nid for node.',
      ),
      'fid' => array(
        'type' => 'int',
        'unsigned' => TRUE,
        'not null' => FALSE,
        'default' => 0,
        'description' => 'Primary Key: {file_managed}.fid for file_managed.',
      ),
      'count' => array(
        'type' => 'int',
        'unsigned' => TRUE,
        'not null' => FALSE,
        'default' => 0,
        'description' => 'The number of times this file is played.',
      ),
    ),
    'primary key' => array('nid', 'fid'),
    'indexes' => array(
      'nid' => array('nid'),
    ),
    'foreign keys' => array(
      'node' => array(
        'table' => 'node',
        'columns' => array('nid' => 'nid'),
      ),
      'file' => array(
        'table' => 'file_managed',
        'columns' => array('fid' => 'fid'),
      ),
    ),
  );

  return $schema;
}

```

Then, in mysound.module, you need to create a menu callback to trigger the AJAX call on sound play.

```
/**
 * Implements hook_menu().
 */
function mysound_menu() {
  $items = array();

  $items['mysound/js/%/%'] = array(
    'title' => 'Count played tracks',
    'page callback' => 'mysound_soundmanager2_count',
    'page arguments' => array(2, 3),
    'access callback' => TRUE,
    'type' => MENU_CALLBACK,
  );

  return $items;
}

```

You need to pass two arguments to `mysound_soundmanager2_count()`: one for current node ID and the second for the file ID.

The following code verifies there is already a record for the arguments passed to the function. It updates it or adds a new record.

```
function mysound_soundmanager2_count($nid, $fid) {
  $output = '';
  if (!is_numeric($nid) && !is_numeric($fid)) {
    return;
  }

  $nid = db_select('node', 'n')->fields('n', array('nid'))->condition('n.nid', $nid)->execute()->fetchAssoc();
  $fid = db_select('file_managed', 'f')->fields('f', array('fid'))->condition('f.fid', $fid)->execute()->fetchAssoc();

  if ($nid && $fid) {
    $sound = db_select('soundmanager2', 's')
      ->fields('s')
      ->condition('s.nid', $nid)
      ->condition('s.fid', $fid)
      ->execute()
      ->fetchAssoc();

    if ($sound) {
      db_update('soundmanager2')->fields(array(
        'count' => $sound['count'] + 1,
      ))->condition('nid', $nid)
        ->condition('fid', $fid)
        ->execute();
    }
    else {
      db_insert('soundmanager2')->fields(array(
        'nid' => $nid,
        'fid' => $fid,
        'count' => 1,
      ))->execute();
    }

    // Just for testing.
    $output = t('Node @nid and File @fid', array('@nid' => $nid['nid'], '@fid' => $fid['fid']));
  }

  return $output;
}

```

Now you need a way to pass `$nid` and `$fid` to JavaScript to trigger the AJAX call without altering the SoundManager2 module. The best way I came up with is adding custom attributes on the generated links by the SoundManager2 module. In my example, I created the *mp3* file field (whose machine name is field\_mp3).

The following code will allow you to alter field\_mp3.

```
/*
 * Implements template_preprocess_field()
 */
function mysound_preprocess_field(&$variables) {
  $field_name = $variables['element']['#field_name'];
  if ($field_name == 'field_mp3') {
    $nid = $variables['element']['#object']->nid;
    $items = $variables['element']['#items'];
    foreach($items as $delta => $item) {
      $dom = new DOMDocument();
      $dom->loadHTML($variables['items'][0]['#tracks'][$delta]);
      $linkTag = $dom->getElementsByTagName('a');
      // create attribute data-nid
      $linkTag->item(0)->setAttribute('data-nid', $nid);
      // create attribute data-fid
      $linkTag->item(0)->setAttribute('data-fid', $item['fid']);
      $variables['items'][0]['#tracks'][$delta] = $dom->saveHTML();
    }
  }
}

```

On the JavaScript side, you need to alter one of the SoundManager2 display format (I'm using Page Player) under sites/all/libraries/soundmanager2/demo/page-player/script/page-player.j\` and add the following JavaScript code in play event (line 332).

```
play: function() {
  // keep original code

  // custom code
  var link = jQuery(this._data.oLI).children('a');
  // read attributes
  var nid = link.attr('data-nid');
  var fid = link.attr('data-fid');

  // ajax call
  jQuery.ajax({
    url: Drupal.settings.basePath + 'mysound/js/' + nid + '/' + fid,
    success: function(data) {
      console.log('count + 1');
    }
  });
}

```

This module will allow you to store number of plays per file. If you want to display the results on the same node, you might take a look at `hook_load()`.

Create a new field format view instead of altering `preprocess_field` so play count will work on content view and views view.

First comment out `mysound_preprocess_field()`.

Define field format information.

```
/**
 * Implements hook_field_formatter_info().
 */
function mysound_field_formatter_info() {
  return array(
    'mysound_soundmanager2_page_player' => array(
      'label' => t('MySound SoundManager 2 Page Player'),
      'field types' => array('file', 'media', 'link_field'),
      'settings' => array(
        'stream' => FALSE,
        'audio_type' => 'default',
        'pause' => 'pause',
        'text' => 'filename',
      ),
    ),
  );
}

```

Define the field format view.

```
/**
 * Implements hook_field_formatter_view().
 */
function mysound_field_formatter_view($entity_type, $entity, $field, $instance, $langcode, $items, $display) {
  $element = array();
  $settings = $display['settings'];

  $tracks = array();
  foreach ($items as $delta => $item) {
    // Prepend a random parameter to the URL in case this track appears
    // multiple times in the same page.
    $attributes = array();
    if ($settings['audio_type'] != 'default'){
      $attributes['type'] = $settings['audio_type'];
    }

    $attributes['data-nid'] = $entity->nid;

    $url_options = array('query' => array('uuid' => uniqid()), 'attributes' => $attributes);

    if (isset($item['file'])) {
      // A Media file type.
      $file = $item['file'];
      // Get text to use in link
      $text = $file->filename;
      if (array_key_exists('text', $settings)) {
        if ($settings['text'] == 'description' && !empty($item['description'])) {
          $text = $file->description;
        }
        else if ($settings['text'] == 'title' && !empty($entity->title)) {
          $text = $entity->title;
        }
      }

      $url_options['attributes']['data-fid'] = $file->fid;

      $tracks[$delta] = l($text, file_create_url($file->uri), $url_options);
    } elseif (isset($item['url'])) {
      // A Link file type.
      $file = $item['url'];
      // Get text to use in link
      $text = $item['title'];
      if (array_key_exists('text', $settings)) {
        if ($settings['text'] == 'description' && !empty($item['description'])) {
          $text = $item['title'];
        }
        else if ($settings['text'] == 'title' && !empty($entity->title)) {
          $text = $entity->title;
        }
      }

      $url_options['attributes']['data-fid'] = $item['fid'];

      $tracks[$delta] = l($text, file_create_url($item['url']), $url_options);

    } else {
      // Get text to use in link
      $text = $item['filename'];
      if (array_key_exists('text', $settings)) {
        if ($settings['text'] == 'description' && !empty($item['description'])) {
          $text = $item['description'];
        }
        else if ($settings['text'] == 'title' && !empty($entity->title)) {
          $text = $entity->title;
        }
      }

      $url_options['attributes']['data-fid'] = $item['fid'];

      $tracks[$delta] = l($text, file_create_url($item['uri']), $url_options);
    }
    switch ($display['type']) {
      case 'mysound_soundmanager2_page_player':
        $element[0] = array(
          '#theme' => 'soundmanager2_page_player',
          '#tracks' => $tracks,
          '#attached' => array(
          'library' => array(
            array('soundmanager2', variable_get('sm2_debug_mode', FALSE) ? 'soundmanager2_debug' : 'soundmanager2'),
            array('soundmanager2', 'soundmanager2_page_player'),
            ),
          ),
        );
        drupal_add_js(array('soundmanager2' => array(
          'stream' => $settings['stream'],
        )), 'setting');
        // Add in the config files
        theme('soundmanager2_config');
        if ($settings['pause'] == 'stop') {
          theme('soundmanager2_page_player_pause');
        }
        break;
     }
  }

  return $element;
}

```

### Note

After you implement the new field format, make sure to clear Drupal cache and then select new field format.
> 1 votes

---
Tags: 7
---


# Question
Title: On the 404 page, look for an XML file and read it in. If it doesn't exist, display 404 message
I am wondered if the following is possible: I need to display some XML data on the fly; these should only be created temporarily (ie not nodes or entries in a database and therefore not readable by Google). The URLs for these and the other XML files I import into nodes have the same structure, generated by a third-party system; so I need the page to be generated if the node doesn't exist (so I guess on the 404 page you will be redirected to).

I thought something like this might work. Any pointers?

```
<?php
  $hdr = $_SERVER['HTTP_REFERER']; //Format of http://example.com/item/######
  $idnr =  substr($hdr, -6);
  $file = simplexml_load_file('http://api.service.com/customerID/item/'.$idnr);

  if (file_exists($file)) {
    // Put my XML fields here.
  } else {
    //Echo 404 message
  }
?>

```

**EDIT** After reading Alfred Armstrong's and develkar's answers I guess what I could think about is something like this: In the `module_menu` callback function: Look for a node with that URL alias. If that doesn't exist, load the XML. If THAT doesn't exist, return a 404.

# Answer
In `hook_menu` you define your page:

```
function MODULE_menu() {
  $items['page-not-found'] = array(
    'page callback' => 'MODULE_page_not_found',
    'access callback' => TRUE,
  );
  return $items;
}

function MODULE_page_not_found() {
  $hdr = $_SERVER['HTTP_REFERER']; //Format of http://example.com/item/######
  $idnr =  substr($hdr, -6);
  // return an object : http://php.net/manual/en/function.simplexml-load-file.php
  $file = simplexml_load_file('http://api.service.com/customerID/item/'.$idnr);

  if($file) {
    //Put my XML fields here
  }
  else {
    drupal_set_title('Page not found');
    $cust_err = "";
    $cust_err = $cust_err . "The requested page " . current_path() . " could not be found";
    return $cust_err;
  }
}

```

Then go to *admin \> settings \> error-reporting*, and enter **page-not-found**, the path you defined in hook\_menu.
> 2 votes

# Answer
Drupal let you specify custom 403 and 404 error pages:

```
admin->settings->error-reporting

```

Your custom error page may be PHP, so you can place any logic in it you want, including the one you suggest.

Edit: As already stated by *develkar*, if you do not want this indexed by Google or other search engines, you disallow it in you `robots.txt`.
> 2 votes

# Answer
If the URLs follow a pattern, then what you probably want is a custom menu entry and load function, eg:

```
mymodule_menu() {
  $items['somepath/%xml'] = {
    'page callback' => 'mymodule_callback',
    'page arguments => array(1),
     //... rest of menu definition ...
  };
  return $items;
}

mymodule_xml_load($xml_name) {
  // reads the xml and returns an object or returns FALSE
}

```

See http://drupal.org/node/224170

In other words, the Drupal menu system can already do what you want and all you need to do is code for it.

**Edit**: If there's truly no means by which you can distinguish Drupal paths from the XML ones, the only route I can see is to use custom\_url\_rewrite\_inbound to some checking upfront. But you'd have to effectively duplicate Drupal's own menu logic with some differences when it comes to these cases.

Or you could hack core to the same end. Hint: please don't.

Or you could request an exhaustive list of all the XML paths so you could add them as aliases into the Drupal database. In this case you would map each xml path to something like xml/ORIGINALPATH, then in your module use the logic I suggested above.
> 2 votes

---
Tags: 6
---


# Question
Title: Is there a reason I need to unset CSS files provided by contrib modules if I have CSS aggregation enabled?
As this question makes clear, stylesheets provided by modules can be unset. Some themes, such as Adaptivetheme 3.x, also provide a GUI for unsetting the stylesheets provided by modules. My question is this: if I have CSS aggregation enabled, is there any benefit to unsetting CSS files of modules I do not use? Or is Drupal's CSS aggregation sufficiently efficient that I do not need to bother with unsetting any files?

# Answer
> 1 votes
you might want to unset css files to avoid css limits by ie 7 and 8, such as

Maximum number of possible selectors in a CSS file - 4095 and 31 stylesheets per file

see https://stackoverflow.com/a/11080846

# Answer
> 1 votes
As I understand it unsetting CSS stylesheets is to:

* reduce the final size of the aggregrated css file(s)
* more easily override / implement custom CSS rules

Beyond these 2 reasons, your site probably "uses" all css files defined in the modules you have activated. Unless you need the performance boost from cutting out the extra bloat of X css files, or want to hand-theme certain things completely .... I see little need to unset style sheets.

I've only unset style sheets once .... and it's probably because i'm not making use of drupals multisite capabability where i have 1 site resolving from 2 url domains: http://www.foo.com and https://secure.webhost.com/foo.com/page depending on the domain I use a hook to unset/set a CSS files that fixes image paths in CSS when i'm on a secure url.

---
Tags: theming, performance
---


# Question
Title: Why using of custom date format makes my Drupal date outdated and does not change at all?
I have custom installation profile and I must set date formats programmatically.

I tried:

```
db_insert('date_formats')
    ->fields(array(
        'format' => $format_long,  // PHP Date String
        'type' => 'custom',          // 'custom'
        'locked' => 0,               // 0 = user-specified date format
    ))
    ->execute();
variable_set('date_format_long', $format_long);

```

and

```
$format_long = 'l, Y-m-d G:h';
system_date_format_save(array(
    'is_new' => 1,
    'type' => 'custom',
    'format' => $format_long,
    'locked' => 0,
));

```

and set this up:

```
   variable_set('date_format_long', $format_long);
   variable_set('date_format_medium', $format_medium);
   variable_set('date_format_short', $format_short);

```

At admin/config/regional/date-time all seems to be fine but:

time is e.g 16:04 (now I have 16:38). Time changing, but on settings page time is still the same (after refresh).

I tried to create a content and at admin/content listing I have content updated date as 16:04 too... :(

If I switch to default formats all works ok.

What is wrong?

**EDIT**

At admin/config/regional/settings time is 16:04 too....

**EDIT**

I created module based on suggestion from answer, still no luck :(

```
define('RPKE_DATE_FORMAT_LONG', 'l, Y-m-d G:h');
define('RPKE_DATE_FORMAT_MEDIUM', 'D., Y-m-d G:h');
define('RPKE_DATE_FORMAT_SHORT', 'Y-m-d G:h');
define('RPKE_DATE_DATE_TYPE_LONG', 'rpke_date_long');
define('RPKE_DATE_DATE_TYPE_MEDIUM', 'rpke_date_medium');
define('RPKE_DATE_DATE_TYPE_SHORT', 'rpke_date_short');

/**
 * Implements hook_date_format_types().
 */
function rpke_date_date_format_types() {
    $types = array();
    $types[RPKE_DATE_DATE_TYPE_LONG] = t('Long date format for RPKE');
    $types[RPKE_DATE_DATE_TYPE_MEDIUM] = t('Medium date format for RPKE');
    $types[RPKE_DATE_DATE_TYPE_SHORT] = t('Short date format for RPKE');
    return $types;
}

function rpke_date_date_formats() {
    return array(
        array(
            'type' => RPKE_DATE_DATE_TYPE_LONG,
            'format' => RPKE_DATE_FORMAT_LONG,
            'locales' => array(),
        ),
        array(
            'type' => RPKE_DATE_DATE_TYPE_MEDIUM,
            'format' => RPKE_DATE_FORMAT_MEDIUM,
            'locales' => array(),
        ),
        array(
            'type' => RPKE_DATE_DATE_TYPE_SHORT,
            'format' => RPKE_DATE_FORMAT_SHORT,
            'locales' => array(),
        ),
    );
}

function rpke_date_flush_caches() {
    _rpke_date_purge_date_formats();
}

function _rpke_date_purge_date_formats() {
    $format = system_get_date_formats(RPKE_DATE_DATE_TYPE_LONG);
    variable_set('date_format_' . RPKE_DATE_DATE_TYPE_LONG, RPKE_DATE_FORMAT_LONG);
    if (!empty($format['dfid'])) {
        system_date_format_delete($format['dfid']);
    }
    $format = system_get_date_formats(RPKE_DATE_DATE_TYPE_MEDIUM);
    variable_set('date_format_' . RPKE_DATE_DATE_TYPE_MEDIUM, RPKE_DATE_FORMAT_MEDIUM);
    if (!empty($format['dfid'])) {
        system_date_format_delete($format['dfid']);
    }
    $format = system_get_date_formats(RPKE_DATE_DATE_TYPE_SHORT);
    variable_set('date_format_' . RPKE_DATE_DATE_TYPE_SHORT, RPKE_DATE_FORMAT_SHORT);
    if (!empty($format['dfid'])) {
        system_date_format_delete($format['dfid']);
    }
}

```

**EDIT**

The worst nightmare is that creating custom date format from UI (e.g. custom date format in Views) result display of wrong date too....

# Answer
> 3 votes
Instead of manually inserting stuff in the database, make use of the Drupal API. The blog post Exporting and maintaining custom date formats in Drupal 7 is a great tutorial. It's geared towards modules but I'm pretty sure you can do this in an install profile too.

I think this will solve your problem, and even though I'm not 100% sure, I would always recommend to use the API.

---

Here's a quick copy-paste of the most important code from that blog post, just in case the link would break in the future:

```
/**
 * Define and export date formats.
 */

// Give the date format type a machine name.
define('MODULENAME_DATE_TYPE', 'MODULENAME_date_type');

// Define the string to be passed to date().
define('MODULENAME_DATE_FORMAT', 'l, jS M Y ');

/**
 * Implements hook_date_formats().
 */
function MODULENAME_date_formats() {
  $formats = array();
  $formats[] = array(
    'type' => MODULENAME_DATE_TYPE,
    'format' => MODULENAME_DATE_FORMAT,
    'locales' => array(),
  );
  return $formats;
}

/**
 * Implements hook_date_format_types().
 */
function MODULENAME_date_format_types() {
  $types = array();
  $types[MODULENAME_DATE_TYPE] = t('Default date for MODULENAME');
  return $types;
}

```

The blog post also provides a utility function to clean up old, unused date formats:

```
/**
 * Delete cruft date formats from the database and resync date formats/types.
 *
 * Call this as often as required to ensure date configuration stays in-sync.
 * Don't call this on every page load. hook_flush_caches() or hook_update_N
 * are good candidates.
 */
function _MODULENAME_purge_date_formats() {
  $formats = system_get_date_formats(MODULENAME_DATE_TYPE);
  variable_set('date_format_' . MODULENAME_DATE_TYPE, MODULENAME_DATE_FORMAT);

  // Date formats without a dfid are being read directly from code. We can use
  // the existence of this value to detect "ghost" formats that are not managed
  // in this file.
  if (!empty($format['dfid'])) {
    system_date_format_delete($format['dfid']);
  }
}

```

---
Tags: 7, datetime
---


# Question
Title: How do I update core to only include security patches?
I have a old Drupal 7 installation and I would like to update my Drupal 7 to the latest release, but I know for a fact that some of my custom module will break on the latest update.

All I want installed is the security patches up to the latest Drupal 7. How can this be done or is it even possible without much effort? Also where and how can I view what is being patched during an update of Drupal 7 core?

# Answer
> 36 votes
If you use Drush you can update **all security issues** with your site via (this is Core and 3rd party modules): `drush up --security-only`

if you want to see what it will do, but not do any of the actual changes you can issue: `drush up --security-only --simulate`

If you want an easy way to update Drupal Core to the newest release you can use a patch site such as: http://fuerstnet.de/en/drupal-upgrade-easier

---
Tags: 7, updating
---


# Question
Title: user register hook form alter not reaching
I am trying to request more information from users when they register for my site. I put a set-message in and it's not eve appearing nor any changes in the user register form.

I cant seem to find anything online to work, any help would be greatly appreciated. Thanks!

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

         drupal_set_messge($form_id);

         if ($form_id == "user_register_form") {
              $form['account']['name']['#title'] = t('Full name');

              $form['city'] = array(
                '#type' => 'textfield',
                '#title' => t('City'),
                '#size' => 15,
                '#required' => TRUE,
              );

              $form['state'] = array(
                '#type' => 'textfield',
                '#title' => t('State'),
                '#size' => 15,
                '#required' => TRUE,
               );

               $form['#submit'][] = 'hook_from_alter_submit';

          }

     }

    function hook_form_alter_submit($form, &$form_state) {

       $city = $form_state['values']['city'];
       $state = $form_state['values']['state'];
    }

 ?>

```

# Answer
The naming convention for hooks is:

```
MODULENAME_hook_name()

```

So to implement `hook_form_alter()` in a module called `MYMODULE`, your function would be defined as:

```
function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
  // ...
}

```

Have a look at What is the basic concept behind hooks? for a more detailed explanation.
> 1 votes

---
Tags: users, forms
---


title: Alter Views exposed filter form

text:
# Question
Title: Alter Views exposed filter form
I'm trying to add more elements to the exposed views filter form but am running into an odd problem that is confusing the heck out of me.

I'm using a hook\_form\_alter call in a custom module to add new select drop downs. This works great, except that they get rendered out as part of the submit element.

```
function my_module_form_alter(&$form, &$form_state, $form_id) {
  $form['test'] = array(
    '#type' => 'select',
    '#title' => 'New Filter',
    '#options' => array('value 1', 'value 2')
  );
}

```

Rendered it looks like this:

```
<div class="views-exposed-form">
  <div class="views-exposed-widgets clear-block">
    <div class="views-exposed-widget views-widget-filter-field_node_status_value_many_to_one">
      <label for="edit-node-status"> Approval Status </label>
      <div class="views-widget">
        <div class="form-item" id="edit-node-status-wrapper">
          <select name="node_status" class="form-select" id="edit-node-status"><option value="All" selected="selected"><Any></option><option value="0">queued</option><option value="1">approved</option><option value="2">denied</option></select>
        </div>
      </div>
    </div>

<!-- Select SHOULD go here -->

  <div class="views-exposed-widget views-submit-button">
    <input type="submit" id="edit-submit-wpg-content-bulk-admin" value="Apply" class="form-submit">
    <div class="form-item" id="edit-test-wrapper">
      <label for="edit-test">New Filter: </label>
      <select name="test" class="form-select" id="edit-test"><option value="0">value 1</option><option value="1">value 2</option></select>
    </div>
  </div>

</div>

```

Does anyone know what I'm missing here? Why would the newly added 'test' element be rendered inside the submit element wrapper?

# Answer
You need to turn the new form item `test` into a widget by declaring the item in `$form['#info']`

So your code should look like the following:

```
function my_module_form_alter(&$form, &$form_state, $form_id){
  $form['test'] = array(
    '#type' => 'select',
    '#title' => 'New Filter',
    '#options' => array('value 1', 'value 2')
  );

  $form['#info']['test'] = array(
    'value' => 'test',
  );
}

```
> 5 votes

---
Tags: views, 6
---


# Question
Title: How do I drush vset a number with decimals?
> drush vset latest\_version 6.34a
>
> latest\_version was set to "6.34a"

So far so good.

> drush vset latest\_version 6.34
>
> latest\_version was set to 6.

Hmm...

> drush vset latest\_version '6.34'
>
> latest\_version was set to 6.
>
> drush vset latest\_version "6.34"
>
> latest\_version was set to 6.

# Answer
Turns out that calling Drush as follows does the trick.

\<-- language: lang-bsh --\>

```
drush php-eval "variable_set('latest_version', '6.34');"

```

It also turns out that this is a bug, and that awesome greg\_1\_anderson fixed it within hours of me asking the question.
> 5 votes

---
Tags: drush
---


# Question
Title: How can I use Rules to send an e-mail to the author of a node linked by an entity reference field?
I have a content type called **Help Wanted**. I have another content type called **Reply to Help Wanted**. The reply content type includes an entity reference field that contains a node reference to the original help wanted ad being replied to.

I am trying to use Rules to send an e-mail when a reply is posted to the author of the original **Help Wanted** post.

However, I don't know what to put in the **To** field of the *Send mail* action. I tried the following:

```
[node:field_my_entityreference:author:mail]

```

But this token didn't work. I also tried several other variations to no effect. Is it possible to use tokens to get the author's e-mail of a node linked by entity reference? If not, how do I get the author's e-mail via the entity reference?

# Answer
Here's how I got mine to work:

1. Switch to '**Data selection mode**' which is not how the mail action launches by default:
2. Select through the field sequence just like you already had with tokens!

I noticed that the tokens are otherwise not available if you just use the direct input mode. Weird!
> 5 votes

---
Tags: rules, entities, tokens
---


# Question
Title: How to pass value from form to url parameter
in my sidebar i have block with a form where users add name of restaurant and when they cick Submit they are supposed to be redirected to a page where my webform is.

I need url like this /add-your-restaurant?key=value-from-text-field but im not sure how to pass that value in url with my form.

I have already %get\[key\] as default value for my Name field in webform.

This is my html form:

```
<form name="addres" id="addres" method="post" action="">
<span>
<input type="text" name="addresfield" class="resfield" value="Enter your Restaurant name"/>
</span>
<input type="button" class="btn"/>
</form>

```

# Answer
This is solution and working form as desired.

```
<form name="addres" id="addres" method="get" action="add-your-restaurant">
 <span><input type="text" name="addresfield" class="resfield"
 name="key" value="Enter your Restaurant name"/></span>
<input type="submit" class="btn"/>
</form>

```
> 0 votes

---
Tags: webforms
---


# Question
Title: How to set the parent of menu items creating using hook_menu()?
I need creating a series of menu items dynamically based on values from the database.

Here is a example of my `hook_menu()` function; in this snippet, I removed the DB queries and just added an array to prove the concept:

```
function MYMODULE_menu() {
  $years = array(2011, 2010, 2009);

  foreach ($years as $year) {
    $items['events/' . $year] = array(
      'title' => $year . ' Events Archive',
      'page callback' => 'page_archive',
      'page arguments' => array(1),
      'access callback' => TRUE,
      'type' => MENU_NORMAL_ITEM,
      'menu_name' => 'main-menu',
    );
  }

  return $items;
}

```

This works and I get three menu items in the Main Menu titled *2011 Events Archive*, *2010 Events Archive* and *2009 Events Archive*.

The problem I am having is the position of the dynamically created menu items in the Main Menu tree; they appear at the top level, but I want they appear under the parent *Events* menu item.

Currently, my menu tree looks something similar to the following.

* Home
* Events
* About Us
* Contact Us
* 2011 Events Archive
* 2010 Events Archive 2009 Events Archive

It should look like the following.

* Home
* Events
    + 2011 Events Archive
    + 2010 Events Archive
    + 2009 Events Archive
* About Us
* Contact Us

I know you can move the menu items using the Menu editor UI when logged in, but as these will be automatically created by the system; they need to appear automatically under Events without human intervention.

How can this be done? Is there an easier way to do this?

# Answer
> 6 votes
Since the *Events* menu item links to a node, for which *events* is a path alias, what you are trying to achieve should work if you define the menu items using the following code (I use "11" as node ID).

```
function MYMODULE_menu() {
  $years = array(2011, 2010, 2009);

  foreach ($years as $year) {
    $items['node/11/' . $year] = array(
      'title' => $year . ' Events Archive',
      'page callback' => 'page_archive',
      'page arguments' => array(1),
      'access callback' => TRUE,
      'type' => MENU_NORMAL_ITEM,
      'menu_name' => 'main-menu',
    );
  }

  return $items;
}

```

This is necessary because, if *events* is a path alias for *node/11*, Drupal doesn't expand *events/2011* to *node/11/2011*. In the same way, it will not expand *events/edit* to *node/11/edit*, even thought the Node module defines *nodes/%node/edit* as one of its menu items.

# Answer
> 2 votes
```
<?php
/**
 * GOAL AND STRATEGY:
 *
 * node/6 is a top level menu item in a custom menu called 'menu-main-menu'. I'm
 * creating a child menu item using hook_menu with the path of 'member/pick'. I
 * want this menu item to be rendered as a child of node/6 in the main menu, and
 * I want all of this to happen programatically.
 *
 * Here's how...
 *
 * 1. Create the child item using hook_menu
 * 2. In hook_menu_link_alter, lookup the mlid of node/6 and apply it as the
 * plid of the child item
 *
 */

/**
 * Implementation of hook_menu()
 */
function hook_menu() {
  $items = array();
  $items['member/pick'] = array(
    'title' => 'Member Pick',
    'menu_name' => 'menu-main-menu',
    'page callback' => 'member_pick_page',
    'access callback' => TRUE,
    'type' => MENU_NORMAL_ITEM,
  );
  return $items;
}

/**
 * Implementation of hook_menu_link_alter
 */
function hook_menu_link_alter(&$item) {
  if ($item['page callback'] == 'member_pick_page') {
    $parent_normal_path = 'node/6';
    $plid = db_result(db_query("SELECT mlid FROM {menu_links} WHERE link_path = '%s'", $parent_normal_path));
    $item['plid'] = $plid;
  }
}

```

# Answer
> 0 votes
Here's how I do it... First, create a menu item that will be representing the group:

```
$items['admin/content/example'] = array(
  'title' => 'Example menu group',
  'page callback' => 'example_page_2011',
  'access arguments' => array('administer nodes'),
);

```

Then add your menu items below this group:

```
foreach ($years as $year) {
  $items['admin/content/example/' . $year] = array(
    'title' => $year,
    'page callback' => 'example_page_' . $year,
    'access arguments' => array('administer nodes'),
    'type' => MENU_LOCAL_TASK,
  );
}

```

Event though it works (tested on 7.22), I still don't like that redundancy in page callback. If only there was a type called MENU\_GROUP... Any better solution is appreciated.

---
Tags: 7, routes, hooks
---


# Question
Title: After restoring the database from the live site to development site, the administrator users fails to log in
I want to refresh my DEV site with data from LIVE site.
(both sites have same modules because I play with new modules on my DEV site before I install/enable modules on the LIVE site).

I have set the database configuration to be exactly the same (except localhost for my dev site).
So I dump my database from live site and restore it on my dev site.
(I know I miss some files but I don't care about that.)
All is fine: I can view the dev site with data from the live site, until I try to login as administrator. There is no way to login, no error message; I am simply not logged in.
The password for the administrator user is the same on both the sites, of course.

I checked the hash of the passwords which are different in table *users*.
I assumed it was due to some salt, so I also copied the salt from *sites/default/settings.php*
It does not help: The administrator login is still impossible.
Then I reset the admin password on my dev site as explained in http://drupal.org/node/1023428, but it doesn't help: There is no way to log in.

What did I miss?

# Answer
> 1 votes
Solved by apache configuration, as described in Can't log in to Drupal instance after duplicating database
So to be complete :
1/ apache mod\_rewrite must be loaded :
httpd.conf must include :
LoadModule rewrite\_module modules/mod\_rewrite.so

2/ the **salt in sites/default/settings.php** and the **passwords hash** (in table *users*) must be aligned :
If you keep the hash from the restored DB (the LIVE site), then you have to change the salt from your site (DEV Site) to align with the salt from the site you take the DB from (the LIVE site).

# Answer
> 1 votes
When login fails, you shall get the following error message:

> Sorry, unrecognized username or password. Have you forgotten your password?

You say:

> There is no way to login, no error message; simply I am not logged in.

This suggest that the problem is not with the admin passord, but something else (i.e. your restored site is somehow munged). In that case, you need to start restoring it from scratch.

Resetting the password will not help if the site is munged, but for the record:

There are several ways to reset the Drupal admin password. Here they are, sorted from the simplest to use to most difficult:

1. Request a reset password link sent via e-mail (the most used method).
2. `drush upwd admin --password=<new_password>` (as already mentioned by *develkar*).
3. `./scripts/password-hash.sh <new_password>` (as you've found out yourself).

Usually, all of these works. The shell-script method (#3) is very similar to the drush method (#2), but unlike drush, the shell-script method requires you to insert the generated password hash in the database yourself (using `phpMyAdmin` or similar tool).

# Answer
> 0 votes
If you have drush installed you can reset the password using:

```
drush upwd <username> --password=<new_password>

```

e.g. `drush upwd admin --password=admin`

this will reset the password of the user with username `admin` to have the password `admin`. You can change the password of any user using this command with Drush.

P.S - Make sure you are in your site's directory while using this command.

If you don't have Drush installed, I recommend you to install it. Please see Specific instructions for installing Drush on different platforms.

# Answer
> 0 votes
Try to change the admin password on your production site (do it carrefully) and re-export your users table in your local dev environment

# Answer
> 0 votes
Another temporary trick to get into the site if you are using drush is:

drush uli

This will log you in as user 1 and give you the option to reset your password. This may help you during the debugging process.

---
Tags: users
---


title: alter ajax callback

text:
# Question
Title: alter ajax callback
Is there a way to alter an ajax callback from a form? I need to add a custom command after the existing one.

Or to alter the existing command defined in the js file?

Thanks

# Answer
> 3 votes
I believe what you are looking for is `hook_ajax_render_alter(&$commands)`

---
Tags: 7, ajax
---


title: Javascript widget

text:
# Question
Title: Javascript widget
I'm extremely new to Drupal and have gotten to this point because I merely want a test page for calendar widgets that I want to develop. I am working with a product called Trumba which will generate a snippet of javascript and I'd like to see what that looks like on a web page. At a high level, can I accomplish this with Drupal? I think if the answer is "yes," I can begin the discovery process. If the answer is "no," then you all will have saved me an immense amount of time.

# Answer
> 1 votes
yes, you can do everything with drupal)

Try to use drupal\_add\_js() function to add your js.

---
Tags: javascript
---


title: How to open jquery dialog on menu click

text:
# Question
Title: How to open jquery dialog on menu click
I would like to open a jquery dialog that asks a question before taking the user to the desired page (ie do some page set-up before they get there). The catch here is that I would like to open the dialog when the user clicks the menu item. I am not sure how to go about this. Could someone point me to some examples where this is done or what I need to do? I am using Drupal 7.

Thanks.

# Answer
> 0 votes
You can use dialog ui or colorbox, just attach this scripts to the page and add custom click event for menu item to open popup. Or you can use ctools but it's more complex.

---
Tags: 7, ajax, javascript
---


title: field_widget_form get value

text:
# Question
Title: field_widget_form get value
I am creating a custom field and I am looking to get the value of a textfield during node creation. In the callback I need to get the value of the textfield, how do I do this?

```
function field_zoekproduct_field_widget_form(&$form, &$form_state, $field, $instance, $langcode, $items, $delta, $element) {
      switch ($instance['widget']['type']) {
        case 'field_zoekproduct_field' :

          $element['searchfield'] = array(
            '#title' => t('Zoek naar een product'),
            '#type' => 'textfield',
            '#required' => TRUE,
            '#maxlength' => 115,
            '#size' => 55,
            '#weight' => 0,
            '#default_value' => 'zoek...',
            "#executes_submit_callback" => FALSE,
            '#attributes' => array('onfocus' => "this.value = '';"),  //when textbox gets focus the default value will be removed
            '#ajax' => array(
                  'event' => 'change',
                  'callback' => 'zoekproduct_zoek_getypte_text',
                  'keypress' => true,
                  'wrapper' => 'dropdown-second-replace',
                ),
        );

  return $element;
}

```

# Answer
Your callback must look like this zoekproduct\_zoek\_getypte\_text($form, &$form\_state){}

check what values you receive in $form\_state or $form
> 0 votes

---
Tags: 7, entities
---