# Question
Title: How do I reset the number of failed login attempts?
I am trying to unlock the admin user of a drupal install using these instructions

http://www.aslingandastone.com/2011/how-to-reset-root-password-in-drupal-7-with-ftp-and-phpmyadmin/

But the user is blocked and email reset is not working:

> Sorry, there have been more than 5 failed login attempts for this account. It is temporarily blocked. Try again later or request a new password.

Where in the database can I reset this blocked status? The admin user's status is set to '1' in the user's table.

# Answer
Drupal 7 prevents brute force attacks on accounts. It does so by refusing login attempts when more than 5 attempts failed. The amount of failed logins is recorded in the table 'flood'.

You can either wait before trying to login again, or clean the flood table following one of the procedures below:

1. Manually delete all of (or the last applicable) rows in 'flood' table.
2. Execute the following query on the Drupal database. To execute this query it will be necessary to login to the database. This is typically done through the command line or through a GUI interface such as phpMyAdmin.

```
DELETE FROM `flood`;

```
3. From the command line, with drush installed, execute the following command:

```
drush php-eval 'db_query("DELETE FROM `flood`");'

```
> 18 votes

---
Tags: 7, users
---


title: HTML tags are stripped off from emails

text:
# Question
Title: HTML tags are stripped off from emails
I am using HTML Mail, Emogrifier, Pathologic and Echo modules to theme the outgoing Drupal emails into a template based presentation.

So far, I guess it has not been too hard, but I am having a hard time getting the HTML Mail test message to allow HTML. I am using the Full HTML filter on the test message edit, and using Unfiltered for Post filter setting.

I get my test message, but its stripped of `<h>` tags and `<p>` tags and anything that isn't an anchor, `<code>`, `<span>`, or list. Does anyone know why?

I tried editing various filter formats and nothing affected it. It would seem like it keeps using Filtered HTML no matter what I select, but even still, it is not showing `<h>` tags and `<p>` tags.

# Answer
> 1 votes
im thinking your input format is filtering out the HTML Tags, As DanielGT Said, add a new input format that would allow using HTML tags, or just install a WYSIWYG editor, I personally prefer tinyMCE.

# Answer
> 1 votes
My Drupal setup relies on some other modules, but otherwise I have the same set up. I am not an expert (critics, take note!), but have you tried creating a new input format which ONLY contains the emogrifier filter? I have all my standard filters in one input format that gets applied to all content types, and then I have a seperate input format which applies emogrifier as the post-filtering process in HTML Mail. Just a suggestion. Daniel.

---
Tags: 6, emails, theming
---


# Question
Title: Detect if its first time that user accesses the page
How can I detect if users access a page for the first time? I want to redirect them to their language using GeoIP.

# Answer
I wrote a session variable that is set true if access has been made. Did my function in if, using isset function detected if its already set or not. Don't have to make it complicated using tables and other things.
> 0 votes

# Answer
For authenticated users you can use a table where you write a record for each user who visits a page; in the case there isn't a record for the currently logged-in user, you create the record, and then redirect the user.

For the anonymous users, you can register the IP from which they connect, and remove the record after X hours, as the same IP can be used from different users, especially from users with a dynamic IP.
> 2 votes

---
Tags: redirection
---


# Question
Title: Don't show user fields on admin/people/create
Basically I don't want to have fill out all the required fields that I have added to a user when I am adding a user via admin/people/create. In Drupal 6 there was an option to not even show those fields when the admin makes a user. I have looked around for that but have failed to find it in drupal 7. I suppose I could do a hook\_form\_alter but I was hoping there might be something already made that I can drop in.

I was using content profile in D6 for this and it has become profile2 for D7. Since posting I have found this issue which states that a module needs to be made in order to have that same type of option.

# Answer
> 1 votes
On each of the field settings for user fields, there is an option "Display on user registration form.". Just uncheck it.

# Answer
> 1 votes
you could use a css to hide the fields for the admin. The css\_injector module would be a handy tool for that and you could restrict the css to "#overlay=user/\*/edit".

A hook\_form\_alter would be a more robust solution.

---
Tags: 7, entities, users
---


# Question
Title: How can I do a custom form redirect on the user registration form?
I added a custom submit function to the user registration form. I want to be able to redirect to the user profile edit. How can I get the uid of the record that is about to be created? global $user doesn't work:

```
function my_user_register_submit ($form, &$form_state) {
  global $user;
  $form_state['redirect'] = 'user/' . $user->uid . '/edit?registration=1&destination=blahblah';
}

```

**Edit:**

My use case is this: after registration I want to redirect the user to the "edit profile" page to complete the remaining profile fields. When they "skip" that or complete the form they go to their profile page. However, when a ?destination parameter is passed into the register form I want to carry that value to the "edit profile" page and then direct the user to that destination page when they are done.

# Answer
Have a look at how login toboggan implements `user_register_submit()`: `logintoboggan_user_register_submit()`. It first save the `$user` in order to retrieve `uid` later.

```
function my_user_register_submit($form, &$form_state) {
  //Save $user
  $account = $form['#user'];
  $edit = array_intersect_key((array) $account, $form_state['values']);
  $account = user_save($account, $edit);
  $form_state['user'] = $account;
  $form_state['values']['uid'] = $account->uid;

  //Make the redirection
  $form_state['redirect'] = 'user/' . $account->uid . '/edit?registration=1&destination=blahblah';
}

```

Don't forget to check all the other pieces in the login toboggan's function to not forget any important part.
> 3 votes

# Answer
Login Toboggan has an option for this whereby you can use %uid as an argument for the redirect URL.

Literally a text box where you'd type /user/!uid/edit

It's also got a whole host of awesome features that are worth checking out :)
> 4 votes

# Answer
I think the better option you have is using the Rules module, rather than altering the form.
> 1 votes

---
Tags: 7, forms, users
---


# Question
Title: Give restricted editors access to unpublished nodes
Using Drupal 6.22.

I want to have editors create nodes (in a unpublished state) and be able to edit them. If they navigate away from the node their editing, they can't find it unless they have the full URL to it.

Is there a way to give them access without granting privileges to the admin pages and administering nodes?

I think creating a view of unpublished content and having it only show for editors is one possibility.

# Answer
To let some roles manage unpublished content types without granting them the "administer nodes" permission, I installed the view\_unpublished module and then I made a view of unpublished nodes as you suggested.
> 0 votes

# Answer
I think you'll find the Workbench module (Drupal 7 only) will fit your needs nicely. There's a good screencast explaining the module on the project page.
> 1 votes

---
Tags: views, users, nodes
---


# Question
Title: All my blocks are gone. Even the block menu entry is gone
Anyone know what I might have done? I found a few things about hook\_block being implemented in template.php causing this, but I don't implement hook\_block at all.

# Answer
> 0 votes
The problem was the Context module. Once I disabled it my blocks came back.

# Answer
> 0 votes
If you have a module and theme with the same name, this will happen (regardless if you do/don't have hook\_block in either of theme).

---
Tags: 6, blocks
---


title: How to embed node edit form on page?

text:
# Question
Title: How to embed node edit form on page?
```
module_load_include('inc', 'node', 'node.pages');

$form_id = 'reviewer_rating_node_form';

global $user;
$rating_id = views_get_view_result('get_rating', 'default', $nid, $user->uid);

// Rating hasn't been created yet. Create one.
if (empty($rating_id)) {
    // add node properties
    $newRating = new StdClass;
    $newRating->type = 'reviewer_rating';
    $newRating->title = $user->name . "'s rating of " . $nid;
    $newRating->uid = $user->uid;
    $newRating->created = strtotime("now");
    $newRating->changed = strtotime("now");
    $newRating->status = 1;
    $newRating->comment = 0;
    $newRating->promote = 0;
    $newRating->moderate = 0;
    $newRating->sticky = 0;

    // add CCK field data
    $newRating->field_rating_application[0]['nid'] = $nid;
    $newRating->field_rating_reviewer[0]['uid'] = $user->uid;

    // save node
    node_save($newRating);
}

$rating_node = node_load($rating_id[0]->nid);

$output = drupal_get_form('reviewer_rating_node_form', $rating_node);
return $output;

```

This isn't working for me. If I dpm $rating\_node it looks correct, but when I call drupal\_get\_form I get this error:

```
Fatal error: Cannot unset string offsets in includes\form.inc on line 498

```

If I log the $form variable at that line it's a string that starts with this:

```
Aform action="/devsite/node/423"  accept-charset="UTF-8" method="post" id="node-form" enctype="multipart/form-data">
<div>

```

That "A" instead of a "\<" might be a clue. I have no idea.

Any suggestions on what I'm doing wrong here?

# Answer
Why don't you use Editview module? You can create an editview with a block display and show it on your page to edit your nodes from there.
> 1 votes

# Answer
My problem was that the function you call with drupal\_get\_form is supposed to return an array because drupal\_get\_form builds it for you, so calling drupal\_get\_form within drupal\_get\_form and returning it was not how it's meant to work. Instead I returned an object I built with drupal\_retrieve\_form.
> 0 votes

---
Tags: 6, forms
---


title: Drupal node update detection

text:
# Question
Title: Drupal node update detection
Can anyone suggest how I might detect when a node has been updated via jquery?

I know jquery is a client-side technology but I really need to utilize jquery(ajax) to alert my users when a node is updated.

# Answer
In the classic HTTP model, the server is passive and can only return information to the client when it request it. So, in this model, to alert the users when a node is updated, you have to periodically poll the server the ask it if the node has been updated. If you have a lot of clients waiting for the update of a lot of nodes, this can quickly overload your web server with too much request to handle.

Today, the best solution for this kind of requirements is to use WebSockets or a similar full-duplex technologies. Drupal and PHP are not designed to serve a WebSockets. Technologies like node.js and Socket.IO, or APE are more suited.

The Node.js integration module integrates node.js and Socket.IO in a easy to use solution. It provides an API to easily implements your need.
> 1 votes

---
Tags: javascript, updating
---


title: Services json node object

text:
# Question
Title: Services json node object
There seems to be a problem with the Services module of Drupal 7 when submitting nodes using the node create reosurce, for example I can create nodes just fine, even with custom fields, but the problem is with term reference fields, the values never gets to them, here is an example:

```
var nodeCust={
node:{
  title: 'undefined test 1',
  type:'noticia',
  name: 'admin',
  body: {
    und: [
    {value:'sdasdasd', format:'full_html'}
    ]
  },
  field_custom:{
und:[ {value: 'test placeholder'} ]
  },

  field_theterm:{
und:[ {tid:"1"}  ]
  }
 }
};

```

This is the object I send in JSON, and it works great the body has its value, the title and the custom field as well, but the "theterm" field is a term reference field in this content type, and it NEVER gets its value :o( , I tried with all the widgets, autocomplete, list etc but that should not really affect this since this is a REST Services call w/JSON.

Any ideas anyone? Thanks

# Answer
The structure of what you submit through the API should generally be the same as the structure of the data you submit through the ordinary node form as the resource methods for creating and updating nodes are simply thin wrappers around a form submit. Even the validation and most errors come from the form handlers.

So my suggestion is that you look at how the form submits stuff as that's where you will likely always find the answer.
> 3 votes

# Answer
I've been having similar problems figuring out how to format my node objects as JSON. odly enough, it seem like you have to pass the tid in without the array notation, for example;

{ "title":"my title", "type":"my\_type", "field\_my\_field\_type": { "und": {"tid": "49"} } }

notice there are no brackets around und ... I have no idea why this works, since all of the other fields like body require that you format them with the brackets. I'm also getting different results when posting using poster (for firefox) and when posting the same JSON string in my app. Please let me know if you figure this out.
> 1 votes

---
Tags: 7, nodes, services
---


title: Public file system path problem

text:
# Question
Title: Public file system path problem
The "Public file system path" setting in admin/config/media/file-system was always reflecting the directory name of my multi site directory.

I don't know what caused the problem, but it doesn't automatically set the right dir anymore and I need to manually change it when I create a site.

Does anybody have an idea of what might cause this behavior?

# Answer
I have solved the problem by reverting to a older version of the database. I haven't been able to trace the real cause of the problem.

It had something to do with "Backup and Migrate" module, because that was the only real change between the versions.
> 1 votes

---
Tags: files
---


# Question
Title: Relevant Content Module Custom/Overwirete Theme
The module Relevant Content has a function called

theme\_relevant\_content\_block

Which renders the nodes for the module. The comments say the following

"This is provided (the function) so that an item list is the default, however a themer can easily override this to make a teaser list or table."

I'm not really sure how to use a 'themer' to overwrite this function.

Any pointers on how to do it is appreciated.

# Answer
You are the themer. In your theme, copy that function, but call it YOURTHEME\_relevant\_content\_block. Now change the function to output whatever you want it to.
> 2 votes

---
Tags: 7, theming
---


# Question
Title: Alter views with hook_views_query_alter()
i'm trying to hook all my site views with hook\_views\_query\_alter()

I can't find how to add a relationship and condition in the query.

Here is my (not working) code

```
/**
 * Implementation of hook_views_api().
 */
function taxonomy_location_views_api() { // your module name into hook_views_api
  return array(
    'api' => 2,
    'path' => drupal_get_path('module', 'taxonomy_location'),
  );
}

/**
 * Implementation of hook_views_query_alter().
 */
function taxonomy_location_views_query_alter(&$view, &$query) {
  // get taxonomy term ID
  $tid = subdomain_get_sid(subdomain_get_current_subdomain());
  if($tid) {
    $join = new views_join;
    $join->construct('term_node', 'node', 'nid', 'nid', array(), 'INNER');
    $query->add_relationship('term_node', $join, 'node');
    $query->add_where('term_node', 'term_node.tid', $tid);
  }
}

```

Any ideas?

# Answer
I found a slightly different solution that works.

Instead of adding programatically the relation, I instead added a clause in `$query->where`

```
function taxonomy_location_views_query_alter(&$view, &$query) {
  $tid = subdomain_get_sid(subdomain_get_current_subdomain());
  if($tid) {
    $query->where[0]['clauses'][] = "(node.vid IN (SELECT tn.vid FROM term_node tn WHERE tn.tid = %d))";
    $query->where[0]['args'][] = $tid;
  }
}

```
> 3 votes

---
Tags: views, hooks
---


# Question
Title: How can I programmatically enable clean URLs during a SimpleTest?
How can I enable clean URLs from the SimpleTest setUp() method?

Which .htaccess will be used during a simpletest? I needed to make modifications to RewriteBase to get clean URL's working on the 'non-testing environment', will they carry over to the test environment or do I need to modify .htaccess in setUp() as well?

# Answer
> 2 votes
Did a few tests and here is what I found.

Enable Clean URLs in setUp() method:

```
function setUp() {
    variable_set('clean_url', 1);
}

```

.htaccess from live site is used during SimpleTest. Modifications are not required.

# Answer
> 0 votes
The above mentioned code will work, If mod\_rewrite mod for Apache is enabled. http://drupal.org/node/134439 link will give more info about how to enable mod\_rewrite. If it is enabled then it will read .htaccess from live site.

---
Tags: 7, testing
---


# Question
Title: Colorbox - Only display some of the images in a gallery
I've got colorbox set up and working great, but I'd just like to do one little thing that I can't figure out. I want to have a colorbox gallery of, for example, a dozen photos, but select three to display on the page. Once you click one of the three photos on the page, it opens up the colorbox, which allows you to click through all 12 photos. Is this possible with Colorbox and Drupal 7?

EDIT: I'd like this to be a fix that I can use on a lot of different pages with varying numbers of photos. Sorry for the ambiguity.

# Answer
> 0 votes
Create a custom template page. Display the first 3 images - wrap the remaining images in a div that you hide, with css eg: display: none; or add a hide class to them - attach the gallery\_class class to them all so you can call them using

```
$(".gallery_class").colorbox({rel:'gallery_class'});

```

---
Tags: 7, javascript, media
---


title: Drupal 7 with Mongodb

text:
# Question
Title: Drupal 7 with Mongodb
I am working on Drupal website, and I heard about the MongoDB module. I installed and enabled it, but I don't understand how it works.

How can I switch all my data from MySQL to MongoDB? Is it safe to purely depend on it? Can anyone tell me how to configure MongoDB with Drupal?

# Answer
> 7 votes
You currently cannot use MongoDB for **all** your data. The MongoDB module clearly states what it can store in your mongodb: Cache, Field storage, Session, Watchdog, Lock, Block and Queue. This cover most of your site data. But a SQL database will always be needed.

This tutorial gives configuration to put in your site settings.php to enable various MongoDB storage. But it may be outdated.

---
Tags: 7, database
---


title: How to delete unwanted block

text:
# Question
Title: How to delete unwanted block
I've created a new block in my views.

Let's say the block name is 'slideshow'.

I've put the block into "Main Content" region and it's showing up.

The problem is that "Main Content" region is also displaying a list of nodes of "slideshow" with unformatted. So basically, "Main Content" region is displaying both unformatted version of "slideshow" and "slideshow"

when I inspect unformatted slideshow block, it has an id of "block-system-main".

How do I remove block-system-main ?

# Answer
> 1 votes
Are you talking about the front page or a custom view?

If you are in the front page view, you have probably set the content type for slideshow images to be promoted to front page. Disable that in

```
admin/structure/types

```

by clicking manage and in the footer untick 'promoted to front page'

and they will stop showing up unformatted. In that case you aren't actually talking about a 'block', but the system content that is displayed in the main content block defined in the themes page.tpl.php page with

```
<!-- Page Content -->
<?php print render($page['content']); ?>

```

---
Tags: 7
---


title: add block programmatically

text:
# Question
Title: add block programmatically
How can i add a block from mymodule. The content for the block is a form which contain a dropdown listing the themes. I tried with the following code. but it is not working.

```
function mymodule_block($op = 'list', $delta = 0){
$block = array();
    switch ($op) {
     case 'list':
       $blocks['mymodule_preview'] = array(
      'info' => t('mymodule Preview'),
      'region' => t('header'),
      'weight' => 0,
      'status' => 1
  );
  return $blocks;
case 'view':
  switch ($delta) {
    case 'mymodule_preview':
      $block = array(
          'content' => mymodule_theme_form(),
      );
      break;
  }

  return $block;
}
}

function mymodule_theme_form() {
global $custom_theme;
$themes = system_theme_data();
uasort($themes, 'tmymodule_sort_modules_by_info_name');
$themeOptions[] = 'Select';
$rolesOptions[] = 'Select';
foreach ($themes as $theme) {
    $themeOptions[$theme->name] = $theme->name;
}

// themes dropdown
$form1["themes"] = array(
    '#type' => 'select',
    '#title' => t('Preview the page with themes available'),
    '#options' => $themeOptions,
    '#default_value' => $custom_theme,
    '#attributes' => array('onchange' => "form.submit('themes')"),
);
//Submit button:
$form1['submit_'] = array(
    '#type' => 'submit',
    '#value' => t('Submit '),
        '#attributes' => array('style' => 'display: none;'),
);

return $form1;

}

```

This creates the block but content just prints "Array" only. i am using drupal 6 . What is wrong in this code? Pls help me

# Answer
```
  $block = array(
      'content' => drupal_get_form('mymodule_theme_form'),
  );

```
> 5 votes

---
Tags: 6, hooks
---


# Question
Title: Create node and photo gallery during installation of Drupal 6
I want multiples Node installation with Primary and secondary links, and also want to create Photo Gallery While Installing Drupal.

Is it possible to install and create nodes during installation?

# Answer
> 1 votes
Yes you can !

Check this link Installation Profiles

# Answer
> 1 votes
The short answer: Yes!

You would need to use an installation profile for this. With an install profile you can enable and configure modules, create new content types, add content, etc.

Here's one place to start: http://drupal.org/node/1089736

---
Tags: installation
---


# Question
Title: Modifying the node-form in domain module
Before I start i'll confess that i'm a drupal noob..I'm implementing a requirement in drupal 6.22 with drupal's Domain Access module ( http://drupal.org/project/domain ) which unfortunately has less documentation for a person of my level.

My requirement is such that the people who typically create/add content (page/story) do not need to see the fieldset of domain module with the Domain Access Options, and the created node by default should be sent to all affiliates and published to all the Sites in affiliates list.

I felt that rather than covering up the fieldset in a theme based manner which wasn't much preferrable i felt it needed to be a form alter kind of approach.

Initially planned to use hook\_nodeapi to set the $form\['domain'\]\['#access'\] = FALSE, but realised that it actually does the following as per Drupal's Forms API

> "the element is not rendered and the user submitted value is not taken into consideration."

Since I require the values to be set in an invisible manner that wouldn't help. I wish to learn the following

1. Is my approach of using hook\_nodeapi the right way, else any other like hook\_form\_alter or hook\_form\_FORM\_ID\_alter a better suited one or am i totally on the wrong track.
2. How does one set multiple checkboxes as checked in 'checkboxes' type in drupal forms. Couldn't find examples suited to my level of IQ (:D)
3. If I manage to accomplish my current requirement **is there a possibility where I could set some params such that only specific affiliated sites are set for a node based on the user's access and my business logic.**

Any help or suggestions on this specific issue are most welcome.

Thanks and Cheers!!

# Answer
> 0 votes
I found my solution: I set the respective values in the node save events, which didn't require to use the interface provided by Drupal. I didn't have concerns on the form and its settings.

---
Tags: 6, nodes, forms, domain-access
---


title: Missing video source with Video module

text:
# Question
Title: Missing video source with Video module
I am running Drupal 6.22 and updated the Video module to version 6.x-4.4 and FFmpeg Wrapper to 6.x-2.0-alpha1. Before I was using the swftools to show the videos, but now I wanted to try the HTML5 way. So there are videos in mp4-format (placed in the folder "original") and the converted ones in flv-format (in folder "converted"). After the discribed updates unfortunately no video is showing up - the problem seems to be quite similar. When I edit the content type ("Manage fields" --\> "Display fields") and I select "Generic files", everything works as expected. A link to the mp4-File is displayed. But when I choose "Video" the path to the file is missing (only the jpg thumbnail is working correctly), it outputs only this whitout any tag:

```
<video width="600" height="338" preload="auto" controls="controls" poster="URL TO JPG HERE.jpg" autoplay="autoplay">
</video>

```

Do you have any idea on how I could find the problem?

# Answer
> 0 votes
This only works when you also have an MP4 output format. The original video is not used as a source.

---
Tags: 6, files
---


# Question
Title: What is the Drupal 7 bookmarking module (a la delicious.com) that is equivalent to userlink in Drupal 6?
I am using the Web Links in Drupal 6, and I would like to use its equivalent in Drupal 7. It doesn't appear to be a clear direction, according to Comparison of Links Page modules.

# Answer
> 2 votes
For Drupal 7, I am using the Link module. It defines simple link field types.

---
Tags: 7, uri, navigation
---


# Question
Title: Filter values of a cck field with a view
When I create a new node of a certain type, I would like to filter a certain field depending on a view. For example I would like to filter through the top 3 latest news stories (as the view will filter though a news story content type which will display the 3 latest news story only so the sort criteria would be by the date).

Thanks in advance!

# Answer
If you want to show the latest 3:

1. Set the **Fields** you want to display, most likely Node: Title
2. Under **Basic Settings** set the limit to "3"
3. Add a **Sort Criteria** Node: Post date - ascending
4. Other **Filters** you'll want to add are: Node: Published - Yes & Node: Type

Hope this helps!
> 2 votes

---
Tags: views, entities
---


title: sharing contents between two sites

text:
# Question
Title: sharing contents between two sites
i setup two sites site 1 and site 2 by using drupal multi site functionality.site1 i consider as the master site and site 2 consider as the slave. some contents in both sites have similar content.when updation made in site 1 its reflect in site 2(only similar contents) for this i try to share the DB. while i try to execute following steps i get following error while i see the site pages

"You are not authorized to access this page. "

i follow this steps:

1.create a db prefix like this $db\_prefix = "master\_" in site 1 and $db\_prefix = "slave\_" in site 2.

1. i set the cookie $cookie\_domain = 'site2'; in site 1.
2. Then i add prefix like way in site 1 $db\_prefix = array( node' =\> 'master\_',
'node\_access' =\> 'master\_',
'node\_counter' =\> 'master\_',
'node\_type' =\> 'master-',
);

above thing i did site2 also instead of using 'master\_' i use 'slave\_' is there any thing missed out in my con fig.any one guide me do this. thanks......

# Answer
Multisite isn't really meant for situations where you want to share content. This is what Domain Access module does. Essentially, it allows you to have different behaviors for a site with subdomains, but running from the same database. This is different from multisite, which uses a different database for each site. I would try starting with that before you go down the road of multisite.
> 2 votes

---
Tags: multi-sites
---


# Question
Title: How can I prevent a user from logging in from more than one computer or browser?
In the Drupal 7 web site I am developing, I have a requirement that will not allow a user to login from multiple computers or different browser (IE and FireFox) on the same computer. It looks like the Session limit module used to handle this, but I don't see where it is even under development for Drupal 7. Do you have any idea?

# Answer
> 6 votes
If you look into the modules issue queue, you would see that there is already a very active port underway. You could help to get it to a solid release by testing it out.

See Issue #1047132: Session Limit version for D7

---
Tags: users
---


# Question
Title: Is there a way to display current "event" or "show" in date/calendar modules?
I'm building a radio station page with Drupal 7, and I would like to display in a block the current show on air, but I can't find a way to do it. I have installed the Views, Calendar and Date modules, a show content type with the starting date (and hour) and the ending date (and hour too). How show the query and filtering be done in views to display only one show and the one that is currently at the same time as the system time?

# Answer
> 2 votes
Basically, you want to tell views to display nodes with `starDate <= *NOW* AND endData >= *NOW*`. i.e. if now is 11:50, a program from 11 - 12 should be displayed.

This could be done fairly easy via views, following are two screenshots of the two filters you're gonna add to the view:

Hope this helps.

---
Tags: datetime
---


# Question
Title: How do I export fields of a content type in one website and import it into another website?
I'm trying to set up a data export through views that includes the title and a couple of fields of a content type and import it into another website. I'm using Feeds and Views Data Export and also tried Views XML but is doesn't seem to work.

How do I export fields and import them by creating nodes in another website?

# Answer
> 1 votes
1. Create a rss feed of your view or using Views Bonus Pack create a csv of your data.
2. Create the Content Type that will be the container for your new content. Or alternatively export the content type using the "Content Copy" module shipped with cck and then import it on the new site.
3. Using Feeds Create a node importer to import your nodes. Details in the video linked.

# Answer
> 0 votes
Remember see this: comparison of content import and export modules http://groups.drupal.org/node/21338 and his respective comments.

from all this options Migrate (and also Migrate extras) seems an interesting option to drupal 7 (is my opinion) because is flexible, and stable, altough maybe is best build a custom script to export and import your content.

# Answer
> 0 votes
Views lets you easily create any kind of RSS feeds of your content, if that is what you are looking for.

# Answer
> 0 votes
You may want to look into Bundle Copy if it's structure you're trying to move. This is similar to CCK's Content Copy in Drupal 6.

---
Tags: 7, views
---


# Question
Title: Create a News archive by year; argument year passed by URL
I try to build a News archive with Views 3/Drupal 7.

In a Sidebar there should be several Links to the corresponding years (e.g. 2011, 2010, 2009). After clicking on a link a new page is loaded with a block view, showing all Content types of "News" and creation year according to the previous clicked. How can I do that?

# Answer
> 0 votes
You are describing the basic function of the Views module. Take a look at the video series "Taming the Beast" from nodeone.se

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


# Question
Title: Alter field content inside modules hook_node_view
I'd like to alter, but not save, a fields output. I've got a MODULE\_node\_view already setup. Is there a way to do this? I don't want to save the output permanently.

# Answer
In `HOOK_node_view()` you can alter your fields like this:

```
function MODULE_node_view($node, $view_mode, $langcode) {
  //be sure to be in full page mode, but you can also user 'teaser'
  if ($view_mode == 'full' && node_is_page($node)) {
    //kpr($node); => use devel module and kpr() to inspect your node.
    //Change the title of the node
    $node->title = 'New title';

    //Change the "text" field
    $lang = field_language('node', $node, 'field_text');
    $node->field_text[$lang][0]['value'] = 'New field text value';

    //Change the "body" field which has a slightly different syntax
    $lang = field_language('node', $node, 'body');
    $node->body[$lang][0]['value'] = 'New body value';
  }
}

```

Note the usage of `field_language()` to retrieve the correct value for each field.
> 1 votes

# Answer
You can print the `$node` array and then access your field through index.

```
print_r($node);

```
> -1 votes

---
Tags: entities
---


# Question
Title: How to redirect after submitting a multi-step registration form?
I want to redirect after submitting multi-step registration (Two step registration), and also I want to prevent the automatic logging to drupal website after registration completes.

I tried the normal way

```
$form_state['redirect'] = 'url';

```

But it doesn't work.

Then I checked the form action, it also goes to the specified URL after completing the first step.

I just put some of the codes in my module here

```
function caubo_registration_form_alter(&$form, &$form_state, $form_id) {
if ($form_id != "user_register") return;

// custom codes
.....

if (isset($form_state['storage']['page']) && $form_state['storage']['page'] == 2) {
caubo_register_page_two($form, $form_state);
return;
}

if (isset($form_state['storage']['page']) && $form_state['storage']['page'] == 3) {
caubo_register_page_three($form, $form_state);
return;
}
}

```

I tried the Rules Module and implement the method here, but after completes the registration form, the user is automatically logged in to drupal website, how prevent it?

# Answer
> 1 votes
First, make sure no modules with a higher weight than yours are changing the value of `$form_state['redirect']` in their `hook_form_alter()` implementations. Stepping through with Xdebug is a fairly easy way to do this.

If that is not the cause, then it sounds like a call to `drupal_goto()` is happening somewhere in the process and interrupting the page flow. If your multistep form is working up until the final step, it could well be your own code doing it. Otherwise, check if anything you are doing would trigger any hook implementations or other code that could contain immediate redirects (a.k.a `drupal_goto`).

Devel can also display a redirection page, which may be a useful feature when debugging this.

Finally, check that `$_REQUEST['destination']` isn't being set via the URL or otherwise.

---
Tags: 6, redirection, forms
---


# Question
Title: Taxonomy menu with custom path for taxonomy terms
I am trying to make a taxonomy menu using the Taxonomy Menu modulewith a custom path for the taxonomy terms. Instead of /taxonomy/term/tid I want /proj/!tid (or ultimately /proj/!term-name but I'll settle for what I can get). I have the taxonomy menu working fine when I leave the "menu path type" setting to default, which leaves it as /taxonomy/term/tid. Whenever I try to use the "vocabulary path" option though, the menu terms all disappear. I've tried to follow the instructions in the documentation here.

I have a view with Taxonomy: Term ID (with depth) and Taxonomy: Term ID depth modifier arguments and a page display with the path set to proj/%. I've tried additionally making a url alias at proj and proj/% but that didn't seem to make any difference. But basically whenever I set the menu path type to "vocabulary path" ("custom path" in the documentation), the menu items all disappear. The terms are still there, and I can navigate to /proj/%, but there are no menu items.

Any help with how to have a custom path for the vocabulary while keeping the menu items would be greatly appreciated.

# Answer
If you want to alter taxonomy term paths for taxonomy terms implemented by your module, then you can implement hook\_term\_path(), which is the hook that allows a module to alter the taxonomy term paths.

The function that returns the taxonomy term paths is the following:

```
    function taxonomy_term_path($term) {
      $vocabulary = taxonomy_vocabulary_load($term->vid);
      if ($vocabulary->module != 'taxonomy' && $path = module_invoke($vocabulary->module, 'term_path', $term)) {
        return $path;
      }
     return 'taxonomy/term/' . $term->did;
  }

```

Implementing that hook would also help to modify the path of any vocabularies, if the field `$vocabulary->module` is changed to the short name of the module you created.

Alternatively, you can write the custom\_url\_rewrite\_outbound() and custom\_url\_rewrite\_inbound() that allows to rewrite the URLs being shown to the "outside" world, and convert a URL into the one used by Drupal.
The example given in the documentation should make clear how to use this functions.

```
function custom_url_rewrite_inbound(&$result, $path, $path_language) {
  global $user;

  // Change all article/x requests to node/x
  if (preg_match('|^article(/.*)|', $path, $matches)) {
    $result = 'node' . $matches[1];
  }
  // Redirect a path called 'e' to the user's profile edit page.
  if ($path == 'e') {
    $result = 'user/' . $user->uid . '/edit';
  }
}

function custom_url_rewrite_outbound(&$path, &$options, $original_path) {
  global $user;

  // Change all 'node' to 'article'.
  if (preg_match('|^node(/.*)|', $path, $matches)) {
    $path = 'article' . $matches[1];
  }
  // Create a path called 'e' which lands the user on her profile edit page.
  if ($path == 'user/' . $user->uid . '/edit') {
    $path = 'e';
  }
}

```

In other cases, you can use a module like Pathauto, or Views Term Path Override, which allows to override the taxonomy term paths in views.
Other modules that could be of help are Path redirect, and Taxonomy Redirect; The project page for *Views Term Path Override* suggests Taxonomy Views Integrator as alternative.
> 3 votes

# Answer
Try using Pathauto. I have used it in conjunction with Taxonomy Menu with great results.
> 0 votes

# Answer
You may want to try http://drupal.org/project/tvi I'd have success taking over term pages with that. Especially with attachment displays.

This one claims the same thing: http://drupal.org/project/views\_tpo
> 0 votes

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


# Question
Title: Making clones of Google,Yahoo or Bing with Drupal,is it possible?
Is it possible to make a clone of any search engine in Drupal, and what can be the complexities in making it. Or what can be the nearest possible search engine to make with Drupal.

# Answer
> 0 votes
Drupal isn't suitable for making a search engine. Try something like Nutch instead

# Answer
> 0 votes
I would think you could use drupal for the frontend of your search page, but you definitive needs some seperated search engine/index engine/crawler etc. to be able to get a good amount of data.

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


# Question
Title: system_cron() eats all ram and runs forever
Client doesn't ran Cron for \>6 months. So in database, we had large tables. I have cleared tables accesslog, cache\_\*, watchdog, flood manually in MySQL.

After that, running Cron runs forever. Especially system\_cron(). What part of that function can cause this? It seems that probably mysql is eating RAM, but I'm not sure.

system\_cron() touches following tables - cache\_\* (empty), flood(empty), batch(1 row), queue(159 rows), file\_managed(18,163 rows).

Maybe something is wrong with file\_managed?

# Answer
> 3 votes
Try Elysia Cron, it provides a lot of fine tuning and control over standard cron.

Khalid Bahey from 2bits.com wrote an extensive article regarding this module: Improving the performance of Drupal's cron by using the Elysia cron module

---
Tags: 7, performance, database
---


title: Drupal Calendar mini String overrides

text:
# Question
Title: Drupal Calendar mini String overrides
I want to change **!day-abbreviation S|M|T|W|T|F|S** string in the calendar block view. I used String overrides for other elements (month, week) and they work, but in the calendar block, day letters are not changing.

# Answer
In Views/Block view/Styles (gear icon) change Calendar day of week names to Abbreviated name.
> 1 votes

---
Tags: datetime
---


# Question
Title: Restrict admin/content view by organic group membership
I'm using D7 with organic groups. Have 7 groups each with their own content. Anonymous users can view all content from any group. Group admins can only edit the content from their own group.

When a group admin goes to admin/content they see all content items, though they can only edit their own. Is there a way to restrict the output on admin/content so the group admin can only see their content on this page? This would make it easier for them to review and manage their content as they would not need to page through all of the site content.

Thank you

# Answer
If I understand your needs correctly, you want to have a filtered list of content for og admins, don't you?

You could try to create a **View** for this particular purpose.

Try **Workbench** module, if it suits your general need to organize content workflow.
> 1 votes

# Answer
You can add a module that implements hook\_query\_alter like:

```
function gestionsesion_query_alter(QueryAlterableInterface $query) {
global $user;
if (current_path() === 'admin/content'){
    if ($query->hasTag('tablesort')) {
        $query->condition('n.language', $user->language );
    }
    }
}

```

Here we filter by user language but you could do it by role...
> 2 votes

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


# Question
Title: How can I create a views with right-join relationship?
I would like to create a view with a relationship between 2 tables, where the relationship must perform right-join instead of inner join. How can I do?

# Answer
> 2 votes
I am not sure what you are getting at, but you might need to switch the chain around and start from the rightmost table and left join by not ticking the "this relationship is required".

---
Tags: views
---


# Question
Title: How to get RSS feeds from other sites and display their links in a block?
I am using the aggregator core module, I also have feeds module installed but I can't figure how to make it read a remote rss and display the remote links in a block.

Thanks

# Answer
Drupal 6, Views-6.x-2.12 has built-in Aggregator type you can configure. Make sure you have contents in your aggregator from a valid RSS Feed.
> 1 votes

---
Tags: feeds
---


title: How to create two nodes at a time?

text:
# Question
Title: How to create two nodes at a time?
I have one cck content type and two fields in this content type
**1. is First name**
**2. is Last name**
i am trying TODO when i fill this these fields and click on save button Automatically create **Forum topic** with the name of first name text box value.
how it is possible ? plz help
i am using Drupal 6

# Answer
> 1 votes
You can do it easy with the Rules module.

# Answer
> 0 votes
```
//Load and init the Drupal System
require_once 'includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);
require_once 'modules/forum/forum.admin.inc';

function fourm_activities_form_alter(&$form, &$form_state, $form_id)
{
my_debug($form_id);

  if($form_id == 'testing_forum_node_form')
  {
    global $base_url;
//      my_debug($form);
    //add function to complete to at the end of array

    if(arg(2) && arg(2)!= 'edit')
    {
        $form['buttons']['submit']['#submit'][]='fourm_activities_form_id_submit_handler';
    }
  }
}
    function fourm_activities_form_id_submit_handler($form, &$form_state)

    {
        $name   =   $form['nid']['#post']['field_test'][0]['value'];

        $test_nid = $form_state['nid'];

        global $user;

        $newNode            = (object) NULL;
        $newNode->type      = 'forum';
        $newNode->title     = $name;
        $newNode->uid       = $user->uid;
        $newNode->created   = strtotime("now");
        $newNode->changed   = strtotime("now");
        $newNode->status    = 1;
        $newNode->comment   = 0;
        $newNode->promote   = 0;
        $newNode->moderate  = 0;
        $newNode->sticky    = 0;

        node_save($newNode);
        $final_nid =    $newNode->nid;

        $node = node_load($test_nid);
        $node->field_forum_reference[0]['nid'] = $final_nid;
        node_save($node);

        //$form_state['clicked_button']['#post']['field_forum_reference']['nid']['nid'] = $newNode->nid;

}

```

---
Tags: nodes, 6
---


# Question
Title: Can I make a content type for a single user's blog entries?
I would like site announcements to appear in a block on the sidebar.

I can do that with a content type, but Admin has a blog and I was wondering if/how to automatically give all blog posts of Admin (and no other user) be of a content type

# Answer
I think what you want is to create a view. Show all blog entries by 'user 1' only in your block. Create a view: Under your display(on the left) select block from the drop down. Give it a name, say Test1. Under Fields add Node:Title and Node:Body. In the filters add Node-type:Blog, Node:Published:Yes and User:Name=Admin

Then goto Site building-\>Blocks and you should see Test1:Viewname. Enable that block and configure it to show it on the page where you'd like.

Hope that helps.
> 2 votes

---
Tags: nodes
---


title: Prevent file renaming

text:
# Question
Title: Prevent file renaming
I have a user who is uploading a number of files with the same file name. It is important to them that the files are never renamed. However, the files are getting \_1, \_2, etc on the end.

Is there a way I can ask Drupal to make a new directory for duplicate file names so that a rename is not necessary?

# Answer
> 6 votes
There are two ways you can do this:

1. The Upload File Replace module. A small utility module that automatically stops Drupal from renaming new files upload via filefield CCK. When 2 files with the same name exist, the older files will be renamed.
2. Specify an optional subdirectory within the field setting where files will be stored using a unique token in the file path settings. (e.g. \[current-date:raw\])

---
Tags: files
---


# Question
Title: Problem with the body field after upgrading to 7.7
I recently upgraded to 7.7 because of the security updates, but now, when I try to add content there is no body field... and when I go check the module list I see this message on top of the list.

> Notice: Undefined index: module in \_field\_info\_prepare\_instance\_widget() (line 382 of /var/www/gisele-drupal/modules/field/field.info.inc).
> Notice: Undefined index: module in \_field\_info\_prepare\_instance\_display() (line 350 of /var/www/gisele-drupal/modules/field/field.info.inc).
> Notice: Undefined index: module in \_field\_info\_prepare\_instance\_widget() (line 382 of /var/www/gisele-drupal/modules/field/field.info.inc).
> \[…\]

Does anyone know what could be going on here, and how can I solve this?

# Answer
Are you using OG? Because that could be causing the issue.

Things to do

1. If OG is installed, but not enabled delete it.
2. Clear Cache
3. Update all modules up to their most recent versions
4. Run Update.php (do whenever a module is updated or deleted)
5. Uninstall Views and reinstall it

Issue about this problem here \> http://drupal.org/node/1001060
> 2 votes

# Answer
Besides the core issue, there is also a problem with Entity Reference: http://drupal.org/node/1329354. I'd recommend doing some disabling (as suggested) to determine which of these bugs is the culprit.
> 0 votes

---
Tags: 7, upgrading
---


# Question
Title: Testing site with login access AND login inside
I know it is counterintuitive, but I need to make my testing site secure and within it I need to test the user login module, so apparently I would be needing two login modules.

Is there a module that allows me to have two separate login systems? The "outer" one could be different from the "inner" one, of course. The "outer" one would only be for accessing a subdomain. The "inner" one would deal with user names and passwords.

Any idea and suggestions are welcome.

Thanx in advance.

# Answer
Use the Secure Site module. This module allows you to authenticate users with a browser-based password (HTTP Auth). Giving you the "outer" authentication layer. Then use Drupal core's login for the "inner".
> 0 votes

---
Tags: users, 6, testing
---


# Question
Title: Include theme stylesheets after base theme stylesheets
I'm using Tao as a base theme in Drupal 6. However, The base theme stylesheets are being included after the sub theme ones which is causing the base theme to override the the sub theme. As a result Tao's reset.css is coming after my theme stylesheets. Is this correct Drupal 6 behaviour?

My subtheme.info file looks like:-

```
core = 6.x
engine = phptemplate
name = Sub theme
base theme = tao

stylesheets[all][] = css/common.css

```

# Answer
> 2 votes
In Tao's issue queue you will find more info. See Issue #1013440: TAO stylesheet loads last and overrides sub theme styles..

In the readme file:

> Tao does not use the `all` key for any of its stylesheets and expects that you will not either. Be specific - if the stylesheet is for the screen, or for print, say so. Any stylesheet overrides your subtheme provides should use the same media key as the one in `tao.info` for the stylesheet that is being overridden.

---
Tags: 6, theming
---


# Question
Title: Undefined variable - base_url in include() in Drupal 7 html.tpl.php
I am getting this error, but everything else is fine; even that variable is getting printed. Then why does the error appear?

> Notice: Undefined variable: base\_url in include() (line 26 of htdocs\atins\drupal\sites\all\themes\live\html.tpl.php).
>
> Notice: Undefined variable: base\_path in include() (line 26 of htdocs\atins\drupal\sites\all\themes\live\html.tpl.php).

This is my code:

```
<a href="<?php print $base_url;?>"><img src="<?php print $base_path . $directory; ?>/img/logo.png" height="35" width="211" alt="AtinsLive Logo" title="Home" /></a>

```

# Answer
> 6 votes
You will need to bring the variable $base\_url and $base\_path into the global scope. At the top of your function or template file add:

```
global $base_path, $base_url;

```

or call `base_path()`

# Answer
> 1 votes
I ran into this same issue when using $base\_url in page.tpl.php in the following:

```
print l(theme('image', array('path'=>path_to_theme().'/css/images/logo_orig.png')), $base_url, array('html' => 'true'));

```

I fixed this by preprocessing `$base_url` in template.php:

```
function yourTheme_preprocess_page(&$vars, $hook) {
  global $base_url;
  $vars['base_url'] = $base_url;
}

```

So, I'm thinking you can preprocess you html template as well. This will be cleaner that calling a global in your tpl directly.

---
Tags: 7
---


# Question
Title: Select fields from two tables using db_select()
I am using `db_select()` and I don't understand the syntax of the `fields()` method. I'm using a `join()` to join another table. So for tables `t` and `n`, I want to do something like

```
SELECT t.tid, t.field1, t.field2, n.title, n.author
FROM table t INNER JOIN node n ON t.nid = n.nid;

```

I have

```
$results = db_select('table', 't')
  ->fields( ... )
  ->join('node', 'n', 'n.nid = t.nid')
  ->execute();

```

But as you can see, I'm lost at `fields()`. The examples I've seen only specify fields for one table:

```
->fields('t', array('tid', 'field1', 'field2'))

```

What is the syntax that I want to use?

# Answer
> 28 votes
Easy, just call fields() twice.

```
$query = db_select('table', 't');
$query->join('node', 'n', 'n.nid = t.nid');
$result = $query
  ->fields('t', array('tid', 'field1', 'field2'))
  ->fields('n', array('nid', 'field1', 'field2'))
  ->execute();

foreach ($result as $row) {
  // Do something with $row.
}

```

You can call most methods multiple times (multiple fields, multiple conditions, multiple sort orders, multiple joins, ...).

Note that, as shown in my example, the call to join() needs to be separate and can not be "chained" (that's the technical term for having multiple method calls in a row) because it does not return the query object but the name for the table alias.

# Answer
> 2 votes
An implicit join will still work with db\_query(), if you're not doing anything fancy. I'm not sure if this is bad practice or not though. I asked once in IRC and didn't get a response from anyone. So if you've got any of those left over from D6, they'll still work.

---
Tags: database
---


# Question
Title: Easiest way to add an existing site to a Drupal 6 multisite setup?
I have an existing Drupal 6 site. We've completed development but we're told it needs to be added to a multisite setup which involves moving key files and modules to different directories. Can someone please give me a few tips on how to do this or point me to a tutorial?

EDIT: would it be easier to rebuild the site from scratch (ouch) or to make the changes to the existing site? Any help would be appreciated!

# Answer
> 3 votes
Not a complete guide, but here are some hints.

* In general, modules aren't a problem, Drupal can deal with it if you move them around. Just do a cache clear after moving them and Drupal will go out and look for the enabled modules in all possible places (mainly sites/all/modules and sites/yoursite/modules). Make sure that you have no hardcoded path in your modules (contrib modules probably don't, but maybe custom ones), always use `drupal_get_path()` and similar functions.
* You can do a big part of the multi-site conversion in your existing site, just rename the default folder to yoursite.com. Note that you need to execute drush commands within that order or use the -l argument from then on, if you use drush.
* You probably want to move modules from sites/all/modules to sites/yoursite.com/modules in a first step (see first point). The existing site will probably have modules in sites/all/modules, you can then download them to your local site. Note that modules in sites/yoursite.com/modules override those in sites/all/modules. Then, figure out which modules are common, note that downgrades aren't possible, if you used a newer version of a module, you either need to keep it or upgrade the one in sites/all/modules. Make sure to properly test the changes (your site and the existing multi-sites, if you change anything in sites/all/modules). Same game for themes.
* The main issue will probably be file links in the files table, which you will need to change if your previous public path was in sites/default/files. If you already do the multi-site switch locally, you can again do and test this locally. Luckily, this has improved in D7, which doesnt't store the actual file path but something like public://the\_file.jpg.
* It is possible to share some tables, for example the users table, by having a single database for all sites and use a common prefix for some tables and a different one for others. If that's the case, you're in for some work (as you will need to rename all separated tables and merge the content of the shared ones). But it should be doable.
* If you have hardcoded path's in your nodes and other content, you'll probably need to update them manually. You might be able to write a script that does it, but that could be tricky, dependin on how the path looks exactly.

---
Tags: 6, multi-sites
---


# Question
Title: How can I cascade field display formatters?
I need to display a thumbnail of my images and the count of its downloads below the thumbnail.

I am using these modules:

1. CCK
2. FileField
3. ImageField
4. ImageCache
5. DownloadCount

and I think I need something like cascading these two formatter:

1. Generic files with download count (comes from DownloadCount)
2. examination\_question\_image image linked to image (comes from imagecache where examination\_question\_image is my "Preset Name")

Is there any module or anything else for this?

# Answer
You should try the Media module. I think it will solve your problems.
> 1 votes

---
Tags: 7, media, entities
---


title: Apache SOLR indexing stop working

text:
# Question
Title: Apache SOLR indexing stop working
solr indexing has suddenly stop working.

Here is all the detail which i got from system admin

while running cron we are getting message during run cron.php through command

PHP Notice: Undefined index: REMOTE\_ADDR in /var/www/XXXXXXX/includes/bootstrap.inc on line 1670 PHP Fatal error: Exception thrown without a stack frame in Unknown on line 0

where should i look first and what are the possibility for apache solr indexing to stop suddenly.

# Answer
> 2 votes
The not to good solution was, deleted all the index of apache solr and tried with the fresh indexing and all of sudden all thing work well.

---
Tags: 7, search
---


# Question
Title: How to disable "add comment form" from a OG group content?
When I'm showing content that belongs to a group I don't want to show the "comment form" to users that don't belong to that group. How can I do that?

# Answer
> 0 votes
Go to the group permission page, and uncheck the comment option for non-members.

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


title: Mobile CSS and media queries?

text:
# Question
Title: Mobile CSS and media queries?
What is the easiest way to create a mobile stylesheet for a Drupal 6 site? Is there a simple way to just create a css file, declare it in the info file add a viewport meta tag to your templates and have it all be automatically recognized by the site pages? Based on my own attempts, I'm thinking it's a little more complicated than that, but maybe someone has a fairly simple solution...?

# Answer
> 3 votes
Take a look at the Omega base theme. I haven't used this with D6, but the D7 version handles all of the media queries and makes it pretty easy to customize them via the UI settings page.

# Answer
> 3 votes
There are modules like mobile\_tools(http://drupal.org/project/mobile\_tools) and mobile plugin(http://drupal.org/project/mobileplugin) that have preconfigured themes you could tweak those.If you want to configure/make a mobile theme MOBILE PLUGIN is quite useful. http://drupal.org/node/1008582 follow this link for details of making zen subtheme.

# Answer
> 1 votes
There are several modules which can help you achieve vasts amounts of media detection. Most come with the option to then customize the called stylesheet so you can edit it to your hearts content.

Noteworthy Resource:

http://mobiledrupal.com/content/overview-mobile-modules-drupal

---
Tags: 6, theming
---


# Question
Title: Change de default status: Published to Not Published in Publishing Options
Is it possible to alter somehow the Publishing Options of the content type so that the default status of the article is Not Published?

I would like to do it in a preprocess function if possible. Thanks.

# Answer
> 1 votes
You can set the default status on /admin/structure/types/manage/YOURCONTENTTYPE in the publishing opitons. Just uncheck "Published".

---
Tags: nodes
---


# Question
Title: How to give image instead of text in pager?
I need to change the text in to image in pager.

For example:

```
<< First < Previous  4 5 6 7  Next > Last >>

```

Now instead of the above i need to print as below:

```
<< <  4 5 6 7  > >>

```

**Note:** Consider the less than and greater than symbol as images.

**Here is the syntax :**

```
theme_pager_next($text, $limit, $element = 0, $parameters = array())

```

**Here is my code :**

```
$li_next = theme('pager_next', theme_image(drupal_get_path("theme", "fluid") . "/images/text.gif"));

```

**My output is as follows for the above code :**

```
<img src="/sites/all/themes/fluid/images/text.gif" alt="" title="" width="7" height="13" />

```

**But my desired output is to print the image which is in the image tag.**

Any help will be thankful and grateful.

Thanks in advance.

# Answer
See How to change text-links to image links in the pager. By using the `theme_image()` function Drupal should nicely format the `<img>` tag, and output it to your theme. Well, this works, but unfortunately somewhere in this `theme_pager()` process a `l()` is telling Drupal to only output plain text here.

The trick here is not to rewrite your whole pager functions. Have a look at theme\_pager\_link(); this function is building all the links that are used by the pager functions. When you look closer to the `l()` formatting the output is done using the following code:

```
return l($text, $_GET['q'], array('attributes' => $attributes, 'query' => count($query) ? implode('&', $query) : NULL));

```

You'll see the options aren't setting the HTML output. So I placed the whole function in my template.php (changing `theme_pager_link()` to \`landrush\_pager\_lin()k) with a different output:

```
return l($text, $_GET['q'], array('attributes' => $attributes, 'html' => TRUE, 'query' => count($query) ? implode('&', $query) : NULL));

```

Note `'html' => TRUE`.

Now `l()` is allowing me to print HTML tags (images!) within the pager function.
> 1 votes

---
Tags: 6, theming, paging
---


# Question
Title: Create a block with articles from the current edition
Hello I need to create a block that when is on the article page to show all the related content from the edition it belongs.

I tried with views but the problems comes from the fact I cannot add a filter of the current edition.

I think this should be done within a module but I needs some clues. Thanks.

# Answer
I presume you categorize your content using taxonomy terms, or? So, as an example, you create an article for issue number '122' and you 'could' use this in the url of your article, such as www.example.com/articles/issue\_number/node\_id

In this example, if the node id was 12345, the full url would look like this:

```
www.example.com/articles/122/12345

```

Now you could use views and arguments - in Views 3 'Arguments' was renamed to 'Contextual filters'. So,

1. Create a view -\> create block -\> unformatted list -\> titles (linked)
2. add a Contextual filter
3. Content -\> Has taxonomy term ID
4. When the filter value is NOT in the URL: -\> Provide default value -\>
5. Type: Taxonomy Term ID from URL -\> Load default filter from node page, that's good for related taxonomy blocks.
6. Check the boxes of the taxonomies you want involved here
7. skip to point 11

------------ old way -------

1. Provide default argument -\> php code

```
$node = node_load(arg(1));
if($node) {
//Be sure to rename ->field_taxonomy_name to your field name
foreach($node->field_taxonomy_name[LANGUAGE_NONE] as $term) { $terms[] = $term['tid']; }
 return implode('+',$terms);
} else { return; }

```
2. Allow multiple terms per argument -\> yes
3. Reduce duplicates -\> yes

^^----------- old way ---------^^

1. Create a second argument to remove the currently displayed node from related content block
2. so, add a 2nd Contextual filter
3. Select Node: Nid
4. Action to take if argument is not present -\> Provide default argument
5. Default argument type -\> Node ID from URL
6. Exclude the argument -\> yes
7. Save
8. Add block to node pages, only display in articles/\*
> 1 votes

---
Tags: blocks
---


# Question
Title: Creating content types with fields that are other content types?
I have an existing content type in my current Drupal application, person. This contains all of the data you would expect, more or less - name, address, employer, etc.

I'd like to create a project content type. A project will consist of a name, description, and multiple members. Each of these members should be a person node that will already exist. It would be great if I could have the ability to add members by either selecting from available persons as a dropdown, or maybe some sort of autocomplete on name. I already know how to do autocomplete, but the issue then is that the field will be autocompleting just the person's name. I need a project node to actually contain multiple entire person nodes, so that I can get ALL of the info out of them - name, position, etc. etc. Is this sort of functionality natively in Drupal?

Alternatively, I could implement hook\_node\_load in this module, and add person nodes to any node loaded that happened to be a project node. Would this be a more viable alternative?

# Answer
In future it would help to know what version of Drupal you are using.

In D6 you can use Node Reference CCK field, which creates a cck select list, auto complete, radio buttons or checkboxes listing the node types you have selected to be referenced.

There you could use your autocomplete form, type the users name and add them to the project.

This module however no longer exists in D7, instead have a look at these modules which could do the same or similar:

http://drupal.org/project/references

http://drupal.org/project/Relation

http://drupal.org/project/entityreference
> 0 votes

---
Tags: 7, nodes
---


# Question
Title: Load JS only on specific content_type node creation
Drupal 6. What is the proper way to execute `drupal_add_js` only when specific content\_type is being created?

I have some jQuery code that needs to execute only to control some form elements in a specific content\_type creation.

# Answer
> 3 votes
you need to write a simple module where you hook into the page you need and add drupal\_add\_js()

e.g. when you create a content type the form `node_type_form` is being called. so you have to hook into the form with

```
/**
 * implimentation of hook_form_alter()
 */
yourmodulename_form_node_type_form_alter(&$form, &$form_state, $form_id) {
  drupal_add_js('jQuery(document).ready(function () { alert("Hello!"); });','inline');
}

```

I asume you need to add a JS to a content\_type being **viewed**. in this case you will need to use `hook_view()` :

```
/**
 * implimentation of hook_view()
 */
yourmodulename_view($node) {
    if ($node->type == "your_type") {
        drupal_add_js('jQuery(document).ready(function () { alert("Hello!"); });','inline');
    }
}

```

**Update:**

of course you can modify your `template.php` in the theme directory as well. remember that the theme for administration is different than the site theme by default. be aware which template.php file you are changing.

---
Tags: nodes, 6, javascript
---


title: Drupal 6 & Custom query sanitization

text:
# Question
Title: Drupal 6 & Custom query sanitization
Reading through Drupal 6 docs, it appears that `db_query` and `db_query_range` take the entire query.

This is different from Drupal 7, which can separately take user input as an argument, effectively sanitizing it.

What is the proper way to deal with custom queries, that contain unsafe input in Drupal 6?

# Answer
> 2 votes
The Drupal 6 version of db\_query supports placeholders. The best explantion of these is probably the Writing secure code article.

A (contrived) example would be

```
$query = "
  SELECT node.nid FROM {node} node
  INNER JOIN {content_type_foo} content_type_foo ON content_type_foo.nid = node.nid
  WHERE content_type_foo.field_foo_value = '%s'
";

$foo = $_GET["foo"];
$nid = db_result(db_query($query, $foo));

```

The referenced article also shows how to use placeholder arrays for handling a variable number of arguments, like for `WHERE IN` queries.

The second edition of Pro Drupal Development, which covers Drupal 6, is also a good reference for using the database abstraction later.

---
Tags: 6, database
---


# Question
Title: Beginner trying to use jQuery in a custom location, but not sure where to insert the code
At the moment, I'm working on a website that requires an on-mouse over effect where the things that are going to be displayed is an image. I figure that the best way to go about this is by using jQuery.

Being a beginner at Drupal, I've noticed that all of the content in this website is generated from database calls. I was wondering if there was a module or a way to see how these calls are made so that I may be insert the correct code at the right place.

# Answer
If you are customising a theme, I would add a custom jquery script you have written. In your themes template.php you can then simply call the .js file from within the theme folder.

For example you could add this to your template.php file:

```
drupal_add_js(drupal_get_path('theme', 'YOUR_THEME_NAME') . '/js/jquery.custom.js');

```

in the jquery.custom.js file you could have something like this:

```
(function($) {

 $(document).ready(function() {

  // hover effect
  $(".hover_effect").hover(function() {
    //add effects here
  }

 });

}(jQuery));

```
> 2 votes

---
Tags: hooks
---


title: What's wrong with my sub-theme?

text:
# Question
Title: What's wrong with my sub-theme?
I wanted to make some customizations to the "Seven" administration theme, so I started by installing the "Blossom" sub theme of Seven found here: http://drupal.org/project/blossom-admin .

This worked fine. So then I copied /sites/all/themes/blossom-admin and named it /sites/all/themes/myadmin

In the .info file for myamin, I changed

```
name = Blossom
description = Drupal Gardens administration theme.

```

to

```
name = myadmin
destription = my description of this theme

```

And just to be safe, I also renamed any files that had the "blossom" name to "myadmin" in both the .info file and to the actual files themselves. (Like renamed blossom.css to myadmin.css)

Now when I go to the Drupal admin and select myadmin as the administration theme, it works, but includes my main navigation and a footer region content at the top of the theme. Does anyone know why this would happen to a straight copy of the blossom theme which worked fine?

# Answer
Did you rename all the functions in the template.php file as well? These need to start with your theme name ;-)
> 2 votes

---
Tags: 7, theming
---


# Question
Title: Ajax pager won't work after other ajax event
I have a View called 'example' with the Pager turned on and Ajax turned on.

I have a script that refreshes the View by providing a path as an argument.

```
    $('.view-example a')
        .live('click', function(e) {
            e.preventDefault();

            var trigger = $(this),
            arg = trigger.attr('href');

            $.ajax({
                dataType: 'json',
                type: 'GET',
                url: '/views/ajax?view_name=example&view_display_id=block_1&view_args='+arg,
                success: function(data) {
                    $('#container').html(data.display);
                },
            });
    });

```

That all works fine. Although once the Ajax event has succeeded the View's pager doesn't work as expected. Instead it displays the json data of the view.

# Answer
Append the following line in the 'success' function

```
Drupal.attachBehaviors('#container');

```
> 1 votes

---
Tags: views, ajax, paging
---


# Question
Title: Title field input textbox way too long in firefox browser
This looks a very simple question but I seem to find it rather difficult to find a very easy solution...

Textboxes in forms are way too long when looking at it using Firefox but not in Chrome. In Chrome, container widths are respected so the textbox width does not go over containers' width. However, default size of 60 when using Firefox just breaks the container width declaration and does not get respected...

# Answer
> 0 votes
I had the same css issue. you need to address the input field correctly with the inputtype "text":

e.g.

```
.mywrapper-form input[type="text"] {
   width: 100px;
}

```

---
Tags: 7
---


# Question
Title: How do I associate multiple users to a node?
Let's say we have a node as a School class, and I'd like to assign users (students) to that particular node. I have seen couple of modules (signup) or (user reference) but I'd like to make it much simpler and just assign those users to that node somehow. is there any easy way of doing this without using CCK or other modules?

# Answer
> 2 votes
User Reference sounds perfect for what you are trying to achieve. Not much is simpler than being able to select the users in the edit node form. Can you describe what kind of GUI you would like to use to select the use

# Answer
> 1 votes
Ofcourse you could do that with your own custom module.

Just alter node form with form\_alter and add your own field (autocomplete?) which could poll users table. You also need some place to store references. Nid\_uid table would do it.

On save you could save data to your table.

But as most people mentioned CCK user reference field would be the best bet.

---
Tags: users
---


# Question
Title: A little calendar icon to show when something was posted?
I seem to recall trying a theme - I forget which; maybe Marinelli? - where each post on the from page had a nice little calnedar icon with the day and month of the pst.

Is that a module which I can use on other themes?

# Answer
> 3 votes
It's a simple theme modification, probably also easily done via .css. There is not need for a module for this.

Simply edit your themes node.tpl.php page in your theme directory/templates/

Find:

```
 <?php print $submitted; ?>

```

Wrap a simple tag round it like so:

```
      <span class="date_submitted"><?php print $submitted; ?></span>

```

Write your css:

```
.date_submitted {
  background: url("../img/icons/calendar_view_month.png") no-repeat scroll left top transparent;
}

```

You have to save the calendar image or create your own -\>

You also probably need to do some simple formatting in the css like padding-left (to push the text to the right to stop it overlaying the image) etc ...

If you don't know what I am on about, read up about css3 and drupal themeing and learn some basics.

---
Tags: 7, datetime
---


# Question
Title: How to have different URLs for microsites?
*First of all, thanks for anyone bearing with me with this issue. I know that I really should start looking into how Apache settings work etc., but first of all, I would like to get this working. (Plus points for anyone recommending good Apache learning material, right? ;) )*

I'm working on a Drupal 6 site running on Apache where several users (around 120) will have content which will act as a microsite. I have defined a content type for this purpose, used ThemeKey to switch to another theme only on those nodes etc.

I would like to be able to serve any of those nodes on a different domain (e.g. microsite.com) than the main site (e.g. mainsite.com). What should I do to "redirect" (sorry if I'm using any wrong terms here) the new domains to the right place? I would like to keep the new URL for the new pages (so it would not occur as mainsite.com/microsites/microsite, but microsite.com in the address bar).

*\[I've heard that it would be a bad idea to serve the same microsite with two different URLs from a SEO viewpoint - so that's another issue I should consider, but I have no idea on how I should address this...\]*

# Answer
This is what the Domain Access module is for. Essentially, it allows you to run multiple Drupal sites out of the same database, and share content.

Sending particular pieces of content to different domains is rather easy; a new tab shows up on edit panels.

It integrates nicely with Panels, Views, and other modules that use cTools, as domain rules show up as selection criteria.

For the Apache side, you need to configure it so that your multiple domains point to the same DOCROOT. How this is done depends on how you are running your sites. If you are using virtual hosts, then you set up additional ServerAlias settings for your `<VirtualHost>`
> 5 votes

---
Tags: redirection
---


# Question
Title: Where is links__system_main_menu defined?
I searched for `links__system_main_menu`, but just find usages of this theme. Where is it defined?

# Answer
Drupal 7 core doesn't actually define this function.

`links__system_main_menu` is a theme hook pattern of the form `[base hook]__[context]`. When links are themed with `theme('links__system_main_menu', $vars)`, `theme()` will search for and use `theme_links__system_main_menu()` if it has been defined. If not, it will use `theme_links()`.

See theme() for the official documentation of this behavior. Chapter 3 of Drupal 7 Module Development does an excellent job of explaining this and provides several examples.

BTW, the same principle applies to template files. If, for example, we call `theme('node__article__1', $vars)`, `theme()` will search for a `node--article--1.tpl.php` file, and then for `node--article.tpl.php`, finally falling back to `node.tpl.php` if neither of them are defined.
> 24 votes

# Answer
`theme_links__system_main_menu()` is not currently defined from Drupal, but Drupal will use `MYTHEME_links__system_main_menu()`, if you define it in your theme.

```
function MYTHEME_links__system_main_menu($variables) {
  $html = "<div>\n";
  $html .= "  <ul>\n";

  foreach ($variables['links'] as $link) {
    $html .= "<li>".l($link['title'], $link['path'], $link)."</li>";
  }

  $html .= "  </ul>\n";
  $html .= "</div>\n";

  return $html;
}

```

You can find some more info on http://drupal.org/node/1033442#comment-5076932.
> 11 votes

---
Tags: 7, theming
---


# Question
Title: Can I post a blog entry in a user's name?
I just found a new user has posted a dozen or so "blog entries" which were actually all posted as comments to a single forum question

I have explained to the user who will - hopefully - "add content" / "type = blog" in future.

Ideally, I would like to somehow edit those user comments and change them into user blog posts. Can I do that?

If not, I can copy /paste them; but can I create a new blog post entry in the user's name? And can I change its time-stamp to agree with the original?

# Answer
> 3 votes
> If not, I can copy /paste them; but can I create a new blog post entry in the user's name? And can I change its time-stamp to agree with the original?

In Drupal 6, the users with the permission of administer nodes can set the author of a node they are creating, using the following field set:

It is possible to change the author of a node already existing, and a node that is being created.

The same is true for Drupal 7.

# Answer
> 1 votes
You can copy and paste the comments into new nodes where the type is "blog". If you have adequate permissions, you can change the author on the node edit form. It is in the "Authoring information" in the set of vertical tabs at the bottom of the form.

---
Tags: nodes
---


# Question
Title: How to check node authorship info in views
I want to show users their published articles in a block. Those articles have their author name set in by Admin manually while the articles are created by Admin on behalf of the users.

In views I don't find any field in Node to compare authorship of the node with logged in user.

I've found a related article: http://drupal.org/node/228959 but no idea about how to look for following point in the article:

```
Go to 'Arguments' and select "User: UID is Author" and set the default
value to 'Return Page not found'.

```

I don't see "User: UID is Author". I only see "User:UID".

# Answer
> 1 votes
Add a filter to your view of `User: Current`. This will filter the nodes to ones created by the current user.

---
Tags: views, 6
---


# Question
Title: trying to edit user profile (/user/4/edit/?destination=admin%2Fuser%2Fuser) results in error
Clicking on the edit link for any user (even admin) listed in `".../admin/user/user"` results in an error page.

"The page isn't redirecting properly"

Link goes something like this `"edit?destination=admin%2Fuser%2Fuser"`

To be honest, I don't have full access to this Drupal install so I cannot turn on/off modules to test freely.

Has anyone encountered this kind of error? Which modules could be most likely to produce this error?

Thanx in advance.

# Answer
I found the culprit: the redirection option of the Account Profile module. I disabled that and the problem has been solved.
> 2 votes

---
Tags: 6, users
---


# Question
Title: Any way to do custom action from clicking an #autocomplete_path option
I'm attempting to hack the search\_autocomplete module. I inject my own suggestions in the matches portion in order to grab results from external sources. I would like to make it so that when I click one of these external suggestions, instead of filling in the search box, it re-directs the user to this external source. Is it possible to do this?

# Answer
> 1 votes
It is not possible: The purpose of the autocomplete callback is to offer suggestions to autocomplete what the user is entering.
Basing on what entered from the user, the callback needs to return the possible values the user could be writing; it is not supposed to redirect the user to a different page, considering that the user has not selected any of the values returned from the autocomplete callback, and that the callback doesn't know which of the returned values the user selected.

---
Tags: 7
---


title: Block doesn't show up in blocks listing

text:
# Question
Title: Block doesn't show up in blocks listing
Custom block doesn't show up on block listing and pages allowed to display that block. After switch theme everything is ok, so it is not module layer issue.

I check template.php everything seems to be ok. I check CSS (display: none, etc), it seems that it's not CSS issue.

I asked about other idea's, why that block doesn't show up? I am struggling few hours and starting to have no new idea's to solved that issue

# Answer
* Make sure the region variable is getting printed in `page.tpl.php` which is associated with your block.
* Make sure there is content for your block. If `$block['content']` is set to empty in hook\_block then the block does not appear at all.
* Check block visibility condition as well
> 2 votes

# Answer
The thing to watch out for is the possibility of overriding `hook_block()` through configuration in the ui.

If you don't get it right first time in `hook_block()`, subsequent changes to your code won't be reflected - you have to delete the entry for that block in the database first.

Setting the region as it's machine name in the theme's `.info` file is important too.
> 0 votes

---
Tags: 6, blocks, theming
---


# Question
Title: How do I create a variable that my page.tpl.php file can access?
In Drupal 7, I have a module that implements hook\_node\_load. It creates a variable that I'd like to make use of in my page.tpl.php file. Let's pretend it is the count of nodes that are of the same type as the currently loaded node. As of now, I'm just making the variable global, like so:

```
global $node_count;
$node_count = db_query("SELECT count FROM {node} WHERE type = :type", array(":type" => $node->type"))->fetchAll()[0]->count;

```

Then, within my page.tpl.php file, I have to do something like the following:

```
global $node_count;
echo "<p>$node_count</p>";

```

I know that there is a way to make my `$node_count` variable in scope, in the same way that `$node` or `$user` are. The tutorials I find on the subject seem to involve rewriting the entire theme function - I'm not trying to do anything that complicated. Is there a simple way to just make this variable in scope in my .tpl.php files? Something like a function?

# Answer
> 6 votes
In Drupal theming, template preprocess functions are the functions that prepare the variables that can be used in a certain template. Template preprocess functions are executed one after another and they pass around an array with all variables. You can add your own in your theme's template.php, in the form of `function THEMENAME_preprocess_TEMPLATENAME(&$variables) { // Your code here. }`.

If you're adding a value to a node object in a hook\_node\_load implementation, that probably looks something like this:

```
function mymodule_node_load($nodes, $types) {
  foreach ($nodes as $node) {
    $node->myvariable = 'somevalue';
  }
}

```

Now you want to access $node-\>myvariable in your page.tpl.php. For this, you don't even need to write a preprocess function, because Drupal already adds the current node object to the variables by default. (This happens in template\_prepocess\_page.) This means that you can simply add this to your page.tpl.php:

```
<?php if ($node->myvariable): ?>
  <div class="myvariable">
    <?php print $node->myvariable; ?>
  </div>
<?php endif; ?>

```

# Answer
> 0 votes
Variables that are accessible from a template file can be set in its preprocess function, which can be implemented in a module too.

In your case, your module should implement code similar to the following one (replace "mymodule" with the short name of your module):

```
function mymodule_preprocess_page(&$variables) {
  if (!empty($variables['node'])) {
    $variables['node_count'] = db_query("SELECT count FROM {node} WHERE type = :type", array(":type" => $variables['node']->type"))->fetchField();
  }
}

```

I verify `$variables['node']` is not empty because the page template is also used for pages that are not associated with a node.
In page.tpl.php, you access the same variable set from the preprocess function using `$node_count`.

---
Tags: 7, hooks, theming
---


title: How to create test_endpoint?

text:
# Question
Title: How to create test_endpoint?
I am new to drupal and I am using services module for using REST and RESTWS module. I used RESTWS and could get the content of the node by http://base\_url/node/1.xml and now I need to add a node and users from my external PHP application in to drupal. I googled and I found here that we need to use http://base\_drupal\_url/drupal7/test\_endpoint/users . I tried to create a service from Drupal 7, but I dont know what should I give on endpoint title ,name and endpoint path and I assume I need to give the same endpoint path in the curl.

Any help as to how to check if rest server is installed and how to create endpoint path would be of great help.

I am using Drupal 7 with services module services-7.x-3.0-rc3

# Answer
> 56 votes
Services module is easy to use, but it can be tricky to configure especially if you are new to the concept. So, I am going to post the screenshots to make configuration of Services modules easy for "Drupal Answers" users.

**Following is the version of Services module installed on my machine:**

**Create an endpoint called 'rest' as shown below:**

**Select the type of server and endpoint path:**

**Select the list of resources that you want to enable and specify aliases:**

**Select the response formatters and request parsers that you want to enable:**

**You can test your configuration as shown below:**

**You can get the list of all nodes as below:**

**And specific node as:**

Following are the excellent examples scripts provided by MichaelCole here http://drupal.org/node/910598#comment-4677738 to create nodes from any external PHP application.

I am duplicating his code for completeness of this answer.

```
//--------------login to the server------------------------
$service_url = 'http://example.dev/rest/user/login.xml'; // .xml asks for xml data in response
$post_data = array(
    'username' => 'test',
    'password' => 'test',
);
$post_data = http_build_query($post_data, '', '&'); // Format post data as application/x-www-form-urlencoded
// set up the request
$curl = curl_init($service_url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);  // have curl_exec return a string

curl_setopt($curl, CURLOPT_POST, true);             // do a POST
curl_setopt($curl, CURLOPT_POSTFIELDS, $post_data); // POST this data
// make the request
curl_setopt($curl, CURLOPT_VERBOSE, true); // output to command line
$response = curl_exec($curl);
curl_close($curl);
print "LOGIN RESPONSE:\n";
var_dump($response);

// parse the response
$xml = new SimpleXMLElement($response);
$session_cookie = $xml->session_name . '=' . $xml->sessid;
// print "SESSION_COOKIE: $session_cookie";

file_put_contents('session_cookie.txt', $session_cookie);

//----------------create a node -------------------------------

$node_data = array(
    'type' => 'ct_metadata_core',
    'title' => 'test layer',
    'field_core_lat_n[und][0]' => array('value' => '90'),
    'field_core_lat_s[und][0]' => array('value' => '-90'),
    'field_core_long_e[und][0]' => array('value' => '180'),
    'field_core_long_w[und][0]' => array('value' => '-180'),
    'field_core_description[und][0]' => array('value' => 'National Data Buoy Center'),
    'field_core_originator[und][0]' => array('value' => 'NDBC'),
    'field_core_url[und][0]' => array('url' => 'http://www.ndbc.noaa.gov/kml/marineobs_as_kml.php?sort=pgm'),
    'field_cont_res_name_org[und][0]' => array('value' => 'test'),

);

$service_url = 'http://example.dev/rest/node'; // .xml asks for xml data in response
$session_cookie = file_get_contents('session_cookie.txt');

$node_data = http_build_query($node_data, '', '&'); // Format post data as application/x-www-form-urlencoded
// set up the request
$curl = curl_init($service_url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);  // have curl_exec return a string

curl_setopt($curl, CURLOPT_COOKIE, "$session_cookie"); // use the previously saved session

curl_setopt($curl, CURLOPT_POST, true);             // do a POST
curl_setopt($curl, CURLOPT_POSTFIELDS, $node_data); // POST this data
// make the request
curl_setopt($curl, CURLOPT_VERBOSE, true); // output to command line
$response = curl_exec($curl);
curl_close($curl);
print "CREATE NODE RESPONSE:\n";
var_dump($response);

//----------------logout from the server-------------------------

$service_url = 'http://example.dev/rest/user/logout';
$session_cookie = file_get_contents('session_cookie.txt');

// set up the request
$curl = curl_init($service_url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);  // have curl_exec return a string

curl_setopt($curl, CURLOPT_COOKIE, "$session_cookie"); // use the previously saved session
curl_setopt($curl, CURLOPT_POST, true);             // do a POST
curl_setopt($curl, CURLOPT_POSTFIELDS, ""); // POST this data
// make the request
curl_setopt($curl, CURLOPT_VERBOSE, true); // output to command line
$response = curl_exec($curl);
curl_close($curl);
print "LOGOUT RESPONSE:\n";
var_dump($response);

```

# Answer
> 6 votes
I suggest you read Creating a resource for Services 3.x.

Also, I'm note sure if Services and RESTWS are compatible; they both offer variations of the same thing, and as such may conflict.

---
Tags: 7, services
---


# Question
Title: Seeking a point/level module to encourage user activity
I have a very new site. Users have occassionaly popped in to say "hi" and that's about it.

I suspect a chicken and egg situation - I won't get content until there is content.

I seem to recall that Drupal Commons (sadly my server seems too slow for it) has a system which is fairly standard in forums, where users get points and gainlevels for activity.

Is there something like that which is simple to add for a new admin on D7?

Thanks in advance

---

p.s. That's at its simplest, from an old school forumer; maybe I need +/-or "like/dislike" or new-fangled facebooky stuff?

# Answer
> 4 votes
For various voting and similar systems you could check these modules (including some quotes from their project pages):

1. Voting API:

> ... helps developers who want to use a standardized API and schema for storing, retrieving, and tabulating votes for Drupal content.

2. Fivestar:

> ... adds a clean, attractive voting widget to nodes and comments and any entity.

3. User Points:

> ... provides an API for users to gain or lose points for performing certain actions on your site. In conjunction with other modules, such as the Userpoints Nodes and Comments users can accumulate points for actions such as posting nodes, commenting or moderation duties.

4. Flag:

> ... is a flexible flagging system that is completely customizable by the administrator. Using this module, the site administrator can provide any number of flags for nodes, comments, users, and any other type of entity. Some possibilities include bookmarks, marking important, friends, or flag as offensive. With extensive views integration, you can create custom lists of popular content or keep tabs on important content.

# Answer
> 1 votes
I also like the rate module.

When launching any new social site I suggest you do anything you can to create enough compelling content to make it look like an already busy and interesting site. You could create content yourself or invite friends to create content for you.

Daily "teaser" questions will also help to get activity on the site.

In the beginning you'll have to "fake it" until you make it ;-)

---
Tags: 7, users
---


# Question
Title: Inserting jQuery corresponding to a certain element ID
I have a website in which I want to apply a custom drop down menu to a block. However, I have no idea how to go about doing this.

I posted this yesterday and came to the agreement that the jquery was to be added from a separate location, but I do not know where to implement it! I was wondering if perhaps this should be added to the /modules/block/ location or if it should be called elsewhere.

The content that I want to edit may be seen at mag-ds.com in the lower portion (the entries with #id=T\_roll.

Help?

# Answer
> 3 votes
You can add a javascript file from a module or a theme, whatever is most appropriate. For scripts that should be loaded on (nearly) all pages, just add a line to the .info file of your module or theme:

```
scripts[] = somescript.js

```

For scripts that you only want to load in certain occasions, use the drupal\_add\_js module. See Managing JavaScript in Drupal 7 for details.

That said, there are a lot of modules out there for drop down menus, so that may even be easier. Check Comparison of various drop down menus for instance, or simply search drupal.org or drupalmodules.com.

---
Tags: blocks, javascript, theming
---


title: How should I use token_replace()?

text:
# Question
Title: How should I use token_replace()?
Could somebody give me an example of how to use `token_replace()`?
I'm trying to write a custom PHP rule for the Rules module that will rewrite few fields of a new saved content, using the values from tokens.

# Answer
> 15 votes
```
$text = token_replace('token example - [node:title]', array('node' => node_load(123)));

```

# Answer
> 3 votes
As you are asking about how to replace tokens in a Rules action that is executing custom PHP code, you don't need to replace the tokens with `token_replace()`.

If you enter something similar to the following code, the tokens will be replaced by the Rules module.

```
drupal_set_message(t('This is the node ID: %node-id', array('%node-id' => [node:nid]));

```

The list of the available tokens is reported in the custom PHP action page.

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


# Question
Title: How can I set a node reference programmatically?
I'm trying to write a custom PHP action in Rules module. Each time after creation of a certain type of content, it should create an additional node with a reference to the created node.( Field by Node reference module )

I've tried to pass the values of nid and/or title of the main node to this field using tokens and it didn't work.

If the field is a text field it passes the variables correctly.

What value should be passed to the node reference field to set it in code?

# Answer
> 4 votes
First, I"ll answer your question, then suggest another way.

Assuming that this is a monolingual site, use

`$additional_node->field_created_node[LANGUAGE_NONE][0]['nid'] = $created_node->nid;`

However, Rules already has actions that can change values on a node, and when you create a node using Rules, it creates a new variable containing the created node. If I were you, I'd just add actions that use that data and not write custom PHP code to do it. I just created one to assign populate a user reference field on a created node (within the same rule) the other day, and it worked fine.

---
Tags: 7, entities, nodes, rules, tokens
---


# Question
Title: IS there a replacement for 'taxonomy_node_get_terms_by_vocabulary' in Drupal 7?
The closest I have come is `taxonomy_term_load_multiple` but the conditions argument will be deprecated in V8. They now recommend `EntityFieldQuery` as a replacement. I am new to coding and have not worked with setting up the conditions for the query and am having trouble finding documentation/tutorials. If a simpler function exists, I would prefer to use it. Answers addressing a function or how to use `EntityFieldQuery` are welcome.

Thanks

# Answer
I don't think an `EntityFieldQuery` would work in this case as you'd be trying to reference two types of entity in the same query (which cannot be done currently). The easiest way would be to build up the query yourself:

```
function taxonomy_node_get_terms_by_vocabulary($node, $vid) {
  $terms = &drupal_static(__FUNCTION__, array());

  if (!isset($terms[$vid])) {
    $terms[$vid] = array();
  }

  if (!isset($terms[$vid][$nid])) {
    $query = db_select('taxonomy_term_data', 'td')
      ->fields('td', array('tid'))
      ->condition('td.vid', $vid)
      ->condition('i.nid', $node->nid)
      ->orderBy('td.weight');

    $query->join('taxonomy_index', 'i', 'i.tid = td.tid');

    $terms[$vid][$nid] = taxonomy_term_load_multiple($query->execute()->fetchCol());
  }

  return $terms[$vid][$nid];
}

```
> 1 votes

---
Tags: taxonomy-terms
---