# Question
Title: Adding a module dependency to a public project
I have a module on drupal.org that is currently just has a -dev branch. The module feature detects for another module, and uses it if available. Otherwise, it can safely ignore it. In other words, it is not listed a dependency in the .info file.

A bug report came in, and it looks like I may need to make this a proper dependency.

Is there proper way to handle this situation which minimizes people breaking sites if they update?

# Answer
I would use `hook_requirements()` for this, at least in your next version.

It takes severity parameter:

> The requirement's result/severity level, one of:
>
> * REQUIREMENT\_INFO: For info only.
> * REQUIREMENT\_OK: The requirement is satisfied.
> * REQUIREMENT\_WARNING: The requirement failed with a warning.
> * REQUIREMENT\_ERROR: The requirement failed with an error.

What you want seems to be REQUIREMENT\_WARNING

> Requirement severity -- Warning condition; proceed but flag warning.

That way admin will see that requirement is not satisfied, but will be able to proceed anyway. I currently have this in one of my projects:

If I click "try again", I can proceed, but I will not be surprised if next version will not allow me to proceed, and I am aware that some important functionality will not work if I will proceed now, without addressing this warning.

It's also a good idea to provide a link to installation instructions or drush installation helper syntax in your warning message, as seen on the screenshot.

It should be a **temporary solution** only, of course. After a week or two you could move your dependency to `.info` file. Module users will expect it, informed by your warning, and no further logic or warnings will be needed anymore.

Of course **changelog** and project's page should be a main source of information about serious changes, but many people update using Drupal's built-in functionality and will not even see module's page before update, so it is unsafe to assume they will know basing only on the assumption you posted it there.
> 9 votes

# Answer
Really this is a greater problem, which is "What do I do if I have made a change that could break people's site", because it isn't limited to dependencies, it can be API changes, removing sub modules, functionality changes, markup changes, etc.

In my opinion I think a note that stands out on the project page and also in the release notes is all you really need.

You can add the note to the project page as soon as the code goes into dev and say that the next release (and the current dev) will have such and such requirement.

You can also add change notices: like https://drupal.org/list-changes/zen

These can be quite descriptive and you can link to them from the project page or release notes, although a lot of people probably don't see the normal link to them off in the sidebar.

You could also add a message that is displayed on screen when upgrading to notify the user if the required module isn't enabled. - This is most useful if the site is not going to completely implode from running one without the other for a single second, for examlpe if the requirement only affects certain areas of the site. Unless of course the requirement is such that the site might break the second you are running one module without the other.

You could then create a new release now with the warning message saying the next version will have a new requirement, and then in a month or however long you deem appropriate, you release a new version with the dependency.

I think that is sufficient. I think people should be able to read the release notes and be responsible for their site.

Plus it will teach them a valuable lesson if they upgrade the module straight on the live site without testing and without reading the release notes & project page.

One final thing, if the change is great enough you might also consider creating a new major version, for example keep the 1.x version as is and create a new 2.x branch for the potentially site breaking change.

In your specific case where you only currently have a dev version you have no obligation to anyone because it is not a proper release and is expected that it could possibly change.

This is the downside of choosing to use a dev or alpha module on your site.

It does make it a bit harder though becasue you can't say as of version 1.1 you now need some module, you can only say as of the dev version on date such and such, there is now this new requirement.

This is where it might be handy to roll a release now and then another later with the dependency.

**Note** This is obviously also in addition to adding the dependency to the info file and the README file.

**Some examples**

https://drupal.org/node/959790
https://drupal.org/node/883044 \- In this case the module also showed a message to the user in previous versions leading up to the full change.
https://drupal.org/node/1543432
https://drupal.org/node/2022741
> 4 votes

# Answer
I wish you had provided more information here but maybe that was intentional.

The answer is within the question...

> The module feature detects for another module, and uses it if available. Otherwise, it can safely ignore it.

*Then it's not a dependency, is it?*

Maybe an issue was posted that would not have been posted if the user had taken the time to RTFM. Or maybe had a look at the README file, or maybe the online help. But a module on a dev system can behave behaving differently when enabled on a production system and leave even good people scratching their heads.

You are correct in that best efforts in documentation are often ignored. If something works wonderfully out of the box, very few will read the documentation.

When was the last time you read the instructions for xmas lights?

I have a similar dev story. My module has a page with a configurable url. Before this can be changed, url availability must be checked. Drupal offers a variety of functions for this but the are not consistent across D6, 7 & 8 and some not available at all in D8. All fail under some scenarios.

So I opted to write a small purpose built function that made use of the php cURL library. I thought cURL was a pretty common library (it is) and I did not give this much thought. The purpose built function works in all versions of Drupal without modification.

It did not, however, install with Drush because the drush config did not include cURL. Drush did not, at the time, behave very elegantly either, attempting to repeat the same failed process repeatedly without proper error reporting until it gave up or timed out.

I was developing in Windows at the time and did not use drush. This problem confounded me for a long time because it worked for me and others but did not work for some. Those included people who were performing code reviews needed before my sandbox project could become an official Drupal project.

There were also **great objections** during the review process to the purpose built function -- *why not the Drupal **standard** API functions available?* I finally figured out it was a curl dependency when one reviewer finally mentioned it.

My solution was to to use a series of tests for url availability which started with the Drupal API functions. If all of the Drupal API calls passed, then I used a php function\_exists('curl\_init') call to detect if the library is installed.

So this now works with a drush install with or without cURL being installed. If cURL is installed, it works better, catching that use case that the Drupal API misses altogether.

*This is not a dependency, it's a **serendipity**.* (forgive the grammar)

Will I make it a dependency (how is that done?) or implement hook\_requirement()? NO WAY. It is not necessary.

Of course this does not deal with the issue of unexpected different behaviour that a serendipity might toss in the face of an admin who was previously delighted with those new xmas lights.

After reading your question and giving it some thought, I reckon I will take this approach:

In the soon-to-be-released 1.0 versions, there will be a message that appears on the admin config screen, in bold colors, announcing that **This module will work better with the cURL library installed**.

And this message will only appear if the cURL library is NOT installed. I figure that this will be the edge case. Who cares otherwise?

Enjoy your xmas lights.
> 2 votes

# Answer
It also sounds like if you're going from -dev to a solid release using this new dependency; maybe you should have a Major version increase to note the new hard dependency. Just food for thought -- Major versions can "break" stuff or require new things, Minor versions should not.

And in my opinion the same for -dev to stable.
> 1 votes

---
Tags: 7, community-official-site
---


# Question
Title: Allow user to change term, for views and taxonomy
I have a view which displays a content type in a grid and is working fine.

The content type has a taxonomy field - so when a node is created the user selects a taxonomy term from a list (Hierarchy) - it is then displayed on the node once posted.

In my view I have added 'Content: Has taxonomy term' under 'Filter criteria' but i'm not sure how to get it to work. On the block the user sees I would like them to be able to type a term into an auto complete field which will then change the content which is displayed in the view. I have chosen 'Auto Complete' as the selection type in my filter criteria section and I have ticked the box which says 'Expose this filter to visitors'. The view is working and is displaying content but there is no option presented to the user to change the filter term.

How can I do this please?

Thanks

# Answer
You've done everything right. However, there's a kind of a usability problem with Views, Blocks and Exposed Filters. You can include the exposed filters within the views block by editing the View, then changing "Use AJAX" to yes. Specifically:

Advanced \> Other \> Use AJAX: Yes
> 0 votes

# Answer
Never mind, I found it, I had the 'Required' field checked, I un-ticked it and now all content shows by default and works how I want it :)

Thanks for the help
> 0 votes

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


title: ctools_modal_render() in a condition

text:
# Question
Title: ctools_modal_render() in a condition
I have the following code in my custom.module (using it in `hook_init()`):

```
if ($js) {
  // Required includes for ctools to work:
  ctools_include('modal');
  ctools_include('ajax');
}

if (user_is_logged_in()) {
  $title = 'hello';
  $output = 'more hellos';
  ctools_modal_render($title, $output);
} else {
  return NULL;
}

```

Problem is if even i'm not logged it shows to me a modal windows with infinite loading text. How to unset `ctools_modal_render()` if i am not logged in?

# Answer
You can use below code to redirect anonymous user to user login page.

```
if ($js) {
  // Required includes for ctools to work:
  ctools_include('modal');
  ctools_include('ajax');
}

if (user_is_logged_in()) {
  $title = 'hello';
  $output = 'more hellos';
  ctools_modal_render($title, $output);
} else {

  ctools_ajax_command_redirect('user/login');
  ctools_modal_command_dismiss();

}

```

Or, If you do not want to display popup to anonymous user, then you need to check user is anonymous or not before redering the ctools popup link.

```
<?php if (user_is_logged_in()): ?>
<a href="your_link" class="ctools-use-modal ctools-modal-[yourpopupclass]">Link 1</a>
<?php else: ?>
<a href="user/login">Login</a>
<?php endif; ?>

```
> 0 votes

---
Tags: 7, chaos-tool-suite
---


title: Add widget to file field

text:
# Question
Title: Add widget to file field
I am looking to write a field widget to extend the file field in Drupal 7. The reason is that I want to do some file parsing after it has been uploaded. Are there examples I would be able to look at? How should I got about writing this new module? Or is there a better way I can do this?

# Answer
You can check the hook\_field\_widget\_info()

```
function hook_field_widget_info() {
  return array(
    'text_textfield' => array(
      'label' => t('Text field'),
      'field types' => array('text'),
      'settings' => array('size' => 60),
      'behaviors' => array(
        'multiple values' => FIELD_BEHAVIOR_DEFAULT,
        'default value' => FIELD_BEHAVIOR_DEFAULT,
      ),
    );

}

```
> 0 votes

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


title: Who is online in domain access

text:
# Question
Title: Who is online in domain access
I am developing a website with Domain Access. Each domain has the same structure but different content. I would like to show online users. When I activate who's online block from block list in admin, it will display all online users. But, I want to display the 'online user' for a particular domain.

I use Domain Strict module so users login only their assigned domain.

How can I show 'online user' of a particular domain using `Who's online` block.

# Answer
> Domain Strict - Forces users to be members of domains in order to view content.

So they are still logged in to the whole system, that's what other modules can see.

The best you can do is to create your own module, or use PHP module to create a block with PHP filter. Use code similar to the one from this Drupal.org post:

```
// Count users with activity in the past defined period.
$interval = time() - 900;

// Perform database queries to gather online user lists.  We use s.timestamp
// rather than u.access because it is much faster is much faster..
$anonymous_count = sess_count($interval);
$authenticated_users = db_query('SELECT u.uid, u.name FROM {users} u INNER JOIN {sessions} s ON u.uid = s.uid WHERE s.timestamp >= %d AND s.uid > 0 ORDER BY s.timestamp DESC', $interval);
$authenticated_count = db_num_rows($authenticated_users);

// Format the output with proper grammar.
if ($anonymous_count == 1 && $authenticated_count == 1) {
  $output = t('There is currently %members and %visitors online.', array('%members' => format_plural($authenticated_count, '1 user', '@count users'), '%visitors' => format_plural($anonymous_count, '1 guest', '@count guests')));
}
else {
  $output = t('There are currently %members and %visitors online.', array('%members' => format_plural($authenticated_count, '1 user', '@count users'), '%visitors' => format_plural($anonymous_count, '1 guest', '@count guests')));
}

echo $output;

```

Now you have 2 modifications to make:

1. Get rid of the whole "anonymous" part, as you don't need it.
2. Modify the `$authenticated_users = db_query` part to `JOIN` the table Domain Strict module uses, and only count users that have access to the current domain.
> 0 votes

---
Tags: blocks, domain-access
---


# Question
Title: Meta Tag are not display on some of pages
I adding meta tag on my site, but some of page showing page title as a Meta title, I want to change it with other name. But I don't know why it is not showing/Working on some of pages .

I observed that some page that connect with View those pages are only fail to add Meta tag.

Anyone know what is issue. Why I'm fail to add meta tag.

# Answer
> 0 votes
Finally i found reason behind it.

I haven't call `<?php print render($page['content']); ?>`.

After adding it , it is working superb.

---
Tags: views, meta-tags
---


# Question
Title: Using hook_form_alter to hide a field in a view exposed filter
I am using hook\_form\_alter to hide a field in a view exposed filter.

```
function cars_form_alter(&$form, &$form_state, $form_id) {
if($form_id == "views_exposed_form"){
    $form['field_price__1']['#type'] = 'hidden';
  }
}

```

My questions are :

1. It only works if use $form\_id == "views\_exposed\_form". But I don't want for all views only for my specific one which has form\_id=views\_exposed\_form\_car-results\_panel\_pane\_3 ,but it doesn't work if I use the specific form id
2. Using the above snippet,I can hide the field but not its Label.How can I hide also the label?

# Answer
One possible way to alter the exposed filter for specific view is the following:

```
/**
 * Implements hook_form_alter().
 */
function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
        // Check if the form contains exposed filter form element.
    if ($form_id == 'views_exposed_form') {
        // Here you can define the check for specific view so that it doesnt apply to all views.
        $view = $form_state['view'];
        // If you have multiple display in view than you can add a check for specific display
        // as '$view->current_display == 'DISPLAY_NAME' in the below if condition with '&&'.
        if ($view->name === 'MY_VIEW_MACHINE_NAME') {
            // Add your code for specific form.
        }
    }
}

```

And for hiding the label of particular element, check #title\_display: Indicates how the label should be rendered. The label includes the #title and the required marker, if #required. If the #title is empty but the field is #required, the label will contain only the required marker.

> '#title\_display' =\> 'invisible'

---

**UPDATE:**

Also you may try using hook\_form\_views\_exposed\_form\_alter as below:

```
/**
 * Implements hook_form_alter().
 */
function MYMODULE_form_views_exposed_form_alter(&$form, $form_state, $form_id) {
  // To check the form id of your view.
  print_r($form_id);
}

```
> 6 votes

---
Tags: forms
---


# Question
Title: Creating some fields for a taxonomy menu with the active trail CSS classes?
I have a taxonomy vocabulary which I want to use to create some navigation on my site.

Terms:

* Weather
* Clothes
* Calendar
* Sports

I want to be able to pull these terms and put them in the navigation of the site. However, I want to be able to rewrite the links that these terms go to, so that rather than going to the taxonomy terms default page they go to:

/topic/\[insert\_taxonomy\_term\_here\]/step-2

This is because I have a view with the \[name\] of the taxonomy term using that term as a contextual filter.

I'm having no problem creating such a menu tree in Views, but when I grab the taxonomy terms, as a views field, they are output without the standard Drupal active trail css classes, so that I cannot style them to show them as active.

Is there a way therefore to create a taxonomy menu in a view where the fields output the Drupal active trail?

# Answer
> 0 votes
Silly me!! This is how you do it, without even thinking

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


# Question
Title: Can we customize user login block in Hybridauth module
Can we customize user login block in Hybridauth module in our custom theme? Like writing **block-hybridauth-hybridauth.tpl.php**.

I need to customize the way of output. Instead of the Sign In icon which gives the overlay of enabled social accounts list, I need some text to replace it and add div and content along with it? Is it possible?

# Answer
> 4 votes
There are two template files used

**hybridauth\_widget.tpl.php**

This one is used to create the list of the icons. It gets a variable called $providers which has all the enabled providers.

**hybridauth\_provider\_icon.tpl.php**

This one is used to print the individual icons. Two variables are used here. $provider\_name is the name of the provider like facebook twitter etc. and $icon\_pack\_classes which has the current selected icon pack classes.

These template files can be found in with in the templates folder of the module.

You can make copy of the same in your theme and make the required changes.

---
Tags: 7, theming, authentication-authorization
---


# Question
Title: Drupal Commerce Paypal WPS - Connection refused
I am trying to get the WPS module to work for Drupal Commerce but I am getting an error. After the payment is made in my logs I see.

> Attempt to validate IPN failed with error -111: Connection refused

The code that this relates to in the pay pal module is:

```
// Process the HTTP request to validate the IPN.
$response = drupal_http_request($host, array('method' => 'POST', 'data' => implode('&', $variables)));

// If an error occurred during processing, log the message and exit.
if (property_exists($response, 'error')) {
  watchdog('commerce_paypal', 'Attempt to validate IPN failed with error @code: @error', array('@code' => $response->code, '@error' => $response->error), WATCHDOG_ERROR);
  return FALSE;
}

```

The `$response` has an error in it (Connection refused).

As I am using the sandbox the `$host` is `https://www.sandbox.paypal.com/cgi-bin/webscr`.

I can confirm that I do receive the IPN from PayPal (some `dd()` statements proved this), but when we check to see if PayPal sent it, the code falls over.

Any ideas what could be going wrong? I am preusming it is more likley to be enviromental rather than code.

# Answer
**This was an environmental problem**. The Drupal server did not have a direct connection to the internet. Setting the proxy settings in `settings.php` got this to work.

http://devincarlson.ca/blog/configuring-drupal-use-proxy-server-when-making-external-http-requests

In my case the settings I had to set were:

```
$conf['proxy_server'] = 'my server';
$conf['proxy_port'] = 1234; // port number

```
> 1 votes

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


# Question
Title: Get Node ID in hook_field_formatter_view()
I'm currently working in a custom video player. For that I've created a content type which uses a field\_collection (for the video file and other stuff) and a field\_caption for a XML file.

The video file field uses a custom field formatter, which I'm using to theme up the player. I need the field\_caption file to be added there so I'm trying to get the node id of the field\_section Field Collection in the hook\_field\_formatter\_view() to get that info....with no luck!

If I print $entity-\>vid from the function parameters I will have NULL, because the field is within a field\_section I believe.

Is there a way round this?

Thanks in advance!

# Answer
As the Field Collection docs says:

> A field collection is internally represented as an entity, which is embedded in the host entity

So what you need to do in your field, is:

1. Test if it's container is a node. This case works already.
2. Test if it's a Field Collection entity.
3. Fallback to situation when you can't obtain parent container or it's an unexpected entity.

Now we'll take care about 2. point. If you can safely assume your field is always in a node, you can use code from answer by Chris Muench:

```
$model = entity_load_single('field_collection_item', $model_id);
$node = $model->hostEntity();
echo $node->nid;

```

Note that you are writing formatter, and it means you have no guarantee that host entity will always be a node. If it's not, go to point 3 on my list.
> 1 votes

---
Tags: nodes, files, entities
---


# Question
Title: Extract info from profile insert into node creation
Hey Guys I hope you can help!

In short: User Profile fields should be exported to certain parts of the add new page fields, Text and Taxonomy Terms

For example, User profile will have 2 html codes for pictures and 3 taxonomy terms or just the text and these fields need to be filled in automatically inside node creation so the user doesn't need to do this and all goes well. User should not be able to edit or change it as well.

I don't want users to fill in the following things on node creation since it only makes things complicated for them. But it needs to be different for each user and it needs to be done for every node or else things will get displayed on the wrong pages. So I want to set it up once and then it will be automatically filled in the rest of the times. I think its easiest to have this information stored in the user profile which they get after I create the account for them. They don't need to see this and Drupal should pull in the information from the user profile. But how

1. text field which will need an image html code which is the same for every node of this user displays a small image for the view that shows up in the panel. (so its needs to be filled every single time with an image link)
2. text field which will need an image html code which is the same for every node of this user but this one display a bigger image for the node. (so its needs to be filled every single time with an image link)
3. Taxonomy Term 1.
4. Taxonomy Term 2.
5. Taxonomy Term 3.
6. Text user can fill in
7. Another text a user can fill in.
8. Date field a user needs to fill in.

# Answer
In broad strokes, you could intercept the node edit/add form via hook\_form\_alter() to remove the fields from the form and then you could implement their population via the hook\_node\_presave() to grab all the information from the node owner's profile and save the fields in the new node.

Caveat: if the user can change this information in his/her profile, it won't automatically update any of the node fields unless you add in that logic as well on the saving of this new information to all the nodes already created.
> 0 votes

---
Tags: nodes
---


# Question
Title: How to define path in anchor tag in blocks?
I'm working on localhost server and I added an anchor tag like below in block.

```
<a href="contactus">Contact</a>

```

In front page it goes to the path directly, but if it is other than front page, it added the current path also, for example

```
http://localhost/r4launch/content/contactus

```

It add the "content" in front of the path, then it return "**page not found**".

how to define path in anchor tag ? or is that anything I'm missing ?

# Answer
> 0 votes
If you are using the non-aliased path, use `l()` to create your link. By non-aliased, I mean the Drupal system path (e.g. `node/235` instead of `about-us`). The non-aliased path for the Contact page is `contact`. This is really the best approach.

```
<a href="<?php print l('contact'); ?>">Contact</a>

```

But if you have an aliased path (e.g. `about-us` or `contact-us`), then use `base_path()`.

```
<a href="<?php print base_path() .'contact-us'; ?>">Contact</a>

```

# Answer
> 1 votes
You can use the base\_path() function to get the url with trailing slash '/'

# Answer
> 1 votes
Do you have a path alias defined for contactus (i.e. alias: contactus, system: node/3)?

I don't have a D6 system handy to look at, but in D7 you can check this at admin/config/search/path

If so, and assuming Drupal is at the domain root "/", then you just need to adjust your link from:

```
<a href="contactus">Contact</a>

```

to

```
<a href="/contactus">Contact</a>

```

And it should work everywhere on your site.

---
Tags: 6, uri
---


# Question
Title: Administer block permission let the user to see admin theme name
I gave the site admin role permission to administer blocks, but the problem is in admin/structure/block page, there is a tab that shows the admin theme name (Rubik).

he can click on Rubik but doesn't have permission to see the page. what I want is to hide the tab.

other issue is in admin\_menu module under structure \> blocks there is a Rubik item too, which shouldn't be there too since the user doesn't have the permission to edit admin theme blocks.

So I'm wondering why does rubik block page link shows up!

# Answer
> 2 votes
I have had such a issue in the recent past, the only solution to this is the "Block Access" Module.

# Answer
> 1 votes
In theory, you could write a module that uses `hook_menu_alter()`. It would modify the `access callback` element in the "admin theme" menu item (and maybe sub-menu items?). The callback function would check `user_access('administer themes')`. You could probably write this in 30 minutes or less.

That would cover both cases -- the block admin page and the admin menu.

---
Tags: 7, users, blocks
---


title: Access Denied For Views

text:
# Question
Title: Access Denied For Views
We have a View showing all nodes of type 'member'. We have set permissions to view this node only for authenticated users. If anonymous user tries to access this view then it displays blank page. We expected that it will be redirecting to the page set under 'admin/config/system/site-information' for the 403 page(Access denied), but it is not. It is redirecting if anonymous user tries to access any node instance of 'member' itself but not if the view. How to configure 'Access denied' page for a view? Thank You

Drupal 7.23

Thank You

# Answer
I think in this case you should set access to the view directly under page access in the view itself (assuming this is a page view). You would select Access \> Role \> "member" (and any other role that needs access).

Then users who do not have the role "member" should get a 403, and your custom redirect should work.
> 5 votes

---
Tags: views
---


title: How to use custom tables in Views

text:
# Question
Title: How to use custom tables in Views
I have multisite DRUPAL6.26 website using VIEWS 3.0 module in it.

Both sites are install in single DB.
The first/parent site has no prefix for its tables.EX: node,block,role etc..
The second/childsite has prefix of child. EX: child\_node,child\_block,child\_role etc..

I have a VIEW showing all pictures uploaded by user in there PARENT site account.
And the same VIEW for CHILD site showing pictures that they upload on CHILD site.

**What I want is to show all pictures in PARENT site account of user whether they upload on PARENT site OR CHILD site.**
\[users are shared between the 2 sites.\]

Any help of 'views master' required :)

# Answer
There's a hook for exposing custom fields to Views: `hook_views_data()`

> Describe table structure to Views.
>
> This hook should be placed in MODULENAME.views.inc and it will be auto-loaded. This must either be in the same directory as the .module file or in a subdirectory named 'includes'.
>
> The full documentation for this hook is in the advanced help.

The link also includes example code.
> 0 votes

---
Tags: 7, views
---


title: Private file (video) timeout?

text:
# Question
Title: Private file (video) timeout?
I'm wondering if the private file system has a timeout. Because after many tries of watching a video uploaded by the file system both in public and private mode, with a low speed connection, the video from private always stops loading at around 20 minutes of playing. The same video, from public, works perfect ( it keeps loading after 20 minutes, until the end ).

I've tried on many computers, with different videos, always the same.

Can someone explain me how the private files works, so i can try to find a workaround.

Sorry for my english.

Thanks !

# Answer
There is an issue with streaming video from the private folder because Drupal handles the permissions rather than apache. Use the resumable download module to overcome this. You should be able to enable the module and you are good to go.
> 2 votes

---
Tags: files
---


# Question
Title: How to add existing taxonomy terms to node on saving
I've a field organization\_name which is term reference with unlimited values. Whenever somebody saves the node I want to attach a few more terms in this field.

I've tried doing using hook\_presave and also using submit handler of Forms API.

But the problem is that they both expect the term to be filled with plenty other values as below. Where do I get those values? From taxonomy\_term\_load ?

This is the dsm out of the form\_state array in the form submit handler.

# Answer
The only place you need to add values in your `hook_form_alter()` is the `$form_state['values']` array. In there you should only see the `tid` value, not the whole term entity.

Alternatively, you can use the Rules module
> 0 votes

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


title: PHP code contextual filter (arguments)

text:
# Question
Title: PHP code contextual filter (arguments)
I try to display a list of content with exposed filter in Drupal 7 and Views 3, I create a page and it works, but I also want to display a map with the filter, so I create a block for the gmap and for get the information about the filter I add a contextual filter with php code like this (where province is the name of the field)

```
return $_GET["province"];

```

In Drupal 6 it works this method, but in Drupal 7 I receive this error

> Notice: Undefined index: province in eval() (line 1 of /pathtomodule/views/plugins/views\_plugin\_argument\_default\_php.inc(49) : eval()'d code).

So where is the error, I return only one argument (I know that I need some control if the code is null, but in this case I )

# Answer
> `Notice: Undefined index: province in eval() (line 1 of /pathtomodule/views/plugins/views_plugin_argument_default_php.inc(49) : eval()'d code).`

This error occurs when the array key `province` does not exist. The PHP documentation goes into greater detail - http://www.php.net/manual/en/language.variables.basics.php

> Relying on the default value of an uninitialized variable is problematic in the case of including one file into another which uses the same variable name... **E\_NOTICE level error is issued in case of working with uninitialized variables**, however not in the case of appending elements to the uninitialized array. **isset() language construct can be used to detect if a variable has been already initialized.**

Instead of

`return $_GET["province"];`

Use isset() logic. Also, you shouldn't be directly accessing $\_GET, $\_POST or $\_REQUEST; best practice is to use drupal\_get\_query\_parameters()

```
$param = drupal_get_query_parameters();
if (isset($param['province'])) {
  return $param['province'];
}
return NULL;

```

To address the problem in your comment:

> But i receive: Notice: Undefined offset: 1 in `location_handler_argument_location_proximity->query()`

This is (for all intrinsic purposes) the same as the undefined index; `location_handler_argument_location_proximity->query()` is expecting an array with at least two elements (offset 0 and 1), and that method expected, but did not receive an array with two elements. It might not even be getting an array.
> 1 votes

---
Tags: 7, views
---


title: render php code in view result

text:
# Question
Title: render php code in view result
What's the proper method to render a field within the views?

In node templates I render php code using

```
echo render($content['fancy_field']);

```

But when I want to render php code within a view I was using

```
echo render($view->result->_field_data['nid']['entity']->fancy_field);

```

But it didn't works, any ideas?

# Answer
> 1 votes
Best practice is to implement hook\_field\_formatter\_info() and hook\_field\_formatter\_view($entity\_type, $entity, $field, $instance, $langcode, $items, $display). The examples module shows how to do this in greater detail in the field\_example submodule.

---
Tags: views
---


# Question
Title: Automatically scroll to content when block link clicked?
On responsive themes, where both sidebars and content areas collpase to 100% width,the distance between block links and their corresponding node content which come before or after all blocks is usually large. So user need to scroll down a lot to reach the desired content, which is obviously not a good user experience.

So I am wondering if there is any module/javascript/other solution to slide to the node's content whenever user clicks the link?

# Answer
First, you need to know the ID of the Drupal region/element that you want to jump to when the responsive theme is activated. With the standard Bartik theme the id is the main content region is "block-system-main".

Then you could append #block-system-main to all links within your side. This will cause the browser to jump to the HTML element with that ID after clicking the link. You could append this tag to all links using javascript. See this question. It could also be done in PHP. This would be a good module and AFAIK no exists currently.
> 2 votes

---
Tags: 6, javascript
---


# Question
Title: Radioactivity and Rules- difference between "add an incident" and "set the energy"
I want to increase the radioactivity level after flagging the node. But I don't know exactly how to set the value.

If I fill in the value form field with 60, the Radioactivity text field will increase over 200.

So maybe the action settings are wrong. **What is the difference between the following actions?**

* *add an incident to a field*
* *set the energy of a field*

# Answer
You can do any custom logic you want using the Rules module which integrates with the radioactivity module.

Add an incident to a field - this **increments or decrements** the energy level by a specified amount. Set the energy of a field - this **sets** the energy level to the specified amount.
> 1 votes

---
Tags: rules
---


# Question
Title: Pass the id of one node by url for new node
I have 2 content types, person and date. Date have a relation with person, in one node of person, you can see the dates of that person.

I want add a link in the nodes of person for add a date for that person (this is easy), i need pass the id of the person node automatically to the new node of date.

I don't know how to do this, anyone can help me?

Thanks.

EDIT:

Will try to explain it better:

I use node reference module for create the relation between the two content types. When i add a node of date, all fields are in blanc, if i add one date node through node of person, the id of that node, will add automatically to the new date node in the field that relation the two content types.

# Answer
> 1 votes
One easy way to do this is with the module

nodereference\_url

> The Node Reference URL Widget module adds a new widget to the Node Reference field type. It auto-populates a node reference field with a value from the URL, and does not allow this value to be changed once set. It can automatically provide a link on the referencing node types, that will contain the proper URL to prepopulate the field.

---
Tags: nodes
---


# Question
Title: combining drupal commerce product display page with checkout page
I am trying to find a good way of combining the Drupal Commerce Product Display page with the checkout page. I am trying to eliminate a page, so that the user would choose the product variation and fill in his profile data all on the same page.

I see that there is a hook\_commerce\_checkout\_page\_info\_alter() which looks like it may be a start, but it would need more thought of how to actually combine these two pages.

# Answer
> 2 votes
You can't get to checkout pages without products in your cart ( try visiting /checkout with an empty cart). At least, not without extensive hacks.

I'd recommend keeping the catalogue browse / add to cart separate from the checkout process.

If suitable, you can redirect straight to checkout with a Rule after the product is added to the cart, for user detail input and order completion.

---
Tags: commerce
---


# Question
Title: Fetching title of articles with taxonomy terms which are its siblings
I am making a view that gives the title of an article. It has a term reference field. Taxonomy tree is somewhat like:

1. A
    * a
    * b
    * c
2. B
    * 1
    * 2
    * 3

So I want to make a view that work in such a way that when one is on the taxonomy term page "a", he could see all the relevant title of taxonomy term 'a','b' and 'c'.

This is the query that the view has generated.

`SELECT node.title AS node_title, node.nid AS nid, node.language AS node_language, node.created AS node_created, node_counter.totalcount AS node_counter_totalcount
FROM
{node} node
LEFT JOIN {field_data_field_categories} field_data_field_categories ON node.nid = field_data_field_categories.entity_id AND (field_data_field_categories.entity_type = 'node' AND field_data_field_categories.deleted = '0')
INNER JOIN {taxonomy_term_data} taxonomy_term_data_field_data_field_categories ON field_data_field_categories.field_categories_tid = taxonomy_term_data_field_data_field_categories.tid
LEFT JOIN {taxonomy_term_hierarchy} taxonomy_term_data_field_data_field_categories__taxonomy_term_hierarchy ON taxonomy_term_data_field_data_field_categories.tid = taxonomy_term_data_field_data_field_categories__taxonomy_term_hierarchy.tid
LEFT JOIN {node_counter} node_counter ON node.nid = node_counter.nid
WHERE (( (taxonomy_term_data_field_data_field_categories__taxonomy_term_hierarchy.parent = '46' ) )AND(( (node.status = '1') AND (node.type IN ('article')) AND (node.language IN ('en')) )))
ORDER BY node_created DESC, node_counter_totalcount DESC
LIMIT 7 OFFSET 0`

But is still not working.

# Answer
Can you create contextual filter in Views -\> taxonomy parent term ID. This should work.
> 4 votes

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


title: get url() to translate the alias

text:
# Question
Title: get url() to translate the alias
Ok, I have my own menu on my multilingual site. I have a page with the alias "about" in english. And english is my default language. So, when I am browsing the site in spanish I would like the spanish alias. I have tried all combinations I can think of to get the url() fucntion to translate "about" to "acercade",as it is in the system. What would be the correct way? Is it even working?

> url('about',array=("absolute"=\>TRUE, "alias"=\>TRUE)) ;

thats my best guess.

Thanks for any hint, Michael

# Answer
No need for `$options['alias'] = TRUE`, that will prevent alias lookup.

> If you provide an internal path and $options\['alias'\] is set to TRUE, the path is assumed already to be the correct path alias, and the alias is not looked up.

Use the `node/$nid` path and let Drupal find the correct alias.

If that doesn't work, you could try manually passing the `$options['language']` parameter

> 'language': An optional language object. **If the path being linked to is internal to the site, $options\['language'\] is used to look up the alias for the URL.** If $options\['language'\] is omitted, the global $language\_url will be used.

https://api.drupal.org/api/drupal/includes%21common.inc/function/url/7
> 3 votes

---
Tags: uri
---


# Question
Title: Expose two filter blocks from the same view using drupal 7 ?
I'm not sure how to overcome this. So far I have managed to do it by simply duplicating the view, but this is not a good idea.

The view needs to have two exposed filters. These blocks are styled different and sit in different parts of the site, so they need to be independent.

Is it possible to expose two filter blocks from one view?

# Answer
> 4 votes
An alternative to this is to

* Clone your page display - but do not change the cloned pages path...
* Override and modifty the filters for that cloned display

You will have an exposed block with different filters that submits to the original view.

# Answer
> 3 votes
So you're reusing a single view in multiple places on a site, but based on where it is in the site it will have different filters exposed?

What I would do is just expose both filters in the view, but use CSS to apply a `display: none;` property to which ever filter you don't want exposed/manipulated. Assuming you don't give default values to the filters when they're displayed on a page, hiding individual filters using CSS won't have any negative affects when you apply them.

**EDIT**: Also, I think if an input element has it's display property set to none, then most browsers won't even send the data contained in that field along in the HTTP request when the form is submitted.

# Answer
> 2 votes
Personally I use the context module to manage one display with the path as condition of displaying the occurence of the exposed fitler block in the region I choose, and on the other hand the block display system of Drupal (in structure) to manage the second display type with path conditions too (only on those pages). Then css is the last step using the id or class of each region for example to identify the display style.

# Answer
> 1 votes
A little late, but maybe still useful. The Views module does not support this out of the box. But I have written a module that addresses this problem: MEFIBS - More exposed forms in blocks

The rationale behind it is explained here: http://blog.dev030.com/posts/additional-exposed-filter-block-views

---
Tags: 7, views
---


# Question
Title: Looking for best way to approach user profiles
I'm looking for the best way to approach user profiles, I'll tell you what I want to achieve and maybe someone can give me some advice - There are a few things I'd like to do but not sure where to start, so here I go...

First I'd like 2 different user types, personal and business. When registering the user chooses which type of account they want and fills out the relevant form (personal and business will have different fields available to them, for example a business account will display a vat number where as a personal will not)

Then when a user creates a node I'd like fields from their profile to be displayed on their node, for example their name, location, picture and a link to their profile to name a few. (I would like this so people can search content based on users location for example)

I think these are the 2 main functions I'd like to get out of user profiles - what would be the best way to tackle this? I have seen a couple of modules - 1 being Profiles2 but I'm looking for an all in one solution if possible because I seem to be having trouble using multi modules for different tasks regarding this unless someone has a good guide on how to do this?

Thanks

EDIT:

Sorry to reply to my own post, but I have been looking more at Profiles2 and think this may be the best approach, I have created 2 'Rolls' "Personal" & "Business", Now I'm thinking I will create 2 'Profile' types, 1 for each, and a personal roll can only use personal profile fields and business roll for business profile. I think I can do this but its all in my head at the moment, but how could I go about giving the user which type of account they want on registration? (Without having 2 separate registration pages) I can see a way to create 1 page for each type of registration but is there a way that the user can check a radio button for which type of account they want during registration, they will then be displayed with the relevant profile and wont be able to see the other profile type - Do you know what I mean? So just to summarize the user clicks register -\> they choose a username and password and then they check a box for which account type they want, (in my case business or personal) once they click submit they have to fill out the profile they chose after their account is activated. Is this possible? Thanks

# Answer
Yes, Profile2 is probably the best approach there.

However, I don't think you'll be able to switch within a single registration form without custom coding.

To present alternative registration form pages for profile type, you can use the module:

profile2\_regpath
> 1 votes

---
Tags: users
---


title: Approach for doing Entity Relationships

text:
# Question
Title: Approach for doing Entity Relationships
I'm looking for the best way to approach creating relationships using Drupal 7. I am looking for advice on creating the following:

1) A "letter" content type (as in an old fashioned letter) a) From Person (i.e. "John Doe") b) Associated From address ("12348 Street") c) To Person d) Associated To address e) Postage Date f) File attachment of scanned letter

2) A person can have one or more addresses (I am recording some family history of letters sent and people have changed addresses over time)

3) Ability to select the Person/Address in the Letter content type for the From / To Person.

I've been reading the documentation, but I'm just unclear on the best approach. Would appreciate suggestions. For example, I started out creating a field for From Name and To Name and From Address and To Address, but realized I'd be creating a lot of redundant data and that it would be better to create relationships, but am not sure how to accomplish that. Should I create a Person Content type? If not explicit instructions, would appreciate a general point in the right direction.

# Answer
> 0 votes
Yes, I would create a *Person* content type in addition to the *Letter* content type.

You may also consider creating a *Place* (address) content type. It depends on how many letters you have and how complex the requirements are for filtering the data later.

Depending on your situation, you could make some assumptions (such as if people are only going to live at one address at a time, if you track the time that they lived at such an address, then you just need to know the time the letter was sent, and then you can generate the address, etc.)

I would do something like this:

Content type *Letter*

* Field: Sender (Entity reference, takes a *Person* content type)
* Field: Sender Address (Entity reference that takes a *Place* content type)
* Field: Recipient (Entity reference, takes a *Person* content type)
* Field: Recipient Address (Entity reference that takes a *Place* content type)
* Field: Postage date (Date)
* Field: Scanned letter (File field, built-in to core)

Content type *Person*

* Field: Name (Text, built-in to core)

Content type *Place*

With this approach, although it is a little complex to build, you can use Views to build screens that show, say, all of the people who lived at an address, or all of the addresses at which a person has received letters.

# Answer
> 0 votes
Just general ideas, not a solution...

I would check out the entity reference module (https://drupal.org/project/entityreference) as a starting point, to get an idea of how it works, so you can plan your project with this in mind. Entity reference makes it easy to link one entity to another, then build views to generate lists of related items. Entity views attachment (EVA, https://drupal.org/project/eva) can help you attach views of related items to entities. (i.e. you could display a list of letters as a view attached to a person)

You may also want to check out the addressfield module (https://drupal.org/project/addressfield) especially if you have international addresses to work with. It's a little tweaky, since it handles the entire address as a single field, but it saves you the trouble of implementing several fields to catpture each address.

From your description, it seems like you would want at least these content types: letter, person, address (or place). But it's hard to say for sure without knowing your complete vision.

---
Tags: 7
---


# Question
Title: how to let a form field be hidden and at the same time the value be able to acces the id using javascript?
How can I get the #value of a hidden form field in javscript as for hidden form
field I am unable to get its id in the (inspect element) html.
How can I extract the value(#value) for the field using ajax for the hidden fields

# Answer
> 1 votes
Try this:

```
$form['hidden'] = array(
 '#type' => 'hidden',
 '#value' => 'Your_value',
 '#attributes' => array('id' => array('your_id')),
);

```

Now using javascript or jquery you get the value of the hidden field.

In jquery: `jQuery("#your_id").val();`

---
Tags: 7, forms
---


title: How do I mass update entities?

text:
# Question
Title: How do I mass update entities?
How do I perform mass updates for entities? Suppose I want to publish 50 nodes at once. How should I do that?

# Answer
You can use Views bulk operations module which support the mass update on the Drupal site.

> This module augments Views by allowing bulk operations to be executed on the displayed rows. It does so by showing a checkbox in front of each node, and adding a select box containing operations that can be applied. Drupal Core or Rules actions can be used.

As you said that you want to update the number of nodes, so there is already module in Drupal Administration Views which replace administrative pages with views.

> Features
>
> * Filter all administrative views via AJAX.
> * Perform any kind of bulk/mass operations on items in administrative views.
> * Filter content by title, node type, author, published status, and/or vocabulary.
> * Filter comments by title, author, node title, or published status.
> * Filter users by name, ban/blocked status, or user roles.

Or, if you want to update using code, you can follow harshal's answer.
> 3 votes

# Answer
You can perform most of the mass updates in Admin \> Content page.

If you require any advanced actions, sorting, filtering, I'd suggest you use Views and Views Bulk Operations modules.
> 6 votes

# Answer
If you have a big number of nodes that need to be updated (say, 10,000 or more), the best option available for you is to use DRUSH (Drupal Shell).

With drush you can perform bulky tasks very fast.
> 1 votes

---
Tags: 7, entities
---


# Question
Title: How to put drop down list of content type page in to another content type pages
I have crated two content type like A and B .some of field are similar .I don't want to repeat that field .I want to put drop down list on any one of A or B.

# Answer
> 3 votes
YOU should use the entity reference module for the above purpose.

> Provides a field type that can reference arbitrary entities:
>
> A generic entity reference field Four widgets: Two implemented on top of the Options module (Select and Radios/Checkboxes), Two autocomplete widgets (one with one text field per entry, one tag-style with comma-separated entries in the same text field) Two formatters: A "Label" formatter, with optional link that displays the label of the referenced entity (the node title, the user name, etc.) A "Rendered entity" formatter, that renders the references entity using a configurable view mode Integration with Views (for both forward and backward references) Integration with Entity Metadata (and as a consequence with Search API and the like) Integration with Devel generate Integration with Feeds and Migrate (\>= 2.3) for painless data import This modules depends on Entity API and CTools.
>
> Modules extending Entity reference functionality:

**Earlier answer deleted following comments :<br>** If you want to use the existing field then just go to manage fields tab under
**Home » Administration » Structure » Content types » A**
and use existing field option where you will get the existing field of other content type
Check the image below for existing field option :

Or else you can do it in the following way :

You can get your dropdown list for content type in `$form_state['values']['your_field_name_for_dropdown']` and
and Save that value in `$_SESSION['module_name']['your_field_name_for_dropdown']` After saving that value you can use that value to insert into another content type in the hook\_form\_alter function or your custom\_form itself.

# Answer
> 0 votes
Simply go to `/admin/structure/types/manage/<your-content-type>/fields` and at the end of page you will find a 2 options : `Add new field`, and `Add existing field`

Use `Add existing field` to add a field from one content type in another content type.

---
Tags: views, nodes
---


# Question
Title: programmatically saving a node doesn't add any record to dblog
When I call `node_save` to save a node, no record for "a new node has been saved.." is added to watchdog.

Is this normal? If yes, how do I also add a watchdog record? (without calling the `watchdog` function directly)

# Answer
The reason that the save operation is not logged during `node_save` is because it is done during the node form submission process by `node_form_submit` which internally uses node\_save.

Please refer this elaborate and well-written response of saving the node using `drupal_form_submit` answered by user Francisco Luz. Pasting the code for the sake of completion here for saving an article resulting in both the watchdog logging and the `drupal_set_message` of the acknowledgement.

```
global $user;
module_load_include('inc', 'node', 'node.pages');

$node = (object) array(
  'uid' => $user->uid,
  'name' => $user->name,
  'type' => 'article',
  'language' => 'und',
);
node_object_prepare($node);

// Get default values from attached fields.
$fields = field_info_instances('node');
$form_state = array();
foreach($fields['article'] as $field_name => $values) {
  $form_state['values'][$field_name] = array('und' => array());
}

// Add the $form_state field values.
$form_state['values']['title'] = 'my title';
$form_state['values']['body']['und'][0] = array(
  'value' => 'my body',
  'format' => 'full_html',
);
//$form_state['values']['field_MYFIELD']['und'][0]['value'] = 'blah blah';

// Without this line, not quite sure why, it wont work.
$form_state['values']['op'] = t('Save');

drupal_form_submit('article_node_form', $form_state, $node);

// Tell watchdog if any of the fields fail validation.
$errors = form_get_errors();
if (!empty($errors)) {
  foreach ($errors as $field_name => $message) {
    watchdog('MYMODULE', '%field: %message',
      array('%message'=> $message, '%field' => $field_name));
  }
}

```

I did run this once with devel php console and it logged the node during the node creation. Hope this helps.
> 3 votes

---
Tags: 7, nodes, log-messages
---


title: Product Inquiry form in ubercart?

text:
# Question
Title: Product Inquiry form in ubercart?
Can we provide an inquiry form for products in ubercart ? I want to provide a form to each product so that the user can send his/her requirement to site owner. Site owner can later on check who has contacted him and why. I do not want to provide add to cart option.

# Answer
> 0 votes
Create a form in a block with a hidden field the captures the product name or information and then place the block wherever you want it.

Either store the information or just email it directly.

# Answer
> 0 votes
* Create a form in a block with a hidden field the captures the product name or information and then place the block wherever you want it.
* Enable the below custom module(Replace form id with yours first).
* This custom module will work when you will check 'Show all webform pages in block ' from block configuration. By default multi-page webforms redirect to the node page for all pages after the first one. If checked, all pages will be shown in the block instead.

```
function webform_nodevalues_form_alter(&$form, $form_state, $form_id) {
  if ($form_id == 'webform-client-form-5') {
    if ($node = menu_get_object()) {
      $form['submitted']['product_name']['#value'] = $node->title;
      $form['submitted']['my_webform_field_key']['#value'] = $node->my_cck_field[0]['value'];
    }
  }
}

```

---
Tags: forms, ubercart
---


# Question
Title: Export node report base on Word and Excel template
I want to export node content to Word or Excel. Are there any module to do this?

# Answer
You can use the Views Data Export to export in many popular table formats. XLS, CSV, DOC, TXT and XML.

Some other modules worth mentioning here:

Views Datasource

Service Views

It should go without saying that the modules above will require Views be installed and enabled.
> 1 votes

# Answer
1. For exporting the node to excel sheet you can use the Sheetnode module. It also has other options of import and export (e.g. import from Microsoft excel .xls and .xlsx; also from OpenOffice.org calc .ods files; also the sheets from Google Docs.
2. For exporting to word you can use the Node to Word module. Currently it is for version 6.x. But, a working copy of the module for Drupal 7 can be downloaded from the thread running for D7 port.
> 1 votes

# Answer
For excel you can use feeds module too. It has many advance configurations for import and export.
> 0 votes

---
Tags: nodes, importing-exporting
---


# Question
Title: How to submit form on selecting image in file select widget?
I am using Drupal Form API to upload profile image for user. I found two file upload widgets in FORM API:

1. `'#type' => 'managed_file'` &
2. `'#type' => 'file'`

`managed_file` requires first selecting the file, then uploading the file and then submitting the form to change the image

`file` requires first selecting the file and then submitting the form to change the image

What I want to do is just when you select the image file and click ok in the file browser, the form should get submitted and image should be changed.

Is it possible using FORM API? If not please recommend an alternative solution.

# Answer
> 0 votes
Of course it is possible. You need to take regular managed file and add some JavaScript to the file selection in it. To see how it is done, please see AutoUpload module:

> This module removes the extra button press and hides the "Upload" button via JavaScript for a quicker, automatic file upload. When JavaScript is not enabled, it falls back to the "Upload" button.

The most interesting is line 9, out of it's 22 lines of code:

```
$('.form-item input.form-file', context).change(function() {

```

And maybe simply *using* this module is all you really need?

---
Tags: forms, files
---


# Question
Title: How to fix combination Dutch domain - English uri
In Google Webmaster Tools I have 60 non-existing combinations of my Dutch domain and the English original blog. Example:

http://website.nl/enlish-blog

The from English to Dutch translated blog exists.

This problem leads to a degraded customer satisfaction, as Drupal reports the web-page not to be found.

I have checked the Global Redirect property to correct this, and automatically replace the English link with the Dutch link. To no avail.

I tried to correct it in Path redirect, but also to no avail. It is not allowed, because the module interprets it as the redirection of an alias, and advises the alias to be corrected. This does not work, because then the English web-page cannot be found.

My questions:

1. How do I fix this?
2. Why did I get it in the 1st place?

Thanks for any comment or suggestion.

# Answer
> 0 votes
My favourite way of dealing with 404 like that is to use module like Search 404:

> Instead of showing a standard "404 Page not found", this module performs a search on the keywords in the URL, e.g. if a user goes to http://example.com/does/not/exist, this module will do a search for "does not exist" and shows the result of the search instead of the 404 page. This should help retain visitors coming in from old URLs linked from other sites or from search indices.

That way user will see a link to an article on a proper domain, if he will enter bad URL.

To prevent creation of "interesting" links it's worth to use Global Redirect \- with it even if you will have temporary misconfiguration, users and bots (including Google bot) will get redirected to content's main URL, and that's what will get indexed.

Last but not least, be sure to always set canonical URL for your content, if you care how it looks in search results.

I'm afraid you will never know what misconfiguration caused this in the first place, unless it still occurs. Things to check would be:

1. Canonical URL - are you sure it does not direct everyone to one single domain?
2. Web Archive \- maybe they have a snapshot from time when your site was actually displaying something under these URLs. If so, you could use backups to unpack a copy on a dev machine, and examine configuration that made this.

---
Tags: 6, i18n-l10n
---


# Question
Title: add light box effect to login, create account form
How to add light box effect to login, account creation, forget password and password reset forms?

# Answer
> 4 votes
Go to `admin/config/lightbox2` and then expand the Modal form settings and check the first option.

>

or you can try Ajax Login/Register module see the demo.

> This module provides a smooth way for the user to login, register and request new password via AJAX at any Drupal site.

or you can try Popup module and don't forgot to read the documentation

> The popup suite allows builders to popup tooltip-like text, nodes, blocks, menus, forms, views and php-generated content.

---
Tags: javascript
---


# Question
Title: Parse error on JSON response containing URL value
In my code it is making Ajax request for json data. For JSON output I am using `drupal_json()` function.

But on browser side it is invoking error handler instead of success handler and getting 'parsererror'.

The JSON data is like this:

```
{
    "affiliate_urls": {
        "4131": {
            "nid": "4131",
            "title": "play.com - Books",
            "file_path": "sites/default/files/playlogo.gif",
            "url_value": "http://www.play.com/Search.html?searchstring=asd+asdasd\x26searchsource=0\x26searchtype=allproducts"
        }
    }
}

```

When put on http://jsonlint.com/ I am getting this error:

```
Parse error on line 7:
...       "url_value": "http://www.play.com
-----------------------^
Expecting 'STRING', 'NUMBER', 'NULL', 'TRUE', 'FALSE', '{', '['

```

What is wrong with passing URL value over JSON? and still using `drupal_json()`.

Please help on it.

Thanks

# Answer
> 0 votes
The problem is with drupal\_to\_js() which is called by drupal\_json() to do the job. drupal\_to\_js() will perform `str_replace(array("\r", "\n", "<", ">", "&"), array('\r', '\n', '\x3c', '\x3e', '\x26'), addslashes($var))` to every string it receives. Converting '&' to '\x26' is making problem to me here. Anyway I cannot use json\_encode() because of PHP dependency (Drupal 6).

I solved the problem by URL encoding the URL value on server side using PHP function `urlencode()` when preparing JSON data. And URL decoded it on browser side by JS function `decodeURI()`.

---
Tags: 6, ajax
---


# Question
Title: Make block visible to specific IP (in D6)
On a D6 site I want a block that it visible only to visitors from a specific IP. If I choose `Page specific visiblity settings` with the PHP code

```
<?php
  if(strcmp(ip_address(),'1.2.3.4')==0) {
    return true;
  } else {
    return false;
  }
?>

```

it works fine on all pages, except for the front page.

How can I make this setting work also on the front page?

Is this snippet not executed on the front page?

Update: Or is this some caching issue? It's working on the front page, if I connect with https. But block caching is disabled on the site.

# Answer
The commentators questions and remarks pointed me in the right direction, so here's the solution to my own question:

With page caching enabled, the above PHP condition is evaluated only occasionally on cache rebuild. If someone with the correct IP visits the site at the right moment the block can get visible and cached. Visitors with the wrong IP may then also see it (from the cache). Therefore the above approach is wrong.

Correct solution: Use IP login to authenticate some real or special user, then make the block visible to this user with the PHP condition:

```
<?php
  global $user;
  if($user->uid==123) {
    return true;
  } else {
    return false;
  }
?>

```

Of course, one could also define a new group and use the group-based visibility settings.
> 0 votes

---
Tags: blocks
---


title: Metatag and page title modules conflict

text:
# Question
Title: Metatag and page title modules conflict
I am using Drupal 7 with the Metatag module along with the Page title module.

I have a requirement to build the title of a custom content type using some node fields and additional conditions that I can't reproduce using the tokens provided, so I have hooked to the page title API ( `hook_page_title_alter(&$title)`) to build my custom title only for one node type.

The function works and the page title is set. But the meta tags are wrong, they are not using the page title found in `<TITLE>` (under `<HEAD>`) but the node's title which I don't want to use.

How do I feed metatags module with my custom title ? I am out of ideas, so anything is appreciated.

As commented by someone you don't need the page\_title module if you use metatags, but page\_title provides an API with hooks to alter the page title, and that's what I am using and what I need to use, so maybe the question could be reformulated to "How do I alter the page title generated by metatags?"

# Answer
It is indeed a bad idea to have both modules altering the page title. A better approach I have found is to create a custom token, (which is really trivial with the provided example) and use it inside a metatag configuration for the desired node type. This way page\_title could be uninstalled since it's no longer needed.
> 2 votes

---
Tags: hooks, meta-tags, 7
---


# Question
Title: Making taxonomy dropdown on the basis of previously selected dropdown of two different taxonomies?
I have two different taxonomies Taxonomy 1:

```
Category
-music
-football

```

Taxonomy 2:

```
Sub-category
-Jazz
-Rock
-Fifa
-Russian Open

```

I have linked Jazz, Rock to music and Fifa, Russian Open to football by term-reference field.

I have content type event, having term-reference to both Category and Sub-category. I want drop-down for sub-category should be populated after selection of Category. Eg. if we select music as category then in sub-category only jazz and rock should be shown.

# Answer
> 0 votes
I think you will have to go for some custom code if you want to use seperate taxonomy vocabularies.

An easier way would be to have all terms in the same hierarchical vocabulary and use Hierarchical Select to create the "populate dropdown"-feature.

# Answer
> 0 votes
Use Hierarchical Select, where you can display category and subcategory in a tree structure. Then use JavaScript to handle the drop down menu. You can get the taxonomy id of parent from the first drop down using jQuery. Then create an Ajax request to get all the child terms. taxonomy\_get\_children(); function can be used to find all child terms.

You can refer the following code to get better understanding.

```
(function ($) {
 Drupal.behaviors.custom_filter = {
  attach: function (context) {
    $('#selelctid1').change(function() {
      var id = $(this).val();
        $.ajax({ url: Drupal.settings.basePath + 'yourmenu/' + id,
          async:false,
          success : function(msg) {
            $('#selelctid2').html(msg);
          }
        });
    });
  }
 };
})(jQuery);

```

Then create a new menu under hook\_menu

```
function mymodule_menu() {
  $items = array();
  $items['yourmenu/%'] = array(
    'page callback' => 'mymodule_get_child_terms',
    'access callback' => TRUE,
    'type' => MENU_CALLBACK
  );
return $items;
}

```

Create callback function

```
function mymodule_get_child_terms() {
  $tid = arg(1);
  $taxonomy = taxonomy_term_load($tid);
  $vid = $taxonomy->vid;
  $children = taxonomy_get_children($tid, $vid);
  print '<option value="All">- Any -</option>';
  foreach ($children as $key => $value) {
    print '<option value="' . $value->tid . '">' . $value->name . '</option>';
  }
}

```

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


# Question
Title: Multiple Content Types sharing a lot of common fields
I wanna have three types of Events on my website. All three types of events have common fields such as: name, date, location, time, host, price.. and many more.

Now each event type has few extra fields that do not apply to other events types.

It is very important requirement in UI administration form *not to show* fields that do not apply to a specific event type.

I was considering the idea of creating 3 separate Content types (one for each Event type), but somehow I feel this is not the best way to go since there is a lot of common elements.

Any suggestions?

# Answer
If the content types share the majority of fields, it makes sense to keep them as a single content type.

I'd suggest adding a field for "Event type" or similar to record what sub-type of Event the content is and perhaps group the additional fields in fieldsets.

You can then show/hide the additional relevant fields with `hook_field_attach_form` (or equivalent) by setting '`#access`' =\> FALSE on the relevant field.

If you don't mind showing the fields to the user, you could also use a module like conditional\_fields (D7 dev works ok)
> 4 votes

# Answer
If you want to create three different content type for the events, then you can add common fields in one content type and then can add existing field in other content type as below.

* Go to Administration -\> Structure -\> Content types
* Click on "Manage fields" link in row of content type
* In the "Add existing field" section, select the your field from in "select an existing field" drop box and save the form.

I also prefer the solution which is suggested by David, but if I need to add multiple condition to hide other fields, then creating different content type would be easy solution.
> 1 votes

---
Tags: entities, nodes
---


# Question
Title: Drupal form: sum of each rows user input and compare to
I've searched on SE and google for 2 weeks, and mostly found JavaScript or jquery solutions. I have very little knowledge of coding either. I have altered a custom Drupal module form and added a user "wager" input. I have `#element` validate (it is a positive integer) working correctly for each row of the "wager" input. It is also saving correctly to MySQL table for each "wager" input.

*Questions:* How do I sum all of the users "wager" boxes and compare `>=` to the users total available points for form validate? Is there an alternative solution to the jquery or JS? If not, how the heck would I begin to implement for that form? I can post code or screenshots if needed.

Edit: added screenshot of form:

```
 > //  * Menu callback; presents the list of all weeks and games.  *
> function mypicks_all_page($league) {   return theme('mypicks_all',
> array('league' => $league)); }
>
>
> /**  * Display the list of all weeks and games.  * The user would pick
> a week link from here to make their weekly picks.  */ function
> theme_mypicks_all($variables) {   global $_PICKEM_MY_LEAGUES;   global
> $user;  /*******************blakestart*/
>
> /********blakeend*******************/   $league =
> $variables['league'];
>
 >   // Param check: user must be a member of this league to continue.
 > if ( !is_my_league($league) ) {
  >     return drupal_not_found();   }
  >
   >   drupal_set_title(t('My Picks - %user_name', array('%user_name' =>
 > $user->name)), PASS_THROUGH);
   >
       >   $breadcrumb = drupal_get_breadcrumb();   $breadcrumb[] =
       > l($league->name, 'pickem/' . $league->lid);
        > drupal_set_breadcrumb($breadcrumb);
    >
    >   $teams = get_teams(array('gameset_id' => $league->gsid));   $games =
      > get_games(array('league_id' => $league->lid), array('by_week' => 1,
  > 'order_by' => 'week_ended, g.gamestart, g.gid'));
    >
  >
      >   $header = array(t('Week'), t('Games'));   $rows = array();   foreach
  > ($games as $wid => $weeks_games) {
    >     $cols = array();
 >     $current_week = '';
 >     foreach ($weeks_games as $gid => $game) {
   >
   >
     >
    >
    >
    >       // Figure out the matchup operator.
 >       if ($game->neutral_venue == 1) {
  >         $matchup = "vs ";
     >       }
     >       else {
 >         $matchup = "@";
>       }
>
>       // The first column should be the week number link.
 >       if ( count($cols) == 0 ) {
>         $cols[] = array('data' => l(t('Week %wk_number', array
('%wk_number' =>     $game->wk_number)),
> "pickem/$league->lid/mypicks/" . $wid, array('html' => TRUE)), 'class'
> => 'week');
>       }
>       $current_week .= '<div class="picks-float">' . $teams[$game->v_id]->short_name .     '<br/>' . $matchup .
> $teams[$game->h_id]->short_name . '</div>';
>     }
>     $cols[] = $current_week;
>     $rows[] = $cols;   }   return theme('table', array('header' => $header, 'rows' =>        $rows, 'attributes' => array('class' =>
 > array('pickem-mypicks-all')))); }
>
>
> function mypicks_week_form($form, &$form_state, $league, $week) {
> global $user;  global $wager;
>
>
>
>   $form = build_picks_week_form($form, $form_state, $league, $week,
> $user, $wager);   return $form; }
>
>
> function theme_mypicks_week_form($variables) {   global $user;
 >
 >
 >      $form = $variables['form'];   $league =
 > league_load($form['league_id']['#value']);
>
>   // Drupal sets the default timezone to be the user's   //if
> available, otherwise, the system's.   $timezone =
> date_default_timezone_get();
>
>   $header = array();   $header[] = t('Matchup');   if
 > ($league->scoring_engine->features['with_confidence'] == 1) {
>     $header[] = array('data' => t('Confidence'), 'class' => 'confidence-pts');   }          $header[] = t('Status');   $header[] =
> array('data'=>t('Game time'), 'title'=> t('Timezone is @timezone',
 > array('@timezone' => $timezone)));  if
 > ($league->scoring_engine->features['with_spread'] == 1){   $header[] =
 > array('data'=>t('Wager'), 'title'=>'This is Wager column');  }   $rows
 > = array();   $last = count(element_children($form['games']));   $count = 0;   foreach      (element_children($form['games']) as $gid) {
 >     $count++;
>     $cols = array();
 >
 >     if (isset($form['games'][$gid]['pick'])) {
 >       if ($form['games'][$gid]['pick']['#default_value'] == '') {
  >         $cols[] = array('data' => drupal_render($form['games'][$gid]['pick']),  'class' => 'no-pick');
  >       }
 >       else {
 >         $cols[] = array('data' => drupal_render($form['games'][$gid]['pick']));
  >       }
 >     }
 >     else {
  >       $cols[] = drupal_render($form['games'][$gid]['pick_v_score']) . drupal_render($form['games'][$gid]['pick_h_score']);
 >     }
 >
 >     // Render confidence boxen
 >     if ($league->scoring_engine->features['with_confidence'] == 1) {
 >       if($form['games'][$gid]['confidence']['#default_value'] == '') {
 >         $cols[] = array('data' => drupal_render($form['games'][$gid]['confidence']),
 > 'class'=>'no-pick');
 >       } else {
 >         $cols[] = array('data' => drupal_render($form['games'][$gid]['confidence']));
 >       }
 >     }
 >
 >     $cols[] = drupal_render($form['games'][$gid]['pick_status']);
 >
 >     $cols[] = drupal_render($form['games'][$gid]['gamestart']);
 >
 >
 >     $cols[] = drupal_render($form['games'][$gid]['wager']);
 >
 >
 >
 >     $rows[] = $cols;   }
 >
 >   $output = $league->scoring_engine->description;   $output .= '<p>' .
 > t('Game time is represented in the @timezone timezone.',
 > array('@timezone' => $timezone)) . '</p>';   $output .= theme('table',
 > array('header' => $header, 'rows' => $rows, 'attributes' =>
 > array('class' => array('pickem-mypicks-week'))));   $output .=
  > drupal_render_children($form);   return $output; }
 >
 >
 >
 >
  >
 >
 >
 > function mypicks_week_form_validate($form, &$form_state) {   $league =
 > league_load($form_state['values']['league_id']);   if
 > (($league->scoring_engine->features['with_confidence'] == 1)) {
 >     $conf_values = array();
>     $max_conf = count($form_state['values']['games']);
>     foreach ($form_state['values']['games'] as $gid => $pick) {
>
>       // Skip empty confidence values.
>       if ($pick['confidence'] == '') {
>         continue;
>       }
>
>       // Out of range confidence numbers
>       if (!is_numeric($pick['confidence']) || $pick['confidence'] < 1 || $pick['confidence'] > $max_conf) {
>         form_set_error('games][' . $gid . '][confidence', t('Confidence point must be a number from 1 to %max.', array('%max' =>
> $max_conf)));
>       }
>
>       // Duplicate confidence numbers
>       if (isset($conf_values[$pick['confidence']])) {
>         form_set_error('games][' . $gid . '][confidence', t('Confidence point %pt already used.', array('%pt' =>
> $pick['confidence'])));
>       }
>       $conf_values[$pick['confidence']] = TRUE;
>
>
>
>
>
>
>       }}}    /**  * Implements hook_form_alter().  */ function webform_calc_form_alter(&$form, $form_state, $form_id) {   if
> ($form_id == 'mypicks-week-form') {
>     $form['#validate'][] = 'webform_calc_validate';   } } function webform_calc_validate($form, &$form_state) {
> switch($form_state['input']['details']['page_num']) {
>     case '1':
>       $bet = $form_state['input']['submitted']['wager'];
>
>
>       $totalbet = $wager + $wager;
 >       form_set_value(
>         $form['submitted']['totalbet'], $totalbet, $form_state);
>       break;
>     case '2':
>       $totalbet = $form_state['storage']['submitted'][4];
>       $form_state['webform']['component_tree']['children']
>         [11]['value'] = 'Total bet: ' . $totalbet;
>       break;   }   return $form; }
>
> function mypicks_week_form_submit($form, &$form_state) {   global
> $user;
>
>
>   $league = league_load($form_state['values']['league_id']);   $week =
> week_load($form_state['values']['week_id']);
> $form_state['values']['wager'] = array();
>
>
>
>   // You should not be able to save picks after lockup.   if
> ($league->pick_lock == PICKEM_PICK_LOCK_WEEK && $week->week_started ==
> 1) {
>     drupal_set_title(t('%week_name picks are locked.', array('%week_name' => $week-      >wk_name)), PASS_THROUGH);
>     return t("You cannot change your picks now.");   }
>
>
>
>
>
>
>
>   // Check and see if the user wants to save to all their leagues that
> use the same gameset.   $save_for_these_leagues = array();   if (
> $form_state['values']['apply_to_all_leagues'] == 1 ) {
>     $save_for_these_leagues = get_my_leagues($league->gsid);   }   else {
>     $save_for_these_leagues[] = $league;   }
>
  >   foreach ($save_for_these_leagues as $l) {
>     // Only save for league using the same scoring system.
>     $success = TRUE;
>     if ($l->scoring_type == $league->scoring_type) {
>       foreach ($form_state['values']['games'] as $gid => $pick) {
>         $pick['gid'] = $gid;
>         if (set_pick($user->uid, $l, $pick, 'user') != TRUE) {
>           $success = FALSE;
>         }
>       }
>
>
>
>      if ($success) {
>
>
>
>
 >        drupal_set_message(t('The picks have been saved for league <i>%league</i>.', array('%league' => $l->name)));
>
 >       }
 >     }   } } //

```

# Answer
> 1 votes
Where do you want to do that calculation? Before or after submitting?

Assuming you want to do it before submitting the form, you can use the hook\_form\_alter() to set a custom submit function where you will receive the values from the form and do whatever you need with them. Something like:

```
function YOUR_MODULE_form_alter(&$form, &$form_state, $form_id) {
    if ($form_id == "YOUR_FORM_ID") {
        $form['#submit'][] = "_YOUR_MODULE_do_calculations";
    }
}

function _YOUR_MODULE_do_calculations($form, &$form_state) {

     $total = 0;
     if (isset($form_state['values']['YOUR_FIELD_1'])
      && isset($form_state['values']['YOUR_FIELD_2'])
      && isset($form_state['values']['YOUR_FIELD_3'])) {

        // Sum up values, save in DB or anything you need

     }
}

```

---
Tags: forms
---


title: views ajax form alter

text:
# Question
Title: views ajax form alter
I have some slightly complicated ajax form logic that I'm struggling with.

I would like to replicate the following form conditions.

radio1 - always visible option1 option2 option3

radio2 - only visible if option 2 and 3 are selected in radio1 option1 option2 option3

select3 - only visible if option 1 is selected in radio1 contents of select list to be controlled by on options in radio2

**Problems**

when radio2 is changed it still fires the ajax function

when the form is submitted the select list uses the default option set rather than one that has been built from the selection radio2

Below is the code I have used following the ajax example from the examples module.

```
function uk_general_form_views_exposed_form_alter(&$form, &$form_state, $form_id) {
if($form['#id'] == 'views-exposed-form-documentation-search-page') {
if(!empty($form_state['values'])) {
  $form_state['input'] = array_merge($form_state['input'], $form_state['values']);
}
$doc_type_options = $form['type']['#options'];
$form['type'] = array(
  '#type' => 'radios',
  '#options' => $doc_type_options,
  '#title' => '',
);

$doc_line_options = $form['line']['#options'];
$line_selected = isset($form_state['values']['line']) ? $form_state['values']['line'] : key($doc_line_options);
$form['line'] = array(
  '#type' => 'radios',
  '#options' => $doc_line_options,
  '#title' => '',
  '#ajax' => array(
    'callback' => 'uk_general_forms_documents_products',
    'wrapper' => 'products-dropdown-replace',
  ),
  '#states' => array(
    'visible' => array(
      ':input[name="type"]' => array(
        array('value' => '29'),
        array('value' => '31'),
        ),
      ),
    'disabled' => array(
      ':input[name="type"]' => array('value' => '30'),
      ),
    ),
  );
$form['title'] = array(
  '#type' => 'select',
  '#prefix' => '<div id="products-dropdown-replace">',
  '#suffix' => '</div>',
  '#options' => _get_products($line_selected),
  '#states' => array(
    'visible' => array(
      ':input[name="type"]' => array('value' => '29'),
    ),
    'disabled' => array(
      ':input[name="type"]' => array(
        array('value' => '30'),
        array('value' => '31'),
      ),
    ),
  ),
);
}
}

function uk_general_forms_documents_products($form, $form_state){
  return $form['title'];
}

function _get_products($selected) {
  $product_query = new EntityFieldQuery;
  $product_query->entityCondition('entity_type', 'node')->entityCondition('bundle', 'product')->fieldCondition('field_line', 'tid', $selected)->propertyOrderBy('title', 'ASC');
  $result = $product_query->execute();
  $product_nids = array_keys($result['node']);
  $products = entity_load('node', $product_nids);
  $titles['All'] = '- Any -';
  foreach($products as $product) {
    $titles[$product->title] = $product->title;
  }
 return $titles;
}

```

# Answer
i finally worked this one out, I strppied the form right back and removed all the states and got the ajax call working first. This was a bit of a hack as I had to access the $\_GET variable directly and using the following line I was able to check whether or not the page had already been searched.

```
if(isset($_GET['line_2'])) {
  $line_2_selected = $_GET['line_2'];
}
else{
$line_2_selected = isset($form_state['values']['line_2']) ? $form_state['values']['line_2'] : key($doc_line2_options);
}

```

After this the problem was either having the ajax selectively removed ot depending on the values in the parent checkboxes. What I actually did was add the same list twice and then disable one or the other depending on the value in the first checkbox. Doing this greatly reduced the complexity of the states array.

```
$form['line'] = array(
  '#type' => 'radios',
  '#options' => $doc_line_options,
  '#default_value' => $line_selected,
  '#title' => '',
  '#prefix' => '<div id="lines-dropdown-replace">',
  '#suffix' => '</div>',
  '#states' => array(
    'enabled' => array(
      ':input[name="type"]' => array('value' => 31)
    ),
    'visible' => array(
      ':input[name="type"]' => array('value' => 31)
      ),
  ),
);

$form['line_2'] = array(
  '#type' => 'radios',
  '#options' => $doc_line2_options,
  '#default_value' => $line_2_selected,
  '#title' => '',
  '#prefix' => '<div id="lines-dropdown-replace">',
  '#suffix' => '</div>',
  '#ajax' => array(
    'callback' => 'uk_general_forms_documents_products',
    'wrapper' => 'products-dropdown-replace',
    ),
  '#states' => array(
    'enabled' => array(
      ':input[name="type"]' => array('value' => 29)
      ),
    'visible' => array(
      ':input[name="type"]' => array('value' => 29)
      ),
    )
  );

```

The previous ajax functions all worked as expected.
> 0 votes

---
Tags: views, ajax, javascript
---


title: Add span inside views pager

text:
# Question
Title: Add span inside views pager
I need to add a single span inside of the list items of a views pager. This needs to be there even when the list item doesnt contain a link (when you are on the current pager's page).

I cant see any tpl files for doing this (my preferred method as im more of a themer.)

Ive looked for a theme override and ive found the following. The problem is that I cant figure where I would add the span.

```
function theme_views_mini_pager($vars) {
  global $pager_page_array, $pager_total;

  $tags = $vars['tags'];
  $element = $vars['element'];
  $parameters = $vars['parameters'];

  // current is the page we are currently paged to
  $pager_current = $pager_page_array[$element] + 1;
  // max is the maximum page number
  $pager_max = $pager_total[$element];
  // End of marker calculations.

  if ($pager_total[$element] > 1) {

    $li_previous = theme('pager_previous',
      array(
        'text' => (isset($tags[1]) ? $tags[1] : t('‹‹')),
        'element' => $element,
        'interval' => 1,
        'parameters' => $parameters,
      )
    );
    if (empty($li_previous)) {
      $li_previous = " ";
    }

    $li_next = theme('pager_next',
      array(
        'text' => (isset($tags[3]) ? $tags[3] : t('››')),
        'element' => $element,
        'interval' => 1,
        'parameters' => $parameters,
      )
    );

    if (empty($li_next)) {
      $li_next = " ";
    }

    $items[] = array(
      'class' => array('pager-previous'),
      'data' => $li_previous,
    );

    $items[] = array(
      'class' => array('pager-current'),
      'data' => t('@current of @max', array('@current' => $pager_current, '@max' => $pager_max)),
    );

    $items[] = array(
      'class' => array('pager-next'),
      'data' => $li_next,
    );
    return theme('item_list',
      array(
        'items' => $items,
        'title' => NULL,
        'type' => 'ul',
        'attributes' => array('class' => array('pager')),
      )
    );
  }
}

```

# Answer
Have a look at YOUR\_SITE\_ROOT/includes/pager.inc

I think you are looking for the **theme\_pager\_previous()** and **theme\_pager\_next()** functions.
> 0 votes

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


# Question
Title: Conditional display of views based on comparing node taxonomy and user taxonomy
I'm using drupal 7 and working on a site that displays nodes based on a user's taxonomy option. A quick example, i want users to make a blog entry and select a taxonomy option "Target audience". The target audience contains selected "Interests" of logged in users. Both "target audience" attached to node and "Interest" attached to user profile are from the same taxonomy vocabulary, so that when a user selects a target audience, he matches a user interest.

Is it possible to build a single view of all blog enteries and then display parts of the view based on certain conditions like "if blog entry is tagged with taxonomy value which is equal to the interest of logged in user, then display blog enteries which match the logged in user's interest.

Another use case is this: taxonomy value location = New York. Blogger makes a post and selects target audience = New York. User logs in with selected location = New York (mandatory during registration), view checks if target audience = user location, then displays only posts tagged with "New York". Another user logs in with location = Washington, but there are no posts with tag = Washington, views empty field is then displayed or default display is used (when all conditions fail).

I'm also using panels. currently with panels, to achieve this, i have to build a separate view for each user with selected taxonomy option. This makes it cumbersome because, for instance, to display for all users logged in from 52 cities, you have to create 52 views. My intention is to build a single view that decides what to display based on the checked conditions.

Help is greatly appreciated. Thanks

# Answer
First, your view needs to be set up with a display of type "Content Pane". For this to be possible you need to enable the Views Content Panes module which is part of Ctools.

Next, you need to add a contextual filter (also called an argument) for your taxonomy field. The option to do this is under Advanced on the Views UI for the view. The process is similar to adding other parameters to a view, so I'll not cover it in detail.

Once the contextual filter has been added you need to ensure it can be supplied by the panel you are going to add it to. To do that, click on the Edit link next to "Argument input" under Pane settings. Set the source of the argument to be "from context" and the required context to be "term ID of first term".

On the panel editor, you need to add a context for the logged in user. On the contexts tab for the panel, select "user" for the type of context to be added, then press the add context button. Choose suitable identifiers for the user context and select the "logged in user" option, then hit Finish.

Now from the same tab, under Relationships, you should be able to find an option to add a taxonomy context via the user context. It'll be labelled something like "Taxonomy term from User (on User: fieldname \[field\_fieldname\])". Add it and assign it a meaningful identifier.

Now finally you should be able to add your view display pane to the panel. On the content tab, you'll find it under "View Panes" on the add content dialogue. After you click on it you should see the settings for it, which should consist of a selector linking the contextual filter from the view to the context from the panel. If there is only one taxonomy term context available, the correct value will probably be already correctly set. Save everything and test.

Good luck!
> 1 votes

---
Tags: views, panels
---


# Question
Title: Filter criteria affecting different displays in same view
I have a view that displays content in a table form so admins can quickly look through the content. There are two displays (pages).

Page1: Lists all content and exposes the filters for type and published to the user so they can narrow down there view. But initially all content should be displayed.

Page2: Has criteria set to show only type=photo and published=no.(not exposed)

Everything else is the same between the two.

The filters on page2 are affecting page1. When you first land on page1, the filter controls say -any- and -any- but the view is filtered to type=photo and published=no (page2 filters). If you hit apply the filters are removed, but you can see how this could be confusing to users.

How can I prevent the filters on page2 of the view from affecting page1.

# Answer
> 2 votes
Whenever you apply any filter criteria / sort criteria / contextual filters / relationships; you have to make sure you apply settings to current display (page/block) only. In this way the current setting doesn't interfere with other displays.

---
Tags: views
---


title: How to check a mysql table field type

text:
# Question
Title: How to check a mysql table field type
I need to check whether a certain table field is of type 'int' (I am referring to table schema)

e.g. for table field\_data\_field\_myfield field\_data\_field\_myfield\_value is of type int(11)

I actually need a generic function that check if a certain field is of type in the schema.

\[Edit\]

I want to explain better my difficulty:

I have a feature that holds a certain field of type 'datetime'. Now as this type creates performence problems on database sides, I decided to change it to 'datestamp' \[= unix format\]. I did this editing the file MYFEATURE.features.field.inc that is a database field table mirror.

Now the reports are:

```
FieldException: Cannot change an existing field's type. in field_update_field()

```

This is an exception raised due to the fact I am not supposed to alter schema while data is in. Therefore I create a hook\_update\_N for data migration.

Now I believe I need to do a hook\_update\_N for schema migration too. HERE is the point I need to alter schema in a hook\_update\_N.

# Answer
> 3 votes
You want something like:

```
function _mymodule_is_db_column_int11($drupal_field_name) {
  // See example output below.
  $drupal_field_info = field_info_field($drupal_field_name);

  // From this table you can get the table name, which follows a known
  // convention in the Field API (but this lets you get it grammatically)
  // and also value field names from the definition array.
  $sql_details = $drupal_field_info['storage']['details']['sql'];
  $table_name = key($sql_details[FIELD_LOAD_CURRENT]);
  $value_col_name = $sql_details[FIELD_LOAD_CURRENT]['value'];

  // Then in MySQL check the column type. I see no way to do this using
  // the drupal api.
  $raw_table_info = db_query("SHOW COLUMNS FROM :tbl;", array(':tbl' => $table_name)->fetchAll();

  $is_int11_field = FALSE;
  foreach ($raw_table_info as $result_id => $recObject) {
    if ($recObject->field == $value_col_name && $recObject->Type == 'int(11)') {
      $is_int11_field = TRUE;
    }
  }
  return $is_int11_field;
}

```

An example of output of field\_info\_fields() for 1 field:

```
/*
[field_foo_feedback023] => Array
    (
        [entity_types] => Array
            (
            )

        [foreign keys] => Array
            (
                [format] => Array
                    (
                        [table] => filter_format
                        [columns] => Array
                            (
                                [format] => format
                            )

                    )

            )

        [indexes] => Array
            (
                [format] => Array
                    (
                        [0] => format
                    )

            )

        [settings] => Array
            (
            )

        [translatable] => 0
        [storage] => Array
            (
                [type] => field_sql_storage
                [settings] => Array
                    (
                    )

                [module] => field_sql_storage
                [active] => 1
                [details] => Array
                    (
                        [sql] => Array
                            (
                                [FIELD_LOAD_CURRENT] => Array
                                    (
                                        [field_data_field_foo_feedback023] => Array
                                            (
                                                [value] => field_foo_feedback023_value
                                                [format] => field_foo_feedback023_format
                                            )

                                    )

                                [FIELD_LOAD_REVISION] => Array
                                    (
                                        [field_revision_field_foo_feedback023] => Array
                                            (
                                                [value] => field_foo_feedback023_value
                                                [format] => field_foo_feedback023_format
                                            )

                                    )

                            )

                    )

            )

*/

```

If you're going to try and use this you'd probably want to add caching, probably want to assure your type check is always forced to lower-case etc. Also check your mysql credentials allow for this sql usage of `SHOW`.

**EDIT: A slightly simpler solution**

The only problem I see with this solution is for complex or custom fields you will always have to *know* what the value field you want to check is; and require a custom check -- for default simple value fields this should work without needing custom SQL:

```
function _mymodule_is_db_column_int11($drupal_field_name) {
  // See example output below.
  $fields = field_read_fields();
  $my_field = &$fields[$field_name];

  $field_uses_sql_storage = $my_field['storage']['type'] = 'field_sql_storage';
  $field_value_uses_int_11 = $my_field['columns']['value']['type'] == 'int' && $my_field['columns']['value']['length'] == 11;

  return $field_uses_sql_storage && $field_value_uses_int_11;
}

```

---
Tags: database
---