title: Help with adding GMap on contact page

text:
# Question
Title: Help with adding GMap on contact page
I'm trying to add a GMap to my contact page, I don't have the need for Location / GMap modules. I'm following the tutorial here but following it I have to add everything to the head in my html.tpl file:

```
<script>
  function initialize() {
    var map_canvas = document.getElementById('map_canvas');
    var map_options = {
      center: new google.maps.LatLng(44.5403, -78.5463),
      zoom: 8,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    }
    var map = new google.maps.Map(map_canvas, map_options)
  }
  google.maps.event.addDomListener(window, 'load', initialize);
</script>

```

Where else can I place this script? I've tried to add it in a separate JS file and call it through my info file but it doesn't work that way.

# Answer
May be you have miss something.

For Gmap on Drupal site there are many ways to implement.

You can try this approch:

* Put whole the code in any block with full text format.
* Place that block in a specific region.
* Set visiblity of that bock as per your requirment.

Implementation code be like this
> 1 votes

---
Tags: google-maps
---


# Question
Title: To Connect to MYSQL - How to access database array in setting.php
I need to connect to my database in php file in drupal 7. Each time I move from local server to development server, I have to change my db and host. I have seen `setting.php` file which have array of database.

```
$databases = array (
  'default' =>
  array (
    'default' =>
    array (
      'database' => 'my_db',
      'username' => 'root',
      'password' => '',
      'host' => 'localhost',
      'port' => '',
      'driver' => 'mysql',
      'prefix' => '',
    ),
  ),
);

```

How do I aceess this database array in drupal 7 to use it connecting to database

```
$con = mysqli_connect('localhost','root','','my_db');

```

Thanks for Help

# Answer
If you want to access the Drupal database from a standalone script.

Firstly, consider if you can put the PHP code in a Drupal module instead.
Secondly, consider bootstrapping Drupal in your PHP script

```
/**
 * Root directory of Drupal installation.
 */
define('DRUPAL_ROOT', '/var/www/drupal');

// Bootstrap to database level for db api
require_once DRUPAL_ROOT . '/includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_DATABASE);

```

You can then use the Drupal database API to query content from the Drupal database.

Thirdly, if connecting to a different database is required, consider defining the other database in settings.php and switching to a target database using `db_set_active`

```
// Settings.php
$databases['default']['default'] = array(
  'driver' => 'mysql',
  'database' => 'drupal7',
  'username' => 'drupal_user',
  'password' => 'drupal_password',
  'host' => 'localhost',
  'prefix' => '',
);

$databases['other_database']['default'] = array(
  'driver' => 'mysql',
  'database' => 'other_database',
  'username' => 'other_database_user',
  'password' => 'other_database_password',
  'host' => 'localhost',
  'prefix' => '',
);

```

Then you can switch between databases with `db_set_active`

```
// Query other database
db_set_active('other_database');
// $query = db_select('my_table'); // e.g
// Return to default database
db_set_active();

```
> 2 votes

---
Tags: 7, configuration
---


# Question
Title: How to properly create an alias to a content
When I create a content from Dashboard, I assign it an alias, to be exact I assign it:

> `offers`

But the route I'm getting is:

> `http://example.com/?q=offers`

How can I make it to be just:

> `http://example.com/offers`

# Answer
> 1 votes
Welcome to Drupal Stack Exchange :-)

You need to Enable Clean URL's .. Find more information regarding Clean URL's in D.O here

Go to "admin/config/search/clean-urls" and enable clean URL's

---
Tags: nodes, path-aliases
---


title: How to configure gmap in template file

text:
# Question
Title: How to configure gmap in template file
I override node display for content type Match Fixtures by creating node--match-fixtures.tpl.php file and put code below:

```
<?php
$location = $content['field_stadium'][0]['#locations'];
$stadium_map = array('id' => 'stadium_map',
             'latitude' => $location['latitude'],
             'longitude'=> $location['longitude'],
             'zoom'     => 13,
             'width'    => '100%',
             'height'   => '400px',
             'type'     => 'Satellite',
);

echo theme('gmap', array('#settings' => $stadium_map))
?>

```

But it show wrong map and also not 100% width. I use gmap and location module. What is the correct way?

# Answer
If its showing the wrong map, you might be displaying the wrong view mode. Make sure you have set the gmap display for view mode full.
> 0 votes

---
Tags: 7, location, google-maps
---


# Question
Title: insert data into database using web service
I am creating a custom web service. In this, as soon as service call, data should be store into database. I am using Hook\_service\_resource() function. How can i implement insertion into database using services. I created my\_module.install file and prepare database schema. BUT i actually don't know how to use query in hook\_service\_resource() function.

# Answer
1. Create a Custom Drupal Module

Create these empty files in the new directory:

> ```
> my_module.info
> my_module.module
> my_module.install
> my_module.resource.inc
> my_module.services.inc
>
> ```

Place this code in the my\_module.info file:

```
name = My Module
description = My custom Drupal module.
package = Other
core = 7.x
dependencies[] = services
dependencies[] = rest_server

```

Place this code in the my\_module.module file:

```
<?php

/**
 * Implements hook_ctools_plugin_api().
 */
function my_module_ctools_plugin_api($owner, $api) {
  if ($owner == 'services' && $api == 'services') {
    return array(
      'version' => 3,
      'file' => 'my_module.services.inc'
    );
  }
}

```

Place this code in the my\_module.services.inc file:

```
<?php

function my_module_services_resources() {
  $resources = array(
    'my_module_resources' => array(
      'actions' => array(
        'insert_into_database' => array(
          'help' => t('Insert Database Example.'),
          'file' => array(
            'type' => 'inc',
            'module' => 'my_module',
            'name' => 'my_module.resource',
          ),
          'callback' => 'my_module_insert_into_db',
          'args' => array(),
          'access arguments' => array('access user profiles'),
          'access arguments append' => FALSE,
        ),
      ),
    ),
  );
  return $resources;
}

```

Place this code in the my\_module.resource.inc file:

```
<?php

function my_module_insert_into_db() {
  $id = db_insert('example_table') // Table name no longer needs {}
->fields(array(
  'title' => 'Example',
  'uid' => 1,
))
->execute();
  if ($id) {
    return TRUE;
  }
  else {
    return FALSE;
  }
}

```

Change the access arguments as per your permissions settings..

Call the service

http://www.example.com/?q=**serviceendpoint**/my\_module\_resources/insert\_into\_database.json
> 2 votes

---
Tags: services
---


# Question
Title: What will be my function name in template.php for particular .tpl.php
I have template.php and node--product.tpl.php files. What should be my function name in template.php to pass variable from template.php to .tpl.php

Here is template.php code

```
function mytheme_process_product(&$variables){  **//What should be my function name here**
$variables['temp_var']="This is demo Temporary Variable for Perticular Product .Tpl.php";
}

```

node--product.tpl.php

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

```

And my .tpl.php file name is node--product.tpl.php where product is my content type name.

Please reply.

# Answer
You need to use theme\_preprocess\_node function in template to add variables..

```
/**
 * Override or insert variables into the node templates.
 *
 * @param $variables
 *   An array of variables to pass to the theme template.
 * @param $hook
 *   The name of the template being rendered ("node" in this case.)
 */

function YOURTHEME_preprocess_node(&$variables, $hook) {

  // define $node object, so it's be easier to use it
  $node = $variables['node'];

  // add variables to node--nameofnodetype.tpl.php file
  if ($node->type == 'product'){

      // $variables: an array with variables
      // you need to add one, so just define it
      $variables['my_variable'] = 'whatever';

  }
}

```

In your node--product.tpl.php file:

```
// check if your new variable exist
print $my_variable;

```
> 1 votes

---
Tags: theming
---


# Question
Title: What is "alias" in db_select() function?
Beginner Drupal Developer. The drupal API didn't provide info for what purpose the $alias must be used in db\_select? And what is that anyway?

# Answer
> 1 votes
In Drupal database API alias means exactly the same thing it means in SQL world - short name assigned to table or field to simplify further referencing it **during this one query**. Some table names are pretty long, and you can't always count on Drupal to be able to resolve prefixes, so aliasing `mystupidlongprefix_field_revision_field_some_pretty_long_name_for_field_containing_a_gallery` with something simple, like `frg` (field revision gallery), or something other you will recognize when you will read this query, both make it way easier and faster to write and understand code, and also allows you to use this table for example in conditions, where using `{table_name}` syntax for automatic prefixes is not always feasible.

---
Tags: database
---


# Question
Title: sort a view by Most Viewed, Most Favorited, Latest
I have view which contains all nodes of a content type(article). default sort criteria of view is recent nodes. But i have three links Most Viewed, Most Favorited, Latest.I have to sort this view by clicking on these links .

I am making a node favorite by using flag module .

How can i achieve that .

Please Help.

# Answer
> 6 votes
* Create three different views, Most Viewed, Latest, Most favourite with display type block.
* For sorting by views, You need to enable statistics module.
* For sorting by latest, use post date sort filter in views.
* For sorting by favourite, flag module has integration with views. You can able to create a filter to sort by number of flags.
* Use Quick Tabs module to group above three different view blocks as a single block and display it where ever needed.

# Answer
> 5 votes
You can achieve it using VIEWS.

First of all enable **statistics module** and create 3 blocks Most Viewed, Most Favorited, Latest and Add required fields

* Views : Latest Block

+ Sort by POST DATE
    +
* Views : Most Viewed Block

+ Enable statistics module and go to `admin/config/system/statistics` configuration page and check **Count content views**
    + Add the statistics counter field in VIEWS BLOCK if you want to see the count
    + Add **Add filter criteria** to sort the VIEWS block to sort based on most Viewed
* Views : Most Favorited Block

+ Add the relationship
    + Add filter criteria to sort based on flags

---
Tags: views, flags
---


# Question
Title: Allow anonymous users to post content but require login/register before it is saved
I have a website with a node form displayed as a block on the frontpage. This is done to make sure users get down to posting content easily and quickly.

However I'm interested in saving details of the poster so they can later be notified of comments, etc to their node. I would like for the user to then be required to login or register before their content is posted.

So from nodeform block, they click Save and then they are asked to login or register..After that content is saved.

Is there any module that does this, or what approach can I take to code my own?

Thanks

# Answer
There is a module that does something similar (**Anonymous Publishing**) http://drupal.org/project/anonymous\_publishing \- I.e. it rolls posting and registering into one process, but delays publication of content until the user confirms his identity by means of an verification email.

The anonymous user is not formally registered as a *user*, but his email is kept on file in a visitors table, so the effect is very similar.

There is also a submodule named **Anonymous Publishing Claim** that allows the anonymous user to "claim" any content posted before he/she registered if he/she later decides to register as a regular user.

I want this functionality for myself for Drupal 7, so I've ported it to Drupal 7. I'll appreciate help with this, both for testing and for writing code. Please use the project page on Drupal.org for such interventions (not DrupalAnswers.SE).
> 4 votes

# Answer
This module might be worth looking at as well: Create and Register. Below are some more details about this module, and how it works (summary from the module's project page).

> This module allows an anonymous user to create the content. After doing so the user must login (or registers to the site). Here are some more details about the process to do so:
>
> * anonymous user creates a content.
> * the user will be redirected to the login page (if you set it on the settings form) after the user finished the node creation.
> * the user registers or logs in.
> * the created node(s) will be assigned to the user after logging in.
> 7 votes

# Answer
You can use the inline\_registration project and combine it with both email\_registration and either genpass or registration\_toboggan.

In effect, this adds an e-mail field to the form for anonymous node posting. An account will be created at the same time as posting a node, and the password and activation link sent to the new user.

You can have the same functionality for comment posting as well by adding comment\_registration.
> 1 votes

# Answer
anonymous users can post their answers without logging in/registering and if they want to receive notification when have new comment you can give an option to check/uncheck. Very easy.
> -1 votes

---
Tags: users
---


# Question
Title: How to get a dropdown list with content of other content type
I have a content type trainer where i have the fields trainer\_name, trainer\_tel and trainer\_email.

I have a second content type club where i want a field that is a dropdownlist with all the trainer names of content type trainer.

How can i do this?

# Answer
> 0 votes
You need to use Entity Reference module..

Project page says

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

---
Tags: nodes
---


title: How can I get an entity edit path?

text:
# Question
Title: How can I get an entity edit path?
I made a module, and defined my custom entity there. I set the path for the administrative page using the following array.

```
'admin ui' => array(
  'path' => 'admin/structure/optimizations',
)

```

How can I get the edit path for one instance of my entity, for example admin/structure/optimizations/manage/2?

I don't think its a good idea to hard-code the path as with `'admin/structure/optimizations/manage' . $entity->id`.
Is there any function to get the edit path for an entity?

# Answer
> 1 votes
You may want to take a look at hook\_menu()

Here you can define paths and route variables to where they are needed.

For example:

```
function hook_menu() {
  $items['admin/structure/optimizations/manage/%'] = array(
      'title' => t('Your Page Title'),
      'page callback' => '_your_callback', // The callback that is building the page
      'page callback' => array(1), // This is the value from the % array key
      'access arguments' => array('administer users'), // A permission to require
      'type' => MENU_NORMAL_ITEM,
  );
}

function _your_callback($val) {

  //Access the % from the URL defined in hook menu using $val.

  ...

}

```

# Answer
> 0 votes
You can use the `'uri callback'` key in `hook_entity_info`

> **uri callback:** The name of an implementation of callback\_entity\_info\_uri().

That function can be used to return the URL to the entity.

e.g:

---
Tags: 7, entities
---


# Question
Title: Draggable views module doesn't sort content
I wanna sort my view with Draggable Views Module , but my view display content not field. is there any solution to sort my views ?

# Answer
> 3 votes
Only solution that worked for me was the following:

* go to your content type/vocabulary
* add a weight field (label: weight | machine name: weight | field type: integer
* edit your sorting view and add sort criteria for your newly added weight field
* edit your draggable views field and change "Handler" from Native to FieldAPI
* under Field select your weight field
* go to your content view and add the new weight field as you sort criteria

This is the only thing that worked for me. If it doesn't work immediately, just reorder a few items on your draggable view so that the ordering values are reset.

Hope this works for you too.

# Answer
> -2 votes
http://www.metaltoad.com/blog/custom-sort-drupal-content-draggable-views-module

see this I think its may be helpful..

---
Tags: views
---


# Question
Title: how to add link to null path in menu in drupal 7
I have added superfish menu in menu bar in that one of the link have sub-link. How to add a sub-link with null path.

Please help me.

Thanks

# Answer
> 8 votes
You can use the Special menu items module.

> Features:
>
> * User can create a new menu item and place either "\<nolink\>" or "\<separator\>" to the Path field, without quotes.
> * "\<nolink\>" item will be rendered similar to a normal menu link item but there will be no link just the title.
> * You can change HTML tag used for menu item
> * "\<separator\>" item will be rendered to an item which is no link and by default title will be "-------".
> * Breadcrumb of "\<nolink\>" will be rendered same as "\<nolink\>" menu item.
> * CSS class "nolink" is added to "nolink" menu item.
> * CSS class "separator" is added to "separator" menu item.

---
Tags: routes, navigation, uri
---


# Question
Title: Link manually uploaded file to files-private folder
I have uploaded a large size folder via winscp to a external hosted server to the files-private folder in drupal. when i try to access the index file inside the folder in browser i get access denied. Is this because there is no entry in file\_managed table ? however i could access the URL by doing same setup on a dev server without any issues.

# Answer
With the private file system you cannot link direct to the file path because navigation of the private files directory is prohibited.

You have to link to drupal's private file handling url, which will then check that the current user has the correct permissions to view the private file and if so grants them access and gives them the file.

To utilise this you need to use drupal's system/files path.

So if your private files directory is files-private and you have a file files-private/filename.txt you would link to /system/files/filename.txt and drupal will handle the rest.

**\[Edit\]** The above is still valid information, however to answer our question, yes the files need to be in the file\_managed table otherwise file\_file\_download(), which handles private file downloads, will skip over your files because it uses file\_load\_multiple() to try to load your file from the database.

file\_load\_multiple() uses entity load and system\_entity\_info() defines the database table file file entities as file\_managed.
> 0 votes

# Answer
I have the same problem before, when you put a file in private directory Drupal don't know it as private file , you should write a record in file table to introduce that file to Drupal system.
> 0 votes

# Answer
Thanks everyone! Finally i used https://drupal.org/project/private\_files\_download\_permission module and sorted the problem. I could manually upload the files to files-private and this module allows access to private-files folder and we can restrict based on role.

In the question I forgot to include that we wanted to disable the file access to public and enable only for authenticated users. So this module helped to satisfy both the requirements.
> 0 votes

---
Tags: files
---


# Question
Title: How to create a separate theme for a custom page?
How to create a custom theme for a page? I want to create a template for my `example/123` page.

# Answer
> 1 votes
To create a *custom template* for `node/123`, copy your theme's default `page.tpl.php` to a file named `page--node--123.tpl.php` (D7) in your theme's or subtheme's `templates/` directory, and then edit it to do any customization.

To do custom *theming*, add custom classes where you need them in the custom template, and then add the CSS to style those classes.

Btw.: I usually do this by creating a sub-theme, to avoid any customization from being overwritten when the super-theme is upgraded.

PS: If your page really has the path `example/123`, the name of the template overide file should be `page--example--123.tpl.php`

Remember to clear the cache after doing this. Until you do, your override will not be visible.

---
Tags: 7, theming
---


title: Render quicktabs in view template file

text:
# Question
Title: Render quicktabs in view template file
I am using quicktabs module for grouping three view blocks as a single block. Everthing is working fine with quicktabs . But according to my design , i Have to render tabs created by quicktabs in my views template file .

How can i achieve that.

Please Help !

# Answer
You can reder quick tabs using quicktabs\_build\_quicktabs function..

> Constructs a Quicktabs instance.
>
> This function can be called by other modules to programmatically build a quicktabs instance.

```
<?php
   $quicktabs = quicktabs_build_quicktabs('recruitment_quicktabs'); // use your qt name here
   print render($quicktabs);
?>

```
> 2 votes

---
Tags: views, blocks
---


title: Banner Management

text:
# Question
Title: Banner Management
Anyone knows is there any plugin/Module which can provide banner/slider management with basic functionality plus play & pause functionality on the banner

Please Guys what to do? Suggestions welcome

# Answer
You can achieve above using Views Slideshow module...

Project page says

> Views Slideshow can be used to create a slideshow of any content (not just images) that can appear in a View. Powered by jQuery, it is heavily customizable: you may choose slideshow settings for each View you create.

* Create a content type called Slideshow Banner
* Add Image Field
* Create view which lists above content and use display type Slideshow
> 1 votes

---
Tags: 7
---


# Question
Title: How we can change the Select option into Autocomplete
I have one search index view for content type, here there are two term reference fields called, category and location.

I added those two term reference fields in that view exposed filter as select options. But i have one stuff here, if i change select options to Autocomplete filter means i couldn't see the view results, just blank page is coming.

So i needs to make those Select options to Autocomplete in hook\_form\_alter.

Please help me to solve this stuff.

# Answer
While not a direct answer to your question, I would recommend trying the Chosen module, which integrates the jQuery Chosen plugin. It will essentially convert most of your selects into something searchable / autocompletable, while keeping them as selects. It works particularly well with multi-selects, and I have it working with some large vocabularies in Views exposed filters on a few sites.
> 2 votes

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


title: Custom Content Type Design

text:
# Question
Title: Custom Content Type Design
I have a custom content type with a image field and several other fields, how do I make the other fields appear next to or inline with the image?

# Answer
> 1 votes
Two ways here. The fields all have CSS that is unique to them. All CCK fields start with "field-" you can absolutely position the items or make them inline and then float the image on the left or the right.

I found a good blog post on this from my bookmarks.

http://zroger.com/2009/06/theming-cck-fields-the-right-way/

You can also make a custom tpl file that drupal will call when it opens the given node type. The link to that is below. The prose used is interesting and shows their frustration over making these.

http://www.advantagelabs.com/drupal-colonoscopy-or-how-theme-cck-field-drupal-6

# Answer
> 0 votes
You might also create a view using the Views module to display the fields as columns in a table or use the Panels module with the custom layout to arrange the information however you want. Neither of these require and coding, although if you are not familiar with these modules it will take some to to learn them. The effort will be well worth it.

# Answer
> 0 votes
If you have a content type with image and several fields - including custom text fields, the image might push some or all of the text below. The solution depends on your theme, but it's often fixed with css (no need to make a custom view or template). Some themes use a clearfix::after for the display of these fields. So if you want to float your image to the right on the full nodes of a content type, you might try something like this:

```
/* Find a class matching a field or a group of text-fields.
Replace mytype with your content type. (Replace myfield/myfield2 with your field names
and repeat for each field that uses the clearfix-class). */
.node-type-mytype .node-full .field-name-field-myfield.clearfix::after,
.node-type-mytype .node-full .field-name-field-myfield2.clearfix::after {
  clear: left;
}
.node-type-mytype .node-full .field-type-image {
  float: right;
}

```

(Make sure you hit the right fields only. If you edit/change the general clearfix-class, you will have other elements in your design collapsing. Try one or two colons clearfix:after)

---
Tags: 7, nodes
---


# Question
Title: Modify checkbox event on custom line item type to hide show div
I have a block of custom length fields and a rule to figure them and put the correct total in the cart however I want to hide the div that contains them unless the exact lengths checkbox is checked

however currently this always shows on my test site and from how the site is set up now with a paragraph of instructions and a textbox i've found that people are lazy and don't read directions. so I don't want to give anyone the opportunity to fill in fields without the checkbox checked

I have tried using JS\_Injector to add some js to hide and show but it only seems to be able to add js to the header or footer which doesn't help me add it to the form on the checkbox change event does anyone have any other suggestions short of telling me to write a module with a hook\_form\_alter()?

# Answer
I think the Conditional Fields module should do the job.

It allows you to create rules to hide or show fields based on another fields value - so perfect for you.
> 1 votes

---
Tags: javascript, forms, commerce
---


# Question
Title: How to get all nodes of a content type as header menu item?
I want to get all nodes of Article type added dynamically to header menu. Any module that can do it for me?

# Answer
> 0 votes
You can configure content type to create menu items. So look at content type configuration. It will dynamically create menu items when new node is created.

---
Tags: routes, nodes
---


# Question
Title: How do I find a vocabulary ID for use with tokens
I need the Id for tokens. I know in Drupal 7 it is based on the label but when using tokens for rules the label doesn't work in the identifier. I don't need to find it programmatically. Is there another way?

# Answer
> 1 votes
One way to do it is actually looking at the database tables... In MySQL phpmyadmin its under {Table: taxonomy\_vocabulary} and it shows appropriate ID's associated with the label. Another way is through the UI is to navigate to the site's url aliases page.

# Answer
> 2 votes
Sure, just pop into the `taxonomy_vocabulary` table in the database and see what `vid` is associated with the correct vocabulary.

For the record if you do need to get it programmatically you can do so like this:

```
$vocab = taxonomy_vocabulary_machine_name_load('vocab_name');
$vid = $vocab->vid;

```

# Answer
> 0 votes
Just had to do this on a dev server for which I didn't have any mysql or phpmyadmin access. SO for the record, here's a few alternatives:

One option is to temporarily create a view of taxonomy terms filtered by the vocabulary. If you enable view query display in views settings, you should see the vocabulary id in the query.

Or, in the same view .. if you expose a filter of vocabularies, the vid will be visible if you inspect the html of the select option.

If you have Devel Themer module enabled, I'm sure you will find the vid if you investigate the arguments of templates on the taxonomy page.

---
Tags: taxonomy-terms, rules, tokens
---


# Question
Title: Change height of CKEditor (per profile) without using WYSIWYG Module
**Problem**

How can I change the height of the CKEditor window without using the solution outlined here which requires the WYSIWYG module. I can't spot where the height is defined in the CK module.

Ideally I'd like to be able to set it per profile and I'd prefer not to add an extra module if possible.

Has anyone dealt with this before?

# Answer
> 0 votes
UPDATE:

The patch in this thread on DO fixes this issue.

---

Looking at the ckeditor demo on this page it is possible to change the height of the editor with css alone.

The div .cke\_contents has an element style setting the height to 300px, however a rule in the stylesheet marked as important would overrule this.

So, if you can add the roles of the user as a classes of say the body, then you could include:

```
.role1 .cke_contents {
    height: 400px !important;
}
.role2 .cke_contents {
    height: 100px !important;
}

```

Alternatively there may be a class added by the CKEditor profile type that you could use.

---
Tags: 7, wysiwyg
---


# Question
Title: Replace a specific integer value with a string?
I have a View that displays a list of all the content types, with price as one of the fields you can sort and filter by.

However, the client wants to have some items show up without a price, i.e something like "Price on demand" / negotiate.

Therefore I want to replace '0' value to show up as that text (translated for other languages), how would I best do this?

I use some exposed range filter in my view but couldn't see any extra functions to replace values of field items with strings etc.

I would need it changed in the View as well as the items' individual page (and generated PDF file, but that part I can do)

*EDIT:* I have Better Exposed Filters, but after setting the replacement as:

```
0|Price on demand

```

It didn't seem to work or do anything. However my views uses a template, and I output the price by doing:

```
print render($content['field_price']);

```

So I would first need to check if $content\['field\_price'\] value is 0, then output my text string? Ideally I would prefer using some settings that can handle replacing the value for me.

# Answer
> 2 votes
This seems like the simplest method:

```
print $content['field_price'][LANGUAGE_NONE][0]['value'] == 0 ? 'Price on demand' : render($content['field_price']);

```

---
Tags: views
---


title: VIEW COUNT comments total per node

text:
# Question
Title: VIEW COUNT comments total per node
I have found code to show the total:

How To Show Node Comment Count in node.tpl?

Unfortunately I need to have this value available via VIEWS because I want to list 5 nodes based on total comment count. Short of caching the total as a field in the node (intercepting comment post and incrementing the number) -- what are my options?

# Answer
There is a field available in views called "Comment count" - just add this field and your done.
> 5 votes

---
Tags: views, comments
---


# Question
Title: Conditional 404 response based on inclusion of /node/# in URL
I've been requested by a client to completely block the URLs that contain a `/node/##` after the hostname to prevent these locations from being indexed by search engines. My issue is that I've already defined a Page Not Found node that gets shown with error 404s.

I've already implemented a modification in the `robots.txt` file to include

```
Disallow: /node/
Disallow: /?q=node/

```

to prevent the web-crawler bots. However, the URLs are still directly accessible. So in this case, the client wants two different 404 actions:

* www.clientname.com/testttt -\> Drupal renders 404 page
* www.clientname.com/node/897 -\> blocked completely without returning Drupal's 404 page.

Does any module allow for this kind of functionality?

# Answer
What about using hook\_init in a custom module?

```
function hook_init() {
    // check arg(2) is empty as otherwise will block node edit and delete pages
    if(substr($_SERVER['REQUEST_URI'], 0, 5) == '/node' && arg(2)=='') {
        die(); // to stop completely
        //return drupal_not_found(); // to return 404 page
        //return drupal_access_denied()(); // to return 403 page
    }
}

```

Saying that it would be quicker to block these pages in .htaccess...
> 0 votes

# Answer
I solved this with a .htaccess addition

```
RewriteRule ^node?$ - [F]
RewriteRule ^node/[0-9]+$ - [F]

```

These throw the 403 errors before Drupal catches them, which is what the client wanted.
> 0 votes

---
Tags: nodes, uri, blocks
---


# Question
Title: Adding .htaccess within httpd.conf correctly
I am looking for advice on the correct way to place my .htaccess settings within my httpd.conf. Here is the server httpd.conf with the htaccess placed within a directory as per most instructions I have found.

```
SuexecUserGroup "#502" "#502"
ServerName example.com
ServerAlias www.example.com
ServerAlias webmail.examplee.com
ServerAlias admin.example.com
DocumentRoot /home/example/public_html
ErrorLog /var/log/virtualmin/example.com_error_log
CustomLog /var/log/virtualmin/example.com_access_log combined
ScriptAlias /cgi-bin/ /home/example/cgi-bin/
ScriptAlias /awstats/ /home/example/cgi-bin/
DirectoryIndex index.html index.htm index.php index.php4 index.php5
<Directory /home/example/public_html>
Options -Indexes +IncludesNOEXEC +SymLinksIfOwnerMatch +ExecCGI
allow from all
AllowOverride All Options=ExecCGI,Includes,IncludesNOEXEC,Indexes,MultiViews,SymLinksIfOwnerMatch
AddHandler fcgid-script .php
AddHandler fcgid-script .php5
FCGIWrapper /home/example/fcgi-bin/php5.fcgi .php
FCGIWrapper /home/example/fcgi-bin/php5.fcgi .php5
</Directory>
<Directory /home/example/cgi-bin>
allow from all
AllowOverride All Options=ExecCGI,Includes,IncludesNOEXEC,Indexes,MultiViews,SymLinksIfOwnerMatch
</Directory>
RewriteEngine on
RewriteCond %{HTTP_HOST} =webmail.example.com
RewriteRule ^(.*) https://example.com:20000/ [R]
RewriteCond %{HTTP_HOST} =admin.example.com
RewriteRule ^(.*) https://example.com:10000/ [R]
RemoveHandler .php
RemoveHandler .php5
php_admin_value engine Off
IPCCommTimeout 61
FcgidMaxRequestLen 1073741824
Alias /pipermail /var/lib/mailman/archives/public
<Files awstats.pl>
AuthName "example.com statistics"
AuthType Basic
AuthUserFile /home/example/.awstats-htpasswd
require valid-user
</Files>
<Directory /home/example/public_html>
AllowOverride None
<FilesMatch "\.(engine|inc|info|install|make|module|profile|test|po|sh|.*sql|theme|tpl(\.php)?|xtmpl)(~|\.sw[op]|\.bak|\.orig|\.save)?$|^(\..*|Entries.*|Repository|Root|Tag|Template)$|^#.*#$|\.php(~|\.sw[op]|\.bak|\.orig\.save)$">
  Order allow,deny
</FilesMatch>
Options -Indexes
Options +SymLinksifOwnerMatch
ErrorDocument 404 /index.php
DirectoryIndex index.php index.html index.htm
<IfModule mod_php5.c>
  php_flag magic_quotes_gpc                 off
  php_flag magic_quotes_sybase              off
  php_flag register_globals                 off
  php_flag session.auto_start               off
  php_value mbstring.http_input             pass
  php_value mbstring.http_output            pass
  php_flag mbstring.encoding_translation    off
</IfModule>
<IfModule mod_expires.c>
  ExpiresActive On
  ExpiresDefault A1209600
  <FilesMatch \.php$>
    ExpiresActive Off
  </FilesMatch>
</IfModule>
<IfModule mod_rewrite.c>
  RewriteEngine on
  RewriteRule ^ - [E=protossl]
  RewriteCond %{HTTPS} on
  RewriteRule ^ - [E=protossl:s]
  RewriteRule ^ - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
  RewriteRule "(^|/)\." - [F]
   RewriteCond %{HTTP_HOST} .
   RewriteCond %{HTTP_HOST} !^www\. [NC]
   RewriteRule ^ http%{ENV:protossl}://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteCond %{REQUEST_URI} !=/favicon.ico
  RewriteRule ^ index.php [L]
  <IfModule mod_headers.c>
    RewriteCond %{HTTP:Accept-encoding} gzip
    RewriteCond %{REQUEST_FILENAME}\.gz -s
    RewriteRule ^(.*)\.css $1\.css\.gz [QSA]
    RewriteCond %{HTTP:Accept-encoding} gzip
    RewriteCond %{REQUEST_FILENAME}\.gz -s
    RewriteRule ^(.*)\.js $1\.js\.gz [QSA]
    RewriteRule \.css\.gz$ - [T=text/css,E=no-gzip:1]
    RewriteRule \.js\.gz$ - [T=text/javascript,E=no-gzip:1]
    <FilesMatch "(\.js\.gz|\.css\.gz)$">
      Header set Content-Encoding gzip
      Header append Vary Accept-Encoding
    </FilesMatch>
  </IfModule>
</IfModule>
</Directory>

```

Often Drupal updates come along and add in a .htaccess and due to my setup (virtualmin servers on a Centos machine) I have to go through each site after update and change the htaccess files on each so I would like any .htaccess to be ignored. Setting `AllowOverride None` in the public directory should block(ignore) these but then I am unsure if the subsequent Overrides have an impact on this.

The config works but is dirty (duplication and overrides of overrides :S) so in essence I would like to clear it up. What is provided is the raw drop in, I think I should be able to delete some permissions but not sure

Apache makes it very clear that if you have access to httpd.conf it SHOULD be used instead of .htaccess but I have been unable to find any info about the correct config for drupal apart from 'wrap in directory and drop it in'....

*There is no clear documentation on Drupal.org so please don't bounce this over to SE or SO, it is very drupal centric and with D8 about to land and Apache 2.4 finally landing in many server repos htaccess and httpd.conf will cause many people headaches so this will be helpful to many drupalers !*

Here is some additional for those that some who use .htaccess may not be aware of: From the Drupal Installation docs: Step 6: Configure clean URLs:

> If you have complete control of your server, for example: You run your own server; are installing a development site on your personal computer; or you have a dedicated server hosting account, then you should enable clean URLs in the httpd.conf file for better performance and security.

Here is an outstanding D7 & D8 patch that is aiming to remedy some of the permission (override) issues that I am trying to clarify: +FollowSymLinks to +SymLinksIfOwnerMatch

# Answer
> 6 votes
I still don't know why more people do not use include like this. All you have to do is restart apache for changes in drupal's .htaccess to take effect.

```
<Directory "/var/www/html">
  Options Indexes FollowSymLinks
  AllowOverride none
  Order allow,deny
  Allow from all

  # For Drupal, the rules in .htaccess are included here.
  RewriteEngine on
  RewriteBase /
  Include /var/www/html/.htaccess
</Directory>

# Enforce new security rules from SA-CORE-2013-003.
<Directory "/var/www/html/sites/*/files">
  # Turn off all options we don't need.
  Options None
  Options +FollowSymLinks

  # Set the catch-all handler to prevent scripts from being executed.
  SetHandler Drupal_Security_Do_Not_Remove_See_SA_2006_006
  <Files *>
    # Override the handler again if we're run later in the evaluation list.
    SetHandler Drupal_Security_Do_Not_Remove_See_SA_2013_003
  </Files>

  # If we know how to do it safely, disable the PHP engine entirely.
  <IfModule mod_php5.c>
    php_flag engine off
  </IfModule>
</Directory>

```

Change `/var/www/html` to `/home/example/public_html` in your case.

---
Tags: .htaccess
---


# Question
Title: how should i send data form my custom module to a php file after submitting?
I have a Drupal form like this:

```
    function myblock_menu() {
  $items = array();
  $items['my_module/form'] = array(
    'page callback' => 'my_module_form',
    'access arguments' => array('access content'),
    'description' => t('My form'),
    'type' => MENU_CALLBACK,
  );
  return $items;
}

function my_module_form() {

      return drupal_get_form('my_module_my_form');
 }

 function my_module_my_form($form_state) {
      $form['name']['price'] = array(
        '#type' => 'textfield',
        '#title' => t('price:'),
        '#value' =>t('100'),
        '#size' => 6,
        '#field_suffix' => t('$'),
        '#disabled' => TRUE,
      );
      $form['submit'] = array(
        '#type' => 'submit',
        '#value' => 'Submit',
      );
      return $form;
 }

```

And i have submit function:

```
function my_module_my_form_submit($form, &$form_state) {

 $form_state['redirect'] = 'result.php';
}

```

**My problem:** how can i get $form\_state\['values'\]\['price'\] inside result.php? or in another way: how should i sent my data to a normal php file? I studied several similar questions but didn't get my answer!
one suggestion was storing data in database which is not proper for my module! another suggestion was using sessions which i couldn't manage it(between module and php file)!

# Answer
the answers of rooby and clive were right but just solved that by using session as well and want to share it here: inside your module add this:

```
if (isset($_SESSION['myvalue'])){
    unset($_SESSION['myvalue']);
}
$_SESSION['myvalue'] = t('your data.....');

```

and inside your php file:

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

print_r($_SESSION['myvalue'] );

```
> 1 votes

# Answer
If all you are doing in your submit handler is redirecting to result.php then you should instead make your form submit direct to there, so that all the form post values will be available in the $\_POST global variable in result.php.

To do so, in your my\_module\_my\_form() function add this:

```
$form['#action'] = '/result.php'

```

**Edit:**

As Clive has pointed out, you cannot post that field value as you currently have it because it is a disabled field.

To make that field post you either have to make it not disabled, or if you don't want the user to be able to edit it you can use a different field type.

You can use type value to pass a value straight through, however the user won't be able to see it before they submit as it is a type of hidden value.

If you want the user to be able to view the value but not change it you could have 2 fields, one disabled (or just an item field) one that the user can see but doesn't submit, and a second value type field that submits the value.
> 1 votes

---
Tags: forms
---


# Question
Title: Countdown timer field with a scheduler module
i am using https://drupal.org/project/field\_countdown and https://drupal.org/project/scheduler modules.

I have added field\_countdown field to my content type 'items'. I have enabled scheduler for my content type 'items'.

When i am creating a node, i have to choose a date for field\_countdown (it shows jQuery timer countdown until set date), also i have to set Scheduler date after that. So you have to set 2 dates instead of one, because these modules are not working together.

So i want to fill only 1 field instead of 2 of them, in my case its a field\_countdown and copy its options to a scheduler input.

I've tried jquery without success:

```
(function($) {
    // jquery timer
    Drupal.behaviors.MyTimer = {
        attach: function (context, settings) {
            // This code will run, on load, even in overlay!!!!!!
            var timerDate = $('#input-id').val();
            alert(timerDate);
        }
    };
})(jQuery);

```

But js console says that `timerDate` is undefined. I am using overlay and bartik theme for administration pages.

# Answer
Here is a good place to start:

http://code.zeurois.com/jquery-countdown/configurator/new/-/tpl/t105-900
> -1 votes

---
Tags: javascript
---


title: Multiple taxonomy views do not work

text:
# Question
Title: Multiple taxonomy views do not work
I got taxonomy menu 'Categories' which list all Terms as menu links, so when clicked, it would open a list of items tagged with that term:

So if you click on Hats & Visors, it would open the list of hats and visors. The problem is, that it doesn't, only the first view (in this case t-shirts) works. In the rest of the views it only generates empty views container. Also if I changed filter in the T-Shirts view to filter Hats & Visors, it would work, the Hats & Visors section would show hats, but then T-Shirts section would stop working. I do not understand the problem.

My views settings:

Non-working views:

# Answer
> 0 votes
Boy this is a big one. Got solution with Commerce Search API, simply re-created Kickstart's Collection view and got same result. View looks like this now:

As you can see it all runs in one Display only. Each taxonomy term menu link generates a view display for its category term listing product display nodes rendered via entities.

Also following this Commerce Search API video tutorial really helped to understand the basics how it works: http://vimeo.com/53404289

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


# Question
Title: How do you theme a content type's create/edit form?
Like it says -- I've got a D7 content type whose editing form needs to be themed. I did this all the time in D6 by registering theme functions in template.php and writing the associated theming functions, but things seem to have changed in D7, especially regarding what goes into template.php, or if D7 has shifted to using .tpl.php files for this, or whatever. Is there any advice out there?

# Answer
> 4 votes
According to the handbook page on theming node forms in Drupal 7, you would indeed make changes in the .tpl.php template files.

That said, we have usually found it easier to use Field Group and Display Suite. Node Form Columns is another option.

# Answer
> 22 votes
You have two options.

***option 1: using the template.php of your admin theme***

* Pick the right theme to customize. Remember that by default, drupal 7 uses a different theme for administration and there is a setting under admin/appearance that says what your admin theme is and if content editing should use the admin theme. look at this setting and figure out whether you want to customize your main theme or your admin theme.
* once the theme has been identified, if that theme is a core theme and not one that resides in sites/all/themes or sites/something.com/themes, you may want to create a base theme rather than changing the existing theme. it is a bad idea to change a core theme anyways. Even if it is a downloaded theme, it makes sense to create a subtheme so that you can keep upgrading the downloaded theme when new versions come out.
* (optional) to create a subtheme. lets say, your admin theme is **seven** and it is also being used for content editing, simply create a folder called **my\_seven** under sites/all/themes. next add a my\_seven.info under the newly created **my\_seven** directory with the following contents

base theme = seven name = My Seven description = My simple one-column, tableless, fluid width administration theme (child of Seven).
* Now add a file called **template.php** under the same folder with the following contents. please note that the form id is strictly derived from your content types machine name. the template name however can be anything you please but -node-form looks like a good convention to follow.

```
<?php

function my_seven_theme() {
  return array(
    '<my_content_machinename>_node_form' => array(
        'arguments' => array('form' => NULL),
        'template' => '<my_content_machinename or anything else>-node-form',
        'render element' => 'form',
    ),
  );
}

```
* now create a \<content\_type\_machinename\>-node-form.tpl.php file with the following contents to test if things are working.. once you see the custom form, just change the tpl.php to your heart's content. pick a custom field other than title to be sure it is working fine.. ideally pick something that is not a simple text field. a term reference field type would be a good candidate to ensure that your subtheme is working ok.

```
<div>
    <?php print drupal_render($form['title']); ?>
</div>
<div>
    <?php print drupal_render($form['field_<my_field1>']); ?>
</div>

```
* clear your theme registry cache (actually not required for the first time a theme is made use of but do it anyways)
* set the new subtheme as the admin theme using the admin/appearance page.
* edit a content or create a new content and you should see your modified form.

***option 2: using your own drupal module to customize the form***

* create a new folder called custom\_content\_forms under sites/all/modules
* create a custom\_content\_forms.info file with the following contents

```
name = My Custom Content Forms
description = A trivial module to customize my content entry forms such as smartphone
core = 7.x

```
* create a custom\_content\_forms.module with the following content

```
<?php

function custom_content_forms_theme() {
    return array(
        '<contenttype_machine_name>_node_form' => array(
            'template' => '<contenttype_machine_name>-node-form',
                'render element' => 'form',
        ),
    );
}

```
* now create a \<content\_type\_machinename\>-node-form.tpl.php file with the following contents to test if things are working.. once you see the custom form, just change the tpl.php to your heart's content. pick a custom field other than title to be sure it is working fine.. ideally pick something that is not a simple text field. a term reference field type would be a good candidate to ensure that your subtheme is working ok.

```
<div>
    <?php print drupal_render($form['title']); ?>
</div>
<div>
    <?php print drupal_render($form['field_<my_field1>']); ?>
</div>

```
* go to administration and enable the new module and you should see your customized form when you add or edit content of the targeted type.

**NOTE: If you customize using both mechanisms, drupal will prefer the theme over the module.**

EDIT: the above will only produce the fields. you wont get the node settings menu and submit and preview buttons by default. if you just add a

```
<?php print kpr($form); ?>

```

on the page *(devel module needs to be enabled for kpr to work)* to produce a dump of the $forms array. You will see that you can get these things on your form page quite easily by adding the following to the tpl.php

```
<div><?php print drupal_render($form['additional_settings']); ?></div>
<div><?php print drupal_render($form['actions']); ?></div>

```

# Answer
> 1 votes
To change node forms from Admin interface you may use:

Display Suite - http://drupal.org/project/ds

Field Group - http://drupal.org/project/field\_group

Renderable Elements - http://drupal.org/project/rel

Enable the following modules: Display Suite, Display Suite Forms, Display Suite Extras, Field Group, Renderable Elements

Set the Renderable Elements settings by going to the settings page at admin/structure/rel/config and making sure the "Enable form registration" checkbox is checked.

Now go to the "Manage fields" form of one of your content types. Click on "Manage form display" at the top of the page to register the form with Renderable Elements to select which fields to enable. Upon saving this form you will be able to manage the display of ALL fields on your content type using the standard Display Suite UI.

source: http://getlevelten.com/blog/ian-whitcomb/drupal-form-layouts-renderable-elements

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


title: Views AJAX not work in block node.tpl

text:
# Question
Title: Views AJAX not work in block node.tpl
i have some block with sorting exposed filter on region "tab" and i show his in node.tpl like this:

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

```

In my block i not have any problem with AJAX in paginator. But my sorting exposed filter not work at all.

After several hours testing i figured out what my block works ( AJAX sorting filter + paginator) if i show his in any another region on page.tpl.

That things i see in header, if show his through any region on page.tpl:

> "better\_exposed\_filters":{"datepicker":false,"slider":false,"settings":\[\]},"views":{"ajax\_path":"/views/ajax","ajaxViews":{"views\_dom\_id:7ff6de2549b84f9553122b84f32d822b":{"view\_name":"person\_books","view\_display\_id":"block\_1","view\_args":"61/61","view\_path":"node/61","view\_base\_path":null,"view\_dom\_id":"7ff6de2549b84f9553122b84f32d822b","pager\_element":"0"}}}

That things i see in header, if show his through region "tab" in node.tpl:

> "better\_exposed\_filters":{"datepicker":false,"slider":false,"settings":\[\]},"views":{"ajax\_path":"/views/ajax","ajaxViews":{"views\_dom\_id:21d228e5cc07884c39ecda6d29b417c4":{"view\_name":"person\_books","view\_display\_id":"block\_1","view\_args":"61/61","view\_path":"node/61","view\_base\_path":null,"view\_dom\_id":"21d228e5cc07884c39ecda6d29b417c4","pager\_element":"0"},"views\_dom\_id:a94bccf7913b478becb33a3a27ec903d":{"view\_name":"person\_books","view\_display\_id":"block\_1","view\_args":"61/61","view\_path":"node/61","view\_base\_path":null,"view\_dom\_id":"a94bccf7913b478becb33a3a27ec903d","pager\_element":"0"},"views\_dom\_id:da94f68eea44bf9ead4034e965977935":{"view\_name":"person\_books","view\_display\_id":"block\_1","view\_args":"61/61","view\_path":"node/61","view\_base\_path":null,"view\_dom\_id":"da94f68eea44bf9ead4034e965977935","pager\_element":"0"}}}

How can i fix it? Why views send many view\_dom\_id in header if i show my block through region in node.tpl?

P.S. i tryed show views through views\_embed\_view in node.tpl - same things, not helped me :/

# Answer
fixed... always, REMEMBER!! always shutdown block in block UI. if not do it, this piece of shit gives something like:

> {"view\_name":"person\_books","view\_display\_id":"block\_1","view\_args":"61/61","view\_path":"node/61","view\_base\_path":null,"view\_dom\_id":"a94bccf7913b478becb33a3a27ec903d","pager\_element":"0"}

in page header and your ajax may work not so clear :)
> 0 votes

---
Tags: views, ajax
---


# Question
Title: How to change the order of attributes in the Ubertcart cart page
In the screenshot, you can see that the attributes for this product are listed in seemingly random order. Actually, it seems to be ordered by the attribute ID. Is there a way to change this order? Each attribute has a "List position" property but this only seems to be for the product page, it doesn't affect the cart.

# Answer
> 1 votes
By looking at ubdercart's theme\_uc\_attribute\_add\_to\_cart function and how it is themeing the output including attributes, it appears that you can achieve what you want by implementing `hook_form_alter`. I would start by finding the `form_id`, perhaps by adding a debug statement in the function. Then I would implement hook\_form\_alter and would alter the way the attributes are ordered to my desired order.
If this does do what you want, try and follow the logic to see where the attributes are being themed and/or built. Then hook into that mechanism (`form_alter` or a preprocess function) and I am confident you will achieve what you want. Hope this helps.

---
Tags: 7, ubercart
---


title: Place a Page before Context Blocks

text:
# Question
Title: Place a Page before Context Blocks
I want to achieve this result in my Drupal front page:

```
[Headers]
[Welcome Block]
[View of contents]

```

So I created a Welcome Page (as a Basic Page), and put it as a *Front Page* from *site configuration*. Then I add the view by the context module.

The problem is that the welcome page appears after the view, at the bottom of the page:

```
[Headers]
[SECTION Content]
  [View of contents] (view, added with context)
  [Welcome]          (Basic Page with path /welcome)
[/SECTION Content]

```

A possible solution is to make a Block instead of a page, but I would have no more welcome/ path where to link the *front*. I want also to use a page so that editors can edit, update and translate that when needed. With blocks I should add higher permissions. My purpose is just to show the welcome basic page before the view of contents.

# Answer
> 0 votes
You can use panel page for this. Create a panel, set it is as front page and pull the things you want to pull like blocks, views, nodes etc.

---
Tags: blocks
---


# Question
Title: How to prevent jQuery from loading during ajax callback
Using Drupal 7's implementation of jQuery and Drupal.behaviors, how can I get some of my jQuery to run ***only once*** when the page is initially loaded, and the rest to run when the page is loaded ***AND*** during AJAX callbacks.

How can I prevent ajax callbacks from triggering certain parts of my Drupal.behaviors?

```
(function ($) {
    Drupal.behaviors.fsrevs_user = {
        attach: function (context, settings) {

            //I want to run this only during the first page load.
            jQuery('#edit-message').after('<div>Do Once</div>');

            //I want this to run during first load and during each ajax callback.
            jQuery('#edit-message').after('<div>Do Every Time</div>');
        }
    }

})(jQuery);

```

# Answer
This'll do it:

```
var msg = $('#edit-message');
msg.once('fsrevs_user', function() {
  msg.after('<div>Do Once</div>');
});

msg.after('<div>Do Every Time</div>');

```
> 2 votes

---
Tags: 7, javascript
---


title: Use views to prepopulate fields

text:
# Question
Title: Use views to prepopulate fields
I have a site that generates letters to be sent to schools.

The visitor arrives at the front page where they are presented with a map (leaflet map) with all the local schools marked on it. They then can click on a specific school to view its page (node with school location (addressfield) info).

Here they have the option to 'generate a letter to the school' - I have the form (entityform) set up but it needs the visitor to type in the school address again. How can I dynamically fill the address-field in my form based on the school the visitor navigated to the form from?

map\>school\>school-specific-form

There are over a hundred schools, so would prefer not to have to duplicate my form...

Thanks.

# Answer
> 0 votes
**Setting the scene:**

"School-Info" content type = Fields (email, telephone, address, etc...) + Letter generator

* I want to pull the values from the already-populated fields of my "School-Info" content type to my 'letter generator'...
* I did not want the user to have to re-type the school's (addressfield) information into the addressfield of my letter-generator because it's hassle and might discourage them from sending the letter.
* Therefore my problem was passing the values of a field-type addressfield to an Entityform on the same node... and from there to a pdfof that specific entityform submission.
* Generating the PDF from my entityform alone and not on a per-page basis helps me manage the generated letters on a per-user basis ... letter response times can be tracked etc...

I did this:

1. Use views to make a block that displays the addressfield for the particular school - this can be done by setting a contextual filter for the node ID.
2. Inside the 'letter generator' entity-form type add an entity reference to this view/block.
3. Done

# Answer
> 1 votes
If you don't want coding, this is one possibility:

If you only have one form, but hundreds of nodes, another way I would suggest to do it is to use Webform Template for the School content type. You can create one webform template and then reuse it for every school node, but the address field in the webform should have a default value that is a token of the node's address field. All you would need to do is set up your webform template's address field to have a default value of something like \[node-field-school-address\] and every instance of the webform will have the address of the node it belongs to.

In order to use tokens in a webform, you will need this module: Webform Patched . This is a module that contains the Webform module itself along with token support an therefore the original Webform module should be disabled. I implemented this myself for my site and it worked without any problems.

I never worked with addressfield, but I found this module in case you need it: Addressfield tokens

---
Tags: entities
---


# Question
Title: Getting a list of nodes of a certain type sorted by number of votes
I would like to get a list of nodes of a certain sorted by votes (voting api) in one of my modules. Is there an entityFieldQuery that could do this? If not, is there a sql query I could use that might accomplish this task?

# Answer
> 1 votes
You can use views module to list nodes sorted by votes..

You can see the query executed in views when you enable Show SQL Query in views settings (admin/structure/views/settings) in the view preview...

---
Tags: 7, rating, database
---


# Question
Title: Links in map markers are for default language pages, not localized
I am building a multilingual website where a page will display all locations on a map. Each marker on a map has a link to the location's page. However, only links to English pages are displayed in markers. I have tried both Geofield Map and Leaflet to no avail.

How can I make urls in map markers to be language specific?

Given the fact that I couldn't find an answer on the web, I might have missed something simple. I am new to drupal and any help is appreciated.

# Answer
> 0 votes
Here is how I solved it:

When creating View I added Language into Fields and Language into Filter Criteria.

That simple!

---
Tags: uri, navigation, i18n-l10n, google-maps
---


# Question
Title: how to create expire flagged node after custom time
I need code that make expire flagged node after custom time, after custome time reached node become unflag automatically, have tried flag\_expire module but it no work at all. any help?

# Answer
You need the rules module along with its Rules Scheduler module. The flags module is well integrated with rules and you can do a lot of stuff with this combination.

A simplified instruction how to achieve your desired functionality:

* Enable rules, rules scheduler.
* In admin/config/workflow/rules/components crete an actions component which, when triggered by the scheduler, will unflag your node. You will have to set its inbound variable to 'content' (usage: parameter). Action will be unflagging your node.
* In admin/config/workflow/rules create a rule which will start the scheduler (the triggering event should be 'node has been flagged' and the action should be 'schedule component evaluation' which passes the node id (content) to your component.

This way whenever a certain node is flagged with a certain flag, a new scheduler entry is added and when its expired, your node gets unflagged. Bear in mind the entry is only evaluated on cron run, so you will be hitting that cron button many times during debugging.

You can find rules tutorials all over the place, but not so much scheduler tutorials. This comment is a good starter.
> 4 votes

---
Tags: 7
---


title: Grab URL as file upload for Drupal 7?

text:
# Question
Title: Grab URL as file upload for Drupal 7?
When creating a content type, you have the option of adding a "file upload" field. How can I extend the functionality of this upload file to allow for the option of simply entering a URL instead of manually downloading the file and uploading it again? I basically want another field, called URL, where I enter the URL of the image. Drupal must then grab the URL as if though I uploaded it. Which means I must be able to "press upload" and actually see the thumbnail as per normal functionality.

I have a site from which we often grab images, but every time I first have to download it. It would save me a lot of trouble if I could just provide the URL and let Drupal do its thing.

# Answer
> 1 votes
You're looking for the FileField Sources module:

> FileField Sources is an extension to the FileField module. The FileField module lets you upload files from your computer through a CCK field. The FileField Sources module expands on this ability by allowing you to select new or existing files through additional means, including:
>
> * Re-use files by an auto-complete textfield
> * Attach server-side files uploaded via FTP
> * **Transfer files from a remote server (cURL required)**
> * Paste a file directly from the clipboard (Drupal 7 only)
> * Select existing files through the IMCE file browser

Emphasis mine.

---
Tags: files
---


title: How to add body to field group?

text:
# Question
Title: How to add body to field group?
I have installed Fieldgroup module to create groups in node edit form.

However, when I am on Manage fields page (for content type) I cannot add body to a group. Is there any workaround using some hook?

thanks Tomas

# Answer
The only solution I have found was to replace body with CCK field. The body in D6 is not CCK field, and it cannot be threated as CCK in many occasions
> 0 votes

---
Tags: 6, entities, nodes
---


# Question
Title: Drupal 7 - How to show an upcoming event from site 1 on site 2?
For Drupal 7, Is it possible to show an upcoming event from site A on site B's block?

Also, is it possible to show an upcoming event by category? For example, I wanna have an upcoming event for swimming class and an upcoming event for hiking group. However, they are all in one same calendar.

Thanks, HL

# Answer
You can use Shared Blocks, it has both drupal 6 and 7 stable releases:

```
If you have a main site with blocks that you want to syndicate across several
other websites, you need this module!

Features:

Allows publishing and subscribing of Drupal blocks
Changes to published blocks are updated on sites with subscription blocks
Published blocks provides a JSON endpoint at sharedblocks/{module}/{delta}
Block subscriptions are updated on cron with an adjustable refresh interval

```
> 1 votes

# Answer
You can use Remote blocks module. to display 'site A' data on 'site B'. For more info go through the module documentation.

On 'site A' create a view having filter event date is greater than current date.You can also apply category filtration as per your requirement.
> 0 votes

---
Tags: datetime
---


title: use Views module with organic group

text:
# Question
Title: use Views module with organic group
Using `Views`, I was able to apply `CSS` elements to content fields, but after applying Organic Group module and assigning each content to each group, I don't know how to take control of these content. The contents looks fine in the front page but inside the group's page it is a bit messy.

So is there's any way to fix that?

# Answer
This module Code Per Node will make things alot easier for you.

```
Code per Node makes it possible to add custom CSS and Javascript per node, per content type, per block, and globally. The code is stored in the database, but served from the file system. It also supports syntax highlighting with CodeMirror.

```
> 0 votes

---
Tags: views, organic-groups
---


# Question
Title: How do I send a privatemsg to all users that have flagged a node using Rules?
I am using the Privatemsg module, Flag module and Rules module.

I wonder if using Rules I could send a private message to all the people who have flagged a specific node when a new comment is posted.

Thus, the flag would act like a subscription for new comments notification.

# Answer
> 1 votes
1. Create a new rule triggered on After saving a new comment\`.
2. No conditions necessary; set them up only if you require something specific.
3. Actions:
    * Fetch users who have flagged a node
    * Loop through those users (argument will be populated automatically)
    * Under that loop create a new action "Send a message". This will require you to have "Privatemsg Rules Integrations" module enabled.

---
Tags: rules, flags
---


# Question
Title: Hover over image and display above like EBAY and AMAZON
I've tried searching but i cant figure out how to achieve this effect.

Basically i have a VIEW of a content type PICTURE. In the view a main Image is displayed and 3 other images displayed below it, i want to have an effect when a user hovers over one of the 3 images below then the main image shows that image, it doesnt matter if the image stays there or goes back to its original once users mouse goes off the image, but just having it change is what im struggling with. I see this effect done on Amazon as a good example.

Anyone have any ideas? Or even maybe a name for this sort of JQuery effect so i can search for it and try to implement it in to my Views TPL file or something?

Thanks a bunch

# Answer
> 2 votes
Hi You can use combination of Views Slideshow & Views Slideshow JCarousel to make such effect.

See this video also:

http://buildamodule.com/video/advanced-site-building-in-drupal-7-building-a-slideshow-using-views-slideshow-how-to-create-a-pager-of-thumbnail-images-in-views-slideshow

# Answer
> 1 votes
If there is animation, there is likely some JavaScript involved, but you can do hover effects with CSS alone.

Just work with the markup you get from views and do something like this:

```
<div class="hover-here">
  <img src='#' />
  <div class="to-display"><p>Some Text to show</p></div>
</div>

```

Example CSS

```
.to-display { display: none; }
.hover-here:hover .to-display { display: block; }

```

Obviously you would want to use the markup supplied from views instead of the code above, but this should work.

---
Tags: views, javascript, theming
---


# Question
Title: Resolution of Recaptcha Error in Drupal 7 forms
I am using Recaptcha module for filtering the spam on the form. But the form contains some alax file upload field which stop recaptcha to work properly. Every time I upload the file in the form by AJAX it is giving me following message:

CAPTCHA session reuse attack detected.

This made me difficult to use the module. Please let me know if there is any work around to solve the problem.

I am just newbie in Drupal 7. If there is any better spam protection module than recaptcha then also suggest me.

# Answer
~~I personally use the Are You a Human PlayThru Module:~~

> PlayThru is designed to be more simple, more intuitive, and more fun than other CAPTCHA options. We use game mechanics to create an experience that’s more enjoyable than figuring out what that awful squiggly text says.
>
> PlayThru is also more secure. Because users interact directly with PlayThru, we can analyze that interaction and track the resulting data to generate a Human Confidence Score: our level of confidence that a user is an actual human.

~~You can also check out a video about it this module here:~~

~~Drupal 7 Are You a Human PlayThru Module - Daily Dose of Drupal episode 78~~

# Update

The Are you a human PlayThru service has shutdown, I recommend you go with ReCaptcha

> Uses the Google reCAPTCHA web service to improve the CAPTCHA system and protect email addresses.
>
> reCAPTCHA helps power massive-scale online collaboration.
> 1 votes

---
Tags: 7, advertising
---


# Question
Title: How to override some text in the login form located in a block put on a panel?
I create a subtheme base on `bartik` theme.

Then I create a panel, and put the user login block to the panel.

I want to change some text in the default user login from.

I find the theme suggestion about how to override block: `block--[region|[module|--delta]].tpl.php`

So I try to create `block--user--login.tpl.php`, And try to type whatever word to this file:

```
111

```

when I visit the login form, still default, not changed.

I try to clear cache, can not work too.

**EDIT:**

I paste the follow picture for better explain.

* the `111` is a `login form` block in page, the right form is a `login form` block in a panel.

* this is my `block--user--login.tpl.php` file

# Answer
> 2 votes
This sounds like a job for hook\_form\_alter() and it can be used from either a custom module (eg, `MODULENAME_form_alter()`) or in this case probably more easily from your theme, eg, something along these lines inside your `template.php` file:

```
function THEMENAME_form_alter(&$form, &$form_state, $form_id) {

  switch ($form_id) {

    case 'user_login_block':

      // drupal_set_message('<pre>' . print_r($form, TRUE) . '</pre>');  // uncomment to see what you have to work with

      $form['name']['#title']='Enter UserID here'; // originally "Username or e-mail"
      $form['pass']['#title']='Enter Secret here'; // originally "Password"

      break;

    // other form ids go here

  }

}

```

The above (after clearing caches) will turn this:

into this:

If you need to change other text in the form, you can uncomment the drupal\_set\_message() and look in the form to see what you have to work with and change it appropriately.

ADDITION:

If you want to get rid of both of the `links,` eg, the `Create new account` and `Request new password` you can either do:

```
unset($form['links']);

```

or set the access to them to `FALSE`, eg:

```
$form['links']['#access']=FALSE;

```

Lots more information about this can be found in the Drupal Form API Reference. I would look into the #weight key for changing the position/ordering of elements in the form.

# Answer
> 0 votes
Edit your panel and make sure you are in content. Now you will notice very block has a small gear icon on its right. click on the gear icon and then select css properties. Under div class put the name you want. For example loginblock

then go to your subtheme .css file and add the div there and make the changes you need.

For example:

```
.loginblock { color: red; }

```

PS: I suggest you watch part 1,2,3 of this series Drupal 7 Panels Module Basics it has great info on panels, that's is how I learned.

# Answer
> -1 votes
is this what you want to do?

then you need to go to your website then right mouse click and then click view source. then search for user-login-form you need to copy all the code where the form starts and ends onto the block--user--login.tpl.php file

for example block--user--login.tpl.php contains:

```
<form method="post" id="user-login-form" accept-charset="UTF-8"><div><div class="form-item form-type-textfield form-item-name">
  <label for="edit-name">I just edited this, woo<span class="form-required" title="This field is required.">*</span></label>
 <input type="text" id="edit-name" name="name" value="" size="15" maxlength="60" class="form-text required" />
</div>
<div class="form-item form-type-password form-item-pass">
  <label for="edit-pass">Password <span class="form-required" title="This field is required.">*</span></label>
 <input type="password" id="edit-pass" name="pass" size="15" maxlength="128" class="form-text required" />
</div>
<div class="item-list"><ul><li class="first"><a href="/user/register" title="Create a new user account.">Create new account</a></li>
<li class="last"><a href="/user/password" title="Request new password via e-mail.">Request new password</a></li>
</ul></div><input type="hidden" name="form_build_id" value="form-_elpq-7B19Scnbgk13TZtp9YWCcANc-rDYCWcHPuihI" />
<input type="hidden" name="form_id" value="user_login_block" />
<div class="form-actions form-wrapper" id="edit-actions"><input type="submit" id="edit-submit" name="op" value="Log in" class="form-submit" /></div></div></form>  </div>
</div>
  </div>

```

**Pros:** You don't need to know PHP nor how to create a custom module. (The noobie approach).

**Con:** If you change theme's you will need to make a copy of this template and put it in your new theme's template folder.

**Counter the con:** There might be some other (views, blocks, nodes?) templates that also need to be moved if you change themes, since this is in the `/sites/all/themes/yourtheme/templates` folder, you will likely not forget to move it with the others? Therefore, this approach is not as bad as people may think.

Don't get me wrong, the accepted answer is the better approach, if you have the knowledge that is.

---
Tags: theming, panels
---


title: How to use NUSOAP in my custom module?

text:
# Question
Title: How to use NUSOAP in my custom module?
My users have to be guided to Bank Gate to pay the money After filling a Form in my custom module. the process of leading them has to be done through NUSOAP but it seems it is not functioaning inside module! it works find when i have the same code in a php file but in module ... I have no idea what is wrong with that! this is my submit function:

```
function my_module_my_form_submit($form, &$form_state) {

  $nusoap_path = drupal_get_path('module', 'myblock') . '/nusoap.php';
  include_once($nusoap_path);

    $client = new nusoap_client('https://de.....com/pg/services/WebGate/wsdl', 'wsdl');
    $client->soap_defencoding = 'UTF-8';
    $result = $client->call('PaymentRequest', array(
                                                    array(
                                                            'MerchantID'    => 'XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX',
                                                            'Amount'        => 1000,
                                                            'Description'   => 'some texts',
                                                            'CallbackURL'   => 'http://......./verify.php'
                                                        )
                                                    )
    );
    //Redirect to URL
    if($result['Status'] == 100)
    {
        $form_state['redirect'] =('https://www.......com/pg/StartPay/'.$result['Authority']);
    } else {
        echo'ERR: '.$result['Status'];
    }

}

```

thanks in advanced for you help

# Answer
my mistake was trying to do it on localhost! once i checked the same code on a real server everything was fine and it worked!
> 0 votes

# Answer
I think I've had a similar issue in the past with a different payment gateway.

Inspect each variable (print\_r or var\_dump) one after another comparing the values between your stand alone php file and the drupal module.

When you find the point at which there is a difference you know what line it's going wrong.

Maybe shout at it a bit at this point, give it a prod, read some more API documentation and then you should almost be there ;)
> 0 votes

---
Tags: 7
---


title: how to use a filter criteria in view?

text:
# Question
Title: how to use a filter criteria in view?
I have one view which shows total number of time a particular node has been visited and few more details. now i want to use a filter which shows most viewed node.

Please help me.

Thanks

# Answer
> 2 votes
Sort your view by node views descending.

Then limit your view to only show 1 row.

The remaining result will be your node with the most views.

Is this what you were asking?

# Answer
> 1 votes
You need to add a field in the **Sort Criteria** which is under filter criteria

# Answer
> 0 votes
You can use a contextual filter to do this all at once - without having to configure both the "sort criteria" and the "pager options"

Assuming something like "content:number-of-views" is accessible as a filter option. Go to:

views\>yourview\>advanced\>contextual-filters\>add\>"content:number-of-views"

You can now configure your contextual filter...

I would try :

When the filter value is NOT available

* "display a summary"
* Configure sort order - "descending"
* Configure sort by - "number of views"
* Override number of items to display - "1."

---
Tags: views
---


# Question
Title: How to move drupal into a subdirectory so non-drupal content works in the original folder?
I have a D7 site and then a lot of other non-drupal stuff I would like to keep in my `joe/` folder on our server as `joe/thing1/` `joe/thing2/` etc. Right now, my folder `joe/` just has the drupal installation and my other stuff is not deployed. I would like to move drupal into a subdirectory, but still have `http://website/joe/` work as my original drupal site with clean urls, etc. Then I would like to be able to deploy my other stuff into `http://website/joe/thing1`, `http://website/joe/thing2` etc.

How can I build an `.htaccess` file to serve drupal from a subdirectory unless a url points to an existing file? Or is that the correct way to go about this?

# Answer
If your non-drupal files are just a few and are static content (just plain HTML files or similar) you can create symbolic links in the root Drupal foolder that point to your non-drupal files.

Webserver (Apache at least) will serve those files if the URL points to them, instead of call index.php with the URL rewriten into params.

This way if you accidentally delete root Drupal directory (for example, using an automatic core update) you only have to put the simbolic links again, not all your non-drupal files.
> 0 votes

---
Tags: 7, .htaccess
---


# Question
Title: How add tab menu item with external link to article node content
I want to add an extra tab menu item to article node type.

I mean a new menu item beside view, edit and other tabs only in article node.

but this tab menu item has **external link** to another site and it's target is **\_blank** (to open destination in new window)

what is your solution for my issue?

# Answer
1. Create custom module Replace mymdulename with your module name.
2. implement hook menu to add "Menu local task" which let your menu item to show along with view, edit ..
3. page call back to add the redirect rule, in below example I am redirecting to google.com, you can add a check according to node and add redirection rule.
4. access callback ensures this menu tabs gets attached to nodes for article content type.

> /\** * Implements hook\_menu(). \*/
>
> ```
> function mymodulename_menu() {
>   $items = array();
>
>   $items['node/%node/movies'] = array(
>     'title' => 'Movies',
>     'page callback' => 'mymodulename_redirect',
>     'page arguments' => array('node', 1),
>     'access callback' => 'mymodulename_content_type_check',
>     'access arguments' => array(1),
>     'type' => MENU_LOCAL_TASK,
>     'weight' => 100,
>   );
>
>   return $items;
> }
>
> /**
> * Access callback
> */
> function mymodulename_content_type_check($node) {
>   if ($node->type != 'article') {
>     return FALSE;
>   }
>   return TRUE;
> }
>
> function mymodulename_redirect($node) {
>   dpm($node);
>   $url = "http://www.google.com";
>   drupal_goto($url, array('external' => TRUE));
> }
>
> ```

**Update**

to open the external link in new tab use jquery to add '\_blank' attribute in your custom

```
jQuery('.tabs a').attr("target","_blank");

```

Remember to pick unique classes instead of ".tab" to avoid having this behaviour to all tabs.
> 1 votes

---
Tags: routes
---


# Question
Title: Show block for specific content type programmatically
How can I show a block on a specific content type programmatically? I want in my image the 'basic page' selected.

I used the xxx\_block\_info() function, should it set in here?

# Answer
> 2 votes
If you look at the node\_module file it controls the node type visibility using the hook\_block\_list\_alter.

So basically it might looks something like this. NOTE: This is a non tested version.

```
function hook_block_list_alter(&$blocks) {
  $node = menu_get_object();
  // list of all block deltas u want to apply this
  $block_delta = array('deltas');
  foreach ($blocks as $key => $block) {
     if (!empty($node) && $node->type == 'page' && in_array($key, $block_delta)) {
       unset($blocks[$key]);
       continue;
     }
  }
}

```

# Answer
> -4 votes
You can do like this:

```
function xxx_block_info() {
    $blocks['xxx'] = array(
    'info' => t('Xxx'),
    'visibility' => BLOCK_VISIBILITY_PHP,
    'pages' => '<?php global $node; if ($node->type == 'yyy') return TRUE; else return FALSE; ?>'
  );
}

```

Verify that the PHP filter module is enabled if you want to use BLOCK\_VISIBILITY\_PHP!

---
Tags: hooks, blocks
---


# Question
Title: define my own entity.tpl for my custom entity?
How to define my own entity.tpl for my custom entity? I am using entity API to declare my entity and its controller and class. I don't want to use entity.tpl of entityAPI but my own tpl.

# Answer
> 3 votes
Unfortunately, is not as simple as creating a custom template named `ENTITYNAME.tpl.php`.

You may want to reconsider theming an entity. Entity-level code should only deal with low-level data manipulation. Rendering for the browser should handled separately by the Drupal theme layer, not the entity itself.

However, if you want to *override* the theme layer for your entity, you can do it by overriding the page template for your entity (i.e. `page–-ENTITYNAME.tpl.php` (where "ENTITYNAME" is the machine name of your entity).

But this is probably not what you're asking about. If you insist on theming your entity, there is a solution is written up here: Theming Custom Entities @ Drupal.org.

To summarize: You do it by means of three functions that you place in the module defining the entity:

* `MODULENAME_menu()` hook.
* Page Callback
* `MODULENAME_theme()` hook.

The MODULENAME\_theme() hook is used create this module's Theme Registry entries.

---
Tags: entities
---


# Question
Title: How to create a checkbox field in a node for Terms and Conditions
I need a field to ensure the users who create a node accept my Terms and Conditions. I've gone as far as creating a boolean field and making it a required field but I don't know how to:

1) Disallow node creation if the checkbox isn't checked, and modify the node creation rejection message.

2) Only make the field required for non-admin roles.

3) Insert a label for the checkbox with html markup so that I can link part of the text.

# Answer
> 2 votes
There are several contrib modules available that enforce users to agree to terms or conditions. Wouldn't it be technically easier and more practical for users to agree to the terms once, when they register? The legal module is quite good for this and has a feature where if you (as the site admin) change the terms and conditions after a user has previously agreed to them, then they can be asked to re-agree to the new terms next time they login.

If you absolutely have to go down your system design path, then:

1. You could use hook\_form\_alter() or hook\_form\__alter() to set a custom validation hook.
2. Have a look at the conditional\_fields module for making it required depending on users role. You could alternatively do this logic in the hook\_form\_alter() or hook\_form\__alter() as per #1.
3. I'm pretty sure the Drupal Forms API won't allow links in the field label, but feel free to correct me. Alternatively you could add the links in the field description or write some jquery to achieve this (albeit a little hacky).

Hope that can help.

---
Tags: forms
---


title: Views Count with multiple fields

text:
# Question
Title: Views Count with multiple fields
I have 2 fields that each can have multiple values. I want to count the number of values for a given content type (Actions). Using aggregation everything works fine when the display/view has one field but when I add subsequent fields the results do not come close to adding up.

Record 1 =\> Field a has 2 values selected, field b has 4 Record 2 =\> Field a has 4 values selected, field b has 6

Result should be ... Field a = 6 and Field b = 10

# Answer
> 1 votes
Since you are using Views, can't you use the delta value of the field? It should give you the amount of fields-a & fields-b per node. If you have 2 value's in field a. `field a:delta` = 2. From there you should be able to aggregate over several nodes.

It won't give you the value's of the selected fields though.

---
Tags: views
---


title: Services Views Multilangual

text:
# Question
Title: Services Views Multilangual
I am totally new to Drupal trying to build a CMS just as a data entry level to gather data, I built a Service View that will retrieve the content of the node and show it as a JSON object , I have a content type with `field collection` in it , this field collection contain a `Text Field` that has `Field Translation` enabled, users can enter the data in the enabled languages. My service works well but it only retrieves the data according to the `Field Language` option under the `Advanced` tag when defining the service.

My Question is how can I get the data in the language I request ? Is this even possible ?

# Answer
I figure it out, I have to choose 'Current User's Language' for Field Language option and enable the language detection in the URL, and I added a filter for the field language and expose it, that way i passed the locale in the URL and passed my filter as query string and got my result.
> 1 votes

---
Tags: views, services
---


title: enable Rule module with fatal error

text:
# Question
Title: enable Rule module with fatal error
I use drupal 7.26 and try to install Rules(7.x-2.6) with drush (`drush en rules -y`)

I can not visit my drupal site Now.

I install Xdebug. this follow is error detail:

```
Fatal error: Class name must be a valid object or a string in /Users/tangmonk/MyGit/Drupal/daxuebao/includes/common.inc on line 7837

#   Time    Memory  Function    Location
1   0.0011  240392  {main}( )   ../index.php:0
2   0.0155  656312  drupal_bootstrap( ) ../index.php:22
3   0.2055  5039280 _drupal_bootstrap_full( )   ../bootstrap.inc:2260
4   0.6304  21000048    module_invoke_all( )    ../common.inc:5158
5   0.6328  21061544    call_user_func_array ( )    ../module.inc:895
6   0.6328  21061744    rules_init( )   ../module.inc:895
7   0.6343  21098688    rules_invoke_event( )   ../rules.module:12
8   0.6343  21099144    rules_get_cache( )  ../rules.module:969
9   0.6666  22764416    RulesEventSet::rebuildEventCache( ) ../rules.module:333
10  0.7564  25670784    rules_config_load_multiple( )   ../rules.plugins.inc:764
11  0.7564  25670872    entity_load_multiple_by_name( ) ../rules.module:804
12  0.7564  25670936    entity_load( )  ../entity.module:252
13  0.7564  25671016    entity_get_controller( )    ../common.inc:7804

```

# Answer
Try going to http://yoursite.com/update.php and execute the form submit.

If this does not work, you must:

1. disable rules by SQL command:

UPDATE system SET status = 0 WHERE system.name = 'rules';
2. Execute drush cc all
3. Active drush again:

Drush en rules -y
> 3 votes

---
Tags: rules
---


title: Views theming, using raw data

text:
# Question
Title: Views theming, using raw data
I am using views to get results which can be filtered (exposed) by the user. So far so good. Now I have to (heavily) modify the end result and while I have figured out which template I need to use, I can not find a way to fetch the actual (raw) data from the view in my template so to theme it as the client likes.

What do I have to do to get the raw data in my template? If I will have to create a module for it which steps do I have to follow to do so?

Side question, is there any other way to expose filters in a page?

# Answer
> 0 votes
Theming info on each views is located under 3-rd col - Advanced on the view. Last row say "Theme:Information". Click on Information. According to your needs select template name, and create file in your current theme. Then click on "Style output" for example if you choose this kind of filename, and get code for the file (copy/paste) in above created file. Type dpm($variables); after opened php tag (install devel module ofcource) This will output available data for this template. After creating file, go agayn on theme Info and click Rescan template files. Your new file will be bolded. If not, there is something wrong - start again this process. There is too many name suggestions - get the last (longest) for your type.

Example: If we have views "Latest content" with all default options, for example we can create a file views-view-unformatted--latest-content--page.tpl.php in the theme folder. Code must be (with our dpm()):

```
<?php

/**
 * @file
 * Default simple view template to display a list of rows.
 *
 * @ingroup views_templates
 */

dpm($variables);
?>
<?php if (!empty($title)): ?>
  <h3><?php print $title; ?></h3>
<?php endif; ?>
<?php foreach ($rows as $id => $row): ?>
  <div<?php if ($classes_array[$id]) { print ' class="' . $classes_array[$id] .'"';  } ?>>
    <?php print $row; ?>
  </div>
<?php endforeach; ?>

```

Also we may create separate view mode for node and use them in this views. This way we may theming node views in separate file according to node view. We can get entity\_view\_mode module for this from DO. This is not alternative to above views theming, but as addition.

There is too many variants how to theming views - this depends what we set on the current views.

---
Tags: views, theming
---


# Question
Title: Is it possible to custom Event Date format?
On the Drupal 7 Upcoming Event, I would like to show the Event Date with abbreviated "Day, Month date, Year - Time". However, There an option that I like, which is "Fri, Mar 28, 2014 @ 4:55pm", but it contained with the "@" symbol. Is there a way to custom this being "Fri, Mar 28, 2014 - 4:55pm"?

PS: I know there is a way to add new date type, by going to "Administration/Configuration/Regional and Language". But none of them work like the way I wanted.

# Answer
You can add a new date/time format by going to Administration \> Configuration \> Regional and Language \> Date and Time. In the upper right corner of the screen you see two tabs: Types & Formats. First go to Formats and add your desired date format there (according to PHP date formatting). In your case, this will probably be something like

```
D, M j, Y - g:i a

```

Next, you go to Types and create a new date type. You can assign your custom date format to this new date type.
> 1 votes

---
Tags: 7, datetime
---


# Question
Title: How to handle DB updates when my Drupal source is in git?
I've put my Drupal installation in Git so that it is easier to replicate the production site on my development system. Then I discovered drush and I think it's way cool. But then it occurred to me: If I use drush on my development box to update a module, then the source code changes will be in git and will end up in production by way of git.

But what about the database changes? How do I apply those in production? Is it sufficient to run `drush updatedb` in production (after using git to transfer the code)?

I'm not sure the version numbers are relevant for this question. Anyhow, running Drupal 6 currently, planning to upgrade to Drupal 7.

# Answer
1. Yes, if you update the files on the production site, all you have to do is to run the `update.php` or `drush updatedb` additionally.
2. For migrating *functionality* from staging to production site, you might be interested in Features. It allows you to export various "pieces" of functionality and transfer them to another installation; this can include content types, fields, views and image styles, to name a few.

Hope this helps!
> 3 votes

---
Tags: drush
---


# Question
Title: Run "git" on remote server with drush alias
I would like to launch git commands, on my production server, from my pc. The document root of the production application is a clone of the git repository.

On prod, on sites/all/drush/drushrc.php I've add this line:

```
<?php

// Drush aliases
$options['shell-aliases']['git-status'] = '!git status';

```

If I login on production and I execute "git status", everything works.

If I try to execute, from my pc "**drush @mysite.prod git-status**" I obtain:

```
fatal: Not a git repository (or any of the parent directories): .git
Command git status failed.

```

Note that if I try to run "**drush @mysite.local git-status**", works (and my local copy is like the production copy, the document root is the clone of git repository).

What's wrong? Document root directory declared on my alias is right (other commons drush commands work) and is a checkout of git repository.

Thanks.

# Answer
> 4 votes
This works just fine for me on both the 6.x and master branches of Drush, and on the 6.2.0 release. So, your first step would be to try with the latest versions, and see if it works. If that doesn't fix your problem, try running your command again using the -v flag to get more verbose output. You will see something like this:

```
$ drush -v @mysite.prod git-status
Loaded alias @server.xxxxxxxxxxx from file                              [notice]
/home/ga/local/config/drush-aliases/server.aliases.drushrc.php
Loaded alias @mysite.prod from file                                     [notice]
/home/ga/local/config/drush-aliases/mysite.aliases.drushrc.php
Include /home/ga/local/drupal/drush_extensions                          [notice]
Include /home/ga/.drush                                                 [notice]
Calling proc_open(ssh -o PasswordAuthentication=no webuser@myserver.com 'cd /srv/www/myserver.com/htdocs && git status');
# On branch master
# Untracked files:
#   (use "git add <file>..." to include in what will be committed)
#
#   ../xxxxx.txt
nothing added to commit but untracked files present (use "git add" to track)
Command dispatch complete                                               [notice]

```

Try running the command inside of "`proc_open(...)`" from the shell, and see if it behaves the same way. Adjust the ssh options until it works right. Then, set `$options['ssh-options']` to adjust.

**NOTE:**

If you want to do something like this without defining a shell alias, the following should also work:

```
drush @mysite.prod ssh git status

```

---
Tags: drush, version-control
---