title: Create if logic with fields

text:
# Question
Title: Create if logic with fields
My task is to create a field that is visible to the author node.

Let's say the content type is "article" and the field is "textid" that contains the node ID number.

I've already created it with Display suite as a custom field with token \[node:nid\], so the result is some text with number of the node ID.

How can I make that field visible only by the node author?

What hook should I use?

# Answer
> 1 votes
You can simply use Field Permissions module:

> Author-level permissions allow viewing and editing of fields based on who the entity owner is.

This seems to be exactly what you need.

To have real field (not display suite element), you can use Computed Field \- more complicated than Display Suite, true, but at the same time more versatile and integrates well with everything field-related.

On the other hand, you can forget all these modules, and in your `node.tpl.php` simply compare current user id with node author's id, and if they are equal, print your data.

---
Tags: entities, hooks
---


# Question
Title: Views Slideshow, items per slide based on screen resolution
I have a Views Slideshow slider with 4 items per slide (see below). I am looking for a way to make it change the items per slide number dynamically when the screen width hits a certain breakpoint -for example 3 items per slide when tablet screen and 2 items per slide when mobile screen. Been trying for few days but without success.

Any ideas are welcome.

# Answer
Ive done it using detect\_mobile class and some tweaking of views\_slideshow\_cycle.theme.inc, changing the $styles\['items\_per\_slide'\] variable based on the device detected. Don't see much of an interest so I won't share the code but if someone is interested please let me know. Cheers ;)
> 0 votes

---
Tags: views
---


# Question
Title: Adding rel=canonical meta tag in comment paginated node pages in Drupal 7
This question is same as that of Drupal 6 question: Adding rel=canonical meta tag in comment paginated node pages but for Drupal 7.

How can I add rel=canonical tag in the paged urls ( like ?page=1) pointing to the main version one?

I could find the feature in the Nodewords module in Drupal 6. But the Metatag counterpart in Drupal 7 does not seem to have any such option.

# Answer
> 1 votes
Answer to the original suggests Nodewords. And D7 replacement of Nodewords module is Metatag module, that supports canonical links.

> Meta tags have additional uses like the Open Graph Protocol used by Facebook, specifying the canonical location of content across multiple URLs or domains.

---
Tags: meta-tags
---


# Question
Title: Reusing drupal forms in a profile installation?
I've setup a custom installation profile, and of my installation steps is setting up Google Analytics. I've downloaded the Google Analytics module and enabled it in my site profile.

What I'm doing in my install step is as follows:

**hook\_install\_tasks()**

```
$tasks['site_google_analytics_form'] = array(
  'display' => TRUE,
  'type' => 'form',
  'display_name' => st('Google Analytics Configuration'),
);

```

**site\_google\_analytics\_form()**

```
/**
 * Configure google analytics.  The only required field is the tracking code.
 */
function site_google_analytics_form() {
  module_load_include('inc', 'googleanalytics', 'googleanalytics.admin');
  return drupal_get_form('googleanalytics_admin_settings_form');
}

```

The probelm I'm having is that, even if I enter a valid web property ID, the form always comes back saying that an invalid ID was entered. I checked to make sure the validation function is firing (which also is in ***googleanalytics.admin.inc***), and it is, but the `$form_state` variable doesn't have any of the form values preserved.

So, I guess my question is this - why is the `$form_state` variable being passed into the validation function not storing the values I specified in the form during the install step?

# Answer
## The problem

A bad implementation of your code is causing the confusion. The input data is not stored in the `$form_state` variable, but in `$form_state['input']` initially.

Once the user submit a form, Drupal will build the form again and process the values. In this step, the system make some checks. You can take a look of functions that have been called.

The function `_form_builder_handle_input_element($form_id, &$element, &$form_state)` is the one that set the values in `$form`.

The previous function is called in the middle of `form_builder()`. At the end of same function, drupal will fill the values in '$form\_state' variable .

Why the function is not filling the values?

Because the next code is checking the input form:

```
// Set a flag if we have a correct form submission. This is always TRUE for
// programmed forms coming from drupal_form_submit(), or if the form_id coming
// from the POST data is set and matches the current form_id.

if ($form_state['programmed'] || (!empty($form_state['input']) && (isset($form_state['input']['form_id']) && ($form_state['input']['form_id'] == $form_id)))) {
  $form_state['process_input'] = TRUE;
}
else {
  $form_state['process_input'] = FALSE;
}

```

The result is `FALSE` because `$form_state['input']['form_id'] != $form_id`.

```
'site_google_analytics_form' != 'googleanalytics_admin_settings_form'

```

So, the input finally is not processed for **security reasons**

## Solution

Your code should be implemented like this:

```
/*
* hook_install_tasks(&$install_state)
*/
function hook_install_tasks(&$install_state){

$tasks['site_google_analytics_form'] = array(
        'display' => TRUE,
        'type' => 'form',
        'display_name' => st('Google Analytics Configuration'),
);

return $tasks;

```

}

```
/**
* Configure google analytics.  The only required field is the tracking code.
*/
function site_google_analytics_form($form, &$form_state){

    module_load_include('inc', 'googleanalytics', 'googleanalytics.admin');
    return googleanalytics_admin_settings_form($form, $form_state);

}

```

The `run_task()` call itself the `drupal_get_form()`, so it was no necessary call yourself in your code.
> 6 votes

---
Tags: 7, forms, google-analytics, installation-profiles
---


# Question
Title: Conditional Stylesheets Set-up: Using the Module
**Problem**

I'm trying to set-up conditional stylesheets. I've followed the instructions but it's still not registering. What have I done wrong?

**Set-Up**

I installed and enabled the conditional stylesheets module. I'm running a Tao sub-theme.

I then added the following lines to my theme.info file:

```
//these are my original stylesheets
stylesheets[all][] = reset.css
stylesheets[all][] = typography.css

//these are my conditional stylesheets
conditional-stylesheet [IE][all][] = styleie7.css
conditional-stylesheets [if !IE][all][] = style.css

```

I then cleared my cache and no style sheets were loaded.

At the moment I'm just trying to have one stylesheet for IE and one for everything else.

I took the syntax from the \[link\] in the conditional css directory.

NOTE:

It's not clear whether you should put

```
conditional-stylesheet OR stylesheet-conditional

```

The documentation says one, a lot of posts suggest the other. However I can't get either of them to work.

# Answer
> 1 votes
Assuming you are using the conditional style module the format would be

```
; Set the conditional stylesheets that are processed by IE.
stylesheets-conditional[lt IE 7][all][] = ie6-and-below.css
stylesheets-conditional[IE 9][all][] = ie9.css
stylesheets-conditional[IE][print][] = ie-print.css
stylesheets-conditional[(gte IE 9)|(gt IEMobile 7)|(!IE)][all][] = modern-browsers.css

```

And there should be no space between the `conditional-stylesheet` and `[IE]`.

If that doesn't work then you should make sure that the stylesheet it is referencing can be loaded. The stylesheet lines don't show up if the stylesheet doesn't exist or cannot be opened.

# Answer
> 0 votes
My final code in my .info file is:

```
stylesheets-conditional[!IE 6][all][] = typography.css
stylesheets-conditional[IE 6][all][] = typographyie6.css

stylesheets-conditional[IE 6][all][] = styleie6.css
stylesheets-conditional[IE 7][all][] = styleie7.css

```

I had three problems. First I had an extra space. Second I was putting `[if]` into the conditional statements i.e.

```
stylesheets-conditional[if IE 6][all][] = styleie6.css

```

The module already adds an `[if]` so it was printing out:

```
<!--[if if IE 7]>
 <style type="text/css" media="all">@import url("http://localhost/drupalie/sites/all/themes/mytheme/styleie7.css?mutp08");</style>
<![endif]-->

```

Lastly I couldn't get it work at all on my Windows 7 machine, but switching to XP worked fine.

IE6 & 7 don't work very well on Windows 7 (hacks needed...) so might be worth setting up an XP test machine as you wouldn't need them to work on 7 anyway.

---
Tags: 7, theming
---


# Question
Title: call js into theme from flexsilder library folder
I have flexslider library in my library folder. how to add jquery.flexslider.js file in my theme or how to call in my template.php file.

# Answer
If the library has been created than you can use libraries\_load() as below:

```
// Load the library of flexislider plugin.
libraries_load('flexslider');

```

libraries\_load: Loads a library.

Parameters:

* $name: The name of the library to load.
* $variant: The name of the variant to load. Note that only one variant of a library can be loaded within a single request. The variant that has been passed first is used; different variant names in subsequent calls are ignored.
> 0 votes

---
Tags: theming
---


# Question
Title: Creating a block with installation profile
To create a block I am currently using this code:

```
$default_theme = variable_get('theme_default', getDefaultTheme());
$blocks = array(
  array(
    'module' => 'user',
    'delta' => 'login',
    'theme' => $default_theme,
    'status' => 1,
    'weight' => 0,
    'region' => 'sidebar_first',
    'pages' => '',
    'cache' => -1,
    ),
);

// Save blocks
$query = db_insert('block')->fields(array('module', 'delta', 'theme', 'status', 'weight', 'region', 'pages', 'cache'));
foreach ($blocks as $block) {
  $query->values($block);
}
$query->execute();

```

My question is what do the 'module' and 'delta' field exactly do? What can I fill in there if I made a custom block? And how do I define on which pages this block should be visible, should I add a page name or id?

# Answer
> 0 votes
> I think that's not the correct way of creating the block as it won't fire the required api call for block creation and later on will cause issue.

**Delta**: This is a unique identifier for the block within the module. Delta values only need to be unique and is used in following purposes:

* Passed into the other block hooks in your module as an argument to identify the block being configured or viewed.
* Used to construct the default HTML ID of "block-MODULE-DELTA" applied to each block when it is rendered. This ID may then be used for CSS styling or JavaScript programming.
* Used to define a theming template suggestion of block\_*MODULE*\_DELTA, for advanced theming possibilities.

**Module**: Name of module creating that block. E.g: If you are creating the block from custom module than it will take the value of that module name.

---

To programatically create the block, you need to use hook\_block\_info(), hook\_block\_view() in your custom module something like below:

```
/**
 * Implements hook_block_info().
 */
function MyModule_block_info() {
  $blocks['test1'] = array(
    'info' => t('Block info 1'),
  );
  $blocks['test'] = array(
    'info' => t('Block info 2'),
  );

  return $blocks;
}

/**
 * Implements hook_block_view().
 */
function MyModule_block_view($delta = '') {
  $block = array();

  switch ($delta) {
    case 'test1':
      $block['content'] = 'Required content 1';
      break;

    case 'test2':
      $block['content'] = 'Required content  2';
      break;
  }

  return $block;
}

```

---
Tags: 7, blocks, installation-profiles
---


title: link being printed from "nowhere"

text:
# Question
Title: link being printed from "nowhere"
I'm a bit stumped. For some reason Drupal prints some extra links and I can't find where are they generated.

This is what I see in my output:

The arrows point to the extra ocurrences of \<a href="/areaclientes"\>\</a\>

The template code for this page is like this:

```
<div id="wrapper" class="clearfix">
<div id="header-top" class="clearfix">
<div id="logo"><!--start logo-->
<?php if ($logo): ?>
<a href="<?php print $front_page; ?>" title="<?php print t('Home'); ?>">
<img src="<?php print $logo; ?>" alt="<?php print t('Home'); ?>" />
</a>
<?php endif; ?>
<div id="site-slogan"><?php if ($site_slogan): ?><?php print $site_slogan; ?><?php endif; ?></div><!--site slogan-->
</div><!--end logo-->
 <?php if ($page['search_box']): ?><!-- / start search box region -->
    <div class="search-box">
      <?php print render($page['search_box']); ?>
    </div> <!-- / end search box region -->
 <?php endif; ?>
 <?php if (theme_get_setting('social_icons')): ?>
<ul id="header-social">
<li><a href="http://www.twitter.com/<?php echo theme_get_setting('twitter_username'); ?>" target="_blank" rel="me"><img src="<?php global $base_url; echo $base_url.'/'.$directory; ?>/images/twitter.png" alt="twitter"/></a></li>
<li><a href="http://www.facebook.com/<?php echo theme_get_setting('facebook_username'); ?>" target="_blank" rel="me"><img src="<?php global $base_url; echo $base_url.'/'.$directory; ?>/images/facebook.png" alt="facebook"/></a></li>
<li><a href="<?php print $front_page . ($language->prefix ? '/' : ''); ?>rss.xml"><img src="<?php global $base_url; echo $base_url.'/'.$directory; ?>/images/rss.png" alt="RSS"/></a></li>
</ul><!--end header-social-->
<?php endif; ?>
</div><!--end header-top-->

<div id="header" class="clearfix"><!--start header-->
    <?php print render($page['header']); ?>
<div id="main-menu">
    <?php
    $main_menu_tree = menu_tree(variable_get('menu_main_links_source', 'main-menu'));
    print drupal_render($main_menu_tree);
    ?>
</div><!-- end main-menu -->
</div>

```

I've been looking all over the place, and can't find WHERE is that coming from. Searching in site's source code I only found 1 instance of a similar looking URL, inside a Module I disabled and deleted from the host; and still the same thing.

The links appear both before the main menu starts building, and after. Several times for the first menu item, but never again. And it only happens with anonymous users, never with logged in users...

Any pointers in where should I be looking to fix this?

Thanks a lot in advance.

Edit:

I found that the problem lies in this piece of code:

```
<div class="search-box">
        <div id="link-clientes"><a href="/areaclientes">ÁREA DE CLIENTES <img height="14" width="14" src="/sites/default/files/pictures/clipart/key.png"</a></div>
      <?php print render($page['search_box']); ?>
    </div> <!-- / end search box region -->

```

If I remove the #link-clientes \<div\>; the ghost links stop appearing later on. Still don't understand why.

# Answer
It can't be that hard to understand. There's a syntax error:

```
<div id="link-clientes"><a href="/areaclientes">ÁREA DE CLIENTES <img height="14" width="14" src="/sites/default/files/pictures/clipart/key.png"</a></div>

```

`<img>` tag is not closed. That's breaking your whole page HTML structure/well formedness.
> 1 votes

---
Tags: 7, theming, navigation
---


title: How can I add fields to blocks?

text:
# Question
Title: How can I add fields to blocks?
Is there a way we can add some fields in Blocks, just like we can do in content types. For now I need an image field attached to a block.

I know about a module named Image Block but that is limited in its functionality.

# Answer
> 11 votes
Try one of the following modules:

**Bean**

> **What is Bean?**
>
> Think of a Bean as a method to provide new types (compared to node this would be a content type) which then provides an add content interface to create as many blocks as you require (see screenshot below). The bean content can then be placed around the site just like any other block.

**Boxes**

> Boxes module is a reimplementation of the custom blocks (boxes) that the core block module provides. It is a proof of concept for what a re-worked block module could do.

My personal preference has always been Bean (before I started using Panels more frequently), but I don't think there's a lot in it to be honest.

# Answer
> 1 votes
Check out Nodeblock module. From the project page:

> This module allows you to specify content type(s) as being a block. This allows the content managers of the site to edit the block text and title without having to access the block administration page. Users only need edit access to that node in order to edit it.

Another option is to have a separate content type and display those nodes as blocks. Depending on your exact needs, this might make more sense. For this option, check out Nodes in Block module.

> Nodes in block makes it possible to add nodes into a block. A number of configurable blocks are generated which you can assign to a region. Visibility settings of this block are automatically set to 'Show on only the listed pages'. On the node content form, you define the weight and visibility per node thus making it easier for content administration as all your content is now in the same place. With this module, you don't have to explain your customers how blocks work but is still able to decide on which pages content must be rendered.

# Answer
> 0 votes
Other module suggestions are Display Suite and / or EVA (Entity Views Attachment).

Display Suites allows you to create a block field. So you can choose a block which will be added to a content type, or more than one.

With EVA you can create a view which you can attach to a content type as a field.

Both quite handy and powerful but as often, it depens much on what exactly you have to do.

---
Tags: entities, blocks
---


title: Hide comments and show them using views

text:
# Question
Title: Hide comments and show them using views
Am using views to display the comments below my node types in drupal 7.

The view works fine but i can't find a way to hide the regular drupal comments above the form.

How do i just display the comment form and the comments using views.

# Answer
In node.tpl

```
    hide($content['comments']);

```

This hides both the comment form and the comments.

To render the comment form alone use

```
    print render($content['comments']['comment_form']);

```

Then you can create your view for them nice comments and display them below the form.
> 1 votes

---
Tags: 7, comments
---


title: Make blog on a subdomain

text:
# Question
Title: Make blog on a subdomain
I need some help figuring this out. I have a main site `mysite.com` on Drupal 7. I want to build a blog for it and want for people to access it using `blog.mysite.com`. So basically it's the same site (so I can manage content from the same place), just on different URLs.

NOTE\*: Individual posts page should show the URL like so: `blog.mysite.com/my-post`

I was wondering if this can be done using a `View` under the path name `mysite.com/blog` and mask the URL somehow to show `blog.mysite.com` instead. I am using `nginx` as a webserver.

# Answer
Sounds like you'll need to use the Domain Access module to get this right. This module allows you to run as many affiliated sites as you need from one single Drupal installation, sharing the same database.

I'm using it for another site at the moment, and it works really well.
> 3 votes

# Answer
First of all, you need to have both domains pointing at your site, but that's a HTTP server config issue I assume you have figured out already.

There are 2 parts to it, serving proper content and displaying proper links.

## Serving proper content

It isn't exactly Drupal only thing. To serve content of a "subdirectory" when subdomain is called, you need to put something like this at the beginning of your htaccess:

```
RewriteEngine on
RewriteCond %{HTTP_HOST} ^blog.example.com [NC]
RewriteRule ^/(.*)$ /blog/$1 [L]

```

With nginx, it would look like this (note: not my personal experience, taken from here):

```
server {
  listen 80;
  server_name blog.example.com;
  location / {
    proxy_pass http://127.0.0.1/blog$request_uri;
    proxy_set_header Host example.com;
  }
}

```

You could also use `hook_url_inbound_alter`, but it would probably be slower than proper webserver configuration. Drupal uses webserver's URL rewriting anyway.

## Revriting URLs

General way would be to use `hook_url_outbound_alter()`. If you don't want hook's slowdown, you can:

* **URL links to nodes, generated by Views** are easy to fix - you can use "rewrite field" option to manually create links you need
* **Links to theme elements and other files** are bit harder to do - basically you need to create exception in rewrite rules above, and for everything that is a static file or directory omit rewriting. Example how to do this is to be found in original config, as it is the same condition that makes static files not to be processed via index.php.
* **Links inside nodes** \- *This section awaits further research*
> 3 votes

---
Tags: views, nodes, subsites
---


# Question
Title: Only show title of referenced node in a view if the node contains files in another field?
Content-type-A has files attached. Content-type-B has a node reference to multiple Content-type-A's.

I making a view which is attached to Content-type-B. It needs to show each Content-type-A title that is referenced and also the files attached to each Content-type-A.

This is easy to do with relationships however I need the Content-type-A title to not be shown if there are no files attached to it.

So if I have this:

NodeB has a node reference to NodeA, NodeA2 and NodeA3.

NodeA and NodeA2 have a file attached but NodeA3 does not.

Then I need my view to just be this:

```
NodeA
-File from NodeA
NodeA2
-File from NodeA2

```

But its currently this:

```
NodeA
-File from NodeA
NodeA2
-File from NodeA2
NodeA3

```

# Answer
> 2 votes
Your view has all the info you want (and then some); simply override the view template or use hook\_view\_preview() to unset/hide the result you dont want.

There are many examples of this on the web and in documentation.

---
Tags: views
---


# Question
Title: cache keys $cid naming practices (cache_set and cache_get)
For using cache\_get and cache\_set

According to this comment

> The convention seems to be to use colons to create a sort of namespacing. So your module may want to do something like $cid = 'mymodule:mything:50';

so:

* is ':' the recommended delimiter?
* should the module name go first? (seems sensible)?
* are there characters to avoid?
* are there other considerations?

# Answer
1. **is ':' the recommended delimiter?** I haven't heard that `:` is recommended over anything else, but since it's definitely used all over core, it would make a lot of sense. All cache backends that work with Drupal will be handling `:` well.
2. **should the module name go first? (seems sensible)?** Yes, this is general practice, not just cache keys.
3. **are there characters to avoid?** None that I've heard of. In general, in 2013, if any system doesn't properly handle any character in a string properly, I would find really bad to be honest. With that said, we'll always be dealing with one form or another of legacy software. So stick to a-z, numbers and `:` if you're feeling risk averse.
4. **are there other considerations?** Can't immediately think of any.
> 3 votes

---
Tags: caching
---


title: Export Recipes from Recipe module

text:
# Question
Title: Export Recipes from Recipe module
I'm working on a site with the Recipe module for cooking recipes installed on it. According to the linked page, it's possible to import and export recipes to and from that module. Unfortunately, I can't find where that can be done. Does anybody know how to do it?

I'm fairly new to Drupal, so I'm sure I'm just overlooking something obvious...

# Answer
Make sure you enabled one of the additional modules that allow you to export the content, e.g. "Recipe recipeML" or "Recipe MasterCook4". They will provide you with extra pages where you can import/export the content.

For example, "recipeML" will add new pages for importing/exporting the recipes on the following paths: `admin/content/recipe/export_multi` and `admin/content/recipe/import_multi`. Visit `admin/content`, then click on "Recipes" from the list of local tasks and from there you can go to the import/export page.

Hope this makes sense.
> 1 votes

---
Tags: 7, importing-exporting
---


# Question
Title: Unable to set Drupal environmental variables using Drush alias
```
$aliases['opendoor_stage'] = array(
    'uri' => 'stage.opendoor.com',
    'root' => '/var/www/stage.opendoor.com',
    'db-url' => 'mysql://someurl',
    'path-aliases' => array(
      '%dump-dir' => '/var/www/database-dumps',
     ),
    'variables' => array(
        'site_name' => 'My Drupal siteSSSSSSSSSSSSSSSSSSSSSSSSSSSS',
        'file_temporary_path' => '/var/www/open_door_files/uploads',
        'file_private_path' => '/var/www/open_door_files/contentfiles',
      ),
     'command-specific' => array (
       'sql-sync' => array (
         'no-cache' => TRUE,
         'structure-tables-key' => 'skip',
       ),
     ),
    'command-specific' => array (
    'sql-sync' => array (
      'sanitize' => TRUE,
      'no-ordered-dump' => TRUE,
      'structure-tables' => array(
       // You can add more tables which contain data to be ignored by the database dump
        'skip' => array('cache', 'cache_filter', 'cache_menu', 'cache_page', 'history', 'sessions', 'watchdog'),
      ),
    ),
  ),
  );

```

I then do the following commands to copy into my stage environment:

```
drush rsync @opendoor_test @opendoor_stage

```

and

```
drush sql-sync @opendoor_test @opendoor_stage --no-cache

```

Everything copies over fine however the information in the variables array never gets set. What am I doing wrong? I am following the documentation verbatim.

# Answer
> 6 votes
The 'variables' entry in a Drush alias file, or in $options\['variables'\] in a drushrc.php file will ***only*** affect Drush code execution; it does not in any way change the variables table in the database, or affect that way that Drupal runs from the webserver at all.

If you would like to change the values in the database, after sql-sync you could run:

```
drush @opendoor_stage vset site_name 'My Drupal siteSSSSSSSSSSSSSSSSSSSSSSSSSSSS'

```

See also sync\_enable.drush.inc, which will enable modules and set permissions after every sql-sync operation. If you often needed to set variables after every sql-sync, you could extend this code to call vset based on the values of entries in the site alias.

**POSTSCRIPT:**

You might also want to consider using $conf\['site\_name'\] in the destination site's settings.php file rather than change the database value. This is what most folks do.

# Answer
> 0 votes
I think it might be useful to state that more clearly in the inline docs. Right now, I'd read this (from the drushrc.php) as that it changes the values, rather than just temporarily overriding them for the purposes of any Drush work.

/\** * Override specific entries in Drupal's 'variable' table or settings.php \*/

# $options\['variables'\]\['site\_name'\] = 'My Drupal site';

# $options\['variables'\]\['theme\_default'\] = 'minnelli';

# $options\['variables'\]\['anonymous'\] = 'Visitor';

---
Tags: drush, path-aliases
---


# Question
Title: ubercart zip/postal code reformatting in views using php
Is it possible to rewrite in views (possibly with php field) ubercart's customers zip numnber? The original format is "12345". I need to put a empty space after 3rd digit like "123 45". Can anybody help me with php code?
I put

```
  chunk_split($data->delivery_postal_code, 3, ' ');

```

inside custom php field inside value field but views output empty field. Thank you very much

# Answer
for anybody interested - this is the working code

```
 return chunk_split($data->uc_orders_delivery_postal_code, 3, ' ');

```
> 0 votes

---
Tags: theming, 6, ubercart
---


# Question
Title: Cannot block access to nodes with hook_node_access_records
I have written a module which adds a node access record. The workflow module is also installed which adds two other records to the node\_access table.

Here Author says that:

> Drupal is a “deny-based” access control system. In other words, **if anybody denies access to a node, then the node is blocked.**

But when I deny access to a node in my module, it is still accessible for all users.(workflow module grants access for both anonymous and registered users)

A solution would be setting the record priority higher than workflow's access records, but I don't want to change the priorities.

```
/**
 * Implements hook_node_access_records()
 */
function mymodule_node_access_records($node) {

   $user = field_get_items('node', $node, 'field_recipient');
   $uid = $user[0]['uid'];

   if ($node->type == 'contact') {
      $grants[] = array(
         'realm' => 'contact',
         'gid' => $uid,
         'grant_view' => 1,
         'grant_update' => 0,
         'grant_delete' => 0,
         'priority' => 0,
      );
   }
   return $grants;
}

/**
 * Implements hook_node_grants()
 */
function mymodule_node_grants($account, $op) {
   $grants['contact'] = array(1234); //1234 is for test and doesn't exists in node_access table
   return $grants;
}

```

Is anything wrong?

# Answer
> 1 votes
Blog post needs to be updated. I remember having discussion with him about it.

hook\_node\_access is a deny access; grants are if a user has any matching grant, they have access.

you can use the alter hook to remove undesirable grants, but doing custom access requires a lot of testing and thinking. Also, read the https://api.drupal.org/api/drupal/modules%21node%21node.module/function/node\_access/7 node\_access documentation/code

---
Tags: 7, users
---


# Question
Title: Access to image uploaded in article content type is denied
when I attach an image to my article content type it doesn't show image. I mean when I creat an article content type and I upload an image to its using Image filed of article content type and publishe my article, the image not shown and when I right click to image and clicl "open in new tab" it goes to "Access Denied" page and says you don't have access to this image. this is true for my galley images too. pleas help me :) thanks

# Answer
If you have uploaded an image as a private file it is not accessible by other users even if any user has access to the node. Please check "Upload destination" in image field settings.
> 0 votes

---
Tags: media
---


# Question
Title: Overriding user edit page with Panels loses the user edit form
I am using panels to override the user edit page (/user/\*/edit) to add a block with a form in it. However I wanted to maintain the existing user edit form, including the password, username, etc. When I overrode the page, I was able to add my block, but lost the original user edit form. I've tried adding the various widgets from the 'User' category (user profile, Profile:Main Profile, etc) on the 'Content' section of the new variant, but they just seem to contain various bits of user information, and none of them add the user form.

How can I add back the user edit form to an panels-overridden user edit page?

# Answer
> 5 votes
I think it's fair to say the pane could have had a better name, but here it is.

---
Tags: panels
---


# Question
Title: drupal 7 views structure: Different nodes should collect different (term) lists
I think I can solve this with views, but can't find a good solution.

I have the nodes: vegetable, fruits..(one content type). Then I have different nodes of vegetables and fruits: carrot sort 1, carrot sort 2.../ salad sort 1, salad sort2.../ apple sort 1, apple sort 2...

The goal is this structure:

1. node vegetable: -text- -headline 1: carrots- -list of different carrots-

-headline 2 salad - -list of different salads-

1. node fruits -text- -headline 1: apples- -list of different apples-

-headline 2 berries- -list of different berries-

Have I built for carrots, salads, apples, berries... separate views? Maybe there is one better way? How can I collect this seperate views on the nodes "vegetable" and "fruits"? I tried it with eva, but (sure) I got on both of my nodes the same result with all fruit and vegetables together.

Any ideas? Thanks in advance

# Answer
> 1 votes
Yes, this is absolutely doable with one View.

What you are looking for is under Format: Unformatted list (or whatever your view style is) | Settings.

Click Settings and set a Grouping Field based on the field you would like to group - "content type" in this case.

# Answer
> 0 votes
This is a typical task for views.

Summary:

1. Create a view of Content
2. Create two pages in the view, fruits and vegetables, with filter criteria for the respective taxonomy term.
3. In the Format settings, choose the taxonomy vocabulary that sets the sub-type for the fruits or vegetables as grouping field
4. Add a header for each of the pages as rendered entity/content/nid

Details:

1. Create a content type for your fruits and vegetables. I will call this content type now "catalog".
2. Additionally to the fields describing each of the catalog items, create a taxonomy vocabulary "catalog\_type" with the terms "fruit" and "vegetable".
3. Add a second taxonomy vocabulary "catalog\_detail" with terms "Carots", "Apples", "Salads", "Berries".

Now, you can create a view or content for the content type catalog.

1. Create view: View of Content of type catalog. Check "Create a Page". Set the "Display Format" to "Table" or "Unformatted list" or whatever you prefer, and choose a generously high number of items to be displayed. Click "Continue and edit"
2. Add fields: Add all fields you want to display (if you chose table), and also the catalog\_detail taxonomy term.
3. Add a filter criteria for the taxonomy vocabulary "catalog type" to be "vegetable".
4. Click on Settings in "Format: xx(yourformat) | Settings" ; In Grouping Fields: Choose "catalog\_detail" Click "Apply for all displays"

Now, you should have your vegetables grouped in the views preview, and need to add the general vegetable node to the header of the output:

* Click "Header -\> Add" (second column of the views form) Check "Entity: Rendered entity " Click "Apply - all displays" Choose "Entity type -\> Content" Enter the node id of your general vegetable node (just the number) Click "Apply - all displays"

That should be your page for the vegetables. You can set your menu path, and title, etc. to your liking.

Now you can clone your page for the fruits:

* On the views form, locate " Display name: Page " Go to the right side of the form, and click on the pull-down menu -\> selection "Clone Page"

On this page, you need to change three things. Change those, and be careful to select on the forms "This display only", otherwise, you'll change the "vegetable" one as well.

1. The filter criteria should be "fruits" now
2. The header node id should get changed
3. Title and path should be adjusted.

That should be it!

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


# Question
Title: Change the size of the form element for content title
I could have sworn that when we created our content type, we could select the size of the textfield for the title. I am unable to find that now as I'm in "Manage Fields" and the edit link that's available for other fields is not there for the title field. It says only in field type "Node module element". I even tried looking through our database to see if there was a place where this was set and I couldn't find anything. Am I missing something simple?

# Answer
> 1 votes
You don't have the options of choosing your title field lengths in standard D7. However, there is a module that lets you change that:

https://drupal.org/project/title\_field\_ui

The only problem is, that the module is only in alpha and not widely used. On the other hand, the module author is very reputable, so I'd give it a try.

Other solutions have been discussed before: Change / Increase the node title length

---
Tags: nodes
---


title: Filter view using taxonomy name in url

text:
# Question
Title: Filter view using taxonomy name in url
I have a view that shows a thumbnail of the node and the teaser of the node for all nodes of a certain content type. What I want to do is to only show nodes tagged with a certain word, using the url

My website taxonomy page has this format /category/tags/beauty

How can I do this?

# Answer
> 1 votes
Add an Argument to your view with Taxonomy: Term ID (with depth). You may want to use %2 for the title (or %3?). At the bottom of the argument config form you'll see "Set the breadcrumb for the term parents."

# Answer
> 1 votes
You can achieve that by using `Taxonomy: Term ID` as argument and than `Validator: Taxonomy term`, `Argument type: Term name/synonym converted to Tern ID` as following:

1. Create view (as per the requirement) and the the required fields.
2. Set the path of page display: **category/tags/%**. (Remember `%` is at third place, this we will be using in contextual filter).
3. Add the argument: **Taxonomy: Term ID**.
4. Configuring the added argument by adding **Validator options: Taxonomy term**.
5. Select **Argument type: Term name/synonym converted to Tern ID**.
6. Save the view and clear the cache to check the changes.

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


# Question
Title: Creating a custom url when navigating to a custom module form
I have created a custom module which can be visited via the address `http://myhost.me/my_module/form` where it will show my created form. Is there a way wherein instead of using `http://myhost.me/my_module/form` I can navigate to `http://myhost.me/mynewmoduleurl` without breaking anything? I'm currently using `Drupal 6`. Please help. Thanks.

# Answer
> 5 votes
There are multiple ways.

1. You could use `hook_menu()` to declare a new path with the same callback (while still leaving the old one intact).
2. You could use Redirect module.
3. You could create a .htaccess redirect. (A `301 redirect` is the proper way to do it if you want the new one to permanently replace the old one.)
4. You could create a new Path Alias.

---
Tags: 7, forms, uri
---


title: Search index in drupal7

text:
# Question
Title: Search index in drupal7
I tried following methods for search index in drupal 7:

1. Click on re-index site.
2. Number of items to index per cron run is 100.
3. Save Configration.
4. Run Cron and check the items count left to index.

I got "There are no new nodes. Cron run successfully." still I am getting (0% of the site has been indexed. There are 51996 items left to index) in index status.

# Answer
> 4 votes
if you have drush installed, you can do it this way: `drush search-reindex --immediate --verbose`

There is a dev module available that does the same thing. https://drupal.org/project/reindex

It's probably a good idea to have the site in maintenance mode while you try this.

# Answer
> -1 votes
Drupal's search engine indexes the text content of the nodes on your site. You can tweak the way it does this.

The search engine does its indexing at intervals you choose by setting "cron runs." Cron (which stands for chronograph) is not a part of Drupal. It's a scheduler that resides on your server and runs tasks (called "cron jobs") at intervals, which you specify. The jobs can run weekly, daily, hourly, or whatever you like.

you can better check Search: an internal site search system

---
Tags: 7, search
---


# Question
Title: How to edit live theme .info file (localhost)
I'm currently building a custom theme from the ground up on drupal on localhost.

At the moment I've managed to add my theme and run my custom templates succesfully. However I can't get it to pick up my CSS or JS files.

These were the lines in my .info file

```
stylesheets[all][] = /css/main.css
scripts[] = javascript/javascript.js

```

However I got an error in the console saying:

```
'GET http://localhost/drupal/css/main.css 404 (Not Found)'

```

So I modified the path of the css and js files to something like this:

```
stylesheets[all][] = sites/all/themes/THEMENAME/css/main.css

```

Yet it still can't find it. I'm not sure what's going on. Has the .info file been cached?

# Answer
May be the problem is of `/` present at the starting in your first attempt(`/css/main.css`), try once with:

```
stylesheets[all][] = css/main.css

```

**Note:** Clear the cache and check if it works.

Also you can check the following links if it helps:
https://drupal.org/node/171205
https://drupal.org/node/171209
> 1 votes

---
Tags: theming, .info
---


# Question
Title: How to restrict number of nodes per content type?
How can we restrict number of nodes allowed per content type. Let suppose if we allow 5 nodes then no one including the admin user can add the 6th node of that content type.

# Answer
one possible solution to achieve the above is by checking the node count of that content type in hook\_node\_validate() as below:

```
/**
* Implements hook_node_validate().
*/
function MyModule_node_validate($node, $form, &$form_state) {
  // For now assign the static values to CONENT_TYPE and MAX_NODES
  // however you can make it dynamic, and get those values using variable_get().
  $content_type = 'CONTENT_TYPE';
  $max_nodes = 'MAX_NODES';
  $node_count = 0;

  // Create a check for the content type.
  if ((isset($node->type)) && ($node->type === $content_type)) {
    $query = new EntityFieldQuery;
    $node_count = $query->entityCondition('entity_type', 'node')
      ->entityCondition('bundle', $content_type)
      // To get published nodes only, use: ->propertyCondition('status', 1)
      ->count()
      ->execute();

    // Check if the node count exceeds the max_node value.
    if ($node_count > $max_nodes) {
      form_set_error('FIELD_NAME', t('Reached the maximum limit of creation of nodes for this content type.'));
    }
  }
}

```

Similarly you can do with the `Rules` also, but the above method seems better to me.
> 2 votes

# Answer
Have you tried the Node Limit module?

> The Node Limit module allows administrators to restrict the number of nodes of a specific type that roles or users may create. For example, if a site has an "Advertiser" role that can create "advertisement" nodes, then the node limit administrator can restrict all users in that role to a specific number of nodes. He may also restrict users on a per-user basis.

You could create a role just for node limit and assign ALL users (including the admin) to that role.
> 7 votes

---
Tags: users
---


# Question
Title: How to get node editing form in a custom module
how to call a drupal node editing form in a custom module? What i have done so far:

```
/*
 *  implementing hook_menu()
 */

function mymodule_menu() {
  $items = array();

  $items['custompage'] = array(
    'title' => t('Sometitle'),
    'page callback' => 'custom_page',
    'access callback' => 'user_access',
    'type' => MENU_NORMAL_ITEM
  );
  return $items;
}

function custom_page() {
  $output = '';
  $output = drupal_get_form(15);
  return $output;
}

```

But it won't output node edit form with nid 15. What i am doing wrong?

# Answer
15 is the node ID of the node whose edit form you want, not the actual ID of the form. This makes sense since node edit forms are defined per nodetype, not per node.

You'll need to call `drupal_get_form()` with the form ID, something like `[nodetype_name]_node_form`.

The second parameter should be the node object, e.g. `node_load(15)`.
> 3 votes

---
Tags: 6, hooks
---


# Question
Title: Is there a module that lists which tables are created, owned or modified by a particular module?
Is there a module that lists which tables are created, owned or modified by a particular module?

I need something that can show me what tables are created or modified by when new modules are installed.

# Answer
Building on what Ursula said about Drupal using hook\_schema() for all modules to define their tables, there is a module called Schema which gives you a full list of all tables and their associated modules.

If you are a module developer, this is an incredibly handy module since it allows you to first create the table manually in your database, and when you load up the Schema page, it will generate the code for the table definition for you.
> 2 votes

# Answer
Since Drupal 7, tables should get created by modules using hook\_schema(), because these tables will also get removed when uninstalling the module.

You can find these tables by executing the code below, or by using the Schema module (https://drupal.org/project/schema):

```
$schema = drupal_get_schema(Null,TRUE);// Get List Of all tables.
  ksort($schema);// Sort Ascending
  foreach($schema as $table => $value){
    print_r($table."<br>");
  }

```

All well written modules should create tables only using hook\_schema, and should not alter tables in other modules.

If you suspect that other tables got changed, you can find this in the .install file for each module. Look for the database layer calls like db\_add\_field or even db\_create\_table.

For a list of all these, consult the Drupal documentation: https://api.drupal.org/api/drupal/includes!database!database.inc/
> 2 votes

---
Tags: 7
---


title: Theming and designing css in Drupal 7

text:
# Question
Title: Theming and designing css in Drupal 7
Ok, I know this is a general question, but I **really** looked information for a long time, and couldn't find helpful info that helped me.

I almost finish developing my community site in Drupal 7. Now I am starting to design it. I chose Zen theme, and created sub-theme.

Can you please recommend me about the best convenient method to **implement CSS to DRUPAL site**?

Thanks in advance

# Answer
> 1 votes
Well that's very vast topic, however few things I would like to share with you are:

I tried to cover few of the quick points that striked me first, but anyways there is no limit of learning, so keep on exploring!!

---
Tags: theming
---


# Question
Title: display list of pages of content type using views + edit and delete option
I've installed the Views Bulk Operations module (VBO). Using this I want to create a block/page to load all the pages of particular content-type. But it should include options like update + check boxes, edit/delete. See the screenshot below.

I couldn't find the built in view 'content', so I've to create from scratch. Please give me solutions.

# Answer
> 1 votes
I got the solution by installing Admin VBO Views module

# Answer
> -1 votes
Check `admin/structure/views/view/admin_views_node`

---
Tags: views, theming, nodes
---


# Question
Title: Passing multiple array to drupal_json_output() is not giving correct output in jquery ajax
Passing multiple array to drupal\_json\_output() is not giving correct output in jquery ajax.

I am using a menu\_callback function and returning a multiple array like

```
function test_callback() {
   for($i = 0; $i < 10; $i++) {
    $arr = array('message' => 'test'.$i, 'data' => 'data'.$i);
    $arrs[] = $arr;
   }
 drupal_json_output($arrs);
}

```

Now, in the jquery, I wrote like this,

```
$.ajax({
url: the above url,
dataType: 'json',
success: function(data) {
$(data).each(function(key,val) {
  console.log(val.message);
});
})
});

```

The output in the console is giving an object.

I tried to use `$.each` for the val also, but the output it is returning as undefined. I tried in a lot of ways using `$.get` etc. but not getting the output. Can anyone help me here??

# Answer
To setup a service which returns a json formatted data, you should set the `delivery callback` to `drupal_json_output`. This will only output the service data and not all the HTML defined in your theme.

For example

```
function YOURMODULE_menu()
{
    $items = array();

    $items['service/ajax'] = array(
        'title' => t('Ajax service'),
        'page callback' => 'YOURMODULE_ajax',
        'delivery callback' => 'drupal_json_output',
        'access arguments' => array('access content'),
        'type' => MENU_CALLBACK,
    );

    return $items;
}

function YOURMODULE_ajax()
{
    for($i = 0; $i < 10; $i++) {
        $arr = array('message' => 'test'.$i, 'data' => 'data'.$i);
        $arrs[] = $arr;
    }

    return $arrs;
}

```
> 5 votes

# Answer
I guess we need to let the ajax call know that the response is in JSON, once give a try to the following code:

```
// Callback function of ajax (PHP file).
function test_callback() {
  for($i = 0; $i < 10; $i++) {
    $arr = array('message' => 'test'.$i, 'data' => 'data'.$i);
    $arrs[] = $arr;
  }

  // Returns data in JSON format.
  drupal_json_output($arrs);
}

// Js code for making an ajax call, and handling the response of ajax.
$.ajax({
  url: the above url,
  dataType: 'json',
  success: function(data) {
  // Check the reponse data in the firebug console.
  console.log(data);

  /** Commenting the code for now, once you get the data than uncomment this.
  $(data).each(function(key,val) {
    console.log(val.message);
  });
  */
}, 'json');

```
> 0 votes

---
Tags: 7, javascript, ajax
---


# Question
Title: How do I change the structure of node's $content variable?
I create a Content Type and I add to it a field (Embedded Media Field) that has thumbnails of Youtube videos.

Now the thumbnails use each a row on its own. I want to make them show in three columns, like in a grid. I understand i have to create a node-MyContentType.tpl.php . But in this file there is a $content variable that holds the html structure of the content and i can't find a way to change that (i want to remove some divs). Can anyone guide what to search for?

# Answer
> 1 votes
Creating a template (`node-MyContentType.tpl.php`) for your content type is certainly helpful to manipulate the display of the entire node, but it sounds like what you're looking for is how to modify individual fields, and these are rendered in a different template.

Drupal uses template files and theme\_xxx() functions to display elements on the site, and there is generally one template or theme function for each object (page, node, block, field, etc.). In order to override them, you use a feature called **Template Suggestions**. These are an alternate template (.tpl.php) file that you have created to override the base or original template file. Read more about these for Drupal 6 or Drupal 7.

The best way to create your own version of a template file is find the original one, copy it into your theme folder (*don't modify the original!*), and rename it using the "template suggestions" convention mentioned in the links above. In Drupal 6, you have to have both the base template (e.g. `node.tpl.php`) as well as the renamed one (e.g. `node-mytype.tpl.php`). In Drupal 7, having the base template in the same folder is not necessary.

In Drupal 6, fields are a part of the CCK module. Here's information on overriding CCK Field templates. The original template `content-field.tpl.php` is located in the CCK module under `cck/theme`.

In Drupal 7, fields are a part of the Drupal core code. The original template `field.tpl.php` is located in `modules/field/theme`.

# Answer
> 0 votes
To theme individual content types in different ways, you need to create a file `node-[type].tpl.php` in your theme's folder, where `[type]` is the machine readable name of the content type.

**$content**: Node content, teaser if it is a summary.

Basically you can edit the template file in anyway you, to add the fields you can make the use of `$node`: **$node**(object): The node object. To view all of the properties of a current $node object, put the following line of code in your node.tpl.php: `<?php print_r($node); ?>`

Also you can check the community docs for overriding the node template files: https://drupal.org/node/11816
https://api.drupal.org/api/drupal/modules!node!node.tpl.php/6
Theming nodes by content type

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


title: Add expression db_select

text:
# Question
Title: Add expression db_select
What is the corresponding alternative in Drupal 7 for the following query

```
SELECT row_id,name,email, COUNT(name) AS name_count
FROM tn_api_users
GROUP BY name
HAVING  (name_count > 1)

```

# Answer
That would need a combination of `SelectQuery::addExpression()`, and `SelectQuery::having()`, e.g.

```
$query = db_select('tn_api_users', 'u')
  ->fields('u', array('row_id', 'name', 'email'))
  ->groupBy('name')
  ->having('name_count > 1');

$query->addExpression('COUNT(name)', 'name_count');

```

Output:

```
SELECT u.row_id AS row_id, u.name AS name, u.email AS email, COUNT(name) AS name_count
FROM
{tn_api_users} u
GROUP BY name
HAVING  (name_count > 1)

```
> 6 votes

---
Tags: database
---


# Question
Title: How can I place brackets around a field in a view?
I'd like to place a field's value in a view between brackets. Let's say that there are 2 fields 'Name' and 'Country'. How can I display these as **Name (Country)** in a view? I know how to inline the fields, but I have no idea how to place the brackets around the second field.

How can I do this?

# Answer
> 0 votes
Simply use the **rewrite field** option: use the 'country' token and place brackets around it.

Special thanks to @Mołot!

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


# Question
Title: How to get next valid `product_id` value within Rules for drupal commerce product?
I'm using Rules to create drupal commerce products. The problem is that the `product_id` is not assigned.

Since the Rules settings page for creating products only gives the following options, I assumed that the `product_id` would be generated automatically:

*Entity type, SKU, Type, Title, Creator, Price, Provided variables*.

If the `product_id` has to be added manually (within Rules) how would I obtain the correct value to use? (Or is there a setting I am missing within Rules?)

Cheers!

# Answer
> 1 votes
You cannot set the product ID manually, because it depends on the AUTO\_INCREMENT value in your commerce\_product database table. What you can do is use "Save an entity" on the product and check the "Force saving immediately" checkbox. The entity will have an ID after that, though I've had scenarios in Rules where for some reason the ID wasn't immediately added to the entity in memory. If this happens to you, you'll just have to use "Fetch an entity by property" after saving and load the product using the SKU or something and use the fetched\_entity from then on.

---
Tags: commerce, rules
---


title: Dynamic file directory for file fields

text:
# Question
Title: Dynamic file directory for file fields
I just learned about the creating fields and content types and had a quick question about the file field. When you create a file field you can specify a relative path that the uploaded resource will be stored by entering a path in the "File Directory" text field, but what I am going to need is to have the value be different depending on the circumstances. For example I might want to clump all of the files uploaded by a certain user so I might want the relative path to depend on the user's name. Is there a way to specify this type of dynamic path? Is the something people normally do? Or would they just organize files based on type?

# Answer
> 3 votes
It's very easy if you have the Token module installed. On the file field edit page you'll see something like this:

The big table is a list of tokens that you can use in the path for the file. By default there are tokens available for `current user`, `current page`, `current date` and a couple of others.

For example you could have a path such as `users/[current-user:name]`, in which the token would be substituted for the current user's name. You just need to click in the text box you want to add the token to and then click the links in the table, it will auto-fill for you.

Hope that helps

# Answer
> 1 votes
I think you may try filefield paths module which extends `Token` and gives you more interesting options like **\[node:nid\]**.

---
Tags: files, uri
---


# Question
Title: Drupal and its modules kept in two different subfolders -- possible/how?
New to Drupal... I was wondering if it was possible to install it with the core and the modules kept in separate folders, rather than in a hierarchy. A bit like with WordPress, so to speak:

```
/.htaccess <-- site is here, in /, and in git
/drupal    <-- Drupal core, pulled as a git submodules
/content   <-- plugins and themes, each pulled as git submodules

```

I'm guessing it's possible, but the installation manual and a bit of googling (skeleton, subfolder, enterprise, etc.) led me nowhere. If so, I could use a pointer to get me in the right direction. If not, will it be possible with Drupal 8, which unless I am mistaking is using Symfony components?

# Answer
> install it with the core and the modules kept in separate folders, rather than in a hierarchy

In short, no.

Drupal must be able to expect to find files in a certain location, and that is not dynamically configurable. The very first line of code Drupal executes is `define('DRUPAL_ROOT', getcwd());`, and file wise, most things are based on that constant.

Symfony, and PSR-0, doesn't inherently change that. PSR-0 only defines the directory structure around files, not where to find them. With that said, I haven't looked in enough detail at D8 to know if there's a simple way to alter where the autoloader looks for files.

If your filesystem (and webserver) supports symlinks, you can work around the problem by symlinking the appropriate directories in place.
> 1 votes

# Answer
try and make a link and see if it works. I have done that for files in drupal and it should work for modules too.
> -1 votes

---
Tags: 7, installation
---


# Question
Title: page-node-nid.tpl.php is not used as template file
I am using the following code.

```
function chgakitheme_preprocess_page(&$vars, $hook) {
  if ($vars['user']->uid == 0 && arg(0) == 'user' && (arg(1) == '' || arg(1) == 'login')) {
    array_unshift($vars['template_files'], 'page-login');
    $vars['body_classes'] .= ' userlogin';
  }

  if (isset($vars['node'])) {
   $vars['template_files'][] = 'page-'. str_replace('_', '-', $vars['node']->type);
  }
}

```

Now I can use page-nodetype.tpl.php, but I can't use page-node-nid.tpl.php because Drupal doesn't see it.

I need all types of template files. I want a template specific for a content type.

What can I do? Can I do this in Drupal 6?

# Answer
> 1 votes
Have a look at the Drupal 6 Template suggestions, The list of suggested template files is in order of specificity based on internal paths. One suggestion is made for every element of the current path, though numeric elements are not carried to subsequent suggestion, order of execution is as below:

* page-node-edit.tpl.php
* page-node-**\[node\_id\]**.tpl.php
* page-node.tpl.php
* page.tpl.php

> So basically you don't need to use the "TEMPLATE\_preprocess\_page" for using "page-node-\[node\_id\].tpl.php" for template suggestion as it is provided by default. May be the problem is of "clearing the cache", try once after **clearing the cache**.

In Drupal6, `page-node-[node_type].tpl.php` is not available by default, to make it work we customize the suggestions in the `TEMPLATE_preprocess_page` as done by you.

If you want more specific templates than you can customize the template suggestions as your requirement in `TEMPLATE_preprocess_page`. Example as below:

```
// Implement TEMPLATE_preprocess_page.
function TEMPLATE_preprocess_page(&$variables) {
  if ($variables['node']->type !== '') {
    // For using "page-node-[node_type].tpl.php" for template suggestion.
    $variables['template_files'][] = "page-node-" . $variables['node']->type;

    // For using "page-node-[node_type]-[node_id].tpl.php" for template suggestion.
    $variables['template_files'][] = "page-node-" . $variables['node']->type . "-" . $variables['node']->nid;
  }
}

```

After using the above code you can use the additional template suggestion as below:

* page-node-\[node\_type\]-\[node\_id\].tpl.php
* page-node-\[node\_type\].tpl.php

**NOTE:** Don't forget to **clear the cache** after making changes to template files otherwise the changes won't reflect back.

---
Tags: theming, 6
---


title: How do I debug permissions?

text:
# Question
Title: How do I debug permissions?
How do I debug permissions in Drupal 7?

I use core reporting, error logs, devel module error logs, backtrace and node access permission block but sometimes it is not enough. What else should I check to find out why certain fields, views or blocks are not showing to a user?

I also found there is a module for Drupal 6 for reporting on permissions called but it is not available for Drupal 7.

I am using various permission related third-party modules:

```
 - devel node access 7.x-1.x-dev
 - fast permissions administration 7.x-2.0
 - organic groups access control 7.x-1.x
 - profile2 group access 7.x-1.x-dev
 - ur-node access 7.x-1.x-dev

```

# Answer
One way you can do is make a custom module, print access info on every page, every node, every block.

menu\_get\_item() function return a router item which has access\_arguments property for current page.

```
/**
 * Show access permission of current page.
 */
function yourmodule_get_page_access() {

  $router_item = menu_get_item();
  if ($router_item) {

    $access_arguments = unserialize($router_item['access_arguments']);

    $arguments = array();
    foreach ($access_arguments as $access_argument) {
      $arguments[] = $access_argument;
    }
    if ($arguments) {
      $output  = '<p>';
      $output .= t('This page needs user to have %p permission(s) to access', array(
        '%p' => implode(', ', $arguments),
      ));
      $output .= '</p>';
    }
    else {
      $output = '<p>' . t('This page needs no user permissions') . ' </p>';
    }
    return $output;
  }
}

```

Then you can hook\_page\_alter, to display the access info on top of every page.

```
/**
 * Implements hook_page_alter().
 *
 * Display access information on top of every page.
 */
function yourmodule_page_alter(&$page) {

  // Make a new area on top of the page for displaying access information.
  $page['content']['theverytop']['#markup'] = yourmodule_get_page_access();
  $page['content']['theverytop']['#weight'] = -10;
  $page['content']['#sorted'] = FALSE;
}

```

Next you can display out the block permission info like this:

```
/**
 * Implement hook_block_alter
 *
 * To display block permission information to the block title.
 */

function yourmodule_block_view_alter(&$data, $block) {
  $delta = $block->delta;
  $output = '';

  $rid = db_query("SELECT rid FROM {block_role} WHERE delta = :delta", array(':delta' => $delta))->fetchCol();

  if (empty($rid)) {
      $output = ' This block does not have any role permission restriction.';
  } else {
      $output = ' This block is viewable for users have role(s): ';
      foreach ($rid as $role_id) {
          $rolename = db_query("SELECT name from {role} where rid = :rid", array(':rid' => $role_id))->fetchField();
          $output .= $rolename . ' ';
      }
  }

  // append the permission info to block title for every block
  $block->title .= $output;
}

```

And so forth, basically the same concept, you can do the same to node, form, views. Hope this helps.
> 21 votes

# Answer
Edit the User module main file; find the `user_access()` function, add 2 lines before the `return` statement, and monitor the PHP error log.

```
$granted = isset($perm[$account->uid][$string]);
error_log(sprintf('--- user_access: %s "%s" = %s', $account->name, $string, $granted ? 'yes' : 'no'));
return isset($perm[$account->uid][$string]);

```
> 7 votes

# Answer
It looks like like you've got all the GUI-based tools already to troubleshoot permissions. One more advanced (and probably more difficult) trick I've used effectively in the past is:

1. Construct a View with the fields, roles, node-types, etc. that I want to test for.
2. Enable "display query" on the Views advanced options page.
3. Execute the View and paste the SQL query into a GUI-based SQL editor such as Navicat (commercial) or MySQL Workbench (free).
4. See what nodes don't show up.
5. Tweak the query to your needs.

I many cases the queries that Views spit out are rather complex (shock full of joins) and to construct them manually would take a little bit more time (plus it would be a little bit more error-prone). Also this approach ensures that you are testing against what the user is seeing. If you have any permissions modules enabled (that make use of Drupal core permissions), their table joins will show up in the query used by Views. Once I got this query I tweak it to show how many nodes of content type x are allowed for role x, for example. It's as accurate and fine-grained as reporting can get. And those are my "advanced" reports.
> 5 votes

# Answer
With Drupal I have to use a debugger some times (xdebug with netbeans). Lot of functions are called indirectly making almost impossible to follow what really append globally by only reading the code, printing a backtrace or checking the final output.
> 2 votes

---
Tags: 7, users, debugging
---


# Question
Title: Why is there a module for version 9 of core?
I checked this module page, it have the download option for Drupal 9 version. Why is Drupal 9 is launched when there isn't an official stable Drupal 8 release? Is there anything wrong with Drupal 8?

Why did they ignore Drupal 8? I also found the Drupal 9 development snapshot release.

# Answer
Well the "Bad Judgment" module you linked to claims:

> This module provides an explicit dependency for modules whose usage requires bad judgement. Joke modules often require "bad judgement".

So I wouldn't take that version number too seriously.

From the core download page you linked to:

> Placeholder for the Drupal 9.x release. Not intended for actual use by anyone except the issue queue version selector.

It's just a placeholder for the next version (forward-thinking and all that). It doesn't mean there's anything wrong with Drupal 8, and it doesn't mean Drupal 9 will be out any time soon.
> 13 votes

---
Tags: community-official-site
---


# Question
Title: Print out a Drupal Commerce field only if it has a value
In Drupal Commerce, you can use the following to print out a field in your node.tpl.php file:

```
<?php print render($content['product:field_NAME']); ?>

```

See here fore more information

But how do you print a field only if it has content?

For a normal Drupal field you would use the following:

```
<?php if (isset ($node->field_NAME)): ?>
  <?php print $node->field_NAME['und'][0]['safe_value'];?>
<?php endif; ?>

```

But that doesn't work with a Drupal commerce field.

I would appreciate if someone could offer any pointers!

# Answer
Content for the referenced product fields is incorporated into the product display(node) using field\_extra\_fields and normally contents go into the #markup key.

You can use template\_preprocess\_node and use something like this:

```
if (!isset($variables['content']['product:field_NAME']['#markup'])) {
  unset($variables['content']['product:field_NAME']);
}

```

You could also try Field formatter conditions module.
> 2 votes

---
Tags: theming, commerce
---


# Question
Title: Is there a way to place the "Add new comment" link where I want?
Is there a way to place the "Add new comment" link where I want in my content type? I'd like the link to be between two already existing fields in the content type. Is there some type of way to add this link via a field? Please help. This issue has been killing me.

# Answer
You can use hide and render to hide/show individual fields. http://tjegz.wordpress.com/2012/03/02/132/

This will allow you to place things in any order in the tpl file
> -1 votes

---
Tags: 7, theming, comments, navigation
---


# Question
Title: How to add extra fields to user profile?
I'd like to add additional fields to the user profile. I'd like user to be able to edit almost all the information I store in the database about him. I have some ideas: maybe it's possible to do using form api.

# Answer
> 24 votes
A way to add user fields by code so you can put this in your module.

I have found this: field\_create\_field with in the comments a way to create a field for your user upon enabling your module:

```
/**
 * Implementation of hook_enable().
 */
function MYMODULE_enable() {
  // Check if our field is not already created.
  if (!field_info_field('field_myField')) {
    $field = array(
        'field_name' => 'field_myField',
        'type' => 'text',
    );
    field_create_field($field);

    // Create the instance on the bundle.
    $instance = array(
        'field_name' => 'field_myField',
        'entity_type' => 'user',
        'label' => 'My Field Name',
        'bundle' => 'user',
        // If you don't set the "required" property then the field wont be required by default.
        'required' => TRUE,
        'settings' => array(
           // Here you inform either or not you want this field showing up on the registration form.
            'user_register_form' => 1,
        ),
        'widget' => array(
            'type' => 'textfield',
            'weight' => '1',
        ),
    );
    field_create_instance($instance);
  }
}

```

# Answer
> 38 votes
I found the page hard to find, but at /admin/config/people/accounts/fields you can add fields to users.

# Answer
> 5 votes
Profile in D7 is a bit weird. The profile2 module may do what you need.

# Answer
> 4 votes
In Drupal 7, use this process to add a new or existing field with different field types (such as Image, Tags field etc.) to the user profile:

1. Enable the **Field UI** module.
2. Go to "**Admin → Configuration → People: Account settings**" in the admin menu, and then to "**Manage fields**" (the second tab).

(Alternatively, use the direct path in the URL: `/admin/config/people/accounts/fields`).
3. Fill out the "Add new field" or "Add existing field" line at the bottom of the form and click "Save".

# Answer
> 1 votes
Which kind of fields do you want to add?

* If this is a social networking site and you are adding privacy settings fields, use the Privacy Per User module.
* If you wants to add tabs or accordion fields, use the field\_group module to add new groups on the user account fields (URL: /admin/config/people/accounts/fields).
* And if you want different fields for different roles, use the profile2 module.

---
Tags: 7, users
---


title: Can I clear front page cache only?

text:
# Question
Title: Can I clear front page cache only?
How to clear only the front page cache? I want to clear the front page cache when a new node is added.

# Answer
> 11 votes
Drupal 6 and 7 use the URL of the page as the cache ID (the `$cid`, see `drupal_page_set_cache()`). This should work.

```
$url = url('<front>',  array('absolute' => TRUE));
cache_clear_all($url, 'cache_page');

```

You will need to adjust the logic a bit if you can access the site through multiple URLs.

# Answer
> 1 votes
Give a try to Flush page cache module:

> Flushing Drupal's cache on a large site can feel like you're waiting to takeoff on the tarmac at JFK. The delay comes from the fact that when you clear Drupal's cache, it clears everything. Most of time you just want to flush the cache for specific object on a page.The 'Flush page cache' module solves this problem by flushing only the cached objects for a single page. Additionally, you can define custom objects and cache tables to be cleared on specific pages

Use cases:

* You have nodes nested in views nested in a panel page. You've edited a node that's displayed on this page, but you want the change to be seen immediately.
* You have a large team of non-technical content editors who frequently run into the scenario above and you want to give them an easy, one-button solution to their content being updated in the lists they manage.
* You've just cleared the entire website's cache through the normal means and for whatever reason, a few pages are rendered and cached in a broken state.

# Answer
> 0 votes
Using drush is the fastest way to clear cache.

// clear all

`drush cc all`

// individual caches to clear

`drush cc theme-registry`

`drush cc menu`

`drush cc css-js`

`drush cc block`

`drush cc registry`

`drush cc views`

I found a blog post which shows how to clear a single page with drush. *disclaimer* I have not tried this method personally. Clear a single page cache drush

```
drush sqlq "DELETE FROM cache_page WHERE cid = 'http://example.com/'"

```

or with using a drush alias

```
drush @your_alias sqlq "DELETE FROM cache_page WHERE cid = 'http://example.com/'"

```

---
Tags: caching
---


title: Fetch data from database

text:
# Question
Title: Fetch data from database
I want to fetch student result from database, by asking user to enter roll number and name. I have created a webform to take inputs but I don't know how to fetch the records from the database and display it in tabular form. Kindly tell how to fetch the record and display it.

One thing I tried is create a form in basic page content type using HTML and do the required using PHP, but I cannot figure out how to do if the form is created using Webforms.

# Answer
> 1 votes
The requirement you have asked can be easily achieved without making custom queries or use of webform module

Consider this: If the students enrolled are supposed to login into your site, then with no doubt use user entity and wherever you want to list the students in tabular form or simple list use views module as suggested before.

If the students are not supposed to login to the system they go well with node entities,for that simply create a content type as students with field on it as you require like roll number etc.. again to list them simply use views module it will do the query for your plus will allow you to show the results in tabular way.

---
Tags: database
---


# Question
Title: how to render a welcome page in page--front.tpl.php
I have a template `page--front.tpl.php`.
It contains all different stuffs and a welcome message, wrapped in a div container. Since, I want it to be editable, I created a new basic page called 'Welcome message'. It opens in a separate node 'welcome-message'.

Now I want this to be rendered in `page--front.tpl.php` in given div container. Any suggestions?

# Answer
Login as admin to the site, visit "`admin/config/system/site-information`" , scroll down to find setting for for front page and then form "Default front page" set the node relative path to be used as default front page that looks like "`welcome-message`" in your case.

with the above process you have informed drupal to use the node you have created as front page.

Now remove the hard-coded page front template you have created before as "`page--front.tpl.php`" because it will be used over the node till its present there.

clear your caches.
> -1 votes

---
Tags: 7, nodes
---


# Question
Title: How to compare custom product bundles in Drupal Commerce
I am a Drupal Commerce newbie, and would like advice on how to accomplish a particular project requirement.

I have two kinds of products - Panel and Converter. Each project has a mix of those panels and converters. The type and amount of each panel and converter comes from a custom module. Each of these converters and panels have different prices.

I'm supposed to create a view with the top 5 combinations of converters and panels, sorted by price and allow the user to select the one they want, which then goes into the cart.

I hope that all made sense...

Does anyone know of any tools, modules, or methods that I could look into to accomplish this task? I feel like I'm looking for the ability to create dynamic product bundles, that are then able to be put into a view to compare. Is that even possible?

Thanks for the help

NOTE: I am just beginning this part of the project, so if this is easily accomplished with ubercart or some other ecommerce module, I'm open to that as well.

# Answer
> 3 votes
For comparing drupal commerce products check out this module: https://drupal.org/project/commerce\_product\_comparison

There is also a module available which allows you to create product bundles using products of your choosing: https://drupal.org/project/commerce\_product\_bundle

---
Tags: views, commerce
---


title: How do I theme the user profile page?

text:
# Question
Title: How do I theme the user profile page?
What is the best / easiest way to theme the user profile page? I'm building a talk radio website and registered members will provide news articles publically avail. eventually there will be thousands of registered users.

I'm worried that I will figure out an answer that works but isn't correct and will force me to go back and rewrite later on.

I don't know if I should use views or just straight code the page-user.tpl - if I straight code, what function gets the uid from the /user/xx url? if I use views how do I assign the view to the pages in /user/xx

For some reason I cannot find any complete info on this; either it's a great secret or I'm missing something really simple. thank you!

# Answer
I decided to use a combination of VIEWS and template overrides, hooks, css and custom PHP.
> -1 votes

# Answer
I would suggest you to use Panels and Views modules and optionally Profile2.

You will add some fields to user account or to the user profile if you installed Profile2. Then enable the 'User profile template' page under `admin/structure/pages` and add a panel variant, select a layout and place the content or fields. If you have Profile2, then you need to add it as a relationship 'Profile2 from user' under the 'Contexts' menu of the panel page. I'm not going into details about how to use panels.

To display the summary of user's recent activity, you should setup a view with a contextual filter of user id, preferably a 'Content pane' display, then you need to place this content pane into you user panel.

It is not a great secret how to build a user profile page, but it's completely dependent of what you want to have. If you have any difficulties implementing the steps I wrote, you can update your question or post another more specific question.
> 0 votes

---
Tags: views, theming, users
---


# Question
Title: Custom jQuery code loaded but not working
I am trying to implement some custom jquery code for a 3D menu on my Drupal 7 site. I created two .js files one with the code and other one calling it on page. I have succesfully loaded both .js files throug my theme's .info file, however nothing happens, even tho i know the js code is 100% correct and working as it should. Im also using jQuery update module set to 1.8 so that shouldn't be a problem. As i am less than a begginer regarding jquery, i ask for your help. I can't understand why is code being loaded but not working. Thanks for reading and all the answers.

```
(function ($) {

   var Menu = (function() {

    var $container = $( '#rm-container' ),
        $cover = $container.find( 'div.rm-cover' ),
        $middle = $container.find( 'div.rm-middle' ),
        $right = $container.find( 'div.rm-right' ),
        $open = $cover.find('a.rm-button-open'),
        $close = $right.find('span.rm-close'),
        $details = $container.find( 'a.rm-viewdetails' ),

        init = function() {

            initEvents();

        },
        initEvents = function() {

            $open.on( 'click', function( event ) {

                openMenu();
                return false;

            } );

            $close.on( 'click', function( event ) {

                closeMenu();
                return false;

            } );

            $details.on( 'click', function( event ) {

                $container.removeClass( 'rm-in' ).children( 'div.rm-modal' ).remove();
                viewDetails( $( this ) );
                return false;

            } );

        },
        openMenu = function() {

            $container.addClass( 'rm-open' );

        },
        closeMenu = function() {

            $container.removeClass( 'rm-open rm-nodelay rm-in' );

        },
        viewDetails = function( recipe ) {

            var title = recipe.text(),
                img = recipe.data( 'thumb' ),
                description = recipe.parent().next().text(),
                url = recipe.attr( 'href' );

            var $modal = $( '<div class="rm-modal"><div class="rm-thumb" style="background-image: url(' + img + ')"></div><h5>' + title + '</h5><p>' + description + '</p><a href="' + url + '">See the recipe</a><span class="rm-close-modal">x</span></div>' );

            $modal.appendTo( $container );

            var h = $modal.outerHeight( true );
            $modal.css( 'margin-top', -h / 2 );

            setTimeout( function() {

                $container.addClass( 'rm-in rm-nodelay' );

                $modal.find( 'span.rm-close-modal' ).on( 'click', function() {

                    $container.removeClass( 'rm-in' );

                } );

            }, 0 );

        };

    return { init : init };

})();
 })(jQuery);

```

And here's the content of other JS file which is calling the function.

```
(function ($) {

$(function() {
Menu.init();
});
})(jQuery);

```

# Answer
May be you to wrap your code in `document.ready` function as below:

```
// Jquery wrapper for drupal to avoid conflicts between libraries.
(function ($) {
  // Jquery onload function.
  $(document).ready(function(){
    // Your JS code.
  });
})(jQuery);

```

**Update:** If you declare a variable without the `var` keyword, that variable is automatically made `global`. Aslo you can check more about the scope of the variable here: http://learn.jquery.com/javascript-101/scope/
> 4 votes

# Answer
Managing javascript in drupal

As per the above link you should put your Javascript or Jquery inside the following :

```
(function ($) {

  Drupal.behaviors.exampleModule = {
    attach: function (context, settings) {
   // add your code here
      });
    }
  };

})(jQuery);

```
> 8 votes

---
Tags: javascript
---


# Question
Title: will be any problem with my website if I empty all the cache tables from Database?
I'm trying to move my website from localhost to a server. the size of DB is too big and from what I saw the cache tables have big size. is there any problem (for my localhost version of site) if I empty all of them? (specially `cache_form`)

besides that when I was trying to import the DB into server the server reported an error when it was inserting `cache_views` table; it is very important for me to empty this table to avoid insertion error in the future.

thanks

# Answer
As per the drupal community doc for clearing the cache you can manually TRUNCATE the tables (empty, not remove) starting with `cache_` and there shouldn't be any problem doing so as on visiting any page the cache is rebuilt.

However I would recommend to either use the drush, or clear the cache from the `/admin/config/development/performance` page.

If you want to clear the cache from code than you may try the following:

```
// clear cache
drupal_flush_all_caches();

```

Also its always safe to keep the **Backup of database** before making any manual operation on database.
> 2 votes

---
Tags: 7, database, caching
---


# Question
Title: How to hide a field based on a specific condition?
I have a website for ads, which are either of those:

* Regular ads.
* VIP ads.

The Regular ads have an additional field "`field_adding_make_vip`". If the user decides to change a Regular ad to a VIP ad, the user will use the description from that field and send a SMS to a specific number and that ad will become automatically a VIP ad.

The filter in Views to show the VIP content is a additional field "`field_vip_date`" that uses a date filter. That mechanism is created with a custom PHP file.

So only left to do is: when the Regular ad becomes a VIP ad, the field "`field_adding_make_vip`" will be automatically hidden and the VIP ad will have additional field "`field_adding_vip_image`" that will show a VIP image, so every user will know that the selected ad is a VIP ad.

How can I hide that field and show the VIP image when the ad becomes a VIP ad?

The Regular ad and VIP ad are the same content type (adding). I'm using the field "`field_vip_date`" as a filter in views by date. Let's say when the date field of a specific node is set to 25 October, that node will be displayed in a VIP block position in the website until 25 of October and the next day it will be automatically removed from that position. That's for a block view position.

In every page node the field "`field_adding_make_vip`" has a description with the node id how to send the SMS, to be used to make it a VIP ad. The whole idea is when the user sends an SMS with the number ID, the field "`field_adding_make_vip`" will disappear, because the regular node has become a VIP ad and that node will have an additional field "`field_adding_vip_image`" that will display an image with a text "VIP".

Somehow the field "`field_vip_date`" (which is a date field) will have to control the field "`field_adding_make_vip`". For an example if "`node/120`" has "`field_vip_date`" set to 25 October, the field "`field_adding_make_vip`" will be hidden until 26 October and the field "`field_adding_vip_image`" will be displayed until 26 October.

**Note**: I've tried the code from @harshal, but it has errors. The name of my custom module is "`custom_alter`" and here's the full code:

```
<?php
function custom_alter_form_alter (&$form, &$form_state, $form_id) {

 $node = node_load($nid);
 $date = date('d/m/Y');
 $todaysdate = strtotime($date);
 $field_date_vip = $node->field_date_vip['und'][0]['value'];
 $date = date('d/m/y',  $field_date_vip);
 $expirydate = strtotime($date);

If ( $todaysdate <  $expirydate )) {
  //Hide the field adding_make_vip using css
  drupal_add_css(drupal_get_path('module', 'custom') . '/css/hide_field_adding_make_vip.css');
             }
else {
// hide field adding_make_vip using css
  drupal_add_css(drupal_get_path('module', 'custom') . '/css/hide_field_adding_vip_image.css');

}

}

```

# Answer
> 2 votes
I'm not sure I completely understand what you need. But if I'm correct and you just need to show / hide specific fields in a node based on some other field in that node the hook\_field\_access should help you.

```
 /**
 * Implements hook_field_access().
 */
function YOUR_MODULE_field_access($op, $field, $entity_type, $entity, $account) {
  global $user;
  switch ($field['field_name']) {
    case 'field_adding_make_vip':
      if ($node['isVIP'][value]) {  //Is the node VIP?
        return false;  //Show the field_adding_make_vip
      }
      else {
        return true; //Hide the field_adding_make_vip
      }
      break;
  }
    case 'field_adding_vip_image':
      if ($node['isVIP'][value]) {
        return true;
      }
      else {
        return false;
      }
      break;

}

```

# Answer
> 1 votes
> Somehow the field "field\_vip\_date" which is a date field will have to control the field "field\_adding\_make\_vip". For an example if "node/120" has "field\_vip\_date" set to 25 October, the field "field\_adding\_make\_vip" will be hidden until 26 October and the field "field\_adding\_vip\_image" will be displayed until 26 October.
> **For the part to disppear the vip image fields after expiry the code is as follows : This is just for a single node.**

```
function module_name_form_alter($form,&$form_state, $form_id) {
    if ($form_id == 'adding_node_form') {
       $nid = $form['nid'] ;
       $node = $node_load($nid);
$form['#submit'][] = 'adding_node_form_after_submit';
    //insert the code here

    }
}

function adding_node_form_after_submit ($form, &$form_state) {
$field_vip_date = $form['field_vip_date']['und'][0]['date'];
$expiry_date = strtotime($form['field_vip_date']['und'][0]['date']);
$date = date('d/m/Y');
$current_date = strtotime($date);
if ($current_date > $expiry_date) {
drupal_add_js( drupal_get_path('module', 'your_module_name') . '/' . custom.js);
}
}

```

Now add a js file in your custom module folder. In your custom.js the code goes as follows:

```
(function ($) {

  Drupal.behaviors.exampleModule = {
    attach: function (context, settings) {
   // add your code here
$('.field-name-field-adding-vip-image').hide();
      });
    }
  };

})(jQuery);

```

---
Tags: entities, nodes
---


# Question
Title: How do I create new content type with editable fields?
I want to create another content type similar to the basic page. I've designed a simple html layout with a block of copy on the left hand side and an image with a caption floated next to it on the right hand side.

I want to be able to add this as a template to the Drupal UI so that a user can pick this template and enter their copy, choose/upload an image, enter an image caption and possibly show a widget below the content based on what the page is about.

How would I go about configuring this so I can add this page template as a content type into the Drupal UI?

# Answer
Based upon the mentioned requirement, to me it seems either of the following situations:

**For Drupal 7:**

* Theming the node add page: **page--node--add--\[content type\].tpl.php**
* Theming the node edit page: **page--node--edit--\[content type\].tpl.php**

**For Drupal 6:**

* Theming the node add page: **page-node-add-\[content type\].tpl.php**
* Theming the node edit page: **page-node-edit-\[content type\].tpl.php**

More info about the same you can get from here:
https://drupal.org/node/1092122
https://drupal.org/node/1089656
https://api.drupal.org/api/drupal/modules%21system%21page.tpl.php/7
> 1 votes

# Answer
I think you are mixing several concepts:

1. You want to create a new content type To achieve that, go to

Structure -\> content types -\> create new content type

Add fields to your liking.

1. You want to theme your input form - change the appearance Ankit gave you good pointers on how to change the structure of the input form. The rest you could do with css.

I assume you do not give access to the administrative theme to your users or editors. So you could style the input forms in the theme you are using.
> 0 votes

---
Tags: theming, nodes
---


title: Node limit for published nodes per user

text:
# Question
Title: Node limit for published nodes per user
I am interested in limiting the nodes a user can publish.So Node limit module cannot help on this. Someone suggested using userpoints and rules to achieve this. How is this possible with these 2 modules? Any help would be appreciated. thanks!

# Answer
Give a try to User Points Contributed module: This module includes the module called **userpoints\_nodelimit** which enables a limit on node creation based on user points.

---

However if you want to do it with the `userpoints` and `rules` module than the idea would be to create the rule to grant certain point on publishing the new nodes, and than create another rule whose `event` would be the node creation and in the `condition` check if the user already has reached limit than prevent node creation and display the custom message.

---

Alternatively one easy way to achieve the same is using the hook\_node\_validate(), one example of using the same is as below:

```
/**
 * Implements hook_node_validate().
 */
function MyModule_node_validate($node, $form, &$form_state) {
  // For now assign the static value to MAX_NODES (No. of nodes),
  // however you can make it dynamic, and get those values using variable_get().
  $max_nodes = 'MAX_NODES';
  $node_count = 0;

  // Get the user uid from the global user variable.
  global $user;
  $user_id = $user->uid;

  if ((isset($node->uid))) {
    // Use entity query to get the number of nodes already published by this user.
    $query = new EntityFieldQuery;
    $node_count = $query->entityCondition('entity_type', 'node')
      ->propertyCondition('uid', $user_id)
      ->propertyCondition('status', 1)
      ->count()
      ->execute();

    // Check if the node count exceeds the max_node value.
    if ($node_count > $max_nodes) {
      form_set_error('FIELD_NAME', t('Reached the maximum limit of creation of nodes.'));
    }
  }
}

```
> 2 votes

---
Tags: nodes
---


title: List all Configured Menus in the System

text:
# Question
Title: List all Configured Menus in the System
Is there a developer tool, module, or code snippet that will show all the menu items currently configured in a Drupal system?

If not, would it be "safe" to invoke the menu hook myself to collect this information? In other words — do individual menu hook listeners (implemented by module developers) alter system state in such a way that invoking the menu hook twice during a page request would be a "bad thing".

Newish to Drupal, not new to programming. I'm specifically interested in a programmer's view of the menu.

# Answer
> 1 votes
You could use menu\_get\_menus, or use a modified version of its code:

https://api.drupal.org/api/drupal/modules!menu!menu.module/function/menu\_get\_menus/7

It returns an associative array of the menus names, either the custom one, or also including the system menus.

---
Tags: routes
---


title: Responsive lightbox module for drupal

text:
# Question
Title: Responsive lightbox module for drupal
Are there any responsive lightbox options for drupal? There are plenty of lightboxes that support fixed widths?

Are there currently any that are designed for mobile in mind?

# Answer
> 0 votes
Ended up using flexbox.

Reveal in the Zurb Foundation theme is another option.

# Answer
> 0 votes
Lightbox2 Swipe Gestures Support Adds swipe gesture support for Lightbox2. This makes a lot of sense on mobile or responsive pages, because the "Next" an "Prev" Buttons are only visible on hover.

> Adds swipe gesture support to the well known Lightbox2 module for mobiles. Just swipe left or right on galleries to show the previous or next element!

---
Tags: 7, theming
---


title: File Upload Issue

text:
# Question
Title: File Upload Issue
I uploaded a image file after creating a new content type. But the uploaded image is not being displayed only the name of the image is being displayed. I need to click on the name to view the image, kindly tell how can I make the image to be displayed in the page itself without having to click on the image to view it.

# Answer
> 0 votes
what I assume file is getting uploaded as you are able to see the file once clicking on the link,if so please change the title.

Regarding problem,I assume you are not using views or any other module to show the nodes,so how a field renders pretty much depends on what manage dsiplay option has been opted for it, you can check the selected manage diaply by visiting "admin/structure/types/manage/your\_content\_type\_name/display" and then selecting the image format display for the field.

---
Tags: media
---


# Question
Title: Change position of Drupal ajax progress throbber
When you are using views built in ajax pager. When you click on any element of the pager ajax throbber appears next to the clicked button. Can i change the location of the throbber, for example outside of pager div?

# Answer
> 5 votes
You can do it by overriding the CSS in your theme CSS file. Here is the class to use for changing the position of ajax throbber:

> .ajax-progress .throbber

You can set the position to whatever you want.

Also have a look at this blog: http://www.antimath.info/css/change-throbber-in-drupal-7/

---
Tags: 7, ajax
---


# Question
Title: Creating a view of relation fields limited to the relations that a currently viewed node is an endpoint of
To first explain the set up, I have a custom content type that represents a candidate. I have a relation between candidate and users where the relation has some fields (using the relation module). I want to have a view that displays the fields of relation on the candidate page that has that relation.

So far I have tried Entity Views Attachment but the issue with that is it adds the relation view I have set up to every instance of candidate. I've also been trying view reference but that doesn't seem to be the module I'm after either.

I think I need to add something like an extra filter or something to the EVA view that only will show relations that involve the current candidate node, but I'm not sure if that is possible or not.

# Answer
> 0 votes
Instead of creating a view of relations, you should create a view of candidate nodes. Then you can use a contextual filter to limit the results of the view to the candidate node you are currently viewing. The fields of the relation can then be added via a relationship.

Create a view of content of type candidate, for example located at node/%/info; then under the Advanced settings of the view add a contextual filter with `Provide a default value: Content ID from URL` (i.e. the candidate node id) as the argument. You can use the same setting when the argument is provided by EVA instead of via the URL, with the default configuration of `Use the ID of the entity the view is attached to` (but the first example is useful to understand where the argument comes from).

Now in order to get the relevant Relation fields displayed, under Advanced add a relationship using `Content: Relation: <your relation label> (node → relation)`.

Under Fields you can now add the desired Relation fields, specifying that it should use the relationship you just added.

Note the difference between relationship (≈ SQL table join) and relation.

---
Tags: views, entities
---


# Question
Title: Views Exposed Filter conflicting with default search
When I'm on a page with an exposed filter and then go to type into the default search, clicking the search button brings me right back to the exposed filter.

For now I am hiding the search block on that page but I would like them to both be on the page. Is there anyway to fix this?

# Answer
Not sure exactly what you have tried so far, but Can you check if Views: Better Exposed Filters can help you with this ?
> 0 votes

---
Tags: 7, search, views
---


# Question
Title: Pre-populate Commerce Shipping Cart using a link
I need capability to pre-populate commerce cart using a link (preferably add to the cart if one already exists).

For example a link like http://aziteez.com/cart?add\_product=prod1+prod2 should add prod1 and prod2 to the existing cart of the user on my website.

Thanks in advance.

# Answer
> 3 votes
You could use Rules for triggering an event on your link with Rules link event and maybe combine it with Rules Link to attach the link to your commerce order entities.

If you prefer to code, you'd need either to create a new menu using hook\_menu or alter an existing one with hook\_menu\_alter and then use commerce\_cart\_product\_add or commerce\_cart\_product\_add\_by\_id to add the product to the cart user, you can retrieve the current cart from the user with commerce\_cart\_order\_load

---
Tags: 7, commerce
---