title: Total indexed is zero with 302 status

text:
# Question
Title: Total indexed is zero with 302 status
I'm using Google Webmaster Tools to manage my site SEO; even with 600 articles my total indexed pages is *zero*.

When I use "Fetch as Google" I get the following.

```
<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
<html>
  <head>
    <title>302 Found</title>
  </head>
  <body>
    <h1>Found</h1>
    <p>The document has moved <a href="http://example.com">here</a>.</p> <hr />
  </body>
</html>

```

My site is made with Drupal 7, and the Boost module.

Is that caused by a wrong configuration? If so, how can I fix it?

# Answer
> 1 votes
It looks like you have a different domain either registered or for testing with Google Webmaster Tools.

e.g `example.com` vs `www.example.com`

When the bot requests `example.com`, it is redirected to `www.example.com` with an HTTP `302 Found` reponse.

The solution would be to register the same preferred domain with Google Webmaster Tools that is used for regular site visitors.

As for 0 pages of a new site being indexed in Google, give it time. If you've registered the sitemap, and signed up for Google Analytics, the googlebot will arrive soon. It can take a couple of weeks.

# Answer
> 1 votes
No you don't have to recreate a new account for your site on google weblaster tools,just wait for few days or weeks and it will be ok . For the boost some make sure that your boost code gotten from the module generator is well copied before

> RewriteCond %{REQUEST\_FILENAME} !-f RewriteCond %{REQUEST\_FILENAME} !-d RewriteCond %{REQUEST\_URI} !=/favicon.ico RewriteRule ^ index.php

test it and everything will be ok

# Answer
> 0 votes
I found the ansewer:
It's the Boost module,i had misconfigured it, i should put the Boost code above this line not under it:

> RewriteCond %{REQUEST\_FILENAME} !-f RewriteCond %{REQUEST\_FILENAME} !-d RewriteCond %{REQUEST\_URI} !=/favicon.ico RewriteRule ^ index.php \[L

For more details please see this post: http://drupal.org/node/1881070

---
Tags: google-search-console
---


# Question
Title: Selection of Nodes Based on Taxonomy Terms Percentages
I am developing a huge Questions bank, where teachers submit questions,which actually are nodes,and the topic subjects are taxonomies..NOw at the end of the term, teachers generate question papers of 100 questions each, but based on percentages of topics,say if it mathematics paper, so 30 percent questions from algebra(a taxonomy term) 20% from SETS( Taxonomy terms)....so how can i get this done?i am currently using database level custom procedure, but it is hardly being maintained...any suggestions plz

# Answer
With so many different possibilities that *might* fit your project and its needs, I'll try to address the forks in the road with how you could do this in drupal.

You most likely wont find any appropriate functionality for this task built into drupal or a contrib module but it is simple enough to implement yourself.

**Option 1** Keep it in the database, but still in drupal.

Build queries using the Database API (most likely the static method as it'll be quicker to get going, instead of the dynamic method), depending on your creativity you can loop through each taxonomy term and execute a number of possible queries to get count() results based on timeframes as well as other criteria. You could also have a specific set of queries that you run on the taxonomy terms as a whole to get a view of the whole database table, instead of looping through each term. Whichever appeals to you, this list of common mysql queries has aggregates, statistics, comparison, frequencies and just about every other basic math centric query to get you started.

**Option 2** Maintain your numbers in close to realtime in a node, variable or database table

This option is really if you'd prefer to do most of your work not just on the PHP side of things but *in just PHP*. The example above puts the burden on your SQL server but all of your logic still actually resides in the PHP (instead of stored procedures).

This would be my second choice of the two. Instead of running a lot of heavy queries on a regular interval, simply write some code to keep track of the total numbers of each taxonomy term as they are added or removed (you can use a hook from the node API such as hook\_node\_presave() - any number of hooks to quickly sniff what taxonomy terms are being applied if you don't know where to do your addition and subtraction of the taxonomy terms as they are added or removed).

**If you really want to hand this to drupal from your stored procedures...**

Get ready to do a little battling with drupal depending on how light or heavy your code is. Queue API and batch API can help you with large background processes, otherwise you'll want to ensure things stay trim and quick if that means incremental updates to your taxonomy statistics or putting time constraints on your processes.

Good Luck!
> 0 votes

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


# Question
Title: Attach drupal ajax events to links that were loaded via ajax
So I have links that are created when a page first loads that use a render array that is something like this:

```
array(
    '#type' => 'link',
    '#title' => html_entity_decode(t($title)),
    '#href' => $href,
    '#post_render' => array('_dva_post_render_ajax_link'),
    '#attributes' => array(
        'class' => array('ajax-link'),
        'rel' => url($href),
    ),
    '#ajax' => array(
        'path' => 'dva/ajax/'. $href,
        'wrapper' => 'content',
        'effect' => 'fade',
        'prevent' => 'mousedown',
        'progress' => array(
        'type' => 'none',
        'message' => '',
        ),
    )
);

```

These all work as expected and properly run the ajax and change the page content, etc.

However, when the page content also includes one of these links, the links included in the ajax response are just normal links and have no ajax functionality. The links are created using this same render array and they render correctly (that is, their markup appears the same as the links that work)

How can I tell Drupal to attach the ajax event handlers to the new links that have just been added to the DOM?

# Answer
> 1 votes
Try using the `"use-ajax"` class on the link

> In addition to using Form API for doing in-form modification, Ajax may be enabled by adding classes to buttons and links.
>
> By adding the 'use-ajax' class to a link, the link will be loaded via an Ajax call.
>
> When using this method, the href of the link can contain '/nojs/' as part of the path. When the Ajax framework makes the request, it will convert this to '/ajax/'.
>
> The server is then able to easily tell if this request was made through an actual Ajax request or in a degraded state, and respond appropriately.
>
> Source: http://api.drupal.org/api/drupal/includes%21ajax.inc/group/ajax/7

e.g:

```
array(
    '#type' => 'link',
    '#title' => t($title),
    '#href' => $href,
    '#attributes' => array(
        'class' => array('use-ajax'),
        'rel' => url($href),
    ),
);

```

---
Tags: 7, ajax
---


title: Print a view within another view

text:
# Question
Title: Print a view within another view
Here is my situation,

1. I have a view-1 which will list the node titles based on Content: Taxonomy term CONTEXTUAL FILTERS
2. View-2 which will list all the taxonomy terms (of a vocabulary) with node count.

Now how do I print the view-1 as a custom field within view-2.

The reason I am trying to do this is, I am trying to construct a UI which will display the nodes on click on taxonomy terms with count.

I tried using below code to print view-1 as a custom PHP field on view-2, but it did not work for me.

```
    print views_embed_view('view-1','block_1', $row->tid);

```

$row-\>tid is the term ID argument I am trying to pass

# Answer
> 0 votes
I got it working using the below code in 'Global: PHP' \> 'Output code' field.

```
    <?php print views_embed_view('view-1','default', $row->tid); ?>

```

# Answer
> 2 votes
The module Views Field View may work for you. It's worth to try.

> This module allows you to embed a view as a field in a view. A new field handler is made available, so this can also be used in area (header/footer/empty) handlers as well as rows.
>
> This view handler can accept arguments from fields of the parent view using tokens and pass them into the child view for each row. Raw or rendered token values can be used, as well as static values.

OR

You can even create two displays in a view - one is **Page** and the other is **Attachment**.
For your case, view-2 would be **Page** and view-1 would be **Attachment**.

You can select various settings in the attachment view such as Attach to, Contextual filter, etc.

Check this answer about an attachment view. I had a book Drupal 6 Attachment Views, but could not find a book for D7.

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


# Question
Title: How to update a field programmatically and keep the fields format and array structure?
I'm trying to update a field with the format full\_html. But when I'm updating the field, all the html tags will disappear and the old text is still there in the safe\_value. So how can I update the the text in field and keep the existing structure and the html-tags?

I have tried this:

```
$node = $node_load($my_node_id);
$node->body['und'][0]['value'] = 'My new text.';

```

My field before editing

```
[body] => Array
    (
        [und] => Array
            (
                [0] => Array
                    (
                        [value] => <p>My old text.</p>
                        [summary] =>
                        [format] => full_html
                        [safe_value] => <p>My old text.</p>

                        [safe_summary] =>
                    )

            )

    )

```

My field after editing

```
[body] => Array
    (
        [und] => Array
            (
                [0] => Array
                    (
                        [value] => My new text. //All the html-tags are removed
                        [summary] =>
                        [format] => full_html
                        [safe_value] => <p>My old text.</p> //The old text is still there

                        [safe_summary] =>
                    )

            )

    )

```

# Answer
Calling `node_save()` won't automatically re-load the node so you'll need to do it manually if you want to see the computed field values:

```
$node = node_load($my_node_id);
$node->body['und'][0]['value'] = 'My new text.';

node_save($node);

// Re-load the node from the db
$node = node_load($node->nid, NULL, TRUE);

// $node->body now has the values you would expect.

```

I just tried that and can confirm I get the same behaviour as you (the safe\_value is not updated) if the call to `node_load()` is commented out.
> 1 votes

# Answer
> I want to update the body text for a node programmatically.

If you want to update the body text, probably better to do it once when the node is saved.

for example, one of the node API hooks

It will be simpler and easier to update there.
> 0 votes

---
Tags: 7, nodes
---


# Question
Title: Alert after form radio has been selected
I am trying to use drupal ajax to test if an email address from the form it is in my database. For that i have altered the form and added the following line to the element:

```
   $form['field_radio']['#ajax'] = array
    (
       'callback' => '_get_member',
       'progress' => array('type' => 'throbber', 'message' => '')
    );

```

and the callback function:

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

     $sid = $form_state['values']['details']['sid'];
    $commands[] = ajax_command_alert("Hello World");

    return array(
    'type' => 'ajax',
    'commands' => $commands
  );
}

```

As you can see from the callback i just want to return an alert message but it does not work. The callback is called because i have tested using watchdog but the alert popup never fires. Why ?

# Answer
'wrapper' is a required key for `#ajax` on form elements, you're probably just missing that. From the docs

> This property is required for using AJAX requests in on a form element

If you add the wrapper it should work:

```
$form['field_radio']['#ajax'] = array (
   'callback' => '_get_member',
   'progress' => array('type' => 'throbber', 'message' => ''),
   'wrapper' => 'some-element-id'
);

```
> 0 votes

---
Tags: forms, ajax, routes
---


# Question
Title: Create a log when user join/abandoned in a og group in Drupal 7
I'm creating a log with several actions in drupal.

I need register in a custom log when a user requests to join a group. Then I need register that the user has joined in the group or has abandoned this.

Appreciate any guidance to investigate. Thanks :)

# Answer
Heartbeat module is the one to try.

I didn't tested it myself, but I read in its description that it's "an API to log activity".

It seems to support OG activity.
> 1 votes

---
Tags: hooks, organic-groups, log-messages
---


title: Role specific dashboard block

text:
# Question
Title: Role specific dashboard block
I created a set of Views based blocks which will be displayed in the Dashboard's Main Content Region.But those all of them are not for the site admins. Some of them are for other roles. So I have configured those blocks' visibility settings. Added those specific roles to the "Show block for specific roles" tab. But the problem is those are being displayed in the admin dashboard as well but with no content, actually it says "empty".

Is there any way to get rid of this?

A possible duplicate but no answers in that post as well. Dashboard - empty blocks are shown

# Answer
> 1 votes
One way to hide the blocks completely without doing any coding is to set up your own custom dashboard using the Panels module. With Panels, you can override pages (such as the admin dashboard) and then add the blocks using Panels. The advantage of this approach is that you can use the **Visibility conditions** feature of Panels to only show the block for certain roles, which will completely hide the block rather than showing an empty version.

The disadvantage of this approach is that this might be overkill if this is all you need to do.

---
Tags: 7, views, blocks, dashboard
---


title: Update Computed field with hook_cron

text:
# Question
Title: Update Computed field with hook_cron
I have a field age in profile of my Drupal Instant which computes age from the D.O.B of the user. How do I make sure the age is updated along with cron job. Is there any way to trigger.

Right now I believe it will only update when the profile is saved.

# Answer
From your question, by hook\_cron() this can be done. You can use a watchdog() function to make sure that the cron was run. The computed field has a table entry in the database, so you just need to find out that one and check each user's birthday from a DOB field stored in another table based on UID. Then if the user has updated the DOB then check for their ages and insert/update the value in the "field\_age" computed field. All of the operation can take place in hook\_cron() which will be invoked by cron.php each time the page is fired in crontab.
> 2 votes

# Answer
I would rather implement hook\_node\_load(), and check if the age field needs updating.

If it needs updating, save the node and reload the node. (I believe that calculated field would be updated when saving)

If you update the age field with cron, then a wrong value could be displayed, if cron hasn't run yet and it's user's birthday.
> 1 votes

---
Tags: 7, cron, entities
---


title: Search API Users filter on roles?

text:
# Question
Title: Search API Users filter on roles?
While I can filter on content types in Workflow / Data Alterations I do not see anything for roles when adding users. Is it somewhere else or is it something needs to be developed? If the latter, where can I find some pointers, examples on how?

# Answer
> 2 votes
At least from my point of view the API of search api is pretty good documented in the .api.php file. There is a plugin type called "callback" which allows you to filter out stuff with configuration. This and the callback\_bundle\_filter.inc should give you enough to provide a patch :)

**And don't forget to add your include file in the .info file**

---
Tags: 7, search
---


title: Radios button in form arrays

text:
# Question
Title: Radios button in form arrays
How can i check which radio button has been checked from a list of radio buttons ? Is there any key in the form array which holds the checked radio ?

I am using an ajax call for a bunch of radios buttons and i would like to do some "checking" only if the right radio button was selected.

As an alternative , how can i append the "#ajax" parameter to only one radio button in a list of radio buttons ?

# Answer
> 1 votes
You can check the element's value in `$form_state['values']`. Add the full parameter list ($form, &$form\_state) to the form builder function.

For example: `function mymodule_something_form($form, &$form_state) {`

---
Tags: forms
---


title: Create a route for AJAX requests

text:
# Question
Title: Create a route for AJAX requests
How should I implement a callback to a single Drupal class (in my case it's Transliteration). I don't need a full Drupal load/bootstrap, but one independent class.

The purpose of the AJAX code would be the following:

* User inputs 'áéíóű'
* The input is sent via AJAX
* The `Transliteration` class changes the input to 'aeiou'
* The result is returned to the client

I've found this related issue, but it would be nice to have a simple example (and documentation) for it.

# Answer
> 7 votes
> How should I implement a callback to a single Drupal class (in my case it's Transliteration). I don't need a full Drupal load/bootstrap just one independent class.

Taken literally, within the confines of Drupal, I don't believe you can. We rely on PSR-0 for class loading, so at the very least you *must* bootstrap Drupal to get the class loader running. (Though not necessarily a *full* bootstrap).

To truly *just* load a single class, you'd need a to call a different file than index.php where you'd hard code the class loading.

I haven't looked at how Ajax requests specifically have changed from D7 =\> D8, but thanks to D8's DI, only classes that are used in a single request will be instantiated, so the need to try to speed optimize things out, as you seem to want to do, should be lessened.

# Answer
> 1 votes
As far as for avoiding to fully bootstrap Drupal to use a callback implemented in a class, I think the answer is not different from the one you would get for Drupal 7: Boostrap Drupal using a custom PHP file.

The fact Drupal is not using anymore the cron.php file that is used in Drupal 7 leads me to think that fully bootstrapping Drupal is not a performance issue.
It is true that Drupal 8 still has its authorize.php, but that is necessary for a specific case which is not a case most of the modules would need to handle.

If you really need to do it, consider the differences that there are between the index.php file used from Drupal 7, and the same file used by Drupal 8.
Keep also in mind that, in Drupal 8, AJAX responses are handled with the AjaxResponse class, and soon the form system will be converted to use the new AJAX API.

---
Tags: ajax, 8
---


# Question
Title: How to run custom function after clicking next on a multi page webform
I've created a multi page webform and I want to run a function after the user clicks the 'Next page' button on the first page only. After the user fills in the data on the first page, I want to grab that data and do stuff with it. After that the webform should work like normal on through the submission process.

How can I do this so that the function runs only once? I've tried using hook\_form\_alter and testing the value of $form\['details'\]\['page\_num'\]\['#value'\]. This value is 2 if I'm on the second page. For some reason the function fires twice and I can't figure out why.

Thanks

# Answer
One way to accomplish this task, because the webform module is so complex, is to just use jQuery and attach to that button and node id and run an AJAX query or whatever else you want to do like redirect the user away and then back.

Otherwise you would probably be neck deep in a custom module that extends Webform. In my experience to alter webform modules becomes a major pain and I generally just go another route.
> 0 votes

# Answer
1. Add a custom submit handler
2. Call it in your submit handler.
> 0 votes

---
Tags: 7, webforms
---


title: Building a simple webservice

text:
# Question
Title: Building a simple webservice
I need to build a simple JSON webservice for an iPhone application and i would like to give drupal a go :)

Here is the content structure i need, admins should be able to create a Newsletter a news letter should contain (title, description, categories) and then it should be possible to create "news sections" each section should contain (title, text, image) so a section is a group of content and it should be possible to create multiple sections in a newsletter.

First question: how would you structure the above content ? i tried two ways of doing it

1. created two content types "Newsletter" and "News section" and inside the News section i created a entity\_reference to the parent newsletter. works fine, but its not so nice for the admins as they cant really get a overview of what their newsletter is when editing because the content is separated into multiple nodes. also the admins cant sort them.
2. created a single Newsletter and added the module "field\_collection\_item" where i setup the "section" fields. This works quite well since it gives the admin a nice way of getting an overview of all the content of the newsletter. But to be honest it looks very messy the admin interface. And i feel like this is a "wrong way of doing it"

When structure is sorted i would like to expose the data as JSON, i found the Services module which seemed perfect. But i have alot of problems exposing the related data, for example if i like to expose a newsletter i would like that all the related news sections is included in the export, but only the id's are exported, i tried alot with Views etc. but cant get it to work properly so i ended up writting a custom hook which looks up the related content. Again i feel like im missing a better way of doing things.

Im very new to drupal so im hoping to get a bit of feedback on how i could build this very simple service in a nice and clean way that makes in intuitive for the admins to administrate the newsletters.

# Answer
> 0 votes
I made a content type Newsletters, You could remove the Body field if you want form the Node. I then used Panelizer with nodes to make newsletter like layouts. The content for the node is actually ctools based custom data.

I also made use of a custom `html--newsletters.tpl.php` file to remove site themeing from the newsletter and apply generic newsletter themeing for the site.

If you got this much working:

* custom content type (title, optional body)
* Panelizer enabled, pick a layout (or layouts)
    + enable node\_panelizer.
* un-embed newsletter from site with custom html.tpl.php for the content type (optional)

Then I would make a `hook_menu` entry for your json service. Just do a `node_load` on the newsletter node and inspect `$page['content']` for your nodes layout and "sections". Just build a json array out of how your page is setup in the page render arrays.

---
Tags: nodes
---


# Question
Title: How to include jquery from URL in custom module?
I've got a question about module building and including JS. I'm working on a D6 custom module, and for JS files I'm including from within my mod drupal\_add\_js(drupal\_get\_path('module', 'ingsavingsmap') .'/js/effects.js');
works just fine.

The question I have is: I'm trying to include jquery from the jquery site. I know: drupal\_add\_js(drupal\_get\_path('module', 'ingsavingsmap') .'http://code.jquery.com/jquery- latest.js');

is very wrong for a number of reasons, but I don't know how to go about adding JS from a URL. Also, is it advisable to event be doing it this way? or should I just keep it all within the mod.

Any help or direction to documentation would be appreciate Thanks! Steph

# Answer
> 1 votes
**D7**

For those who need to do this in D7, its as simple as

```
drupal_add_js('http://example.com/example.js', 'external');

```

**D6**

I can not take credit for this example but found this to be rather nice and easy way of dealing with external js files.

```
$external_js = 'http://www.example.com/a.js';
drupal_add_js('document.write(unescape("%3Cscript src=\''. $external_js . '\' type=\'text/javascript\'%3E%3C/script%3E"));', 'inline');

```

Found this via http://www.wootenswebdesign.com/load-external-js-file-drupal-6

---
Tags: 6, javascript
---


# Question
Title: TinyMCE image float, automatic set margin
I'm using TinyMCE as WYSIWYG editor. When I set the floating of an image to "left" or "right", I want to set a right- of left-margin with CSS automatically. So the images has only a gap between img and text.

When I just add a margin to the IMG, there's a at all sides...

# Answer
If the `styles` WYSIWYG button shows `image right` or `image left` try applying that and save your edit. If that applies ok you can use Firebug to see the CSS class it adds to the image and just alter the css rules to your needs.

Or else, you can supply your own css styles to a wysiwyg profile. They are typically of the form:

`wysiwyg_option_name=css_class_name`

for example:

`ImageRight=img-right`

you then make an image right class in your themes css file:

`.img-right { padding: 0 0 5px 5px; }`

I believe both TinyMCE and/or the WYSIWYG module both support these features.
> 1 votes

---
Tags: 7, theming, wysiwyg
---


# Question
Title: Hide Profile2 fields depending on it's value when viewing user profile
I am relatively new to drupal and for days I'm stuck.

I need to hide fields from the user profile page when they have a specific value. Adding a CSS class would also do it. But I prefer deleting the array element.

I try to use the `hook_profile2_view_alter()` function in my template php. Sure I can access the field options but not it's value directly.

Perhaps I'm digging in the wrong hole and there is a smooth "Drupal way" to do it.

# Answer
> 1 votes
You'd be better off putting your code in a custom module, as you can implement `hook_profile2_view()` instead. That will give you far more control over the output.

Without more specifics it's hard to be accurate but generally speaking the code would look something like this:

```
function MYMODULE_profile2_view($profile, $view_mode, $langcode) {
  $field_items = field_get_items('profile2', $profile, 'field_name_of_field');
  if ($field_items) {
    $value = $field_items[0]['value'];

    if ($value == 'something') {
      $profile->content['field_name_of_field']['#access'] = FALSE;
    }
  }
}

```

---
Tags: entities, users
---


# Question
Title: Why is jQuery UI toggle not working in my theme?
I've tried setting up a jQuery toggle menu without much success. I followed the exact instructions and code from this tutorial, but even this simple script is not working.

Regular JS (like an alert) seems to work fine. I have Views installed and it seems the views admin uses extensive jQuery and works fine. Is there something I have to do to enable jQuery on my theme?

# Answer
jQuery is added by Drupal core and is available globally.

Clear cache at Admin \> Config \> Performance

Check your script.js has been added to the html source.
> 2 votes

---
Tags: javascript
---


# Question
Title: cannot login after theme change or backup/restore
I am using Drupal 7, with VMware 5.0.1 build-894247 with Ubuntu 12.10. 2GB ram, 20GB disk, 32 bit VM, hosted by Windows 7 Enterprise.

I am developing on a team with SVN (subversion) as the source control. All of this works fine on everyone else's (on my team) local dev environment and on our staging/prod servers.

I set up a shared folder from my C: drive on Windows called Sites (`C:\Sites`), and it appeared as `/mnt/hgfs/Sites` on Linux.

My dev folder is under that, so `/mnt/hgfs/Sites/test.dev`

I configured Apache sites-available to point to this new path, and enabled it. I setup the mysql database fresh, and ran through the default install of Drupal. No problems so far. At this point I can log in and out without issue.

When I make a change like importing a theme and setting the theme, then log out, I can no longer log in. The login screen will not even tell me why I am not being logged in (normally there is an error message... it is as if someone disabled java-script or something). If I blow away the database and recreate it, start over with the default install, it works again. My real goal is to enable a backup and restore that to the new site, but that changes the theme and more, and has the same problem (although the theme does change and content is there when I do this... just can't log in)

~~another kicker, if I move the files back to `/var/www/` and re-point apache, it works again.~~ UPDATE: It turns out this problem does not have to do with VMware, as it is now failing in the exact same manner while in `/var/www`.

I have checked permissions and even set everything to completely unrestricted access (`chmod 777 -R`).

Any ideas why? This seems very reminiscent of this other post too...

UPDATE: after hours of diagnosis, discovering drush, and playing with variables, my buddy noticed this: If we switch the theme back to Bartik, and login from login, it will fail without even showing an error message. BUT, if we just go to the home page, there is a login block on the left, and if we login there, **it works!** The top nav bar comes back and everything. Log out and try again from `http://sitename/users`, and it fails again. He thinks it may be a modules or theme-based permissions issue.

# Answer
> 1 votes
Wow, so thanks to an experienced Drupal admin, we discovered the issue was in the Apache setup I have. I never enabled mod-rewrite.

The commands to fix this were

`sudo a2enmod rewrite`

followed by:

`sudo service Apache2 reload`

`sudo service Apache2 restart`.

More details:

There is a helpful test for clean URLs in Drupal 7 under `<site name>/admin/config/search/clean-urls`. This definitively told me that was the problem, then we went back through and tested each required component in my Ubuntu/Apache setup. If you still have issues, check the `.htaccess` file for configuration and the `/etc/apache2/mods-available` and `/etc/apache2/sites-available`. A link that helped me do this was this one: http://www.lavluda.com/2007/07/15/how-to-enable-mod\_rewrite-in-apache22-debian/

# Answer
> 1 votes
Try the following:

1. check the existence of .htaccess file in Drupal root
2. truncate the cache tables in the database
3. check and eventually increase the PHP memory limit in /etc/php5/cli/php.ini
4. Read and check some other trouble shooting ideas at http://drupal.org/node/158043

---
Tags: 7, users
---


# Question
Title: Which type of entity should I use for editable homepage content?
I have a set of social media links that I want to display in both the header and the footer, but I don't know where to put this content so that it is easily editable by users.

Right now I am using Panels and Views, but the links would be in the page.tpl.php, which has the header and footer areas.

I am thinking I could make a block, but it looks like you need to know the ID of a block to render it.

Is there a way to add a node, block, content pane, or mini panel and render it inside page.tpl.php?

# Answer
Sure, there are modules that let you setup "blocks" of service badge/icon widgets for like Twitter, FB, YT, etc.

Look at Widgets, Social Media and Service Links modules.

I've used Social Media (which relies on Widgets) to put a block of badges on most pages via Context. And also to create other badge collection `tokens` that i've used within Footer blocks and embedded into WYSIWYG entries to show a FB link on the homepage for instance, or a mini-block of service links on a newsletter.
> 1 votes

---
Tags: 7, views, blocks, theming, panels
---


title: How to disable required fields in form?

text:
# Question
Title: How to disable required fields in form?
I am building a multi-step form. For one of the steps, I have some required fields. When the user goes back, I'm skipping the validation, but it gets hung up on my required fields. Is there a way to disable or ignore my required fields so my user can go back a step?

# Answer
Yes, you can use

#limit\_validation\_errors

> Used by: button, image\_button, submit
>
> Description: Provides an array of sections which are parts of `$form_state['values']` which should be validated, implying that sections which are not listed should not be validated.
>
> This is normally used in multistep forms in the case of a "back" button, for example, where `'#limit_validation_errors' => array()` would mean not to validate anything as form values on the current page are to be discarded anyway.
>
> `#limit_validation_errors` does not have any effect if `#submit` is not set. More discussion is in the form\_set\_error() documentation.
>
> Values: array indicating sections of the `$form_state['values']` which should be validated.
> 1 votes

---
Tags: 7, forms
---


# Question
Title: Filter the users name in the list of admin / people of organic groups Drupal 7
I have a lot of users in several organic groups, I need filter the users by username to acept or deny join to group.

Generic url group page: `group/node/[nid]/admin/people`

I appreciate any guidance to filter users (contributed module, hook\_form\_alter...) or disable pagination in this page.

Thanks :)

# Answer
You can see `admin/structure/views/view/og_members_admin/edit/default`

In og 7.x-2.0-rc1 exists this functionality
> 0 votes

---
Tags: organic-groups, forms
---


# Question
Title: Adding a theme suggestion programatically
I created a feature module containing only a view and a content type.

Right now my `page-node-x.tpl.php` and my `views-view-y.tpl.php` files lie in my themes directory.

Is it possible to move them into my feature module?

# Answer
I started with the answer of googletorp and built a generic function:

```
/**
 * Overrides a third-party template file with a local copy.
 *
 * To be called from hook_theme_registry_alter():
 * @code
 * function mymodule_theme_registry_alter(&$theme_registry) {
 *   // Override variant of foo template using local copy.
 *   custom_override_template($theme_registry, 'foo--variant', drupal_get_path('module', 'mymodule') . '/templates');
 * }
 * @endcode
 *
 * @param array $theme_registry
 *   Theme registry array as passed to hook_theme_registry_alter().
 * @param string $template
 *   Name of template file without '.tpl.php' extension. Example: 'foo--variant'.
 * @param string $path
 *   Directory to load $template from.
 * @param string $preprocess_function
 *   Optional preprocess function.
 */
function custom_override_template(&$theme_registry, $template, $path, $preprocess_function = NULL) {
  if (strpos($template, '--') !== FALSE) {
    $hook_name = array_shift(explode('--', $template));
  }
  else {
    $hook_name = $template;
  }
  $hook_name = str_replace('-', '_', $hook_name);
  if (isset($theme_registry[$hook_name])) {
    // Copy hook info.
    $hook_info = $theme_registry[$hook_name];
    $hook_info['path'] = $path;
    $hook_info['template'] = $template;
    // Add to theme registry.
    $new_hook = str_replace('-', '_', $template);
    $theme_registry[$new_hook] = $hook_info;
    // Add preprocess function.
    if(!is_null($preprocess_function)){
      $theme_registry[$new_hook]['preprocess functions'][] = $preprocess_function;
    }
    return $new_hook;
  }
  else {
    throw new Exception(t('Unknown theme hook %hook.', array('%hook' => $hook_name)));
  }
}

```

It allows not only to overwrite the position and name of node and view tpl files but also to provide a preprocess function for views.

So if you got your own module called `mymodule` with a template file e.g `sites/all/modules/mymodule/templates/foo--variant.tpl.php` you can now easily modify the theme registry to use your own template directory:

```
function mymodule_theme_registry_alter(&$theme_registry) {
   // Override variant of foo template using local copy.
   custom_override_template($theme_registry, 'foo--variant', drupal_get_path('module', 'mymodule') . '/templates');
}

```
> 1 votes

# Answer
A module that implements `hook_preprocess_page()` or `hook_preprocess_node()` can suggest new template files by altering the variable `$variables['theme_hook_suggestions']`.

The code contained in template\_preprocess\_page() that initialize that variable is the following.

```
// Populate the page template suggestions.
if ($suggestions = theme_get_suggestions(arg(), 'page')) {
  $variables['theme_hook_suggestions'] = $suggestions;
}

```

Each theme suggestion needs to match with an entry returned by hook\_theme().

In Views, there should be an equivalent preprocess function to use in the similar way, or a way that allows to `hook_preprocess_page()` that allows to the function to understand if the page is associated with a view.
> 5 votes

# Answer
The solution to add the 'template file' key to `hook_views_api()` does not appear to work in Drupal 7 yet. However, this works like a charm:

```
/**
 * Implements hook_theme().
 */
function bigtexas_theme() {
  return array(
    'views_view_fields__slideshow' => array(
    'variables' => array('view' => NULL, 'options' => NULL, 'row' => NULL),
    'template' => 'views-view-fields--slideshow',
    'base hook' => 'views_view_fields',
    'path' => drupal_get_path('module', 'bigtexas') . '/theme',
  ),
 );
}

```
> 3 votes

# Answer
The theme registry is where Drupal stores all sorts of info about what template files, theme functions etc to use. Messing with it can lead to WTF moments later on, as things will not work like default.

Anyways like all things drupal, there is a hook: `hook_theme_registry_alter` you can use to alter the theme registry and this move your template files into a module. I wouldn't advise doing this, as it will make maintaining the site more complex. But if you want to do is, this is how it's done.
> 2 votes

# Answer
For views there is in theory a mechanism for views templates(perhaps it works for all templates).

You can set the key "template path" in your hook\_views\_api implementation of your custom module.

Once you have this views will scan your specified directory for template files. Sadly the simpletest currently fails, so this feature is probably not ported yet to drupal7, but if someone wants to get into it, see \_views\_find\_module\_templates() in views.module.
> 2 votes

# Answer
The easiest way is to use `hook_theme_registry_alter()` and just add the path of your module to the theme paths:

```
function mymodule_theme_registry_alter(&$theme_registry) {
  $theme_registry['[theme hook name, ie. page or views-view]']['theme paths'][] = drupal_get_path('module', 'mymodule');
}

```
> 2 votes

# Answer
How about a slightly abstracted approach with Context Reaction Theme?

http://drupal.org/project/context\_reaction\_theme

Wrap up your context in Features and it's even exportable. But maybe this is actually a Drupal guru question looking to create something deeper and know the route.
> 1 votes

# Answer
As @jcsio said, the accepted answer on this page works, but the template cannot be overridden by a theme.

http://www.metachunk.com/blog/adding-module-path-drupal-7-theme-registry offers a solution that allows you to add the path of your module (and sub-folders) to be scanned for all kinds of .tpl.php files.

I slightly changed it, since it contained a 'theme paths' variable that seems not used by Drupal 7.

```
/**
 * Implements hook_theme_registry_alter()
**/
function mymodule_theme_registry_alter(&$theme_registry) {
  $mod_path = drupal_get_path('module', 'mymodule');
  $theme_registry_copy = $theme_registry;       // munge on a copy
  _theme_process_registry($theme_registry_copy, 'phptemplate', 'theme_engine', 'pow', $mod_path);
  $theme_registry += array_diff_key($theme_registry_copy, $theme_registry);
}

```

I tried both the accepted answer and this solution, the latter works for me so far!
> 1 votes

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


title: How do I set a multilingual site name?

text:
# Question
Title: How do I set a multilingual site name?
I'm using a multiligual site in french,english and arabic and i want to set a custom sitename (or logo) for each one,for ex: if my sitename for english is : "one two three" i want it "un deux trois" for frensh version .
Is there anyway to fix that?
Thank you very much

# Answer
> 1 votes
**i18n** http://drupal.org/project/i18n provides "Multilingual variables"

As the `site_name` is a config variable, presumably it can be translated.

See also: http://drupal.org/node/313272

**settings.php**

```
/**
 * Multilingual settings
 *
 * This is a collection of variables that can be set up for each language when i18n is enabled.
 * These are the basic ones for Drupal core, but you can add your own here.
 */
$conf['i18n_variables'] = array(
  // Site name, slogan, mission, etc..
  'site_name',
  'site_slogan',
  'site_mission',
  'site_footer',
  // Different front page for each language
  'site_frontpage',
);

```

---
Tags: i18n-l10n
---


title: hook_library not getting called

text:
# Question
Title: hook_library not getting called
I am trying to implement hook\_library in my custom module. To help narrow down the problem, I wrote a dummy module with just the following two functions: hook\_views\_api and hook\_library. I put a dsm statement in each of the hooks, to test whether the hook was getting executed. The hook\_views\_api hook is getting executed but not the hook\_library hook. Anyone see what I am doing wrong?

I have tried clearing the cache. I have tried uninstalling and reinstalling the module.

Here is the code:

```
// hook_views_api
function mymodule_views_api() {
  $path = drupal_get_path('module', 'mymodule') . '/views';
  dsm ("inside mymodule_views_api");
  return array(
    'api' => 2,
    'path' => drupal_get_path('module', 'mymodule') . '/views',
  );
}

// hook_library
function mymodule_library(){
  dsm ("inside mymodule_library");
  return array();
}

```

# Answer
> 1 votes
The only function that invokes `hook_library()` is drupal\_get\_library(), which is then called by drupal\_add\_library(), the function that modules call to add a library during a page request. Until one of those functions is not called, `hook_library()` is not invoked.

---
Tags: 7, hooks, javascript
---


# Question
Title: Upgrade drupal using drush: Failed to check available update
I am trying to upgrade Drupal from 7.14 to 7.18 using `drush up` command.

Nothing gets updated and I see a bunch of failed warnings:

```
Failed to check available update data for CCK.
Failed to check available update data for CKEditor.
...
Failed to get available update data for 51 projects.

```

I can however download modules using `drush dl module_name` All commands are run as root.

# Answer
As tenken suggested, you might try adding `-d` for debug to your drush command or `-v` for verbose.

Beyond that, I suggest trying to set $conf\['update\_max\_fetch\_time'\] to a higher value (I usually set it to 360). It sounds like you may be running into an issue where fetching the update information is exceeding the timeout.
> 2 votes

---
Tags: 7, drush, upgrading
---


# Question
Title: User gets first x units of a product free, then has to pay per unit thereafter
I am wondering if anyone can point me in the right direction. There is only a single product type on my site, however I want every user to get 1000 "point" credit every month. They can buy 1 product for each credit.

I am assuming some kind of checkout system is also necessary, but the payments only have to be through paypal or something similar.

any suggestions?

# Answer
You will probably want to look at the *Userpoints API* (http://drupal.org/documentation/modules/userpoints) and possibly utilized *Rules* in conjunction with an eCommerce solution like *UberCart*.

Or, if you don't need to actually take payment in money at all, there is a Userpoints Contrib module for facilitating points in conjunction with downloads.

*userpoints-download* Users lose or gain points when the download attachments (requires site to be configured with private download method).
> 1 votes

---
Tags: 7, commerce
---


# Question
Title: Is there anything like attached data storage for a view?
I'm having hard time using Views with i18n Views. What gets me very irritated is that the translations of global fields (headers, footers, etc.) get lost whenever I make changes to that View. I would feel more comfortable if I could somehow permanently attach to a view some custom data, variables, i18n string arrays, and use them both in Views UI and tpl files.

I would imagine to declare a variable named `%my_footer` and provide its translations in a module. Then, in a footer I imagine being able to enter something like `<h3>This is %my_footer</h3>` or call in a tpl file by saying something like \` and have it rendered in the current translation.

The only thing I would hate to compromise on (as instructed by many users here) is to use PHP code in Views UI text fields.

So, is my scenario possible? I just love to have a single data source...

# Answer
If you're comfortable in code, you can do that with Panels and ctools contexts.
> 0 votes

---
Tags: views, i18n-l10n
---


# Question
Title: how to add fields for drupal registration form internally souce code of drupal7.17 application
generally all you are editing template in this location files `C:\wamp\www\drupal\themes\bartik\template.php` i think so ... so please guide me how to create customise registration form step by step in this folder like adding fields like

* first name:-
* last name:-
* date of birth:-
* email:-
* user name:-
* password:-
* confirm password:-
* location:-
* referer:-

{not graphically using wampserver opening site and login go to configuration/managefields}. show me code method where we insert source code

example:-like using other applications home.html,about us.html,form.html,contact.html

we are interlinking these pages.. generally we insert username password field in first page if the user is not register we will add one more option signup ,when user click signup it will display registartion form like this i want to create ....how it is possible and also show database connectivity in dos command base by using my sql software application

not in wamp server application ....create database

please any one suggest me step by step using bartik theme.... or others.

thank you in advance & sorry for bad english

# Answer
To add the fields to user profile you should use Profile2 module.

* With profile2 user account settings and user profiles are conceptually different things, e.g. with the "Profile pages" module enabled users get two separate menu links "My account" and "My profile".
* Profile2 allows for creating multiple profile types, which may be assigned to roles via permissions (e.g. a general profile + a customer profile)
* Profile2 supports private profile fields, which are only shown to the user owning the profile and to administrators.
> 1 votes

---
Tags: forms, users
---


# Question
Title: $scripts variable in drupal 6 adding unwanted script codes
From where does the $scripts variable in drupal gets generated? I am getting an unwanted code generated in the html code like this

```
 <script type="text/javascript" src="/js/js_01770598d5388f7cbcfe786a6df4ef2a.js"></script>

```

I want to remove that code, for that I need to know the details about $scripts varialble used in tpl file

# Answer
You should start at `template_preprocess_node()` where the `$scripts` variable is initialised:

```
$variables['scripts'] = drupal_get_js();

```

Then have a look at `drupal_get_js()` and follow the functions from there to find out how that mechanism works.

Then have a look at any implementations of `hook_page_alter()` throughout your site, where the `$vars['scripts']` variable might be being manipulated.

Even though that technically answers your question, I'd be surprised if you find what you're looking for there. I've never heard of any malware that specifically targets Drupal (which is what this would be if it's manipulating the `$scripts` variable).

I'd check the rest of your page source to see if there's some JS being injected somewhere which is adding that `<script>` tag to the `<head>` dynamically, just in case.
> 2 votes

---
Tags: theming, javascript
---


title: One time Editing Of Profile page

text:
# Question
Title: One time Editing Of Profile page
I am using drupal 7 with profile2 module, Created a profile type which is not filled up by user at registration time. after a user register they have a option to fill up the page . I need a way to restrict user from editing that custom profile page only if they have already submitted the information. Does anyone know how to accomplish this ?

thanks

# Answer
> 1 votes
You can use Field Permissions for this.

> The Field Permissions module allows site administrators to set field-level permissions to edit, view and create fields on any entity.

Just set up the fields on the Profile page so that only authenticated users can fill them in. This will mean that when the anonymous user is registering they won't see the fields, however when they are registered (and therefore authenticated) they *can* edit them.

# Answer
> 0 votes
In ther permissions table there is an option calles 'edit own xxx profile'; ensure this is not checked and check the option for 'create own xxx profile'. This means they can initially create the profile content but would be unable to further edit.

# Answer
> 0 votes
I would do a hook\_form\_alter for the "user\_profile\_form". Then check all the fields if they are filled out and if they are show a message and hide the form fields.

---
Tags: 7, users
---


# Question
Title: Will manually setting the expire timestamp in the boost_cache table actually expire the cache for a node?
I am trying to get myself acquainted with Boost running on my Drupal 6 website. I know that boost has a boost\_cache table where it stores the expires value for each node.

Now I want to know whether that if I set the value in the expire column manually to a preferred value, Boost will recognize it and expire the cached version of the node on the date in the timestamp and there **is no other table related to Boost caching where I should make the changes**.

# Answer
You might prefer to use

boost\_expire\_node

which will actively flush the node from boost static html cache

It could be scheduled, if needed ( e.g a hook\_cron\_queue\_info implementation worker callback ) or done as an immediate expiry
> 0 votes

---
Tags: 6, database, caching
---


title: Create MySQL View in hook_schema()

text:
# Question
Title: Create MySQL View in hook_schema()
I want to create a MySQL View in `hook_schema()` for a module I am developing.

Does anyone know how to do that?

# Answer
I already know how to resolve this issue.

In the .install file instead of trying to create a View in the hook\_schema in hook\_install you can just use de db\_query and create the view. Don't forget in the hook\_uninstall to drop the created View.

With my researches i found that is impossible to create a view directly in hook\_schema like you do in a table, but if someone knows how to that please share.

Hope this help someone out there.

EDIT: Thanks for the correction kiamlaluno
> 3 votes

---
Tags: database
---


# Question
Title: Related nodes displaying same related data
drupal 7, using views and eva.

So i have restaurant nodes and menu nodes, and all menus nodes relate to a restaurant node, now i have a duplicate restaurant node which is just showing an alternative location for the same franchise, how can i reference the menu nodes related to the first restaurant node into the 2nd duplicate one? (which has a seperate nid)

So end result i am looking for, is if node-rest1 is called, it displays the node-rest1 output, followed by the related nodes (currently using eva), and if i open node-rest2 it shows node-rest2 output followed by the related menu nodes from node-rest1.

is this possible and if so how?

# Answer
> 0 votes
The duplicate node with different locations is in question. I would do it using the Location module which can add multiple locations to a single node.

> Location Add Another: Allows you to quickly add new locations to a node.

In your case, you can even add many locations to a restaurant node without creating duplicates. The menus nodes can be entity reference to each restaurant node.

---
Tags: nodes, entities
---


# Question
Title: A question about views and how to let sub menus link to the view like the main menu
I created a view, like products. The path is /products, and the normal menu item is products and I have a vocabulary with the name products.

The vocabulary's terms list:

> ```
> product-a
> product-b
> product-c
>
> ```

I used the module "taxonomy menu" to link the taxonomy to the path /products

My question is: when I browse /products, the page of products views will appear,

```
 <div class="view view-product view-id-product view-display-id-page view-dom-id-fed2ac877a09718419f677c2a601e561" data-thmr="thmr_1">

```

---

but when I click product-a, or product-b or product-c, they do not link to products views.

```
<div id="node-6" class="node node-product node-promoted node-teaser clearfix" data-thmr="thmr_58">

```

How can I get products views when I click on a sub menu item?

# Answer
By default a link will be created to the full node view, as you described. When you want an item to link to another url, you need to rewrite the url.

To do so go to the view settings page and click on the field you want the link to be different of. Next go to the 'rewrite results' part of the settings schreen. check 'display field as link' and enter the correct url in the 'path' field.

Hope this helps
> 0 votes

---
Tags: views, routes
---


# Question
Title: how to fetch result into array or how to fetch 'nid' out of result?
Good day to everyone!

some help needed with fetching result out of EntityFieldQuery. Have a unique value of the field. I try to get 'nid' of node by value of the field with help of EntityFieldQuery. my problem is that i dont know how to fetch result in a right way to get just 'nid'. then knowing nid i will be able to load the node and do some work with it.

```
$query = new EntityFieldQuery;
$entities = $query->entityCondition('entity_type', 'node')
->entityCondition('bundle', 'order')
->fieldCondition('field_reference_number', 'value', $titleref)
->execute();
$result= $query->execute();
drupal_set_message('nid: ' .print_r($result, true));

```

my result is:

```
nid: Array ( [node] => Array ( [2250] => stdClass Object ( [nid] => 2250 [vid] => 2252 [type] => order ) ) )

```

how to fetch it corectly to get 'nid' out of it?

Thanks for your time

# Answer
> 2 votes
The simplest way would be:

```
$result = $query->execute();

if (!empty($results['node'])) {
  $nids = array_keys($results['node']);
}

```

There are a few different ways to get the first nid out of the array if that's what you need; personally I prefer `reset()` as it's non-destructive to the original array (unlike `array_shift()` for example).

```
$first_nid = reset($nids);

```

If you then need the node objects you can pass that array straight to `node_load_multiple()`:

```
$nodes = node_load_multiple($nids);

```

---
Tags: database
---


# Question
Title: Drupal API to check a particular user is logged-in, or not
Is there an Drupal API to check whether a user is currently logged in or not, based on the user ID, such as `is_user_login($uid)`?

# Answer
> 4 votes
No, there is no function like `is_user_login($uid)`, but you can see how the core block "Who's online" is created (source).
Drupal has a "sessions" table, where all current sessions are stored.

# Answer
> 0 votes
Drupal doesn't have such function, but you can use code similar to the following one.

```
function mymodule_user_logged_in($uid, $delay = 900) {
  $interval = REQUEST_TIME - $delay;
  return (boolean) db_query("SELECT COUNT(DISTINCT s.uid) FROM {sessions} s WHERE s.timestamp >= :timestamp AND s.uid = :uid", array(':timestamp' => $interval, ':uid' => $uid))->fetchField();
}

```

---
Tags: users
---


# Question
Title: latest zen theme make the admin drop menu failed to work
I am using the zen 7.5x, however when I tried it, the dropmenu for the admin doesn't work any more.

any one know how to solve this, is this because of javascript side?

# Answer
Is it possible you've confused the Drupal 7 "Toolbar" module (which is enabled by default on D7) with the behaviour of the familiar "Admin Menu" module?

If so, then you can get the behaviour you want by

* Install Admin Menu module
* Visit your modules page and *disable* "Toolbar", then *enable* "Admin Menu" (and if you like, "Admin Menu Toolbar"

Or, with Drush -

```
drush dl admin_menu && drush -y dis toolbar && drush -y en admin_menu_toolbar

```

(Enabling Admin Menu Toolbar style implicitly enables Admin Menu also.)
> 1 votes

---
Tags: theming
---


# Question
Title: Why block id is generating with encrypted id
When I am creating one block view using Views in drupal7 it is creating perfectly but when I am seeing the id using firebug, I am seeing ecrypted id like below.

```
block-views-f4lsdfjiodfofsdfnsdkfbb6213e4c0fece99305

```

How can I remove or override this encrypted value in the id.

# Answer
Views block deltas aren't encrypted, they just use an MD5 hash. The reasoning is thus:

> block.module has a delta length limit of 32, but our deltas can unfortunately be longer because view names can be 32 and display IDs can also be 32. So for very long deltas, change to md5 hashes.

That comes directly from the comments in `views_block_info()`, which then goes on to run this loop:

```
foreach ($keys as $delta) {
  if (strlen($delta) >= 32) {
    $hash = md5($delta);
    $hashes[$hash] = $delta;
    $items[$hash] = $items[$delta];
    unset($items[$delta]);
  }
}

```

Which, as the comments suggest, make sure that the delta is a maximum of 32 chars.

You can try implementing `hook_block_info_alter()` to implement your own naming convention (it might work, I haven't actually tried it). But the 32 char limitation imposed by the block module is set in stone at the database level so you'll have to take that into account.

If you do that you'll probably need to hook into some other parts of views as well, so that it knows how to process the new block deltas you've given.

As kiamlaluno points out in the comments, you could actually control this at a higher level by making sure that your view's name + display ID together don't exceed 32 characters.

I'm not sure exactly why you want to change this delta, but in my experience the most common reason is so that you can target a specific block with a template file.

Just in case that is your use case, this is a snippet I use in projects to level the playing field so-to-speak.

```
function MYTHEME_preprocess_block(&$vars) {
  if ($vars['block']->module == 'views') {
    // Add some template suggestions that are a little easier to manage than
    // the default dom id added by views.
    $delta = $vars['block']->delta;

    $found = FALSE;
    if (strlen($delta) == 32) {
      $hashes = variable_get('views_block_hashes', array());
      if (!empty($hashes[$delta])) {
        $delta = $hashes[$delta];
      }
    }

    list($name, $display_id) = explode('-', $delta);
    $vars['theme_hook_suggestions'][] = 'block__views__' . $name .'__' . $display_id;
  }
}

```

This will let you create a file named like `block--views--viewname--displayid`, regardless of the delta length limit imposed by the block module
> 9 votes

---
Tags: views, blocks
---


title: How to publish link programatically?

text:
# Question
Title: How to publish link programatically?
I am creating Job portal and in that job portal When I create a Job post using admin and save that job as draft instead of posting it to all and for that draft one link is get created and I want to make that job draft link to be accessible to all users including guest.

following is the code for creating draft :

```
case 'draft':
        $new_node = node_load($job_node_nid,null,true);
        $new_node->status = 0;
        node_save($new_node);
        $_SESSION['bf_job_creation'] = array('step'=>1);
        header('Location: ' . url('my-account'));
        break;

 This above code creates job draft but link to access that draft I just want to make that link to be accessible to all by writing code.

```

I have tried following code to make link accessible but not succeed :

```
case 'draft':
    $new_node = node_load($job_node_nid,null,true);
    $new_node->status = 0;
        $new_node->field_job_status = array(array('value'=>'published'));//added this
    node_save($new_node);
    $_SESSION['bf_job_creation'] = array('step'=>1);
    header('Location: ' . url('my-account'));

```

break;

how to make the link to job draft public??

# Answer
your problem is `$new_node->status = 0;` This is setting the node to 'unpublished'. either change the permissions to allow the users to see it or set `$new_node->status = 1;` To create a link use the l() function eg. `l('link text', 'node/'.$node->id);`. http://api.drupal.org/api/drupal/includes!common.inc/function/l/7
> 1 votes

---
Tags: users
---


title: Embedding content in external website

text:
# Question
Title: Embedding content in external website
I'm new to Drupal (and SE) and am looking for a way to embed Drupal 7 content in an external website. D6 had modules for that (web widget and embed widget). How can I do it in D7? Thank you!

# Answer
Web Widgets now has a Drupal 7 release, so it might be worth trying it out.
> 6 votes

# Answer
You can implement the `hook_preprocess_page()` in your theme's template.php file to unset the regions you don't need (if your don't do this it will generate a performance issue. see http://www.lullabot.com/articles/drupal-performance-tip-block-visibility) and then you can set a custom template file for the page using the `$variables['theme_hook_suggestions']` variable. This will give you the ability to show just the content region on the desired path on your Drupal site using a custom HTML structure for instance.

```
/**
 * Implements hook_preprocess_page().
 */
function mytheme_preprocess_page(&$variables) {
  $path = request_path();

  if ($path = 'the/path/you/want/to/customize') {
    unset($variables['page']['header']);
    unset($variables['page']['footer']);
    unset($variables['page']['sidebar_right']);
    $variables['theme_hook_suggestions'][] = 'page__my_custom_template_file';
  }
}

```

Then you need to create the file page--my-custom-template-file.tpl.php on your theme's templates directory to set the HTML that you need in the page.

```
<div id="custom-content-wrapper">
  <div class="custom-inner-content-div">
    <?php print drupal_render($page['content']); ?>
  </div>
</div>

```

For more info about Drupal theme files, see http://drupal.org/node/171194

After that you will just need to add an iframe tag in the place you need that content on the external website following the example:

```
<iframe src="http://mydrupalsite.com/the/url/to/the/page"></iframe>

```

For more info. about the iframe tag. See http://www.w3schools.com/tags/tag\_iframe.asp
> 2 votes

# Answer
Not sure about a Drupal 7 Module that is out yet. As an interim solution maybe PHP scrapping from your Drupal 7 Installation?

http://net.tutsplus.com/tutorials/php/html-parsing-and-screen-scraping-with-the-simple-html-dom-library/

The solution is not ideal but might help until one of the projects you posted is ported to 7/
> 1 votes

---
Tags: 7, nodes
---


# Question
Title: Creating a form that only show form fields for editing the node title, body, and any fields created using the field API
I have created a content type with some field API fields.

How can I create a edit form that allows to edit just the title, the node body, and those fields?

The normal node edit form contains extra form fields that are not necessary for my purpose (i.e. they are not for editing the parts of a node I listed).

# Answer
> 1 votes
I get you want to show a form where the users can enter the values for the fields implemented using the field API, the node body, and the title; other form fields should not be shown.

Using the following code, you can achieve what you want.

```
function mymodule_node_form($form, $form_state, $node) {
  global $user;

  if (!isset($form_state['node'])) {
    if (!isset($node->title)) {
      $node->title = NULL;
    }
    node_object_prepare($node);
    $form_state['node'] = $node;
  }
  else {
    $node = $form_state['node'];
  }

  $form['#node_edit_form'] = TRUE;

  $form['#attributes']['class'][] = 'node-form';
  if (!empty($node->type)) {
    $form['#attributes']['class'][] = 'node-' . $node->type . '-form';
  }

  foreach (array('nid', 'vid', 'uid', 'created', 'type', 'language') as $key) {
    $form[$key] = array(
      '#type' => 'value',
      '#value' => isset($node->$key) ? $node->$key : NULL,
    );
  }

  $form['changed'] = array(
    '#type' => 'hidden',
    '#default_value' => isset($node->changed) ? $node->changed : NULL,
  );

  $function = node_type_get_base($node) . '_form';
  if (function_exists($function) && ($extra = $function($node, $form_state))) {
    $form = array_merge_recursive($form, $extra);
  }
  if (isset($form['title']) && !isset($form['title']['#weight'])) {
    $form['title']['#weight'] = -5;
  }

  $form['#node'] = $node;

  $form['actions'] = array('#type' => 'actions');
  $form['actions']['submit'] = array(
    '#type' => 'submit',
    '#access' => variable_get('node_preview_' . $node->type, DRUPAL_OPTIONAL) != DRUPAL_REQUIRED || (!form_get_errors() && isset($form_state['node_preview'])),
    '#value' => t('Save'),
    '#weight' => 5,
    '#submit' => array('node_form_submit'),
  );
  if (!empty($node->nid) && node_access('delete', $node)) {
    $form['actions']['delete'] = array(
      '#type' => 'submit',
      '#value' => t('Delete'),
      '#weight' => 15,
      '#submit' => array('node_form_delete_submit'),
    );
  }

  // Add the validation handlers.

  field_attach_form('node', $node, $form, $form_state, entity_language('node', $node));
  return $form;
}

```

This code is taken from node\_form(); it is a ripped off version that include only what necessary to allow to enter the title, the body content, and the values for any field implemented using the field API.
As you see, the code still need to define the form validation handler, and the form submission handler. You use the code of node\_form\_validate() as guideline for your validation handler.

The form builder can be used for a menu item as the following one.

```
function mymodule_menu() {
  $items['mymodule/%node/edit'] = array(
    'title' => 'Edit',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('mymodule_node_form', 1),
    'access arguments' => array('the permission users should have to see this menu item'),
  );

  return $items;
}

```

---
Tags: forms
---


# Question
Title: Drupal 7 How to find Nodes, tagged with Broken Taxonomies?
In Drupal 7, some Taxonomy Terms were deleted (by force from direct DB Query, for some reason). So some Nodes left remained by still tagging this deleted Taxo Terms. Then the problem is arising at the Site Indexing stage. The process is getting broken.

So i believe i need to find the `Nodes` which are tagging to these no longer existing/broken `Taxonomy Terms`, to un-tag those.

* Which is the best way to do it?
* What will be the best Query for it?

Thanks.

# Answer
> 1 votes
Just as an FYI, even if the terms had been deleted properly, the references still would have been broken (see Database records not deleted for Term Reference Fields after Term is Deleted).

Either way, to answer your question, you could use use super useful Taxonomy Orphanage module.

> This module provides interfaces (drush, cron, admin form) for removing orphaned taxonomy term references from entities.

# Answer
> 0 votes
Taxonomy Term data is saved in 'taxonomy\_term\_data' table. And when you add a field e.g. Article Category (machine name - field\_category) in your Article Content Type which is of type Term Reference to say Category Vocabulary then system creates a table like 'field\_data\_field\_category'.

Now after knowing your table name for your custom field, you can execute a query which will give you Nodes which are tagging to these no longer existing/broken Taxonomy Terms,

```
SELECT f.* FROM field_data_field_category f left join taxonomy_term_data t on f.field_category_tid = t.tid WHERE t.tid is null;

```

Here you just need to specify your table/field name.

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


# Question
Title: Module to Create Historic Timeline Snapshots of Drupal Sites?
I'm looking for a module to create a functionality where it will take snapshots of the entire site and then replicate it to another domain/sub-domain every X number of days or weeks. I want to do this so I can go visit a previous version of the site in the past to see what was changed. I know you can do this with the module "demo", but that just takes a snapshot of the DB and you would have to revert back to that time overwriting what you currently have. Yes I can create a staging server for this, but I want to be able to have it done automatically where I have the following sub-domains where i can go back to:

1day-ago.foo.com 2day-ago.foo.com 1week-ago.foo.com 1month-ago.foo.com 2month-ago.foo.com 3month-ago.foo.com

How would this be done? Or is there a module for something like this?

# Answer
You should take a look at Aegir. Although it is more than a module, it has the functionality you describe. Basically what Aegir can do for you is create a complete copy (database, codebase and files) of your Drupal website. The catch here is that your Drupal site should be managed by Aegir as well.

On the more technical side, if you take a look at what Aegir does, you will notice that creating a copy of your website is performed by a number of drush scripts. These scripts could of course be used/modified to make your snapshots.
> 0 votes

---
Tags: staging
---


title: field collections and blocks

text:
# Question
Title: field collections and blocks
I have a number of content Types (Basic Pages) and a region (right sidebar)

What I'm looking to do, is display a particular fields content in this block depending on what page I'm on.

I know I could do this for a block for each page, but I have over 200 pages, and doing this for all of them would be time consuming.

I have created a field collection named 'rightcol' which is a text field.

So ideally, what i need is when I'm on a particular page, in the right-hand region, that pages 'rightcol' content will display.

Am I correct in thinking I'd need to create a view for this?

# Answer
> 1 votes
I think you are correct. You should be able to create a view block, set the field to be "rightcol" and then use contextual filters (under advanced features) to filter what is in the view depending on URL.

---
Tags: views, blocks, entities
---


# Question
Title: Using D7 OG I want to force (auto) join - any ideas?
I'm using D7 Organic Groups to create custom member profiles such that when a new user registers, a rule creates a group with their name (/member/firstname-lastname) and redirects them to their group's home page where there is a "build-profile" panel using quicktabs to guide them through the 7 steps of building a complete profile. The build panel is visible until such time as they complete the final step at which point they are autoassigned a new role which uses a different page layout sans the build panel.

This all works well. When users browse for other users they are actually directed to the associated /member/firstname-lastname page for the user whose profile they are viewing.

Here is the issue I'm now having. I need to make it so that when a user "follows" another user (joins or subscribes-to their group) I want the owner of the group being followed to automatically "follow" (join or subscribe-to) their group.

This is really only doable because each member only "owns" or is admin to a single group, so it should be relatively easy to say - if user-a (owner of group-a) joins group-b (owned by user-b) then user-b joins group-a.

I'm just not sure programatically how to do this. Can anyone help me with a code snippet to do this?

# Answer
> 0 votes
I'm going to assume that you are using the `7.x-1.x` branch of Organic groups. I believe there are some major changes in the `2.x` branch - so this solution may/may not work with that.

```
// Assuming your group is of the entity type "node"
// and the name of your bundle is "group". A node bundle
// is the unique name of the content type which is a group
// type as well.
// Say $follower is the follower user entity and
//     $followee is the followee user entity
$opts = array(
  ':uid' => $follower->uid
  ':type' => 'group'
);
$gnid = db_query('SELECT nid FROM {node} WHERE type=:type AND uid=:uid', $opts)->fetchField();
if ($gnid) {
  $group = og_get_group('node', $gnid);
  og_group($group->gid, array(
    'entity type' => 'user',
    'entity' => $followee,
    'state' => OG_STATE_ACTIVE
  ));
}
else {
  watchdog('my_mod', 'Follower (uid=!uid) does not have a member group', array(':uid' => $follower->uid), WATCHDOG_ERROR);
}

```

Still, *own* (group manager) and *is admin of* are two different things, at least in OG parlance. Because a user may have the "administrator user" role in many groups. If you mean *is admin of*, the lookup of the node table above may have to be changed by doing a join with `{og}` and `{og_users_roles}`.

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


# Question
Title: Why am I getting "Access Denied" on /user/login?
Not sure what happened with my Drupal site, but I can't log in :s

When I go to /user/login, /user, /?q=user, /admin, whatever I just get "Access Denied", never presented with a Login form. Server response is 403.

Drupal 6 site.

# Answer
> 4 votes
Probably your IP has been blocked as a potential source of flooding/DoS attack. This may happen if there were a lot of requests from the same IP.

That happened to my company's site once when we rearranged our LAN structure so all intranet users could only access the site through proxy server, and proxy server IP was blocked by Drupal automatically.

You need to check `flood` table - there must be a record with your IP. Just delete that record or all records (`DELETE from `flood``).

---
Tags: 6, users
---


# Question
Title: Allow node author to assign edit rights for other users
Use case: user X creates a node and wants to give user Y the ability to edit the node as well. Think page administrators on Facebook. An Entity Reference field can be used to allow the node author to associate other users with the node, but how to provide edit rights for selected users?

A simple and common use case is a business directory website where Employee X creates a listing for Company Y and wants to allow Employee Z to edit the listing as well. There are several similar solutions out there but I've not been able to find a specific module or recipe for this common use case. Any ideas?

# Answer
As is usually the case, "there's a "module for that": Node access user reference meets the requirements for this use case by allowing node authors to select other users from a user reference or entity reference field and assign view, update or delete rights to the referenced users. Hope this is useful for anyone else who runs into this issue.
> 1 votes

---
Tags: entities, users
---


# Question
Title: Overriding Panels' default category structure
The development house I work at uses Panels for stuff a lot, and they're a central design tool for our clients. While we're able to group our own Panels content types and View Panes by specifying a category name, it isn't so easy for everything else: there's the useless content types in the "Activity" category, the confusing content types in "Entity", the overwhelming and mostly-useless content types in "Node (Tokens)", the *really* useless content types in "Page elements" (Why would I need to repeat design elements already in place on the page?)... I could go on.

Plus random blocks are always dropped in the "Miscellaneous" category -- seemingly the last place I always look for content types I cannot find.

What I really need is the ability to organize Panels content types, and hide categories that aren't needed.

To that end I've started work on a module that lets the use build and organize Panels content types into custom categories. However, the first major roadblock I've run into is convincing Panels to use my layout instead of the one it generates from the plugin info hooks.

In panels/includes/add-content.inc is `template_preprocess_panels_add_content_modal()`, which is where Panels seems to set up its category tree (Via the function's $vars argument).

1. Is there any way of inserting a hook into the function chain that discards the $var variable that Panels is passing to `template_preprocess_panels_add_content_modal()` and instead delivers my own?
2. If not, is there a way to override `template_preprocess_panels_add_content_modal()` with my own version?
3. Or, best yet, is there a module somewhere that already does what I'm trying to do?

Many thanks!

# Answer
*"Whaddayamean you can override functions starting with **'template'** like you can functions starting with **'hook'**?"* I ask...

I've finished my organizer and will post it as a sandbox module if my boss lets me. I ultimately just copied the source of `template_preprocess_panels_add_content_modal()` from `panels/includes/add-content.inc` and changed what was passed on -- `$vars['categories']`, `$vars['categories_array']` and `$vars['root_content']` were particularly important.

Surprised nobody answered this -- would've been an easy 10 points to just say "Yeah, template\_preprocess functions work a bit like hooks in that you can insert your own version higher up the chain just by naming it a certain way..."
> 2 votes

---
Tags: panels, chaos-tool-suite
---


# Question
Title: What does Drupal Commerce have that Magento doesnt? And vice versa
Looking for an ecommerce solution and wanted to know how does Magento compare? Does it have things like the View's module? CCK? Panels? Or the popular modules that are widely used in Drupal.

What does Magento have that Drupal doesnt?

# Answer
Your not going to get a better answer than someone whos done an article on it...

http://www.richardcarterconsultancy.com/2012/07/magento-vs-drupal-commerce/
> 0 votes

---
Tags: commerce
---


title: Give user 1 status to someone else?

text:
# Question
Title: Give user 1 status to someone else?
I'm in the process of leaving my current job, and that requires that all of my accounts be disabled. Well, some of those accounts are user 1 accounts in a few of our Drupal sites. Is it possible to just "transfer" user 1 to another account?

# Answer
As others have said, the user account with ID equal to 1 is a special account: It is one of the default accounts created by Drupal during its installation, and it is the only account to which every permission is assigned. (See @Clive's answer.)

What can be done is changing the password, and the email associated with that account.

Create a file in the same directory containing index.php, and add the following code.

```
define('DRUPAL_ROOT', getcwd());
require_once DRUPAL_ROOT . '/includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);

$account = user_load(1);
$edit = array(
  'pass' => 'New password';
  'mail' => 'New email';
);

user_save($account, $edit);

```

With this code, everybody with access to the filesystem of the server can change the password, and the email of the user #1. I am not suggesting to change the password directly in the database because the password in clear; Drupal saves the hash obtained from user\_hash\_password(), whenever `user_hash_password()` is the function implemented by Drupal, or from third-party modules.

If Drush is available, changing the password is even easier. Everybody could execute the following command:

```
drush user-password <username> --password="<password>"

```
> 1 votes

# Answer
Not as such, no. The `user_access()` function (which is invoked for most, if not all, access checks) has these lines in it:

```
// User #1 has all privileges:
if ($account->uid == 1) {
  return TRUE;
}

```

It explicitly checks for a user ID of 1, and bypasses any further checks based on that. The only way to simulate the same behaviour is to assign all system permissions to a role that another account has.

The easiest thing to do would just be to update the the user 1 accounts with the new admin's details as junedkazi suggests in the comments.
> 0 votes

---
Tags: 7, users
---


# Question
Title: Overwrite taxonomy/term page with custom view isn't working
I'm trying to style my `taxonomy/term` page and as it turns out, a lot of people are trying to do this. Internet is filled with tutorials and how-to-guides, but for some reason, it seems I'm doomed and not able to do so.

I've installed the Taxonomy Display module and I *think* my settings are all good:

And my view is configured with the taxonomy arguments:

But still, the `products/tents` (aka taxonomy/3) doesn't take the View style I've configured... What am I overlooking here?

When I take a look at my live preview of my view, it seems everything is right. Only something looks overwritten on my website because there it doesn't take over the Views layout.

# Answer
Keep in mind

1. The taxonomy path is normally taxonomy/term/% ( not taxonomy/% )
2. Views ships with a default taxonomy/term/% override ( just needs enabling )

Perhaps that will help.
> 1 votes

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


# Question
Title: How can I set a message on the page I am `drupal-goto`ing towards?
I have a page which makes certain verifications and needs to redirect the user in certain cases. In those cases, I want the destination page to show a message, but I can't get it to work. Here is my code:

```
if ($userNeedsToBeRedirected) {
  drupal_set_message(null, "You've been redirected because ...");
  drupal_goto('destination');
}

```

The redirection works, but the message doesn't appear. What can I do?

**Note**: I also tried the following:

```
if ($userNeedsToBeRedirected) {
  drupal_goto('destination', array(
    'query' => array(
      'message' => "You've been redirected because ..."
    )
  ));
}

```

and in the destination page:

```
if (isset($_GET['message'])) {
  drupal_set_message(null, $_GET['message']);
}

```

but is doesn't work either because (I believe) `drupal_set_message` is being called too late the the page creation process.

# Answer
> 3 votes
You are setting a NULL message in drupal\_set\_message, the correct syntax would be:

```
if ($userNeedsToBeRedirected) {
  drupal_set_message("You've been redirected because ...");
  drupal_goto('destination');
}

```

The second `drupal_set_message` `$type` parameter is for the message type:

* 'status'
* 'warning'
* 'error'

---
Tags: 7, redirection
---


# Question
Title: How to use a standalone page with a module
I'm working on a website that communicates with a bank API. During the process, the API sends a request to a callback page. I, therefore, created a "callback\_bank.php" file, and put it at the root of the drupal folder (along with index.php, cron.php, etc.) so it's accessible by http://www.mywebsite.com/callback\_bank.php

How would I go about packaging/deploying that file with the custom module I created, that does the rest of the work ?

Thank you!

# Answer
> 2 votes
Assuming the return path is configurable with the bank, you'd be better to create a hook\_menu callback to handle the bank response.

That way you can leverage the Drupal API, e.g access callback to restrict to their IP address range to prevent spoofing etc..

e.g:

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

  $items['payment/callback'] = array(
    'title' => 'Payment callback',
    'page callback' => 'MYMODULE_payment_callback_handler',
    'access callback' => 'MYMODULE_payment_callback_access',
    'type' => MENU_CALLBACK,
    'file' => 'MYMODULE.pages.inc',
  );

  return $items;
}

```

The bank can then request `https://www.yoursite.com/payment/callback?param1=foo&param2=bar`

---
Tags: 7
---


# Question
Title: creating a new content type with a series of blocks
I have just started with Drupal and I have a question regarding how content types work in Drupal. What i would like to know is how a content type can have a set of blocks attached to it?

If it helps I am trying to make a content type in which the user just gives a topic and then this content type will populate these blocks with information such as the latest news on that topic etc. But I'm unsure the best way to achieve this.

# Answer
I think that what you are looking for is Drupal's Taxonomy feature. I would start with that. This lets you categorize your content.

After that familiarize yourself with the views module. Items created in nodes that are associated with taxonomy terms can be listed in a views block. So if you have a concert site you can create a "show" type with dates. Then you can create a view/block that lists upcoming concerts.

Then when you get those two things I would recommend learning how to use panels.

For a great example of it all put together look here
> 2 votes

---
Tags: nodes
---


# Question
Title: Upload multiple files (with multiple attr) in custom form: how to get files?
I've made a form. Now I want it to upload files. I've made a form element to do that:

```
  $form['attachments'] = array(
    '#type' => 'file',
    '#title' => t('Attachments'),
    '#name' => 'attachments[]',
    '#attributes' => array('multiple' => ''),
  );

```

I've set `#name` and `#attributes.multiple` because I want to use the HTML5 multiple files upload thingie. They invented that for a very good reason. I assume Drupal knows how to handle that.

How do I get the files in the submit handler? I don't want to save them to the file system. I want to e-mail them.

Ofcourse (?) I can just query `$_FILES`, but even I think that's not right in a framework like Drupal.

Is there a better way?

# Answer
> 0 votes
I haven't tried HTML5 Upload yet, but it might help you out.

---
Tags: forms, files
---


# Question
Title: How can I allow users to edit CSS in a WYSIWYG editor
Is there a way to give the administrator of a site the ability to edit and save CSS files in a wysiwyg editor? I thought perhaps the CSS could be node therefor allowing for some type of versioning and reversion.

# Answer
You might be interested in this module:

CSS Injector

> Allows administrators to inject CSS into the page output based on configurable rules. It's useful for adding simple CSS tweaks without modifying a site's official theme
> 2 votes

---
Tags: wysiwyg
---


# Question
Title: Render array to markup after submitting a form
In my Drupal 7 custom moudle, i would like to output result of form as an formatted array. Simmilar like you can print\_r or printf arrays.

```
 $form['results'] = array(
            '#type'     => 'item',
            '#markup'   => $form_state['temporary']
)

```

so $form\_state\['temporary'\] is array, but i do not want "array" text to show up but formatted array representation, whatewer is in it.

Thanks!

# Answer
> 2 votes
Just try like:

```
'#markup' => '<pre>'.print_r($form_state['temporary'], true).'</pre>';

```

you could just save the `print_r()` value to variable and then output that to a Div or something ...

---
Tags: 7
---


title: Pass node field data into Views block

text:
# Question
Title: Pass node field data into Views block
I'm bad with words, so hopefully I can get this across clearly. I'm using Views and the dRealty module. I've tried using relationships, and it's a no go.

I made a Views block of an "Agent" content type that has an agent\_id (field\_agent\_id) text field. The dRealty module creates listings by pulling data from a RETS server, and the agent id (field\_listing\_agent\_id) comes through as a text field. I need to show the data of the agent with the id that matches the listing on the node. How can I pass the field from the node into the Views block?

I'm using Views PHP to filter and I'm referencing How to Filter view by comparing 2 fields, but no luck.

# Answer
> 0 votes
After having no luck with EVA (Entity Views Attachment) as well, I ended up using hook\_views\_query\_alter.

```
function agent_connect_views_query_alter(&$view, &$query) {

  if ($view->name == 'agent_directory' && $view->current_display == "agent_connect") {

        $entity_type = "drealty_listing";
        $entity = menu_get_object($entity_type);
        $agent_id = $entity->field_listing_agent_id['und'][0]['value'];

        if (isset($query->where[1]['conditions'][2]['value'])) {
            $query->where[1]['conditions'][2]['value'] = $agent_id;
        }
    }
}

```

I had to grab the dRealty entity from the page, grab the field value I needed, and change the query before running. If anyone has any code suggestions to this, let me know. I'm still open to getting better at this!

# Answer
> 0 votes
The way I've typically seen that type of thing done is using Contextual filters (formerly called "Arguments" in Drupal 6). The Drupal 7 Advanced Views Tip: Contextual Filters screencast or this tutorial on Using Views Contextual Filters should provide a starting point for using them. In short, contextual filters are like regular filters, except that they allow arguments to be passed in dynamically rather than the filter criteria having to be statically set ahead of time.

---
Tags: 7, views
---


# Question
Title: Node Access User Reference module tries to grant access twice, creates integrity violation
I have a site (7.18) in which I want to grant teachers access to assignments created by their students. My current solution is to set a teacher for each student, using a User Reference field. I then use a Rule to propagate the teacher setting to a field on each node the student creates, and I use the Node Access User Reference module to give access to the user referenced in the teacher field.

This should work fine, but whenever a student creates a node, I get the error message `PDOException: SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '*X*-*Y*-nodeaccess_userreference' for key 'PRIMARY'`, where X is the auto-increment ID for the next node that should be created, and Y is the user ID for the teacher (see the paste linked below for the full error message).

The full error references some code in node.module (lines 3427-3440). I got it to provide a dump of the queries it's doing (also in the paste below), and it seems that the function to insert access permissions in node\_access is being called twice with (almost) the exact same parameters: First it does one query that inserts rows granting access to the admin account, the author, and the designated teacher, then it attempts to do the same thing over again.

This creates a key conflict in the node\_access table. After that it presumably does a rollback, because the permissions (and the node itself) don't appear even once, but the auto\_increment value for the node table does increase.

I've verified that this only occurs when the node access user reference effect is invoked. A student who does not have a teacher assigned can create nodes with no problem, and removing the node access for teachers from the relevant content type also eliminates the problem.

Any idea why this is happening, or how I can fix it? The quickest solution that comes to mind is to change node\_access inserts to use `insert if not exists` but I'd rather not hack a core module in such an ignorant and potentially far-reaching way.

The error messages and database queries are the following.

### ERROR MESSAGE

> PDOException: SQLSTATE\[23000\]: Integrity constraint violation: 1062 Duplicate entry '17-4-nodeaccess\_userreference' for key 'PRIMARY': INSERT INTO {node\_access} (nid, realm, gid, grant\_view, grant\_update, grant\_delete) VALUES (:db\_insert\_placeholder\_0, :db\_insert\_placeholder\_1, :db\_insert\_placeholder\_2, :db\_insert\_placeholder\_3, :db\_insert\_placeholder\_4, :db\_insert\_placeholder\_5), (:db\_insert\_placeholder\_6, :db\_insert\_placeholder\_7, :db\_insert\_placeholder\_8, :db\_insert\_placeholder\_9, :db\_insert\_placeholder\_10, :db\_insert\_placeholder\_11), (:db\_insert\_placeholder\_12, :db\_insert\_placeholder\_13, :db\_insert\_placeholder\_14, :db\_insert\_placeholder\_15, :db\_insert\_placeholder\_16, :db\_insert\_placeholder\_17); Array ( \[:db\_insert\_placeholder\_0\] =\> 17 \[:db\_insert\_placeholder\_1\] =\> nodeaccess\_userreference \[:db\_insert\_placeholder\_2\] =\> 4 \[:db\_insert\_placeholder\_3\] =\> 1 \[:db\_insert\_placeholder\_4\] =\> 0 \[:db\_insert\_placeholder\_5\] =\> 0 \[:db\_insert\_placeholder\_6\] =\> 17 \[:db\_insert\_placeholder\_7\] =\> nodeaccess\_userreference \[:db\_insert\_placeholder\_8\] =\> 1 \[:db\_insert\_placeholder\_9\] =\> 1 \[:db\_insert\_placeholder\_10\] =\> 0 \[:db\_insert\_placeholder\_11\] =\> 0 \[:db\_insert\_placeholder\_12\] =\> 17 \[:db\_insert\_placeholder\_13\] =\> nodeaccess\_userreference\_author \[:db\_insert\_placeholder\_14\] =\> 2 \[:db\_insert\_placeholder\_15\] =\> 1 \[:db\_insert\_placeholder\_16\] =\> 1 \[:db\_insert\_placeholder\_17\] =\> 1 ) in node\_access\_write\_grants() (line 3440 of /Users/ghostlyTrickster/Sites/drupal3/modules/node/node.module).

### Dump of query object

```
InsertQuery_mysql Object
(
    [table:protected] => node_access
    [insertFields:protected] => Array
        (
            [0] => nid
            [1] => realm
            [2] => gid
            [3] => grant_view
            [4] => grant_update
            [5] => grant_delete
        )

    [defaultFields:protected] => Array
        (
        )

    [insertValues:protected] => Array
        (
            [0] => Array
                (
                    [0] => 23
                    [1] => nodeaccess_userreference
                    [2] => 4
                    [3] => 1
                    [4] => 0
                    [5] => 0
                )

            [1] => Array
                (
                    [0] => 23
                    [1] => nodeaccess_userreference
                    [2] => 1
                    [3] => 1
                    [4] => 0
                    [5] => 0
                )

            [2] => Array
                (
                    [0] => 23
                    [1] => nodeaccess_userreference_author
                    [2] => 2
                    [3] => 1
                    [4] => 1
                    [5] => 1
                )

        )

    [fromQuery:protected] =>
    [connection:protected] => DatabaseConnection_mysql Object
        (
            [shutdownRegistered:protected] =>
            [target:protected] => default
            [key:protected] => default
            [logger:protected] =>
            [transactionLayers:protected] => Array
                (
                    [drupal_transaction] => drupal_transaction
                    [savepoint_1] => savepoint_1
                )

            [driverClasses:protected] => Array
                (
                    [SelectQuery] => SelectQuery
                    [DatabaseTransaction] => DatabaseTransaction
                    [InsertQuery] => InsertQuery_mysql
                    [UpdateQuery] => UpdateQuery
                    [MergeQuery] => MergeQuery
                    [DeleteQuery] => DeleteQuery
                )

            [statementClass:protected] => DatabaseStatementBase
            [transactionSupport:protected] => 1
            [transactionalDDLSupport:protected] =>
            [temporaryNameIndex:protected] => 0
            [connectionOptions:protected] => Array
                (
                    [database] => lilacpro_drupwlk
                    [username] => drupal3
                    [password] => hunter2
                    [host] => localhost
                    [port] =>
                    [driver] => mysql
                    [prefix] => Array
                        (
                            [default] =>
                        )

                )

            [schema:protected] =>
            [prefixes:protected] => Array
                (
                    [default] =>
                )

            [prefixSearch:protected] => Array
                (
                    [0] => {
                    [1] => }
                )

            [prefixReplace:protected] => Array
                (
                    [0] =>
                    [1] =>
                )

        )

    [connectionTarget:protected] => default
    [connectionKey:protected] => default
    [queryOptions:protected] => Array
        (
            [target] => default
            [return] => 3
        )

    [uniqueIdentifier:protected] => 50edab60008ef7.00761431
    [nextPlaceholder:protected] => 0
    [comments:protected] => Array
        (
        )

)

```

NOTE: The second query is exactly the same as the first, except that the uniqueIdentifier is different, and `connection->transactionlayers['savepoint1']` is missing.

# Answer
> 2 votes
I was able to fix this by putting in a check to see if access rights had already been granted, before attempting to grant them. Currently it's an ugly hack to node.module (it even uses global variables :P). I'd love to see other responses that can either explain why this happened, or offer a less dangerous solution.

At some point I should try to reimplement it as a proper module, using hook\_node\_access\_records() or something like that. But in case anyone else has an exigent need to deal with this problem, the ugly version of the solution is essentially to declare a global array variable `$already_granted` in node.module. Inside `node_access_write_grants()`, do the following while it iterates over `$grants`:

```
global $already_granted;
$fixkey = $node->nid . "-" . $grant['gid'] . "-" . $grant['realm'];
if(in_array($fixkey, $already_granted)) {
  // the grant was already inserted
  continue;
}
else {
  $already_granted[] = $fixkey;
}

```

---
Tags: 7, users
---