# Question
Title: Single sign on between different Drupal versions
Is it possible to have this module working with different Drupal versions?
We have some big projects in Drupal 6 and we want to start with a migration plan. Without being able to migrate parts of our sites, the task is much more complex than being able to do small migrations and tests.

I have seen there is the Bakery Single Sign-On System, but I don't know if it can be used when the subdomains use different Drupal versions.

# Answer
With the drupal-6 site override hook\_login\_validate() and write your own authentication mechanism. Simpler than it sounds, as any function that returns TRUE or FALSE based on success will work. It could directly access the database or connect via a JSON web service to the drupal-7 server. I described how to implement authentication via JSON on stackoverflow.

```
function mymodule_login_validate($form, &$form_state) {
   $username = $form_state['values']['name'];

   // do if condition to see if your authentication is required.
   // e.g. you might want to keep the drupal administration users.
   if (_mymodule_use_webservice_login($username)) {
     // We are logging in using service.
     if (_mymodule_validate_password($username, $form_state['values']['pass']) {
       user_external_login_register($username, 'mymodule');
       user_authenticate_finalize($form_state['values'];
    } // else drop through to the end and return nothing - Drupal will handle the rejection for us
   }
} else {
    // Username is not an member number, so use standard Drupal authentication function
    user_login_authenticate_validate($form, &$form_state);
}

```

\_mymodule\_validate\_password() is where the authentication occurs and the only other function you need to implement. See the stackoverflow site for calling a JSON web service. Try to use SSL as passing passwords over SSL is not great, although your main site may not be SSL anyway.

Implementing the web service is a function return TRUE or FALSE - drupal\_json\_output. You need to set up a menu, with a function callback. The function callback would call user\_authenticate().

You could also try one of the SSO modules. http://groups.drupal.org/node/182004. It is usually good policy to not implement your own security code so that the code gets tried as much as possible.
> 2 votes

---
Tags: authentication-authorization
---


# Question
Title: Display custom field content in node.tpl
i've a custom filefield in a custom content type and i use to display it in a node.tpl .But here my filefield has no limit number and under D6 i use this code :

```
    foreach($node->field_objectif_bts as $file) {
  if ($file['view']) {
      $header = array('data' => 'Les objectifs des formations BTS');
      $rows[] = array($file['view']);
      $attributes = array('id'=> 'objectif-bts','sticky' => FALSE);
    }
}

$output = theme('table', $header,$rows, $attributes);
print $output;

```

In Drupal 7 it doesn't work, so I'm looking for modifications to do on this code or new code for Drupal 7 theming.

Actually, I tried the following.

```
foreach($node->field_objectif_bts as $file) {
  if ($file['und']['value']) {
      $header = array('data' => 'Les objectifs des formations BTS');
      $rows = array($file['und'][0]['value']);
      $attributes = array('id'=> 'objectif-bts','sticky' => FALSE);
    }
}

$output = theme('table', array('header' => $header, 'rows'=> $rows), $attributes);
print $output;

```

I also tried this code, but I get an error.

```
$w = entity_metadata_wrapper('node', $node);
foreach ($w->field_objectif_bts->getIterator() as $file_w) {
  // $file_w->file returns the wrapper of the File entity. You can
  // then address it's values as:
  $name = $file_w->file->name->value();
  $mime = $file_w->file->mime->value();
  $custom_field = $file_w->file->field_objectif_bts->value();
  // etc. You can see all available fields by inspecting the
  // return value of $file_w->file->getPropertyInfo()
  if ($custom_field) {
      $header = array('data' => 'Les objectifs des formations BTS');
      $rows = array($custom_field);
      $attributes = array('id'=> 'objectif-bts','sticky' => FALSE);
    }
    $output = theme('table', array('header' => $header, 'rows'=> $rows), $attributes);
print $output;
}

```

The error is the following:

> EntityMetadataWrapperException: Unknown data property field\_objectif\_bts. in EntityStructureWrapper-\>getPropertyInfo() (line 339 of /var/www/drupal7/sites/all/modules/entity/includes/entity.wrapper.inc).

# Answer
There are two parts in your problem: one is getting the values, and the second is themeing them.

As far as getting the values is concerned, if you don't mind using the Entity and File Entity modules, a simpler way to access field content is to use entity metadata wrappers. This way you don't need to worry about deltas and languages.

You can write code as follows:

```
$w = entity_metadata_wrapper('node', $node);
foreach ($w->field_objectif_bts->getIterator() as $file_w) {
  // $file_w->file returns the wrapper of the File entity. You can
  // then address it's values as:
  $name = $file_w->file->name->value();
  $mime = $file_w->file->mime->value();
  $custom_field = $file_w->file->field_custom_field->value();
  // etc. You can see all available fields by inspecting the
  // return value of $file_w->file->getPropertyInfo()
}

```

As far as themeing the table goes, I think your call to theme is correct (If unsure, you can check the documentation for theme\_table)
> 2 votes

---
Tags: entities, theming, files
---


# Question
Title: Drupal 7 taxonomy add term missing url path settings
I'm working with a Drupal 7 installation, I watched a video that shows how to work with taxonomy, http://www.youtube.com/watch?v=Qmr2HW6CtJQ but when I go to "add term" to create a new term in my newly created vocabulary, the "URL Path Settings" was missing which has to generate automatic url alias that was shown at 04:15 of the video.

How to get this to show up?

Thanks.

# Answer
> 2 votes
You probably have to enable path module (core) and pathauto module

---
Tags: taxonomy-terms, path-aliases
---


# Question
Title: Custom token [node:customtoken] not available in rules action 'set a data value'
I've created module with hook\_token\_info() and hook\_tokens(). Now i can see my token in list of all availble tokens:

```
$ drush token | grep customtoken
 node        customtoken         Node related token

```

But this token is not available in rules action 'Set a data value'. What is the problem with custom token?

My rule looks like:

1. Events: 'After saving new content', 'After updating existing content'
2. Conditions: 'Content is of type'
3. Action: 'Set a data value'

# Answer
## 1) The easy, but dirty way:

You can nest your tokens in an existing type (see http://drupal.org/node/1714418#comment-6468184). Eg, in hook\_token\_info() do:

```
  return array(
    'types' => $types,
    'tokens' => array(
      'site' => $my_tokens,
    ),
  );

```

Your tokens will appear under "Site information"

## 2) The harder, but cleaner way:

Define your own rules data type with hook\_rules\_data\_info()

```
function mymodule_data_info() {
  return array(
    'vub_events_data' => array(
      'label' => t('My Module Data'),
      'group' => t('My Module'),
      'token type' => 'my_module',
      'property info' => array(),
    ),
  );
}

```

and use this in your hook\_token\_info() implementation.
> -2 votes

---
Tags: rules, tokens
---


title: Get Facebook content from node_load()

text:
# Question
Title: Get Facebook content from node_load()
I want a content type having a field "FB URL" that get the URL of a Facebook Event and that when people load a node of this type, the content of the facebook event is retrieved through FB API. It cannot be retrieved from the database because the content must be up to date with the one on facebook.

So far, I created a module with `node_load()` to add content while the node is loaded but I don't know what function to call from FBOauth module to do so... Before that, I tried with a simple `file_get_contents()`; that worked well until the access token from the FB App expired and didn't know how to get a new one dynamically.

I think I'm getting lost so could anyone guide me on how to do that?

Thanks a lot!

# Answer
Ok, I found!

```
function fb_event_crawler_node_load($nodes, $types) {
    foreach ($nodes as $node) {
        if ($node->type=="event"){
            $fb_url = $node->field_event_url['und'][0]['value'];
            $url = parse_url($fb_url);
            if (!$url['host'] == 'www.facebook.com'){
                echo t('This is not a Facebook URL');
            }

            $path_exploded = explode("/", $url['path']);
            if (!$path_exploded[1] == 'events'){
                echo t("This is not a Facebook event page!");
            }

            $fb_event_id=$path_exploded[2];

                // dpm($path_exploded);

            $app_id = isset($app_id) ? $app_id : variable_get('fboauth_id', '');
            $app_secret = isset($app_secret) ? $app_secret : variable_get('fboauth_secret', '');
            $app_token_url = "https://graph.facebook.com/oauth/access_token?"
            . "client_id=" . $app_id
            . "&client_secret=" . $app_secret
            . "&grant_type=client_credentials";

            $response = file_get_contents($app_token_url);
            $params = null;
            parse_str($response, $params);
            $access_token=$params['access_token'];

                //echo($params['access_token']);

            $fbquery = fboauth_graph_query($fb_event_id."/", $access_token);

            dpm($fbquery);
        }
    }
}

```
> 1 votes

---
Tags: 7, nodes, social-network
---


# Question
Title: How to implement a cancel button with required elements
I have a form in which I have added a cancel button which looks like this:

```
$form['cancel_button'] = array(
  '#type' => 'submit',
  '#value' => t('Cancel'),
  '#name' => 'cancel',
  '#access' => TRUE,
  '#submit' => array('mymodule_cancel'),
  '#limit_validation_errors' => array(),
);

```

This form has required elements in it as well and what is causing the problem. I thought that by having the #limit\_validation\_errors statement would prevent the required elements check, but that is not happening. How do I prevent the required elements from being checked?

**EDIT:** I found this answer on a different question Isn't it possible to have multiple buttons along with a submit button?

This would explain the behaviour I am seeing but it seems to contradict the Drupal documentation about limiting error checking. This would really screw up people who want to save a draft of a form that has required fields. I am pretty sure I have seen this done before, so there must be away around this.

# Answer
> -1 votes
You can make something like this in your function validate :

```
function FORM_validate(&$form, &$form_state) {
if ($form_state['values']['op'] == 'cancel')
{
 ///  Do something
/// drupal_goto() for example
}
}

```

---
Tags: 7, forms
---


# Question
Title: Drupal for Firebug does not work in FF> Works fine in Chrome
I have downloaded and installed Drupal for firebug Module and FF and Chrome extensions.

I log in as admin (uid 1) and do a simple output call:

```
firep("this is some message", "Message Title");

```

On chrome I can see the output fine, but in firefox I get the following message:

> No Drupal for Firebug data was found.

Either this site is not running Drupal or the Drupal for Firebug module has not been installed/enabled.

# Answer
> 1 votes
There are some issues with the Drupal for Firebug plugin depending on which version of Firefox/Firebug/DrupalForFirebug you are running. See the following issue on DO Extension breaks with version 14 of Firefox

It works for me on:

```
Firefox - 18.0.2
Firebug - 1.11.2
Drupal for Firebug Module - 7.x-1.4
Drupal for Firebug Firefox Plugin - 2.2

```

---
Tags: debugging
---


# Question
Title: How can I setup automatic subpages for existing pages using a view with a contextual filter that uses the URL to determine the filter value?
I have two content types that are being linked via entity references.

1. Area of Expertise \[Existing URL: /expertise/specific-area-here\]
2. Employee \[Desired URL: /expertise/specific-area-here/staff/specific-employee-here\]

Employee has an entity reference field that contains all of the areas of expertise and only one value is allowed to be selected.

For example: I have an area of expertise called "Pathology" and an employee named "John Doe". In John Doe, I select that the area of expertise is "Pathology".

When I'm on the area of expertise page for a particular area of expertise, I am showing all of the employees that specialize in that area of expertise in the sidebar second region. To do that I'm using a view that generates a block. Within the view I have a contextual filter using the following chunk of PHP code to provide the default filter value:

```
$filterValue = -1;

$node = menu_get_object();

if(!empty($node))
{
    switch($node->type)
    {
        case 'area_of_expertise':
            $filterValue = $node->nid;
            break;
    }
}

return $filterValue;

```

All of that is working properly.

What I want to do now is have a staff page that shows all of the staff associated with a particular area of expertise. I want the URL to be /expertise/specific-area-here/staff.

For example, if I want to see all of the staff that are associated with the area of expertise called "Pathology" (located at /expertise/pathology) then I would want the staff page to be available at /expertise/pathology/staff.

The issue I'm having is figuring out how to set up the contextual filter such that the "/expertise/pathology" piece of the URL of /expertise/pathology/staff can be processed so that Drupal knows which area of expertise to use to filter.

Also, the breadcrumbs should work as follows:

### If I'm on the Pathology area of expertise page, the breadcrumbs should show:

```
Home > Pathology

```

### If I'm on the Pathology staff page, the breadcrumbs should show:

```
Home > Pathology > Staff

```

### If I've drilled down into John Doe's page, the breadcrumbs should show:

```
Home > Pathology > Staff > John Doe

```

How should I setup the contextual filter to allow this behavior and how should I configure the "Path" under "Page Settings" in the view?

# Answer
> 0 votes
After much trial and error, I found a solution that seems to work for me.

The first thing I had to do was switch from using a "provide default filter value" to specifying custom validation criteria via PHP:

```
$normalPath = drupal_get_normal_path('expertise/' . $argument);
$urlPieces = explode('/', $normalPath);

if(!isset($urlPieces[1]))
{
    return false;
}

$nodeId = $urlPieces[1];
$node = node_load($nodeId);

if(!empty($node))
{
    switch($node->type)
    {
        case 'area_of_expertise':
            $handler->argument = $node->nid;
            return true;
    }
}

return false;

```

Thanks to Cameron for the bits about `$argument` and `$handler->argument`.

Once I figured out how to use argument to generate the URL which then allowed me to look-up the node ID, I was able to reuse most of the code that I had before in the "Provide Default Value" section.

The next issue was the breadcrumbs. Before I did anything extra, the breadcrumbs were showing as `Home > > Staff`. I ended up having to create a new menu item called `Staff` in the main menu that was a child of `Pathology`. So then the breadcrumbs showed as `Home > Pathology > Staff > Staff` which is still not what I wanted.

I found out that views likes to add each contextual filter as a breadcrumb so that you can navigate up and get less and less granular. Normally this would be a nice feature, but I couldn't see any way to turn it off.

So I found a post that detailed how to remove the breadcrumbs which I tried to implement via hook\_preprocess\_page. This ended up not affecting the breadcrumbs at all because the views module was altering the breadcrumbs after that hook was being run.

Then I found another post that detailed how to affect the breadcrumbs after the view was ready to be rendered using hook\_views\_pre\_render.

So I have the following code as my hook:

```
function MODULE_views_pre_render(&$vars)
{
    $page = menu_get_item();

    if(($page['page_callback'] == 'views_page') && ($page['page_arguments'][0] == 'staff_cross_reference'))
    {
        $breadcrumbs = drupal_get_breadcrumb();
        array_pop($breadcrumbs);
        drupal_set_breadcrumb($breadcrumbs);
    }
}

```

And now my breadcrumbs look like `Home > Pathology > Staff` which is exactly what I want!

---
Tags: views, uri, entities
---


title: custom content type

text:
# Question
Title: custom content type
I have created a custom content type (Testimonial), with the following fields: customer name, testimonial, company name. Each of them is stored in a different table.

How can I use the records to display in the front end? Is it advisable to use custom content type for this purpose?

# Answer
Drupal has is own storage system in database. Your don't really need to know how datas are stored and even if datas are in severals tables, you can use functions like node\_load() or node\_view(), which are awesome because you do not write any joined sql queries and fields datas are automaticly returned in a node object

Use the Views module to display a list of nodes of a certain type.
> 1 votes

---
Tags: entities
---


# Question
Title: Entity Reference get nodes based on tags
Let me try my best to make myself understood.

I have a node type Exhibition where I want to display related nodes of type Article, and these related nodes are tagged with taxonomy tags. On the Exhibition node I want a field where I can write one or more words, and related Articles tagged with these words should be displayed.

I want to use the Entity Reference module since this is already in use elsewhere, and I want to limit the number of modules in use. (I know of the Similar By Terms module).

Does anyone know if this is possible?

# Answer
> 1 votes
It can't be done with Entity Reference out of the box, your only option is to install another module or write some custom code (you would need to create a custom widget that searched additional fields on the entity if you went down the custom code route).

One possibility, which seems to be in keeping with your approach, is the Entity Reference View Widget module. This module allows you to search on any field. There is a little bit of additional setup since you have to create a view containing your Article nodes, but it means that you can specify your taxonomy as a field that can be filtered.

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


# Question
Title: Taxonomy formatter that shows a list of links to related nodes
I have a Taxonomy field on a Node. In the display of the node, I'd like a list of links to other related nodes, *not* a link to the Taxonomy category.

Is it best to build or find a formatter that can do this?

Or, is it best to make a View, and if so, what is the proper way to enforce the relationship between the selected Taxonomy Term item in the Node and the View?

Update: I found another StackOverflow answer. Though seemingly complex (I don't yet understand how it works), the initial results are promising.

# Answer
> 1 votes
You set up a contextual filter on the View Block to `Content: Has taxonomy term ID`.

So we need to hand this view a term ID. Since we're going to be calling this block using Context. There won't be a default value given in the URL. Therefore we have to give it one.

Select

* `Provide Default Value`
* `Load default filter from node page, that's good for related taxonomy blocks`
* Choose your default vocabulary

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


# Question
Title: how to manipulate entity field values in drupal 7 in custom module
I am creating a Payroll entity in which I have to manipulate different field values based on another field value (see below).

I have the following fields and I want to calculate the bottom four field values from the value of the basic salary field. Is there any function/hook available for this or do I have to write my own custom function?

1. basic salary field
2. da salary(daily allowance)
3. ta salary(travel allowance)
4. epf salary(Employee provident fund)
5. save\_salary(Save salary)

# Answer
My suggestion, now that I understand you're trying to calculate certain values' amounts based on the amount of a different field, would be to use the Rules module.

Then you can accomplish what you need without writing a custom module. Rules are sometimes a little clunky to create, but the module is really reliable - I use rules for all sorts of things, and once you set it up, it works beautifully.

Here are (roughly) the steps you'd need to take to create a rule that modifies a certain field based on another one. Adjust as you need to, so it suits your particular needs.

1. After enabling the module, go to /admin/config/workflow/rules to add a new rule
2. Set the 'Event' that triggers the rule to be something like '**After updating existing content**'. That will trigger this re-calculation any time the node is updated
3. Next you'll see that the rule also has 'Conditions' and 'Actions'. Set the 'Condition' for your rule to be '**Content is of type**' and select the content type you want to apply this rule to from the given list.
4. Finally, let's go onto the actions. You'll have to do two steps for each of the fields you're modifying 1) First calculate the value from the base\_salary field (and store in temporary variable -- that's how it works) and 2) set the appropriate field with the value of this temporary variable. Here are the 'Action' options that correspond to these
5. When you're calculating the value for one of the fields, the interface has, by default, a field to select from the top, an operator, and then a text field into which you can enter a number. If you would rather add/multiply/etc two fields, just change the bottom one to a data selection option with the following button
6. If your calculation is more complicated than simply adding/subracting/etc two values, just keep selecting the 'Calculate' value action and keep working on the number with multiple chain operations until you're ready and then add the 'Set a data value' at the end.

Hope this helps! I can't do an entire tutorial on using Rules here, as it's a complicated module, but the above should get you started and point you in the right direction. :0)
> 2 votes

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


title: If NID doesn't exist, save node?

text:
# Question
Title: If NID doesn't exist, save node?
I'm using menu\_get\_object() to get the NID for a computed field. The problem is that on a node save, NID doesn't exist yet so the computed field produces an error. If I resave the node, everything works since now the NID exists for the computed field to refer to. How can I go about adding an IF statement that if NID doesn't exist, save the node?

```
$node = menu_get_object();
$assigned_uid = $node->field_agent[LANGUAGE_NONE][0]['target_id'];
$assigned_user = user_load($assigned_uid);
$percentage_split = $assigned_user->field_percentage_split[LANGUAGE_NONE][0]['value'];

$other_ins = (isset(field_get_items($entity_type, $entity, 'field_other_ins_')[0]) ? field_get_items($entity_type, $entity, 'field_other_ins_')[0]['value'] : 0);
$vb = (isset(field_get_items($entity_type, $entity, 'field_vb')[0]) ? field_get_items($entity_type, $entity, 'field_vb')[0]['value'] : 0);
$finder_s_fee = (isset(field_get_items($entity_type, $entity, 'field_finder_s_fee')[0]) ? field_get_items($entity_type, $entity, 'field_finder_s_fee')[0]['value'] : 0);
$broker_fee = (isset(field_get_items($entity_type, $entity, 'field_broker_fee')[0]) ? field_get_items($entity_type, $entity, 'field_broker_fee')[0]['value'] : 0);
$dlc_franchise_fee_hst = (isset(field_get_items($entity_type, $entity, 'field_franchise_fee_hst')[0]) ? field_get_items($entity_type, $entity, 'field_franchise_fee_hst')[0]['value'] : 0);

$value = (($other_ins + $vb + $finder_s_fee + $broker_fee) - $dlc_franchise_fee_hst ) * ($percentage_split/100);
$entity_field[0]['value'] = $value;

```

# Answer
Try this at the top of your code:

```
global $node;
if (empty($node->nid)) {
  node_save($node);
}

```

Worked for me in D5 and D6.
> 1 votes

---
Tags: entities
---


title: Add a filter in views page

text:
# Question
Title: Add a filter in views page
I'm new in Drupal and i have crated a view for content type doctors who have many fields and i choose just some fields to be displayed in the view. Now i want to add a new filter like a select list in my page to select the country of doctor.

# Answer
> 1 votes
Create a filter using the field (eg field\_country), and select 'Dropdown' under settings. If this is a taxonomy term, select 'Expose this filter', then select 'Is one of' as the operator, and save. This will give you the drop down list.

If it is not a taxonomy term, the sequence might vary slightly, but it will be substantially the same.

---
Tags: 7, views
---


# Question
Title: How do I get image styles to function on the original node page?
* I go to create a content type.
* I add an image field and in the "manage display" section I change the format so that it uses the image style that I want.
* I then save it and it, I get the "changed save checkmark up top" and it says Image style: medium on the image section
* **When I create the content and post it, I go to view it and it shows the image at the original size, not scaled and cropped like the image style that was suppose to be applied to it.**

Any idea what I could be doing wrong?

NOTE: This image style works on views, but for some reason not on the original content page/node.

# Answer
On Manage Display page click locate Custom display settings to expand for more display options. check Full Content and Save.

Now you will see the Full Display tab on right top of your content area click that to select that display and than select your desired image style.
> 1 votes

---
Tags: nodes, media, entities
---


# Question
Title: Set a condition in views to remove title link
Currently I have a custom view that lists a series of nodes. One of my fields is "Content:Title" and I have checked "Link this field to the original piece of content". Everything works.

Question: For my list of nodes I would like to selectively "unlink" some of them and have the text remain. So in a way, it would be a preview of what's to come. Then when I am ready to link them I will "reactivate" the link.

Example:

1. Title 1
2. Title 2
3. Title 3
4. Title 4
5. Title 5

# Answer
> 2 votes
1. Add a boolean field to your node to determine if the link is shown or not. Let's suppose it's called `Show Link`
2. In Views add the `Title` field and then check 'Exclude from display'. Don't check 'Link this field to the original piece of content' here.
3. Add a Field that you can use to build your link, e.g. `Content: Path`. (You could also use `Content: Nid`.) Check 'Exclude from display' so this does not show.
4. Add the `Show Link` field and select the formatter type to be **Key** \- *this is important!* it won't work without it
5. Rewrite the output of the `Show Link` as, e.g. `[Title]`. Check the box to 'Output this field as link'. And then fill in the path box with, e.g. `[path]` or if you've gone the Nid route `node\[nid]`
6. Now edit the No results section of the `Show Link` field. In this case you want to output the Title without the link, e.g. `[title]`. Check the 'Count the number 0 as empty' In my testing I also have 'Hide if empty' and 'Hide rewriting if empty' checked.

Make sure you order the fields so that the ones providing the tokens for the rewrites come before the Show Link field.

---
Tags: 7, views
---


# Question
Title: In a Drupal 7 block, how to enable calling a Javascript function using behaviors
I am trying to put code into a block that contains a Javascript onclick handler. Have been trying to figure out how to use drupal\_add\_js, but cannot figure out how to make an onclick function work. I believe I may need to use Drupal behaviors.

I have read the documentation, but it is not clear. Here is what I am trying but doesn't work. Any help would be appreciated.

```
drupal_add_js('jQuery(document).ready(function() { $("#trial").click(function() { alert("Handler called." ); } ); } );', 'inline');

```

# Answer
`$` isn't defined in the global scope...you either need to use a closure:

```
(function($) {
  // Use $ safely here.
})(jQuery);

```

or use jQuery every time

```
jQuery("#trial").click(...

```

If you check the console you should see an error in there to the effect "$ is undefined".
> 1 votes

---
Tags: javascript
---


# Question
Title: How to display registration form fields based on the taxonomy term?
I have three taxonomy terms. And I want to display different fields in the registration form based on the taxonomy term.

I want something like this.

taxonomy term 1:
Registration form fields: Name, Email, Password, City, phone

taxonomy term 2:
Registration form fields: Name, Email, Password, Country

taxonomy term 3:
Registration form fields: Name, Email, Password, State, phone

Is it possible? if yes then please guide me.

# Answer
On Drupal 7 you've a new API named State API. You can use it to hide or show your fields.
> 0 votes

# Answer
I think we can try with combination of two module.

1. field\_collection
2. conditional\_fields
> 0 votes

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


# Question
Title: Is there any danger in caching forms, such as node edit, add, etc?
I am playing with authenticated caching modules to speed up performance while logged in. Currently I am using authcache. However, authcache and other caching modules often have node add, node edit, and other (CRUD) forms excluded from the pages the module will cache.

Why? What is it about a form that it should not be cached? Is there any potential danger in allowing these modules to cache forms found in the authenticated areas?

# Answer
Forms have unique build ids that identify a particular submission. Caching would defeat that and thus defeat Drupal's ability to detect duplicate or invalid form submissions.
> 2 votes

---
Tags: 7, caching, performance
---


title: Services Using views having search

text:
# Question
Title: Services Using views having search
I am using Drupal 6. and using services and view\_service module .

I have created a exposed filter view.
here is screenshot for that view

now i am using service module

here is screen shot

now i want to pass filter result to get name . does anybody tell me how to pass exposed filter arguments in web services. Thanks

# Answer
> 2 votes
If you try using filters via the UI on the page itself (not via a services endpoint request), check how the URL changes. If you are not using AJAX in your view, the URL should append all filter values to itself. Then in your services request (poster), try sending in that same URL pattern with the filter arguments in it.

For example, when I used a node title filter on my view and submitted it, I got this URL returned `.../testpage?title=testfilter`. Then try sending the poster request to this URL with the filter value of your choice.

---
Tags: views, 7, services
---


title: Responsive Superfish module?

text:
# Question
Title: Responsive Superfish module?
I'm trying to make responsive the menu generated by the superfish module and using the Omega theme by using this appoach:

Demo (try resizing your browser)

Script on Github

I also found a theme for joomla which include a superfish responsive menu: here

Before wasting time... Is there any other **tested** solution out there?

# Answer
Superfish is now responsive. ;)
> 0 votes

---
Tags: theming, navigation
---


# Question
Title: D6 - Trying to display variable_get()s in a block
I am trying to display 4 variables in a custom block(created from my custom module). I am accessing the variables using variable\_get('$myvariable', '0').

I am not able to display the array in the block "$content" - is my code not handling the renderable array properly?

```
 function neil_block($op = 'list', $delta = 0, $edit = array()) {
switch ($op) {
case 'list':
  return array(
    0 => array(
      'info' => t('Custom Neil Block'),
    ),
 );

case 'view':
    $subject = '';
    $content = '';
    switch ($delta) {
        case 0:

          $block_content = "";

          $block_content = array(
            'content'   =>  array(
                'blockvar_progress_so_far'          =>            variable_get('progress_so_far', '0'),
                'blockvar_number_of_projects'       => variable_get('number_of_projects', '0'),
                'blockvar_dollars_raised'           => variable_get('dollars_raised', '0'),
                'blockvar_number_children_impacted' => variable_get('number_children_impacted', '0'),

            ),
          );

          $content = $block_content;
          $subject = t('Subject in My Custom Block');
        break;
    }

    }
return $block;
break;

```

} }

Instead of the "$block\_content", I only see the following: "Array"

# Answer
> 2 votes
You need to return the output of the block content as a string, not an array.

```
...
case 'view':
  $subject = '';
  $content = '';
  switch ($delta) {
    case 0:
      $subject = t('Subject in My Custom Block');
      $content =
        'blockvar_progress_so_far = ' . variable_get('progress_so_far', '0') . '<br />' .
        'blockvar_number_of_projects = ' . variable_get('number_of_projects', '0') . '<br />' .
        'blockvar_dollars_raised = ' . variable_get('dollars_raised', '0') . '<br />' .
        'blockvar_number_children_impacted = ' . variable_get('number_children_impacted', '0');

      // Return values so they can be inserted into block
      return array(
        'subject' => $subject,
        'content' => $content,
      );
    break;
  }
...

```

See documentation on Drupal 6's hook\_block() for a more detailed example.

# Answer
> 1 votes
You are not assigning anything to the `$block` variable. Take a look at the following snippet from the Block example module.

```
case 'view':
  // If $op is "view", then we need to generate the block for display
  // purposes. The $delta parameter tells us which block is being requested.
  switch ($delta) {
    case 'configurable-text':
      // The subject is displayed at the top of the block. Note that it
      // should be passed through t() for translation.
      $block['subject'] = t('Title of configurable-text block');
      // The content of the block is typically generated by calling a custom
      // function.
      $block['content'] = block_example_contents(1);
      break;
    case 'empty':
      $block['subject'] = t('Title of block #2');
      $block['content'] = block_example_contents(2);
      break;
  }
  return $block;

```

In your case it would be:

```
  case 0:
    // other code here
    $block['subject'] = t('Subject in My Custom Block');
    $block['content'] = $block_content;
  break;
  // etc

```

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


# Question
Title: zero distance in views geofield proximity problem
I am having trouble getting it views to calculate the distance. I want a current user to see the distance to other users however the only result I have gotten is 0 between users.

I tried to follow this and still got no result:

> Looks pretty straightforward using geofield 7.x-2.0-alpha2:
>
> I assume you have geofield and geophp enabled and assume you have added a geofield to your users that get the location from an addressfield.
>
> create a view of type users add "\[name of your geofield\] - proximity" field select "source of origin", I tried "exposed geofield proximity filter", check the "round" box add "\[name of your geofield\] - proximity" exposed filter and select a "source of origin point" as well. For example, add a "geocoded location" (fancy word for address) add that same field to your sort options to sort by proximity as well. In your example you would probably change the "source of origin point" to "current user".

I have checked the users address and they create points. Do anyone have an idea how to get it to work?

# Answer
I just posted a new documentation page for geofield that shows how to setup a basic proximity search: http://drupal.org/node/1944648
> 2 votes

# Answer
At first I also received only zeroes in the proximity field.

I had created an addressfield field for user location, as well as a geofield field which used that addressfield to store geocoded data.

In views, I set the "Geocoded Location - proximity" settings to: Round: \[checked\] Source of Origin: Current User Source Field: \[name of geocoded user field\]

Still zero; I returned to my test user page and manually entered a location (rather than relying on Smart IP/automatic geolocation) and saved the data.

I also succeeded in adding a contextual filter for User Location: \- Selected filter: Global: Null \- Selected "Provide Default Value" for "When the filter value is NOT in the URL:" \- For Default Value type, selected in dropdown menu: Visitor location attribute (via IP Geolocation) \- For "Location attribute to use," selected "Postal Code."

After updating user data and adding the contextual filter, I received non-zero results for the proximity field.

However, deleting the filter did not change results, so I believe it was the newly-saved user data that made a difference.

Hope this helps in your troubleshooting.
> 1 votes

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


title: A module for generating PDFs

text:
# Question
Title: A module for generating PDFs
I have tried PDF using mPDF and Printer-friendly pages (Drupal 7.x). They both need own styling of an output. I have got a CSS that formats my pages for printing. I would like to generate PDFs by just "printing" to them. I do not want to maintain separate styles.

Is there a module that generate a PDF file with an output that would be sent to a printer?

# Answer
Try Printer, email and PDF versions module.

> This module allows you to generate the following printer-friendly versions of any node:
>
> Printer-friendly version (webpage format) (at www.example.com/print/nid)
>
> PDF version (at www.example.com/printpdf/nid)
>
> Send by email (at www.example.com/printmail/nid)
>
> where nid is the node id of content to render.
> 4 votes

---
Tags: 7, files
---


title: Themekey & Organic Groups

text:
# Question
Title: Themekey & Organic Groups
I have a case scenario in which different organic groups can have different themes. Using "Themekey" I allow the user to select a theme when the group node is created and it works fine. When the user is on the group's home page the right theme is selected but when you click on any content (i.e. group content type) that belongs to that group the theme goes back to the default theme. Is there anyway to apply the parent group theme to all content automatically?

Thank you.

# Answer
I managed to achieve the desired result by using "OG Theme" Module. It adds a field to GROUP pages from which you can select a different theme for each group. Themekey is quite awesome and I will still use it to do mobile version.
> 0 votes

---
Tags: organic-groups, theme-negotiation
---


# Question
Title: How to override default theme to custom module path theme
Is it possible to create template file for custom module created page that override default page theme only when the path is visited?

The code i tried so far is displaying my custom module result inside default page theme content area. I want to display result in my self created template file content area. Is it possible?

```
function mymodule_menu(){
    $items = array();
    $items['mymodule'] = array(
        'title' => 'Mymodule title',
        'description' => 'Mymodule description',
        'page callback' => 'mymodule_page',
        'page arguments' => array(),
        'access callback' => TRUE,
        'type' => MENU_LOCAL_TASK,
    );
    return $items;
}

function mymodule_theme() {
    return array(
        'mymodule_theme_page' => array(
            'arguments' => array('mymodule' => NULL),
            'template' => 'page-mymodule',
            'path' => drupal_get_path('module', 'mymodule').'/template',
        )
    );
}

function mymodule_page(){
    $mymodule = array('key'=>'Hello World');

    $output = theme('mymodule_theme_page', $mymodule);
    return $output;
}

```

# Answer
> 3 votes
The "most drupal" approach would be to place a copy of your template in your theme's directory named `page-mymodule.tpl.php` (eg, page-PATH.tpl.php) and be done with it. However, there are some cases where you may want to do this theming in a module, in which case you could do something along these lines in `mymodule.module`:

```
  // tell drupal that you want to use page-mymodule.tpl.php if you
  // are looking at www.yourhost.com/mymodule

  function mymodule_preprocess_page(&$vars) {

    if ($_GET['q']=='mymodule') {

      $vars['template_file']='page-mymodule';

      $vars['new_variable']=array('foo','bar','baz'); // $new_variable is now available in the template

    }

  }

  // tell drupal to look in .../mymodule/tpl/page
  // for page templates before looking anywhere else

  function mymodule_theme_registry_alter(&$theme_registry) {

    $theme_hook = 'page';
    $modulepath = drupal_get_path('module', 'mymodule') . '/tpl/page';
    array_unshift($theme_registry[$theme_hook]['theme paths'], $modulepath);

  }

```

Now, if you have `page-mymodule.tpl.php` in the directory `.../mymodule/tpl/page` and you rebuild your theme registry, easy if you have the Admin Menu module installed, otherwise, just clear all your caches, you should be on your way to using a page template in your module for that path.

(And, of course, in your page callback, you can return whatever content you want displayed in the content area of this template without using any of the theme functions you have in your original question.)

ADDITION: you can use the preprocess\_page() hook to add any number of variables that are to be available to the template. So, in the above, you now have $new\_variable available to use in there.

---
Tags: theming, 6
---


title: Openlayers Scalability suggestions

text:
# Question
Title: Openlayers Scalability suggestions
So, like everyone, when I came accross the requirement to incorportate maps into my Drupal site, I googled for solutions and that pretty much led me straight to the Openlayers/Geofield solution. Not even sure there is another acceptable out-of-the-box module out there.

Anyway, the module works wonders, it delivers perfectly but I have some questions/issues regarding performance.

What I need to represent in my map, are user entities. The users have a "Location" field, which is a geofield autocomplete. The site (largely due to migrationg) numbers 10.000 users currently. Granted, not all of them will actually be active, but in the worse case scenario, trying to load all 10k users results in very high waiting time in the Data Overlay step meaning the production of 10k projection items for the map to display.

Since the location field was not migrated, I initially filtered by having the field NOT NULL. This will skip querying for useless entities. But as I said, having 10.000 "active" users, who have edited their data and filled in that field might cause a system overhaul when people try to view the map.

**Question 1**: Could the fact that I was querying for users with Location values of NULL have resulted in higher waiting time? I mean, 10.000 users with actual data may get processed faster than 9.000 users with NULL set as location?

**Question 2**: Are there any general suggestions to somehow improve the map's performance? Reminding that the delay occurs in the projections' production process.

# Answer
> 0 votes
I haven't used mapping yet because of the performance contraints of showing more than a few hundred points on an openlayer map.

Leaflet Marketcluster promises to solve this problem:

> All Leaflet maps will now be using clustering out of the box.

---
Tags: 7, javascript, views
---


title: Allow public to edit content type

text:
# Question
Title: Allow public to edit content type
I have a content type that users can vote on so I need that content type to keep tally of the votes.

I'm assuming I need to allow the public to edit that content type but, unsure how to go about doing so.

I on the daily basis use web services on other projects and would just POST the data to the entry on click of a button or something. **Is it a similar way just POST a change to the content type via ajax in drupal?**

Sorry if this is a dumb question, majority of my skills are in front-end dev not server side so any help is appreciated.

# Answer
I'm not sure I understand you correctly but let me clarify:
**A**.If you have a new content type that users can vote for that. You just use the votingapi http://drupal.org/project/votingapi and use with Fivestar module http://drupal.org/project/fivestar or plus1 module http://drupal.org/project/plus1. You will go to plus1 or fivestar for setting the content type that be voted.
**B**.To determine the total of the votes of your content type you should do following:

1. Create a new view and choose the type of your content, remove sort options, fields and other default settings.
2. Add a field for "Content: Type" Expand the "advanced" part on the right and set "Use aggregation" to "Yes"
3. Create the relationships with votes table("Content: Votes")
4. Add another field for "Content: Votes", click "Aggregation settings" and set the aggregation type to "count"
5. The second "Content: Votes" should now look like " COUNT(Votes: Value)" and now you can see your content type and the total votes of that.

**C**. In order to anonymous users can edit your content type just go to permissions and set configuration for anonymous users.
> 1 votes

# Answer
If the "edit" type you need is just for voting purpose, take a look to Flag module
> 0 votes

# Answer
The Fivestar module allows voting permissions to be configured by role, including the anonymous role. The voting is tallied by the module, not in the content type being voted on, so the user does not need any permission but 'View Content'.

You should never give content edit privileges to an anonymous user. Requiring a user to log in before they are allowed to change information on your site is a basic security measure. If a user makes a change, you are able to attribute the change to the user. If the user does something unwanted, then you can deal with that user accordingly.
> 0 votes

---
Tags: nodes, ajax, 8
---


# Question
Title: How to enable caching for ajax callbacks, especially for colorbox node?
I am using colorbox node module on my site, and it looks like the ajax callbacks for rendering the node are not cached at all. Tested it with a simple snippet in the node template:

```
<div>generated on <?php $dt=new DateTime();print $dt->format('d.m.Y H:i:s');?></div>

```

Colorbox is using a custom display, to have a custom node.tpl

```
function mytheme_preprocess_node(&$vars) {
  if ($vars['node']->type == 'my_content_type' && $vars['view_mode'] == 'colorbox') {
    $vars['theme_hook_suggestions'][] = 'node__my_content_type__colorbox';
  }
}

```

Caching for anonymous user is turned on and works for node pages.

is this issue related to colorbox node (e.g. missing caching implementation in colorbox node) or some other module?

I dived into the code of colorbox node and found out that the click on a colorbox link will be rewritten and rerouted through this menu:

```
/*
 * Implements hook_menu().
 */
function colorbox_node_menu() {
  $items['colorbox/%colorbox_node_url'] = array(
    'page callback' => 'colorbox_node_output',
    'page arguments' => array(1),
    'access arguments' => array('access content'),
    'load arguments' => array('%map'),
    'delivery callback' => 'ajax_deliver',
    'theme callback' => 'ajax_base_page_theme',
    'type' => MENU_CALLBACK,
  );
  return $items;
}

```

is there a way to cache `'delivery callback' => 'ajax_deliver',` without hacking the `colorbox_node_output()` function? Whats the best practice here to get this into caching? I think implementing a cache inside `colorbox_node_output()` might already be too late because it is running through the complete bootstrap process before executing that function.

# Answer
This can be done. Will require 2 hooks hook\_menu\_alter() & hook\_boot() and some non trivial code.

Top level overview of how to do this:
Use hook\_menu\_alter() to call a wrapper around colorbox\_node\_output() that will cache its output. Use hook\_boot() to check the cache and deliver the cached content, routing the cached content though ajax\_deliver().

An example of cache code flow can be seen in the 6.x-2.x ESI module. esi\_get\_page\_cache() gets called from esi\_boot. esi\_set\_page\_cache() is what sets the cache; you can see it getting called at the bottom of these functions: esi\__block\_handler() & esi\__panel\_pane\_handler(). Side note: A big reason the ESI module's cache code has a lot of complexity is it's compatible with D6 core and Pressflow; both have different code for the page cache.
> 1 votes

---
Tags: ajax, caching, performance, javascript
---


# Question
Title: Is there any gain using Memcached module when APC is running good on large Drupal 7 site (one server)
I am successfully using the APC Cache module on my prod website (single server). APC is performing good, caching is done very well. I wonder could I gain anything more by implementing Memcache.

I tried it briefly on dev server, I see they can run one with another (Memcached Admin shows many hits in log). But i do not see any performance gain (haven't done precise measurements).

I should mention it is pretty large site, i use 256MB for APC (sometimes cache use is almost full), there is many content types, fields, nodes(over 10k), contrib modules (425 tables in db).

I am pasting at the end of the question my settings.php config (dev, prod just have not memcached implemented). There seems not much logic if i use cache\_default\_class twice, as Memcache will be used (declared lately).

So - have anyone used those two together when using one server? Is there any performance gain ? What are config ?

In addition, Memcached Readme.txt suggests using

```
$conf['cache_class_cache_form'] = 'DrupalDatabaseCache';

```

but APC Readme.txt does not suggest that. I wonder why ?

Here is my code (using APC for Drupal backend cache)

```
# APC
$conf['cache_backends'] = array('sites/all/modules/contrib/apc/drupal_apc_cache.inc');
$conf['cache_default_class'] = 'DrupalAPCCache';
$conf['page_cache_without_database'] = TRUE;
$conf['page_cache_invoke_hooks'] = FALSE;

# Memcache
$conf['cache_backends'][] = 'sites/all/modules/contrib/memcache/memcache.inc';
$conf['cache_default_class'] = 'MemCacheDrupal';
$conf['cache_class_cache_form'] = 'DrupalDatabaseCache';

```

# Answer
> 4 votes
Putting the cache\_form on the database is a good idea. I will help to prevent errors like this: http://drupal.org/node/500646

APC vs Memcache when it comes to the drupal cache mainly comes down to a persons preference. Mine is towards memcache because it allows for a multiple web head server setup. Performance wise APC will usually be a touch quicker, but my vote is still for memcache even on single server setups.

---
Tags: performance, caching
---


# Question
Title: Submit handler is not getting called inside theme function
I have created a draggable table and add a submit button below it. I am able to view the submit button but submit handler is not working. Below is the code.

```
function form_content_reorder($form, &$form_state)
{
$form = array();
$form['items'] = array();
$form['items']['#tree'] = TRUE;
$form['#theme'] = 'usercontentranking_reorder_form';
$form['name'] = array(
 '#type' => 'item',
 '#markup' => 'Hello  '.get_genderval($user_data['gender']).$user_data['user_name'],);
$form['submit'] = array(
 '#type' => 'submit',
 '#value' => t('Save Preferences'),
 '#submit' => array('user_content_ranking_save'),);
 return $form;
 }

function usercontentranking_theme($existing, $type, $theme, $path) {
$themes = array(
'usercontentranking_reorder_form' => array(
  'render element' => 'element'
),
);
return $themes;
}

function theme_usercontentranking_reorder_form($vars) {
$element = $vars['element'];
drupal_add_tabledrag('draggable_table', 'order', 'sibling', 'weight-group');
$header = array(
 'label' => t(''),
 'label2' => t(''),
 'weight' => t('Weight'),
 'operations' => t('Operations'),
);
$rows = array();

foreach (element_children($element['items']) as $key) {
$row = array();
$row['data'] = array();
$row['data'][] = drupal_render($element['items'][$key]['title']);
$row['data'][] = drupal_render($element['items'][$key]['user_fields']);
$row['data'][] = drupal_render($element['items'][$key]['weight']);
$row['data'][] = drupal_render($element['items'][$key]['operation']);
$row['class'] = array('draggable');
$rows[] = $row;

$themes = drupal_render($element['name']);

$themes .=theme('table', array(
  'header' => $header,
  'rows' => $rows,
  'attributes' => array('id' => 'draggable_table'),
));

$themes .= drupal_render($element['submit']);

return $themes;
}

function user_content_ranking_save($form, &$form_state)
{
  print "text";
}

```

The line **$themes .= drupal\_render($element\['submit'\]);** able to show up the button but the function user\_content\_ranking\_save is not getting called. Please help me in this.

# Answer
> 2 votes
It looks like you are declaring your submit button's submit handler correctly. Rather than debugging with `print()`, try using `drupal_set_message()` or the `Devel` module's `dpm()`.

Example with `drupal_set_message()`:

```
function user_content_ranking_save($form, &$form_state) {
  drupal_set_message('Submit handler was called.');
}

```

**Edit:**

Also, if you are constantly refreshing the same form, Drupal may have cached it. Try clearing your cache and see if your submit handler is now being called.

**Answer:**

Are you sure the whole form is being rendered when using your theme function? It may be that the form is not being validated because the rendered output of the form does not contain the form\_id, form\_build\_id, and/or form\_token.

---
Tags: 7, forms, theming
---


# Question
Title: Changing Button Text on Content Type form
I created a content type called "video" and I created a module named df\_video.module with:

```
function df_video_video_node_form_alter(&$form, &$form_state) {
    $form['actions']['submit']['#value'] = t('Upload');
}

```

I am trying to change the button text of my Video content type form from "Save" to "Upload" but nothing seems to work when I hit refresh. I also tried clearing the cache. I've tried many variations of the function name with no success. I would prefer to use the specific name of the form in the function name so I don't need to do a switch statement.

Also, just out of curiosity does anyone know if there is something special for placing hooks in a .inc.php file? Not doing this currently but I'm thinking it would just be an include to the main module file.

# Answer
> 2 votes
You cannot target only the `video_node_form` with an existing hook in D7, but you can target all node forms and then check against the node type to alter the form. Take a look at the documentation and comments on hook\_form\_FORM\_ID\_alter(). It may also help to check out how the Book module implemented this hook in D7.

```
function df_video_form_node_form_alter(&$form, &$form_state, $form_id) {
  $node = $form['#node'];
  if ($node->type == 'video') {
    $form['actions']['submit']['#value'] = t('Upload');
  }
}

```

With regard to your second question, you generally want to place your hooks in the `.module` file so that they are guaranteed to be picked up by Drupal. There are some cases where this is not necessarily necessary, like in hook\_views\_api() where you can points to a file containing other views-specific hooks.

---
Tags: 7, nodes, forms
---


# Question
Title: With Omega, how to inline branding zone with header zone
I want set my branding (logo) zone to 4 cols to the left, and the header zone (8 cols) with the two header regions, inline to the right.

Do I simply do this in CSS? Do I specify the branding and header zone wrappers?

# Answer
> 1 votes
You would just use 1 of the zones, not both. Either move the header regions to the branding zone, or move the branding zone to the header region. Think of it as zones being vertical and regions being horizontal, if you want some regions inline, they should be in the same zone.

---
Tags: 7, theming
---


# Question
Title: Filter child field options by a parent field
There are many scenes, each assigned by an entity reference field to exactly one show. Same for set pieces.

Show
—Scene
—Set piece

I am using entity references rather than taxonomy so that non-technical users can add shows, scenes and set pieces easily. And when users add content, they select a reference to show it belongs to, and optionally a particular scene and optionally a particular set piece.

When they select the show on the first field, how can I have scene and set piece fields under it only show the scene and set piece options for that show?

# Answer
I have done this type of thing before. I did it by creating a map (array) of what 'scenes' belong to which 'shows' and sent the javascript array to the page with a hook\_form\_alter. I then used javascript/jquery to listen for the change event on the 'show' dropdown which then hid or displayed the the corresponding 'scenes' using the array as reference. It could also be done via ajax if you preferred.
> 1 votes

---
Tags: entities
---


# Question
Title: Can't get neither CKEditor nor WYSIGYG Module to work!
I have the Drupal 7.21 installation and I am using a downloaded theme (premium responsive). I am trying to install an editor for my website entries but I have not been able to get it to work. This is the information on the two I have tried:

CKEditor version 4.0.2 and CKEditor Module 7.x-1.12 OR WYSIWYG Module version 7.x-2.2 with TinyMCE 3.5.8

I have carefully checked the installation instructions for all and they are correctly installed. I have been able to enable both (not at the same time, obviously) without any errors. However, when I try to add content I don't see the toolbars, only the plain white box.

So far it has been very frustrating. I have checked every thread that describes similar problems and tried every suggestion but it just won't work.

Can anyone provide a suggestion?

Thanks!

# Answer
1. Go to /admin/config/content/formats and make sure you have a text format for the role(s) you are working with.
2. Go to /admin/config/content/wysiwyg and make sure you have added buttons to the editor (click on "Edit" and then under Buttons & Plugins).
> 1 votes

---
Tags: wysiwyg
---


# Question
Title: How to Display a Block on a Page with a Variable URL
I want to show a block only on these user pages: .../user/**USER\_ID**/recurring-fees. What will be the code to be placed in the PHP box to make this work?

# Answer
> 2 votes
I'm not sure what you mean by the PHP box. You could do this with the block's visibility settings. For example, if you wanted to show the "Powered by Drupal" block on only the URLs you mentioned, you would go to...

```
/admin/structure/block/manage/system/powered-by/configure

```

...and in the Pages tab of the Visibility Settings, enter...

```
user/*/recurring-fees

```

Also make sure you have ticked the radio button for **"Only the listed pages"**.

If you are coding the block yourself, you could do something toward the top of your block function like...

```
if ('user' !== arg(0) || !is_numeric(arg(1)) || 'recurring-fees' !== arg(2)) {
 return array();
}

```

See http://api.drupal.org/api/drupal/includes!bootstrap.inc/function/arg/7

But the usual approach is to use the visibility settings.

---
Tags: blocks
---


# Question
Title: Calculate field value based on another field value with Rules
I am using Drupal 7 and Commerce.

I have Product display where is custom field called **Stock** (field\_stock). This field holds stock value (integer) for Product.

In Product display I have Product Variations. Variations has custom field called **Stock Value** (field\_stock\_value).

When adding new Product display and setting field **Stock** to value 10. And then adding first Variation and setting field **Stock Value** to 6. And to second Variation field **Stock Value** to 4.

I need to have rules which decreases Stock field from Product display. So it is simple: take value from **Stock Value** field and reduce that amount from **Stock** field.

But I have not succeeded to make working rules for that. Any help needed. Thanks!

# Answer
Try Computed Field

> Computed Field is a very powerful CCK field module that lets you add a custom "computed fields" to your content types. These computed fields are populated with values that you define via PHP code. You may draw on anything available to Drupal, including other fields, the current user, database tables, you name it. (Feeling the power yet? :) ) You can also choose whether to store your computed field values in the database with other content fields, or have them "calculated" on the fly during node views. (Although you should note that Views use requires database stored values.) This field is literally the Swiss Army knife of CCK fields. So start cooking up your PHP based values!

Check Conditional Fields too

> Define dependencies between fields based on their states and values.
> 2 votes

---
Tags: 7, entities, commerce, rules
---


title: How to limit the number of privatemsg?

text:
# Question
Title: How to limit the number of privatemsg?
To avoid bulk private messaging by spammers in busy Drupal 6 community site, I'd like to limit the messages an authenticated user can send out in certain time span. I saw Private Message Limits but it is still in dev since 2011 hence it may not be ready for production. So I'm wondering what is the best way to apply the limit? Thanks

# Answer
> 3 votes
Privatemsg 6.x-2.x has a Limits submodule built in, either use that version or use try out the separate project for 6.x-1.x, you will have to find out yourself it is working well enough for you.

---
Tags: privatemsg, advertising
---


title: Contextual filter and path alias

text:
# Question
Title: Contextual filter and path alias
I'm using **Contextual filter** on a view block which reads values from URL. This works on pages that created by Panels; however, it doesn't work on nodes(content type). I'm using url alias for nodes. It seems like even though the url displayed in defined alias, it doesn't pass the alias value when contextual filter read the node's url. The field that I'm using for the url alias is text list field.

Is there any way to make a view block with contextual filter on both pages and nodes?

Drupal 7.12 | views 7.x-3.3 | panels 7.x-3.2

# Answer
I ran into a similar problem recently. The issue is that internally the "Raw value from URL" doesn't get its data from the URL, it gets its data from the *unaliased* url. So if you have a node with an alias like mysite.com/foo/bar, you would expect 'bar' to be the argument passed with a path component of 2.

However since foo/bar is actually node/123, internally it becomes node/123, and '123' is what gets passed to the view.

I have opened a ticket in the views issue queue (http://drupal.org/node/1658352). Hopefully it will see some light with a proper fix, as I dont believe that the expected behavior is to retrieve the unaliased path.
> 2 votes

# Answer
You can use "Provide default value" with type "PHP code". Inside PHP code you can get request\_uri() which has alias and if you need argument from this alias, just use this code:

```
arg(1, request_uri())

```
> 1 votes

---
Tags: path-aliases, views
---


title: Lengthy MySQL query being exec

text:
# Question
Title: Lengthy MySQL query being exec
I've inherited a Drupal site that is experiencing slow load times and I'm trying to troubleshoot the problem. The site is run on a dedicated box with what should be enough resources.

I ran the Devel module to see the MySQL queries and it's telling me that the following query is being run four times taking a total of 2-3 seconds.

```
execute SELECT DISTINCT node.nid AS nid, node.title AS node_title,
node_revisions.body AS node_revisions_body,
node_revisions.format AS node_revisions_format, node.sticky AS node_sticky,
node.type AS node_type FROM node node LEFT JOIN node_revisions node_revisions
ON node.vid = node_revisions.vid WHERE node.status = 1 ORDER BY node_sticky DESC

```

There are almost 400 other queries that are taking over 10 ms, but this one above is by far the longest and that it is being run multiple times, I suspect is causing some of the load problems.

Any suggestions on what is going on here or where to look for more information? All modules and core files are up to date.

# Answer
You have to work very hard at caching. Particularly if the page is static, then make sure you caching on in Home → Administer → Site configuration.

If this is not enough investigate 'boost cache' or alternative caching systems. This can takes some work to setup/prime and tune.

Caching most effective way of getting drupal-6 to be performant. What queries drupal makes can't really be beaten as you can't change the logic of Drupal. If the queries aren't being made at all because of caching they won't be slow.

Second thing. You could also make sure that MySQL is using INNODB tables and that you have set innodb\_buffer\_pool\_size to as high a level as you can given memory limitations. Here is a MySQL tuning script that might provides some hints http://www.day32.com/MySQL/.

Third thing is to make sure that only the modules that are in use are installed on the system. Every module has an overhead.
> 1 votes

---
Tags: database
---


# Question
Title: How to add text to the user registration form?
I've been using the String Overrides module to change a few of the text fields in the `user/register` form. I've found this approach to be simple and effective.

However, I want to insert some text below the "User Account" heading but above the "Email" field. Just some general information about signing up. Unfortunately there is no text there currently so I can't use "String Overrides". Is there a simple way of adding some text? I don't want to create an entire custom registration form and reinvent the wheel, I just want to add some text to the existing form.

# Answer
If you don't want to write your own custom module, you can use the Field Group module. Enable the module and on the `Manage fields` tab for users, add a `Fieldset` and then set the description to whatever text/HTML you like. Afterwards, just drag it to the place you want it to appear.
> 2 votes

# Answer
You can use `hook_form_alter` like this.

```
  function MODULENAME_form_alter(&$form, &$form_state, $form_id){
    switch($form_id) {
      case 'user_register_form': // the value we stole from the rendered form
        $form['cutomtext'] = array(
        '#type' => 'item',
        '#markup' => '<div > Your text goes here... </div>',
        '#weight' => 1, // Adjust so that you can place it whereever
        );
        break;
    }
  }

```

Form API Reference

Also you could try hook\_form\_FORM\_ID\_alter

Usage :

```
function hook_form_FORM_ID_alter(&$form, &$form_state, $form_id) {
  // Modification for the form with the given form ID goes here. For example, if
  // FORM_ID is "user_register_form" this code would run only on the user
  // registration form.

  // Add a checkbox to registration form about agreeing to terms of use.
  $form['terms_of_use'] = array(
    '#type' => 'checkbox',
    '#title' => t("I agree with the website's terms and conditions."),
    '#required' => TRUE,
  );
}

```
> 9 votes

# Answer
'#type' =\> 'item' won't use attribute #value, it should be changed to #markup

```
function MODULENAME_form_alter(&$form, &$form_state, $form_id){
    switch($form_id) {
      case 'user_register_form': // the value we stole from the rendered form
        $form['cutomtext'] = array(
        '#type' => 'item',
        '#markup' => '<div > Your text goes here... </div>',
        '#weight' => 1, // Adjust so that you can place it whereever
        );
        break;
    }
  }

```

You can also place it in your theme's template.php file. In this case the first line changes to function THEME\_form\_alter(&$form, &$form\_state, $form\_id){...
> 2 votes

# Answer
Possibly a bit late for the OP as he has another solution, but for anyone finding this page from Google, a much simpler way is to create a new block with the required text in and just set it to appear at the top of the main section or in a side bar. This does not get it in between the username and email address, but requires less coding to implement
> 0 votes

---
Tags: users
---


# Question
Title: When exporting .sql via phpMyAdmin do you need to include cache tables?
So I built the D7 site on one server and then moved it to other server and I noticed that .sql size is 8MB in total. I then exported .sql without any cache tables, including cache\_\* files like cache\_block, cache\_views and etc. I skipped all tables starting with cache\_ and the total .sql size was below 2MB!

So when moving site from one server to other do I need to include cache tables when exporting the .sql or not? Because looks like those cache tables takes 80% of .sql size. And as I understand cache is something temporal?

I came up with this question after moving site to new server and I noticed that tmp folder has 100% copies of images that I uploaded to nodes, but those original images are held in separate files/ folder. So now I got those original images 50MB and copies of those images in tmp/ dir and its also 50MB. So I get extra 50MB taken. I was thinking maybe its because I moved the site with all caches without running cron and etc. and maybe somehow those images in the tmp dir got lost and forgotten by Drupal system or something? I now removed those from tmp dir and it seems to be all working fine.

Strange, can't really understand that.

# Answer
> 2 votes
You can typically skip the data in all of the cache tables. That is temporary data that Drupal will recreate when as needed. Basically, the cache tables store data the Drupal creates so that it doesn't need to create it the next time.

You can also usually skip the data in the watchdog table if you don't need the system logs. Depending on your situation, you may also be able to skip sessions.

There are a few others you can skip (like flood), but they don't usually don't have much data in them in most situations.

Just remember that you want to back up the table structure (ie, the `CREATE` statements) and just skip the data.

The Backup and Migrate will take care of most of this for you. `drush sql-dump` can skip table, data too.

Normally, I just transfer everything when moving between servers. I just clear cache as part of the restoration process. I would rather have a bigger file than have the chance of missing something.

---
Tags: 7, caching
---


# Question
Title: How to inform future developers about hack in the core?
Let's say I had to patch a core of some module, for some reason that doesn't matter here. Is there any custom, or convention of informing future developers about it? So they will be aware of it and this may stop them from updating this module without thinking? Like creating a text file in root directory named "core-hacks" or "important-info-for-maintainers"? I have many ideas but is there any common one? Or if there is not, what would you consider the best? (the last one is open question, so you can discuss in comments).

**Added:** I'm considering just creating a directory in root when I will describe what I did and put applied patch, but I'm not sure if this is best what I can do, or if someone may overlook it.

# Answer
> 4 votes
Good question. I know that many Drupal shops have their own rules about documenting patches and hacks, but other than that, I have not seen a convention or standard.

That said, the methods I have seen in various organizations do have some common characteristics. Below are some guidelines that come to mind. Note that these are only meant for non-security patches. If you're fixing a security problem, *never* store the patch in a publicly accessible place (ie. under your web root) and do *not* submit the patch in the issue queue but report a security issue instead.

* Have a single directory with an understandable name where all patches and their documentation are stored. For instance `/patches` or `/sites/all/patches`.
* Add the patch file, stored in the patches directory, to your version control system. If you didn't download a patch, but edited some code yourself, create a proper patch file and add it to your version control system.
* If you wrote the patch yourself, submit it in the appropriate issue queue on drupal.org so it can be reviewed and committed by the project maintainer.
* Create in a text file, eg. `/patches/patches.txt`, and write down:
    + What has been patched
    + Why the patch was needed
    + A link to the issue on drupal.org where you found the patch (or submitted your own).
* When committing all of this to your version control system, write a clear commit message (you always do that, right?) that indicates that you are committing a patch.

IMHO when a developer starts working on a site he didn't build himself, he should always be aware that some code may have been patched. If you use the points above as guidelines your own documentation method, other developers should have no problems in finding out what you patched and why you did that.

# Answer
> 3 votes
Build the site from a make file.

Then you establish a single authoritative source of information on all you versions and patches.

Building the site this way, also makes applying the right patches the default action. If you rely on others to read your documentation, you will definitely have people failing this. Drush make however will always apply the patch, unless told otherwise.

Make files can also have comments, meaning there's a natural place to document why the patch is there. This comment should ideally include a a link to a d.o issue.

More info on drush make

# Answer
> 1 votes
Take a look at Drupal documentation for How to report a security issue.

You definitely do not want to be publicly advertising a security loop-hole you find in Drupal core or a contributed module.

# Answer
> 1 votes
The standard we've currently adopted is as follows:

1. In the .info file, add the suffix -patched to the version number.
2. Ensure all patch files are present in the module's root folder
3. Add an entry in the .info file for each patch that's applied like this:

patches\[\] = name-of-patch-file.patch

All patches should also be tied to a problem report at Drupal.org. This standard means that all patches are identifiable and the reason for their being used is documented publicly (and open to discussion with the world).

---
Tags: 7
---


title: Content type that calls in 5 nodes

text:
# Question
Title: Content type that calls in 5 nodes
I have 3 content types

First is `contest` Second is `contest_applicants` Third is `contest_results`

People will submit `contest_applicants` for a `contest` (with references modules i assume)

When making the `contest_results` content, I need to be able to select specific `contest_applicants`to display in the results. Kinda like nesting the nodes.

I been looking for a module that does something like this hut, had no success.

I would uses views but, it needs to be a content type since it will be multiple `contest_results`

Is there any module I can use to achieve the above setup? Any help is appreciated.

# Answer
Sounds like a job for field\_collection and entityreference

> Provides a field-collection field, to which any number of fields can be attached.
> 1 votes

---
Tags: nodes
---


# Question
Title: Error in php snippet using tokens: Show profile field if it isn´t empty
I have this core profile field in Drupal7: `profile-curso-basico`. I want it to be shown in the user´s profile only if the field has information in it (it´s a deprecated field, but some old users have data in it, and migrate modules didn´t import it properly, because it´s a hardcoded list).

I´m using panels, token and Display Suite modules. At the profile page, I have this panel with a special coded DS field, that has dinamic information using tokens.

If I just paste: `Mi Curso: %user:profile-curso-basico` I get the field information properly, but I want to show it only if profile-curso-basico field isn´t empty.

So I thought of this (the input type is PHP, so I can paste some php code):

```
<?php if (!empty(%user:profile-curso-basico)): ?>
%user:profile-curso-basico
<?php endif; ?>

```

And I´ve got this error:

```
Parse error: syntax error, unexpected T_LNUMBER, expecting T_PAAMAYIM_NEKUDOTAYIM in /home/liga/public_html/modules/php/php.module(80) : eval()'d code on line 9

```

What´s wrong with that snippet? Maybe I shouldn´t add tokens into (!empty( )) ? How may I change that in order to work? Thanks!!

# Answer
> 0 votes
You must refer to the actual field in your snippet. Try something like:

```
<?php
global $user;
if (isset($user->profile-curso-basico[LANGUAGE_NONE][0]['value'])) {
  echo $user->profile-curso-basico[LANGUAGE_NONE][0]['value'];
} ?>

```

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


title: Creating a Home Page Template

text:
# Question
Title: Creating a Home Page Template
The index page of a site I am building is to be a video and nothing else which clicks through to the site.

I have read about page templates and seen some modules called 'front page' but I would like to to do this within the code.

Is there a best advised / standard way to do this?

I have tried setting an if statement for $front\_page but this seems to happen for every page.

# Answer
The variable you wish to test is $is\_front, which is only true for the front page.

You can find a list of the variable available for page.tpl.php here.
> 0 votes

---
Tags: 7, theming
---


title: How to create a GET-form

text:
# Question
Title: How to create a GET-form
For example a filter form on admin areas can best be GET forms, that way they are bookmarkable and can filters be maintained across pager-pages.

How can one best use form\_api for such forms? Will the \_validate hooks be submitted? Can the \_submit hook be omitted?

For example views-exposed filters work this way; But the code in views handling this is convoluted and complex, too complex to be used as good example for when developing custom interfaces with simple filter forms.

# Answer
> 11 votes
Use the #method parameter of the form like this:

```
<?php
  $form['#method'] = 'get';
?>

```

# Answer
> 4 votes
Just in case anyone stumbles upon this question, this is a more complete real-life, yet very simple example :)

you will want to **define the form**

```
function YOURMODULE_search_form($form, &$form_state) {
  $form['#method'] = 'get';
  $form['#action'] = '/search';
  $form['#attributes'] = array('class' => array('mymod-search'));
  $form['search'] = array(
    '#type' => 'textfield',
    '#size' => 20,
  );
  return $form;
}

```

and then you can **use it**

```
$searchform = drupal_get_form('YOURMODULE_search_form');
$output .= drupal_render($searchform);

```

The last line could be i.e. a block\['content'\] or whatever you need.

---
Tags: forms
---


# Question
Title: View to display nodes with a random term
I have got a view that selects some images. Each image is tagged with a taxonomy term. I would like the view to display only images tagged with a common term that is chosen randomly at every use.

The view is used as a block.

Example: term: a, images: img1, img2, img3; term: b, images: img4; term: c, images: img5, img6;

One user sees a sequence of img1, img2 and img3. Another one sees img4 only. A next one sees img4 too.

How should I do it?

# Answer
> 2 votes
I would set up an argument (D6) / contextual filter (D7) to filter the view results based upon a taxonomy term, and then for the argument/filter value, select the PHP option for providing the default, and in there randomly return one of your taxonomy terms. Without actually testing the code, I would imagine using array\_rand() would make this rather trivial, eg:

```
$terms=array('foo','bar','baz');
return $terms[array_rand($terms)];

```

---
Tags: views
---


# Question
Title: How can I use a custom table as a node type?
I am reasonably new to Drupal, I have written a couple of basic modules by following the excellent videos from buildamodule.com

Now I need to somehow integrate an existing table into a drupal site. I would like this table to be accessable as a content / node type to the rest of the drupal system. I do not want to add this as a content type to drupal and use the table per field system drupal has as I already have the table structure and need to be able to update the data in this table from an external source.

I tried creating a new content type in a module and was able to create a schema using the schema module. However when i use `field_create_field` and `field_create_instance` I end up with a seperate set of fields.

How do I create a new content type in a module that can use an existing table for its data ( even if I need to provide access functions in my module)?

Is there a good tutorial somewhere that someone knows of?

# Answer
> 1 votes
While you're making work for yourself using a custom table and not the Field API, you can use your own table with

You'll probably also need

if you want to add form elements to the node form.

Keep in mind the Field API will do that all for you though if using standard fields.

---
Tags: 7, nodes, database
---


# Question
Title: How to add facebook iframe code directly to block?
I am trying to display a facebook plugin as a block. I created a new block from the block admin page, and in the "Text" for the block entered the following iframe code and tried a couple of things (none worked) - all show the raw iframe code in the block.

1. Tried 'Input Format' as FULL HTML (doesnt work)
2. Tried 'Input Format' as "PHP" (doesnt work, even tried adding tag.)

Following is the iframe code I am trying:

```
<iframe src="//www.facebook.com/plugins/follow.php?href=https%3A%2F%2Fwww.facebook.com%2Fzuck&layout=standard&show_faces=true&colorscheme=light&font=verdana&width=450&appId=133506150025748" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:450px;" allowTransparency="true"></iframe>

```

# Answer
Just use "Full HTML" input format and paste the iframe snippet in the *source view* of the block (e.g click "Source" on rich-text editor toolbar first )
> 4 votes

# Answer
please make sure that you use full html (no filtering) and make sure you direct html and not using that through TinyMCE or any wysing Editor
> 1 votes

---
Tags: 6, blocks, social-network
---


# Question
Title: Custom Javascript Not Loading On Paginated Pages (Except First Page)
I am running the following jQuery that affects elements on a page view.

```
$(document).ready(function($){
    $(".views-field-field-video").click(function() {
        $(this).parent().find("a.cboxElement").click();
    });
});

```

The code works perfectly, but only on the first page. When I use the pager at the bottom and navigate to any other page, the script does not work. Then, when I navigate back to the first page, the script also fails.

If I reload the page however, it brings me back to the first page and the script works again.

EDIT: The classes I am selecting in the script remains the same on all pages.

# Answer
The problem is when using ajax pagination in the view, document.ready isn't called.

Instead you should follow best practice and use Drupal.behaviors instead.

That way, the behavior will run on document.ready and on the ajax refresh.

Try this:

```
(function ($) {

  Drupal.behaviors.cboxClick = {
    attach: function (context, settings) {
      $(".views-field-field-video").click(function() {
        $(this).parent().find("a.cboxElement").click();
      });
    }
  };

})(jQuery);

```
> 1 votes

# Answer
```
(function ($) {
  $(document).ready(function($){
    $(".views-field-field-video").click(function() {
        $(this).parent().find("a.cboxElement").click();
    });
  });
})(jQuery);

```

Or

```
jQuery(document).ready(function(jQuery){
  jQuery(".views-field-field-video").click(function() {
      jQuery(this).parent().find("a.cboxElement").click();
  });
});

```

... May fix your problem. There could be a fix on your normal pages that converts $ to jQuery, but not in the pagination. Conspiracy theory, but considering you're using $ in your snippet above I think it's the first place to look.

http://drupal.org/update/modules/6/7#javascript\_compatibility

> JavaScript should be made compatible with libraries other than jQuery by adding a small wrapper around your existing code:
>
> (function ($) { // Original JavaScript code. })(jQuery);
>
> This wrapper is an anonymous closure that provides state throughout the page's lifetime and ensures your code does not unintentionally create/override global variables.
>
> It also explicitly imports the global jQuery variable so that your code can use the local $ variable instead of the jQuery global. This is essential because Drupal loads jQuery with noConflict() compatibility so the jQuery library does not setup the normal $ as a global variable.
> 0 votes

# Answer
I stumbled across this while looking for a related topic. I noticed that there was only one upvote. I case that was due to it not solving the issue I've just been working on this problem and this is the solution that worked for me:

Given you're already using jQuery (I'm assuming the latest version) the function you're after would be on().

http://api.jquery.com/on/

What on() does is dynamically update the DOM with any functionality you ask for even after new elements are added via ajax or basic JS.

```
$(document).ready(function($){
  // Attach our function to the click behaviour of all current and future
  // .views-field-field-video elements.
  $(".views-field-field-video").on('click', function() {
    // I'm assuming your original path for this was correct
    $(this).parent().find("a.cboxElement").click();
  });
});

```

With this approach whenever a new ".views-field-field-video" element is added to the DOM the click behaviour will trigger the function that is attached to it.
> 0 votes

---
Tags: views, javascript, paging
---


title: Conditional based field security

text:
# Question
Title: Conditional based field security
Is there any condition based field security in Drupal? E.g. An administrator can only edit user details users who are from the same Country?

# Answer
> 0 votes
You can implement complex field access conditions fairly easily with:

hook\_field\_access

---
Tags: security
---


# Question
Title: How to set access arguments visible to all
i have a simple module which show user to set email frequency but it's content can be seen by only to logged admin users , i want to change it to all the users,in drupal how can i do that

```
function emailf_menu() {
  $items = array();
  $items['emailfrequency'] = array(
    'title' => 'Manage email Frequency',
    'page callback' => 'emailf_page',
    'access arguments' => array('view content')
  );
  return $items;
}

```

# Answer
```
function emailf_menu() {
  $items = array();
  $items['emailfrequency'] = array(
    'title' => 'Manage email Frequency',
    'page callback' => 'emailf_page',
    'access arguments' => TRUE
  );
  return $items;
}

```

`'acces arguments' => TRUE` will allow access to all users, including anonymous
> 4 votes

# Answer
The `'access arguments'` in your `hook_menu` is an array which has the permission `'view content'`; which means that this menu would be accessible only to the users who could view published content. If you want your menu to be accessible to all the easiest way is to use the `'access callback'` instead:

```
function emailf_menu() {
  $items = array();
  $items['emailfrequency'] = array(
    'title' => 'Manage email Frequency',
    'page callback' => 'emailf_page',
    'access callback' => TRUE,
  );
  return $items;
}

```
> 3 votes

---
Tags: 7, forms
---


# Question
Title: How do I use the Video module with Colorbox?
I am using the Video module, and I want to show videos on Colorbox. I have also found a patch for that, but I don't understand something.

I am using the most recent versions.

* Colorbox: 7.x-2.3
* Video: 7.x-2.9

# Answer
I dont know to use video module but can open a video in colorbox easily with Video Embed Field. Just create a content type with field as Video Embed Field and in the manage display tab Select the format as 'Preview with Colorbox'.
> 3 votes

---
Tags: 7, files, javascript
---


# Question
Title: Using Rules to Schedule Publishing/Unpublishing of Content
I have a Triggered Rule that is fired on "Content is going to be saved". What it should do is look at the content type, and if that passes, delete any scheduled task based on that node ID, and schedule the "Publish Ruleset".

The "Publish Ruleset" then is fired, which calls a Schedule Expire Node rule, and Schedule Node Publish rule. The first one schedules another task based on an Expiration CCK Date field, the second publishes the node based on a Publish CCK Date field.

Anytime these rules are fired, any other scheduled tasks with the same node ID are deleted.

Some times nodes are published when they should be, some times they are not, and they don't seem to be unpublished with consistency either.

Is it too specific to have the CCK Date fields using time as well as date for the rule? Should it just be a date without specifying time?

I am having trouble figuring out if this is the correct way to automate the publishing and unpublishing of content with Rules.

I modelled the Rule after this tutorial:

http://drupal.org/node/520012

What I am seeing is sometimes the tasks are scheduled correctly, and the nodes in question are published (or unpublished). The queue never seems to clear itself though. Does Rules know that it can't publish something that is already published, or does it evaluate everything in the queue anyway?

Has anyone found a good way to handle this?

# Answer
I've had a great experience using Scheduler to schedule publishing and unpublishing of nodes automatically.

Although this doesn't specifically answer your question because it doesnt involve rules, its worth mentioning :)
> 4 votes

# Answer
Even though this question is very old.. I wrote small step by step instructions to do this kind of functionality: http://drupal.org/node/520012#comment-7120890

Hope this helps someone.
> 1 votes

---
Tags: 7, nodes, rules
---


title: Assigning template file to a view

text:
# Question
Title: Assigning template file to a view
How to display the custom content type fiels in the custom template file. I have integrated custom content types in views.

How to assign custom template files to a view which is filtered to display certain content type only.

# Answer
> 1 votes
Take a look at Drupal 7 Template (Theme Hook) Suggestions

For content types you can try

**node--\[type|nodeid\].tpl.php**

*base template: node.tpl.php*

Theme hook suggestions are made based on these factors, listed from the most specific template to the least. Drupal will use the most specific template it finds:

1. node--nodeid.tpl.php
2. node--type.tpl.php
3. node.tpl.php

**To theme a view..**

1. Set up your view; by going to Views -\> Add View
2. Once, your view is completely set up, at the bottom of the view (left column), you will see a link called "Theme Information", click on it.
3. What you will be presented with is a list of templates (.tpl.php) files that the views uses to theme your data. Basically the file names that are bolded are the files views is using to theme the data.

Check How to create a Custom Template for a View

---
Tags: views, entities
---


# Question
Title: How to integrate a private Google Calendar?
My client is a counseling center that would like to use Google Calendar to record and manage confidential information when clients schedule appointments online. The catch is that they want it to be a private Google Calendar.

Is this possible?

Can a private Google Calendar be embedded with a drupal site?

# Answer
Check Google Calendar API (GCal)

> This module uses google api php client refer http://code.google.com/p/google-api-php-client/ to interact with google and manage calendars
>
> **Requirements**
>
> GAuth \- Required for authenticating with google.
> 2 votes

---
Tags: datetime, emails, files
---


title: How to Print /PDF entire page

text:
# Question
Title: How to Print /PDF entire page
I was wondering if the Print module can be used to print an entire page, not just nodes. I need to add some blocks to the pdf as well, not just the node content.

Is there any way of doing this, or will I need to manually add the blocks to the `node->content` property?

LATER EDIT: The problem is that the print module takes the node ID as a parameter. This means I cannot print *blocks* on those pages.

# Answer
> 0 votes
Yes. You can show blocks by tweaking templates. See FAQs in the project documentation specifically the entry on blocks.

It says there: add the following to your print.tpl.php template:

```
  print render(block_get_blocks_by_region('content'));

```

**Update** The FAQ also has an entry on Views support. It's doable - have just tested with Drupal 7.20 and Print 7.x-1.2. You have to add the paths to the non-nodes you want in Configuration. There's also a useful point on Views support and hiding the print link on your print out when using Views in the comments on the FAQ page, so worth rooting around there. Don't forget to enable the block to show the print / email / PDF links.

# Answer
> 1 votes
There is a block version of print links `Printer, email and PDF versions`. goto `admin/structure/block` and enable it. next you should goto `admin/config/user-interface/print` and change `Printer-friendly page link` setting to `Block`.

---
Tags: 7, files
---


title: drupal 7.21 views exposed form

text:
# Question
Title: drupal 7.21 views exposed form
The question is - what may be the reason for exposed form to not be working/showing in a block? Thanks so much - hope someone has an idea about that.

# Answer
Assuming that you have chosen 'block' as the display rather than 'page', you have to set 'Use Ajax' to 'Yes' in the Advanced options (See this issue on Drupal.org: http://drupal.org/node/1115782#comment-4384348):
> -1 votes

---
Tags: 7, views
---


title: Show a custom field in a block

text:
# Question
Title: Show a custom field in a block
I 'm getting crazy trying to show a value of a custom field (now in core) in a sidebar block. I have tried to show it with the render function, calling directly the field, with no luck.

I have a custom content type named "content1" and a custom field named "field\_test1"; I want that value to be shown on a block that will be visible while viewing the page node.

Do you have any suggestion on how to do it?

# Answer
I would use the following code, to render a field.

```
render(field_view_field('node', $node, 'field_test1'));

```
> 2 votes

# Answer
Probably the best way would be to create a view, that will output the field you want. And you can create a block out of that view.

If you are new to views, heres a video tutorial on how to do it:

http://learnbythedrop.com/drop/139

With views you can do pretty much without coding.
> 1 votes

# Answer
In your `hook_block_view()` implementation, retrieve the current node with `menu_get_object()`, get the field values using `field_get_items()` and render the first one with `field_view_value()`.

```
$node = menu_get_object('node');
if ($node && $node->type === 'content1') {
  $items = field_get_items('node', $node, 'field_test1');
  if ($items) {
    $rendered_field_value = field_view_value('node', $node, 'field_test1', $items[0]);
  }
}

```
> 0 votes

# Answer
this is the job of http://drupal.org/project/cck\_blocks

when adding a filed you will need to click on available as block.

you may want to hide the display of field from manage display.

Field is available as a block, goto block administration page and place your block in your required region
> 0 votes

---
Tags: 7, theming, entities, blocks
---


# Question
Title: drupal 7 hidden views blocks when node references value is empty
I created Expert and Review content types, both have a node reference field related each other.

```
Expert
    - title
    - field_expert_reviews(node reference)

Review
    - title
    - field_review_expert(node reference)

```

I follow this tutorial create a block show expert's review in the side bar. But I found that when the field\_expert\_reviews is empty, the block doesn't hidden. How to hidden the block when the node reference field is empty?

# Answer
> 0 votes
You need to add a Filter Criteria which validates to "Is not empty (NOT NULL)" on the field which should not be empty.

---
Tags: 7, nodes, views
---


# Question
Title: How do I get the result from a database and show it?
I have a database table with the following fields: name, company\_name, geo\_loction. I want to get those fields using the following query.

```
$zip_code = db_query("SELECT * FROM data_set WHERE id = 1", array(":city" => $city))->fetchObject();

```

Is that the correct code? How do I show the result?

# Answer
> 3 votes
```
//here $id value is hard-coded to 1, you can use your own logic to get the value.
$id = 1;
$result = db_query("select name, company_name, geo_location from {data_set} where id=:id", array(':id' => $id));

//To iterate over each row of the resultset use foreach
foreach($result as $ind_data) {
  echo "name is " . $ind_data->name . "<br/>";
  echo "company name is " . $ind_data->company_name . "<br/>";
  echo "geolocation is " . $ind_data->geo_location . "<br/>";
}

```

---
Tags: database
---