title: Debuging OG access field

text:
# Question
Title: Debuging OG access field
I have few roles in OG groups: Visitor, Reviewer, Member, ...

Visitor and Reviewer are added roles with (at the moment) exactly the same settings. Unfortunately somehow Visitor is inheriting Member's access rights while Reviewer is not.

I checked everything and all looks fine. I tried hacking OG code (I switched off the default role inheritance), checked og\_role\_permission table and all looks fine. But still whenever I give some rights to the Member role, Visitor user is somehow inheriting them while Reviewer is not.

My website is making use of OG roles everywhere. I have context, rules, custom code depending on it. And while everything works fine, field\_access is behaving strange.

Do you guys have any idea how can I go on with debugging this issue? Is there a place in node\_access module where I could put some debug code informing me what is going on?

**UPDATE**

I switched off all the custom code, changed drupal core to older version, made sure that access settings for Visitor OG role are exactly the same as Reviewer's.

I rebuilded cache, rebuilded access rights, changed browsers, went through code in OG and data stored in the db.

Still users with Visitor OG-role inherit rights from Member OG-role, while Reviewer does not. This bug is killing me.

# Answer
Unfortunately I have to surrender. There is a bug somewhere in the og module but I can not track it down. What happens is that the default group membership role can not be changed. Changing the definition of OG\_AUTHENTICATED\_ROLE in the og.module does nothing. Because of that all the access rights given to the "member" role are being inherited by all the other roles and so they can not be weaker.

My solution will have to be creation of new members role - "full\_member" where I will be able to define roles of that member. I will also remove all permissions from the "member" role. The problem is that I will have to redo all the rules, contexts, pages, blocks, custom code and so on. Few days of boring work and debugging.
> 1 votes

# Answer
Unfortunately no walk around works in here.

OG has a major bug for subgroups. Basically permissions for the subgroups (including field access rights) get inherited.

In other words if B is a subgroup of A and I am a member of both, then in A I have access rights from A while in B I have a sum of access rights from A and B.

This issue can be addressed by a simple `og.module` hack

```
function og_user_access_entity($perm, $entity_type, $entity, $account = NULL, $strict = TRUE) {
// ...
    else {
      // An entity can be a group and group content in the same time. The group
      // didn't return TRUE, but the user still might have access to the
      // permission in group content context.
      $result = FALSE;
    }
//...
}

```

What happens here is that if OG module can't find specific access rights for a group that is also a content (is a subgroup), he will treat it as a standard group content and will look for access rights in the parent group. We can fix it by simply returning FALSE.

```
    else {
      // HACK - NO GROUP INHERITANCE
      return = FALSE;
    }

```

This solution seems to me as much more reasonable and consistent. Note that the access rights inheritance is going only one level down and only if you are a member of both, parent and son groups, it also overrides your field access rights that should have nothing to do with a parent group.
> 1 votes

---
Tags: organic-groups, users
---


# Question
Title: Create a view to show a user his or her recent activity
I am creating a view that would display the activity of the users. When user 1 is logged in, it would show the activities of user1 only...his node uploads, his comments etc,,,such as:

User1 commented on "Some Artcile" Time User1 Uploaded his article "Some BLOG" Time

How should i proceed. I am using Views3, and Drupal7

# Answer
To show latest nodes and comments in one view you would new a "views union" which is still a tricky thing to do in views.

You could write a custom module to run the query and display the results. The query would look something like this:

```
$sql = "
    SELECT n.nid, n.title, type, 'comment' as action, max(c.created) as postdate, GROUP_CONCAT(distinct(u.name)) as users
      FROM comment c INNER join node n ON c.nid = n.nid
      INNER JOIN users u on c.uid = u.uid
      WHERE c.uid IN (:uids)
      AND c.created > :timestamp
      AND c.status = 1
      GROUP BY n.nid, n.title, n.type
    UNION
      SELECT n.nid, n.title, n.type, 'node' as action, max(n.created) as postdate, GROUP_CONCAT(distinct(u.name)) as users
      FROM node n INNER JOIN users u on n.uid = u.uid
      WHERE n.uid IN (:uids)
      AND n.created > :timestamp
      AND n.status = 1
      GROUP BY n.nid, n.title, n.type
      ORDER BY postdate desc";

```
> 1 votes

# Answer
Why not just use the heartbeat or the message module and let them do the heavy lifting for you
> 2 votes

# Answer
In the views UI under "filter criteria" you can add a "Content: Author uid" filter and that will filter by user. You will also need to set up a "relationship" under with "Content user". However as mentioned this question is very broad, but maybe this will help you get started
> 1 votes

---
Tags: 7, users, views
---


# Question
Title: Is there an easier way to print taxonomies in the tpl? I get this working code, but it should be a "shorter" way!
After a painful day and a half I get this code, that prints out in my node.tpl.php the taxonomy terms associated to that particular node that the user is viewing.

It works just fine. As it is quite long I´ll just put the whole thing inside a module and into a variable, to just print that.

The thing is that it should get an easier, better way to do this! Any ideas?

```
<?php
$vid = 11; //vocabulary id
$nid = $node->nid; //it looks for the current loaded node
$query = "SELECT tid, name
FROM (
SELECT td.tid AS tid, name
FROM taxonomy_term_data AS td
JOIN taxonomy_index AS tn
  ON td.tid = tn.tid
JOIN node AS n
  ON n.nid = tn.nid
WHERE td.vid = ". $vid ."
  AND n.status = 1
  AND n.nid = ".$nid."
GROUP BY td.tid
) AS t
ORDER BY name ASC";
$result = db_query($query);
foreach($result as $term) {
      echo l($term->name, "taxonomy/term/$term->tid") . ', ';
}
 ?>

```

# **UPDATE:**

This is devel output: (I´ve used (`dpm($node);`) because it let me print the result here without losing the indentation)

```
(object) array(
  'vid' => '5178',
  'uid' => '1',
  'title' => 'PROYECTO',
  'log' => '',
  'status' => '1',
  'comment' => '2',
  'promote' => '0',
  'sticky' => '0',
  'nid' => '155',
  'type' => 'jornadas',
  'language' => 'und',
  'created' => '1095048000',
  'changed' => '1360589684',
  'tnid' => '0',
  'translate' => '0',
  'revision_timestamp' => '1360589684',
  'revision_uid' => '1',
  'taxonomy_vocabulary_4' => array(),
  'taxonomy_vocabulary_6' => array(
    'und' => array(
      array(
        'tid' => '33',
        'taxonomy_term' => (object) array(
            'tid' => '33',
            'vid' => '6',
            'name' => 'Jornadas Gratuitas',
            'description' => '',
            'format' => NULL,
            'weight' => '0',
            'vocabulary_machine_name' => 'vocabulary_6',
          ),
      ),
    ),
  ),
  'taxonomy_vocabulary_7' => array(
    'und' => array(
      array(
        'tid' => '40',
        'taxonomy_term' => (object) array(
            'tid' => '40',
            'vid' => '7',
            'name' => 'Para PH',
            'description' => '',
            'format' => NULL,
            'weight' => '-10',
            'vocabulary_machine_name' => 'vocabulary_7',
          ),
      ),
    ),
  ),
  'taxonomy_vocabulary_11' => array(
    'und' => array(
      array(
        'tid' => '262',
        'taxonomy_term' => (object) array(
            'tid' => '262',
            'vid' => '11',
            'name' => 'colegios',
            'description' => '',
            'format' => NULL,
            'weight' => '0',
            'vocabulary_machine_name' => 'vocabulary_11',
          ),
      ),
      array(
        'tid' => '543',
        'taxonomy_term' => (object) array(
            'tid' => '543',
            'vid' => '11',
            'name' => 'derecho',
            'description' => '',
            'format' => NULL,
            'weight' => '0',
            'vocabulary_machine_name' => 'vocabulary_11',
          ),
      ),
    ),
  ),
  'body' => array(
    'und' => array(
      array(
        'value' => "

```

# Answer
> 0 votes
Few things here:

1. Your SQL is open to injection
2. You're running a query that has already been run, and for which data has already been returned by the core field system. Drupal already runs way too many queries in a page load, adding another unnecessary one should be avoided wherever possible.
3. Your code should be in a template preprocess function (or module file as you've mentioned). But that's not because of the *length* of the code. It's because you should maintain a good separation of logic and display.
4. Drupal has already prepared the display of the field for you, so it would be preferable to use that instead of building up from scratch again.

With those in mind, try simply adding:

```
<?php echo render($content['field_name_of_term_ref_field']); ?>

```

in place of your code.

To control how those field items come out (e.g. as links), navigate to admin/structure/types/manage/TYPE/display, and choose appropriate settings for the display widget.

---
Tags: 7, taxonomy-terms, performance
---


# Question
Title: Drupal commerce order notification to field in a line item type
I have a Drupal 7 install using Drupal Commerce to handle donations. I created a line item type called donations, with fields such as donation amount, anonymous donation, etc.

One field of the donation line item type is called honoree email, which is an optional email field that when filled out is suppose to sends the donation order to the user who created it and the honoree.

In order to send the email to the honoree, I wanted to add a new action to the "Send an order notification e-mail" rule and use data selection to highlight the honoree email field in the "To" value. However, I am unable to find the honoree field. My data selector looks like this:

```
commerce-order:commerce-line-items:...

```

and I'm presented with an array 0-3; commerce-order:commerce-line-items:0: commerce-order:commerce-line-items:1: commerce-order:commerce-line-items:2: commerce-order:commerce-line-items:3:

I'm not sure what the differences are, and the values under each of those keys do not include the custom fields the I added to the donation line item.

How do I access the honoree email field?

# Answer
> 1 votes
What you've encountered here is how Rules deals with multi-value fields. The commerce-line-items field is a multi-value line item reference field using "delta" values represented by those 0, 1, 2, 3, etc. numbers. Without knowing the full details of your situation, the best I can recommend is to add a loop over that commerce-line-items field, passing each line item to a Rules component designed to e-mail the honoree.

If you aren't familiar with Rules components, that's certainly more than we can get into here. Your best bet would be to find the Rules Mastery course on YouTube and get your learnin' on.

Once you have the idea, what you'll need is a Rule component that accepts a Commerce Line Item as a parameter. It should have at least these two conditions:

1. Entity has field - does the line item have your honoree e-mail field?
2. Data value is empty (negated) - does the honoree e-mail field have a value?

If so, your actions section can send the necessary e-mail using the value of that field as the e-mail recipient.

---
Tags: 7, commerce
---


title: Can I set Drush to always use verbose?

text:
# Question
Title: Can I set Drush to always use verbose?
Its quite annoying to have to type -v.

Is there a way to change the drush settings so that it will always use verbose mode so I dont have to bother typing -v?

# Answer
> 12 votes
This works for me in Drush 5.

In a `drushrc.php` file (I tested with my `~/.drush/drushrc.php` you could do this per-project as well).

I simply added:

`$options['v'] = TRUE;` somewhere in the file. Then try issueing drush commands.

This works because of how drush\_parse\_args executes.

# Answer
> 4 votes
Alternatively, if you're using bash or similar, just use the shell to add the argument:

```
alias drush='drush -v'

```

Put this in one of your `.bash_*` files. If you're already using an alias to invoke drush, you'll need to modify it.

---
Tags: drush
---


# Question
Title: Basic Drupal site architecture based on taxonomy
I come from a custom web dev background but I'm working on some Drupal projects now. I am confused about the best method to set up basic site architecture. What I want is for taxonomy terms or variables to drive display of content throughout the different areas of the site. I gather I should be using taxonomies as these variables...If I am wrong please let me know

So say I have one taxonomy (BRANDS) with two terms:

BMW AUDI

I also have three content types:

Article (can belong to multiple brands) Video (can belong to multiple brands) Model (only single brand)

I want to create 3 types of pages (I think what I should be doing is using views) BUT - I should only need to use ONE view per page type:

Index Page (which accepts taxonomy term and displays all videos articles and models associated with the term - this is not an individual node page) (url should be something like /BRAND eg: /BMW)

Model Page (which shows the model node - and also content \[videos and articles\] associated with the BRAND taxonomy term) (url should be like /BRAND/Modelnode eg: /BMW/3-Series)

Article Page (which shows an article node - and also videos and models associated with one or more BRAND taxonomy terms associated with that article)(url should look like either BRANDS/Articlenode - eg: BMW-AUDI/Articlenode or just /article/Articlenode if the taxonomy does not need to be coming from the url to feed into views or whatever generates the page content)

If i was doing a custom PHP driven website, this would be easy to do, but it's confusing as hell in Drupal. What is the standard and best practice way to go about creating each of these page types - and if it is created using views - only use one view per page type \[ ie the view will accept url or internal taxonomy arguments to dynamically show content\]?

# Answer
> 2 votes
You'll need to use Fields and some modules to do this but it looks like you already have the understanding on how to get started.

Fields are basically properties that can be used to extend Drupal entities. You can add Fields to your Content Types and your Taxonomy Vocabularies to include extra properties not available out of the box.

Any Fields that you want associated with your Node, add them to the Node Type. Any Fields you want associated with a Taxonomy Vocabulary, add them to the Taxonomy Vocabulary. And in the end, make sure everything is rendered correctly in your theme.

As soon as you associate a Node with a Taxonomy Term, Drupal already provides a way to display all Nodes associated with a specific Taxonomy Term. If you navigate to `/taxonomy/term/TERM_ID` you'll see what I mean.

If you want to modify that page, I would start looking into Views and Panels which are arguably the building blocks of any Drupal site. It is important to note though that Views and Panels are usually not used to create new content but rather to query and display, respectively, existing content.

For the URL structure you mentioned, look into the Path and PathAuto modules. They provide a way to generate URLs based on a pattern.

So, for your example, if you want a URL `/BMW` to show all Nodes tagged with the `BMW` Taxonomy Term, those two modules will get the job done for you.

So what's the best approach? It depends on your site's content. From your question:

* Index Page: Classic use case for a view that takes an argument from a URL. In this case, a Taxonomy Term. You can choose to filter on specific Node Types, Taxonomy Terms, etc.
* Model Page: Simple Node. Create a field on it's Node Type to associate it with the appropriate Taxonomy Vocabulary. You can also use Views to pull related content, which from your description is what you need here. There are also a lot of modules that can help with this.
* Article Page: Same as above.

Good Luck!

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


# Question
Title: Why is the Pressflow Last-Modified header not like plain Drupal?
The Last-Modified header is set in includes/bootstrap.inc. Plain Drupal uses

```
header("Last-Modified: ". gmdate("D, d M Y H:i:s") ." GMT");

```

which yields

```
Last-Modified: Sun, 27 Jan 2013 21:52:57 GMT

```

Pressflow uses

```
$default_headers = array(
    'Last-Modified' => gmdate(DATE_RFC1123, $_SERVER['REQUEST_TIME']),

```

which yields

```
Last-Modified: Sun, 27 Jan 2013 21:52:57 +0000

```

'+0000' is incorrect according to RFC 2616, and is flagged as an invalid date by http://redbot.org/

What gives? Is this a Pressflow performance technique, or an error, or what? Do browsers care?

We're trying to nail down some load issues on our site, and want to be sure we are not getting more repeat requests than is appropriate.

# Answer
Drupal 6 sets the Last-Modified header with

```
header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");

```

That was changed to

```
$default_headers = array(
  'Expires' => 'Sun, 19 Nov 1978 05:00:00 GMT',
  'Last-Modified' => gmdate(DATE_RFC1123, REQUEST_TIME),

```

during the development of drupal7. Pressflow has backported the patch from drupal7 in 2009. That's the reason of the difference. As for the possible impact of this, in fact it can have bad effects on caching. At least squid 3.1.10 prints a warning about the header and refuses to store the page in cache

```
cannot parse hdr field: 'Last-Modified: Tue, 12 Feb 2013 14:35:43 +0000'
[snip]...[/snip]
refreshIsCachable() returned non-cacheable..

```

Switching to the "GMT" version resolves the issue with squid.

rfc2616 (HTTP/1.1: Protocol Parameters:) specifies that "Last-Modified" header value can conform to rfc1123 (which looks OK with +0000) but all the examples use "GMT".

I think it'll be better to create a bug report in drupal issue tracker and see what the developers answer.
> 2 votes

---
Tags: 6
---


# Question
Title: Bypass drupal theme with hook_menu() function?
I have a page within Drupal administration where I want to bypass all of the normal Drupal theming and calculations to only show the HTML that's returned by the function. Is this possible?

```
 $items['admin/special_blank_page'] = array(
    'title' => 'PDF',
    'page callback' => 'special_blank_page',
    'type' => MENU_LOCAL_TASK,
  );

//...

  function special_blank_page(){
      $html ='<html><head></head><body>Only show this HTML</body></html>';
      return $html;
  }

```

# Answer
> 7 votes
Just to offer an alternative to Ayesh K's solution, you can set the `delivery callback` of your menu item

> The function to call to package the result of the page callback function and send it to the browser. Defaults to drupal\_deliver\_html\_page() unless a value is inherited from a parent menu item. Note that this function is called even if the access checks fail, so any custom delivery callback function should take that into account. See drupal\_deliver\_html\_page() for an example.

# Answer
> 1 votes
Yes, if you `print` the output instead of `return`ing it.

```
function special_blank_page(){
      $html ='<html><head></head><body>Only show this HTML</body></html>';
      print $html;
  }

```

---
Tags: 7, routes
---


title: Unable to edit body field

text:
# Question
Title: Unable to edit body field
One of my content editors reported having trouble editing

However, I have allowed this group to edit any content of this node type.

I'm not seeing any separate permissions for fields. How might I over come this?

# Answer
You also need to grant permissions for the text format that the body field is using, e.g.
> 13 votes

---
Tags: users
---


# Question
Title: How do you build an auto-generating menu for forums?
I am using Drupal 7 with advanced forum and taxonomy menu and cannot figure out how to create a menu that will automatically add topics as menu items to forum containers with the right URL path structure. Taxonomy menu gets close but will not allow URLs other than taxonomy/term/\[tid\] (See: http://drupal.org/node/1161114). They need to generate in the pattern: forums/\[container name\]/\[topic title\]. I cannot seem to do this using the URL alias.

Has anyone built a drupal forum that generates a menu when topics are added and deleted that follow the standard forum URL path structure?

# Answer
Looking back at this, I realize I was asking two questions:

1) How do you configure a URL alias pattern for a forum topic in the format: \[forums\]/\[container\_name\]/\[forum\_topic\_name\]?

Install and enable Pathauto. Then configure a URL alias pattern at admin/config/search/path/patterns in this format \[node:taxonomy-forums:parents\]/\[node:taxonomy-forums:name\]/\[node:title\].

2) How do you then add this Forum topic to a menu underneath a specific parent automatically?

Install and enable Menu Position. Add a Menu Position rule at: admin/structure/menu-position/add for Content Type: Forum topic and select the menu parent item for Forum topics.
> 0 votes

---
Tags: 7, taxonomy-terms, nodes
---


# Question
Title: Editing time for pages in google analytics?
I've been asked for "development/editing" time for pages analytics to be made available.

Is this possible? If so, how?

# Answer
Ok - you want to use Google Analytics custom variables for this and a bit of javascript (though will try and make this as Drupaly as possible). For the timer, you can write javascript/jQuery code to start a timer on the window.load() event and then attach it to the submit button on your particular form. Number of examples of javascript timers, I found this example that looked promising.

Key thing to get this data to your google analytics account is to add a google analytics push event (see documentation above) so your code would look something like this (rough psuedo code)

```
$(document).ready(function() {

   function StartTimer() { some timer function ... }

   function StopTimer() { some timer stop function ... return $time; }

   startTimer();

   $("#id-for-form-submit-button").click(
       $timeValue = StopTimer();
       _gaq.push(['_setCustomVar',
          1, // This custom var is set to slot #1.  Required parameter.
          'Editor Time', // Category Name. Required Parameter
          $timeValue,  // This value of the custom variable.  Required.
          3  // Sets the scope to page-level.  Optional parameter.
      ]);

});

```

Finally, you need to attach your javascript to your form (the drupaly part). I use this quick code snippet (from switchbackcms) as a good way to avoid losing the javascript if the user reloads the form:

```
function hook_form_alter(&$form, $form_state, $form_id){
  if($form_id == 'form_in_question'){
     $form['some_element']['#after_build'] = array('_load_my_javascript);
   }
}

function _load_my_javascript($element){
    drupal_add_js(
      drupal_get_path('module', 'my_module')
        . '/track_editors.js');
return($element);
}

```
> 0 votes

---
Tags: google-analytics
---


# Question
Title: (Good or bad?) Calling a Function in Template File which returns a theme() Function value
I have a function which get some values from a Term, calculates something and at the end of my function, there is a statement like this:

```
return theme('foo', array('bar' => 1);

```

This function is in a self-written module. In the same module, I've got a template file.

Now my question: is it good or bad Practice to call the function which one I describe above in the template file? I know that I could calculate all this before calling the template file, but with my solution, the could would be more readable.

Thank you in avantage for inputs.

# Answer
If you are asking about calling `theme()` from inside a template file, that is possible, but it is rarely done: Out of 214 calls to `theme()` done from Drupal (and the Views module) only two calls are done from inside s template file.

This is the code used in the default implementation of page.tpl.php; similar code is present in the implementation of page.tpl.php for the Bartik theme.

```
<?php if ($main_menu || $secondary_menu): ?>
  <div id="navigation"><div class="section">
    <?php print theme('links__system_main_menu', array('links' => $main_menu, 'attributes' => array('id' => 'main-menu', 'class' => array('links', 'inline', 'clearfix')), 'heading' => t('Main menu'))); ?>
    <?php print theme('links__system_secondary_menu', array('links' => $secondary_menu, 'attributes' => array('id' => 'secondary-menu', 'class' => array('links', 'inline', 'clearfix')), 'heading' => t('Secondary menu'))); ?>
  </div></div> <!-- /.section, /#navigation -->
<?php endif; ?>

```

What you should do is initializing a variable in the preprocess function for the template file, and use that variable in the template file.

Truly, you should not put logic code in your template file; this means that, for example, code similar to the following one should not be used in a template file.

```
<?php if ($condition1): ?>
  <?php print theme('theme_1', $values1); ?>
<?php elseif ($condition2): ?>
  <?php print theme('theme_2', $values2); ?>
<?php elseif ($condition3): ?>
  <?php print theme('theme_3', $values3); ?>
<?php endif; ?>

```

If the code is similar to the following one, then it would be more acceptable, but I would still think of possible future versions of the code, and prefer using a variable in the preprocess function.

```
  <?php print theme('theme_1', $values1); ?>
  <?php print theme('theme_2', $values2); ?>
  <?php print theme('theme_3', $values3); ?>

```
> 1 votes

---
Tags: 7, theming
---


# Question
Title: Best practice to separate content per city
I'm trying to find the best practice to separate user content per country/city in a way that allows the user to select the country or city once so that whenever he adds content it will be automatically assigned to this city/country and when searching, the results will be related to currently select city too. so it's more like a global choice across the website.

How is this best achieved usually in drupal,, I used taxonomy to classify content per city.. but this doesn't feel like the solution. Any guidance is highly appreciated.

# Answer
> 2 votes
You said you already had a taxonomy vocabulary holding the countries and cities. This sounds like a good start. You can add a term reference field to the user profile, so that users can select their locations from the same vocabulary.

One idea (which could work without coding) is that you use Entity Reference for referencing terms from this vocabulary on nodes. Then you can use Entityreference prepopulate to fill out the reference fields automatically based on a value in the URI's query string. As the last step you will need to render the content creation links and make sure the URIs contain the taxonomy term selected on the current user's profile. You can do that e.g. with Page Manager alongside with Panels by adding a *New custom content* pane, where you can use keywords from the User context which you need to add manually to the page.

---
Tags: taxonomy-terms, location, domain-access
---


# Question
Title: Add HTML code outside content area on every page load
I am trying to add HTML code outside the content area on every page load with the use of:

```
function us_page_build(&$page) {
  $page['content'][] = array(
    '#markup' => '<div class="fullscreen"><p>Here is my div content!!</p></div>',
  );
}

```

However, in this way I am placing the element within the content attribute. Is there a way to set it outside, having as parent only the html element? I am aware I can paste code into the template files, but then if I switch to another template(which I will) I will need to re-enter it.

# Answer
> 3 votes
Content is a region in your theme. Site content goes into regions. So, typically you can only put things in defined regions such as Header, Footer, Left Sidebar, Content.

You have slight flexibility with `#prefix` and `#suffix` render array attributes. You either have to edit the html.tpl.php file, or define your own region within a theme. Or you can supply your own `hook_theme()` implementation to hint when using your own html.tpl.php template file.

# Answer
> 1 votes
You can also use the template\_preprocess\_page() in your module:

```
function modulename_preprocess_page(&$vars) {
  $vars['page_top'] .= '<div class="fullscreen"><p>Here is my div content!!</p></div>';
}

```

Or your could set $vars\['closure'\] for Drupal 6 or $vars\['page\_bottom'\] for Drupal 7.

---
Tags: hooks
---


# Question
Title: Drupal shows ?? instead of special characters with oracle
I have a Drupal 7 installation working with Oracle 11g database with Apache/2.2.12 (Linux/SUSE) and PHP/5.3.8

The problem I face is that special characters are not displayed correctly. Instead two question marks ('??') are shown.

I've been able to correct some static pieces of content (in blocks) converting the characters to their corresponding html entity. However, new content and menus dont support this.

I would like to know how to show those characters correctly.

# Answer
> 1 votes
Check you are using UTF8 character set in Oracle database, and in apache config. For data in Oracle db that is not UTF8 be careful if you need to convert, you need to identify what the original characterset is and the best way to convert to UTF8.

> The general rule of thumb is that if you are using UTF8 all the way you should not see those question marks in the browser.

Take a look here for Oracle UTF8 conversion info: https://stackoverflow.com/questions/8239250/how-to-configure-utf8-character-set-in-oracle

---
Tags: database
---


# Question
Title: Profile 2 fields not displaying in registration form
I create 2 Profiles with distinct Fields as well as assigned each one a unique role with permissions to Administer Profile2 registration paths, but all I'm getting is the default Username and E-mail fields nothing else (On both of them).

# Answer
> 1 votes
Make sure you check to "Show during user account registration" on the profile type.

**Admin \> Structure \> Profile Types \> \[Type\] \> Edit**

---
Tags: users
---


# Question
Title: How can I call javascript from another site?
I recently started working in collaboration with another drupal website, and we are trying to figure out how to get some of their content embedded into my site. They sent my some embed code for a widget, which is below (with some pieces changed for privacy:

```
<script type="text/javascript">
  widgetContext = { "url": "http://theirsite.com/mysite/[nid]", "width": "600", "height": 200, "widgetid": "web_widget_iframe_hash" };
</script>
<script id="web_widget_iframe_hash" src="http://theirsite.com/sites/all/modules/web_widgets/iframe/web_widgets_iframe.js">
</script>

```

The problem is that I cannot figure out how to get this embedded into my site. The widget generates calendars for venues, so the content is going to change based on which node is being viewed on my site. So, in my nodes, I added a field that stores the NID of the corresponding node on the other site so that the correct calendar is generated.

I'm trying to create a view, in order to dynamically call the above script for each page on my site. The view uses a token to take the NID field and place it into the first part of the script. However, when I place this code into a Custom Field, views strips the script tags and displays the rest of it as text. When I try to place it into a PHP field, it doesn't display at all.

Does anybody have a suggestion for how I can use the above code on my site? I'm at a bit of a loss.

# Answer
> 1 votes
You could add the JS in code.

e.g:

```
/**
 * Implements hook_init
 */
function mymodule_init(){
  if ($node = menu_get_object('node')) {
    if ($node->type == 'my_type') {
      $items = field_get_items('node', $node, 'field_my_nid_field');
      if (!empty($items[0]['value'])) {
        $nid = filter_xss($items[0]['value']);
        drupal_add_js('
        widgetContext = { "url": "http://theirsite.com/mysite/'.(int)$nid.'", "width": "600", "height": 200, "widgetid": "web_widget_iframe_hash" };
        ', array('type' => 'inline', 'scope' => 'header'));
      }
    }
  }
}

```

The other static script tag can be added in a custom Full HTML block / content pane or similar, where you want the content to display.

---
Tags: views, javascript, entities
---


# Question
Title: getting uploaded file name at node title
Users will upload files. The user will tag the file with a project name and some keywords and an optional text comment. I have made a content-type called 'image', that has filed for title, file, project, keywords and comments.

I want the tile of the node to be the name of the uploaded file. The name of the filed is 'file' the field is of type File, the widget is of type File, and the filed name is field\_file. I have the token module and the "Automatic Nodetitles" module. The token module gives me token "node:field\_file\_body", this is not the file name.

How do I set the title of the each "image" node to the name of the uploaded file?

# Answer
I also battled with this; this is my solution:

Use the Automatic Nodetitles Module as described by the others, and in the **Pattern for the title** text box load up the filefield and extract the filename that way. Example:

```
<?php
//Load the file
$file = file_load($node->field_document['und'][0]['fid']);

// Filename
return $file->filename;
?>

```

Obviously you need to check the **Evaluate PHP in pattern.** checkbox at the bottom for this to work, and replace "field\_document" with the name of your own file field.

Hope this helps somebody!
> 2 votes

# Answer
You could try this module: FileField Paths. From the description, it looks like it might provide you with the tokens you need.

**Edit** Here's the code where it adds the tokens if you're interested: see the repository. If that's not what you need, it's probably pretty close to what you need.

**Edit 2** Looks like you'll have to create a module. Don't stress, it's not hard. This blog post shows you how to create a module which provides custom tokens for nodes. You can combine that with the repository link in my first edit to acheive the token you need. If you've never created a module before, it's simple. Follow the simple tutorial on Drupal.org. All you need is a folder in sites/all/modules with the files mymodule.module and mymodule.info where "mymodule" is your module name.
> 1 votes

# Answer
In addition to what @Jonathan Rowny said, you could also use the Automatic Nodetitles Module and then use the `Token` of the uploaded file name as the auto node title. But you will also need the Token module installed / activated. I have used this method and it works great.

**Added:** screen capture from Auto Nodetitles that can use a token name of the file name.
> 1 votes

# Answer
I got it working with Automatic Nodetitles, Token, and Entity Token. I used the following token:

`[node:field-file:file]`

As you described in the question, I have a field called `file` in my nodetype. I believe the `:file` portion of the token was created by Entity Token.
> 0 votes

---
Tags: nodes, 7, files
---


# Question
Title: How do I properly pass values from PHP to JavaScript?
I am currently writing a module and I am trying to pass some variables to the `Drupal.settings`.

My module uses the following code.

```
function bcc_preprocess_views_view(&$vars) {
    drupal_add_js(array('modulname' => array('key' => 'value')), 'setting');
    drupal_add_js(drupal_get_path('module', 'modulname') .'/script.js');
}

```

The script.js content is the following.

```
(function ($) {
    console.log(Drupal.settings.modulname);
})( jQuery );

```

The output I find in the log is *undefined*, but when I check the content of `Drupal.settings.modulname` from the browser, it gives me the desired value.

When I add this code, the log shows the right values.

```
drupal_add_js('jQuery(document).ready(function({console.log(Drupal.settings.royal)});', 'inline');

```

What is wrong with that? What is the correct code to use?

# Answer
> 6 votes
You first JS snippet executes before the page is done loading. Is it not the same syntax as the shorthand for declaring the document.onready event handler.

You working example runs from an onready, but the Drupal best practice is to use a behavior, eg:

```
(function ($, Drupal, undefined) {
  Drupal.behaviors.mymodule = {
    attach: function (context, settings) {
      console.log(settings.mymodule);
    }
  };
})(jQuery, Drupal);

```

Take a look at Managing JavaScript in Drupal 7 for more information.

# Answer
> -2 votes
okay: this does it:

```
$options = array(
'weight' => 1000, // High number to push this file to the bottom of the list
'scope' => 'footer' // This will output the JS file in the footer scope, so at the end of   the document
);

```

an then hand it over with:

```
drupal_add_js(drupal_get_path('module', 'modulename') .'/script.js', $options);

```

for more details: https://stackoverflow.com/questions/8330757/drupal-7-add-js-weight

---
Tags: javascript
---


# Question
Title: This page was last modified on 1 January 1970
Including the following code:

```
<?php print 'This page was last modified on ' . date('j F Y', $node->changed);?>

```

in `node.tpl.php` displays the correct information on the site. However, I would like to display it in the footer instead at the end of the content so have moved it to `page.tpl.php`.

The problem with this is that on the homepage the following is being displayed:

> This page was last modified on 1 January 1970

Which is clearly incorrect.

In addition, These error messages are displayed on every page:

> Notice: Undefined variable: node in include() (line 201 of /home/mysite/public\_html/sites/all/themes/mysite/templates/page.tpl.php).
>
> Notice: Trying to get property of non-object in include() (line 201 of /home/mysite/public\_html/sites/all/themes/mysite/templates/page.tpl.php).

How do I include the Page last updated text in the footer of every page?

# Answer
> 2 votes
You are trying to access the property of a loaded Node's object in the page template. This variable, `$node`, will only be available to the page template, typically `page.tpl.php`, only if the current path is loading a node.

In other words, if you are loading a path like `node/NODE_ID`, then you are guaranteed the variable will be available. Otherwise it won't be.

The error you are seeing is because of this reason. Try to navigate to a valid node URL and the error will be gone, the variable will be defined, and you can access it normally.

Provide a conditional check in your page template to make sure the variable exists before you access it.

Good Luck!

---
Tags: theming
---


# Question
Title: Help with JQuery Toggle Div, Start in Hidden State
Alright, this has been driving me insane for all too long. I'm trying to toggle a div, but start it in a hidden state. Suggestions on how to modify the following?

```
// Drupal 7 js code
(function ($) {
Drupal.behaviors.togg = {
attach: function (context, settings) {
$('a#togg-link:not(.togg-processed)', context).addClass('togg-
processed').each(function() {
$(this).click(function() {
$("div#togg").toggle(400);
return false;
});
});
}
};
})(jQuery);

```

# Answer
If possible, simply add the CSS class *js-hide* to the div source markup, to hide by default if js is enabled.
> 0 votes

# Answer
Try this - In your loop, where you are iterating over each element to attach a click event handler, add this line:

`$(this).hide();`

That should hide each element. But don't add it to your click event handler. You can also initially hide the element using CSS if you want. Either method should work.

Please consider properly formatting code samples you post so that the community can read and understand it easier.

Good Luck!
> 0 votes

# Answer
```
// Drupal 7 js code
(function ($) {
  Drupal.behaviors.togg = {
    attach: function (context, settings) {
      $('a#togg-link', context).once().each(function() {
        $(this).hide().click(function() {
          $('div#togg').toggle(400);
          return false;
        });
      });
    }
  };
})(jQuery);

```

Are there going to be more than 1 toggle link on the page? If no, you don't need the each(). Otherwise, if each toggle link opens a different div, than the selector in `$('div#togg').toggle(400);` will have to be changed.

There is also the option of just settings display:none in the css to hide them when the page loads.
> 0 votes

---
Tags: javascript
---


title: How to get content type stats into view

text:
# Question
Title: How to get content type stats into view
Hi I am a new drupal coder working a project and making fairly good progress with views an such but i am having a hard time with a specific request.

I need to build a block to display a list of stats in various locations

number of registered users

number of tags uses on a certain content type

number of posts of a certain content type

number of comments contained on all posts of a certain content type

number of revisions on all a certain content type

I am not sure how to get the above data into views.

I would greatly appreciate if somebody could point me in the right direction.

# Answer
> 0 votes
It's hard to know from your question, which part you're having a hard time with exactly, so I'll just be general in my response:

Typically, when you set up a view, you're getting either users, or content, or terms, or comments -- those are very different types of data. Typically, a view will not give you all those things together in one display.

So my suggestion would be to try to get each of the different stat types in separate views, and then you can always combine multiple views in one page or block for display purposes at the end...

So, when you start creating a new view, select the correct type of content to show on the first view setup screen (I'm assuming you're using Drupal 7 - it's always useful to specify in your question or via a tag). In Drupal 7, that first view setup screen will prompt you for the type of data you're going to be displaying, so select '**Content**' for the revisions stat view or '**Taxonomy term**' for the tagging stat view or '**Users**' for the user stat view, etc.

Then go from there... just try to do these separately and that would be easiest!!

---
Tags: views
---


title: How to put a condition on a query

text:
# Question
Title: How to put a condition on a query
in my custom module, i am executing a query.

```
global $user;
$id = $user->uid;
print_r($id);
$query = db_query('SELECT n.nid, c.uid, n.title, f.body_value, fm.uri
FROM challenges c
LEFT JOIN node n ON n.nid = c.cid
LEFT JOIN field_data_body f ON n.nid = f.entity_id
LEFT JOIN field_data_field_challenge_pic fp ON n.nid = fp.entity_id
LEFT JOIN file_managed fm ON fp.field_challenge_pic_fid = fm.fid ');
**// WHERE c.cid = $id ');**

```

when the where clause is commented out the query runs fine. I check it using:

```
foreach($query as $q)
{
            print_r($q);
}

```

But when i add the where clause i get an error: Syntax error or access violation...on the line where i write the where clause. How can i achieve this. Thanks

# Answer
While db\_select() is recommended to use in D7, you can still use db\_query() using named placeholders.

```
$result = db_query('SELECT n.nid, c.uid, n.title, f.body_value, fm.uri
                    FROM challenges c
                    LEFT JOIN node n ON n.nid = c.cid
                    LEFT JOIN field_data_body f ON n.nid = f.entity_id
                    LEFT JOIN field_data_field_challenge_pic fp ON n.nid = fp.entity_id
                    LEFT JOIN file_managed fm ON fp.field_challenge_pic_fid = fm.fid
                    WHERE c.cid = :cid', array(':cid' => $id));

if ($result) {
    while ($row = $result->fetchAssoc()) {
      // Do something with:
      //    $row['nid']
      //    $row['title']
    }
}

```

It prevents SQL injection also.
> 2 votes

# Answer
Clive's comment is right. You should understand the reasons why, however, I will give you the short answer ;)

Use `db_select()`

```
$query = db_select('challenges', 'c');
$query->fields('c');
$query->condition('c.cid', $id, '=');
$result = $query->execute();

```
> 3 votes

---
Tags: 7, blocks, database
---


# Question
Title: SImplenews module. Where does the form come from?
I would like to modify the content of the simplenews form, but where is it being generated from?

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

```

I would like to change the "E-mail" wording, for example.

# Answer
To modify a form in Drupal you dont need to get where the form is built.

You can make use of hook\_form\_alter to modify the form

> Perform alterations before a form is rendered. One popular use of this hook is to add form elements to the node form.

```
hook_form_alter(&$form, &$form_state, $form_id);

```

> Parameters
>
> $form: Nested array of form elements that comprise the form.
>
> $form\_state: A keyed array containing the current state of the form. The arguments that drupal\_get\_form() was originally called with are available in the array $form\_state\['build\_info'\]\['args'\].
>
> $form\_id: String representing the name of the form itself. Typically this is the name of the function that generated the form.

**What is a Hook ?**

Basically they provide a way for a module to extend the functionality of another module. They would go in a module and 'hook' would be replaced by the actual module name.

**Please try**

Examples for Developers

Drupal Hooks Explained
> 1 votes

---
Tags: emails
---


# Question
Title: Change Pager-ItemsPerPage over URL argument
I use Views to get Nodes in JSON format via REST service. I can switch the pages with;

`http://myside/?q=my/path&page=1`

but I want to change the limit of one page like;

`http://myside/?q=my/path&limit=100`.

Has anybody a good solution or one alternative.

# Answer
> 4 votes
there is default option in views pager as "EXPOSED OPTIONS" while adding pager to views.

You can add range output.

So you can show per page option. set results using URL argument like http://example.com/path?limit=100

---
Tags: 7, views
---


# Question
Title: How to execute a script that takes a long time?
I am executing a script by calling a URL using the `wget` command. I want to execute this script 3 times a day for 2 hours each time. To do so, I check the difference between the start time and the current time.

My problem is that sometimes the script runs for 2 hours, sometime 1 hour, and sometimes just 3 minutes. I don't know why. I have increased `memory_limit` and `max_execution_time`. Still, I haven't been able to find the reason.

What my script is doing exactly:

1. It fetches a data from other site using cUrl. The data are articles, journals and some other user's data.
2. After getting the data in XML format, it adds each content.

# Answer
You can break up your work somehow. You shouldn't try to process thousands of things at a time and assume nothing will break or you'll run out of time.

I have recently wrote an in-house Drupal 7 project that allows me to query a webservice for XML data very quickly and process 100,000s of XML entries to an SQL DB pretty fast. A full fetch of all remote SOAP based data is ~100,000 SQL rows after import. This takes ~5 mins to complete. From CURL to DB insert.

The Drupal 7 site performs the following:

* Allows me to fetch a .NET SOAP response for X departments from my university. X any number of department queries from 1 department to 90 departments per school quarter.
    + I used the Background Process module to fetch the CURL requests to local XML files in a Drupal private filesystem.
    + 90 CURL requests with ~2Mb XML responses complete in ~1 minute. (I could request 1 huge xml file of all departments; I break it up for many threads below).
    + The XML files are added to a Drupal queue. Queue's can *lease* queue items as jobs for processing. A developer can set a *lease time per job* for **any length of time**.
* I then use hook\_cron\_queue to define a worker function that parses the XML and inserts the data into a database. This happens to be a non-Drupal database that I connect to via a custom db entry in `settings.php`.
    + I use the Ultimate Cron and Ultimate Cron Queue Scaler modules to actually perform the processing. I set 9 threads in Ultimate Cron Queue to process queue items, and I have set my lease time to literally 2 hours (7600 seconds). Drupal cron runs/checks for work every minute, the lease time assures no thread tramples over work already in progress.
        - with no optimizations a script I'd written using PHP `DomDocument` with Xpath queries inserting SQL queries to a DB took minutes per XML file. After adding some SQL batch inserts with `db_insert` each file takes seconds, but I know from progressively optimizing my scripts a job can have a set lease time. Which is what you want here.

In short. Find a way to break-up your workload and dont be afraid to use `watchdog` log messages in your module code. A Queue is a nice way to store pieces of the whole task to complete in tiny parts. As you run your worker functions you'll be able to find a *lease time* that works best for your data size and processing times.

I realized your post is about Drupal 6; it doesn't really matter. The core pieces you want are the D6 queue project and `hook_cron()`. The Ultimate Cron, Ultimate Cron Queue Scaler, and the Background Process modules have D6 versions.

The project described is a private in-house project, and I cannot easily provide code examples. I've tried to outline how to glue this all together.
> 3 votes

---
Tags: 6
---


title: How can I display a block as a node?

text:
# Question
Title: How can I display a block as a node?
I've got a modules that supplies a bunch of blocks. I'd like to be able to display them individually as stand-alone pages. I can embed them into nodes, but then I'll need to create each node manually. Ideally I'd just create a menu entry specifying which specific block I'd like to display.

Is there anything out there that can do that? I'm looking for basically the inverse of http://drupal.org/project/nodeblock.

Thanks.

# Answer
I would do this by Empty Page module

> The Empty Page module is a simple empty page solution. It provides an interface that assists in managing "empty" menu callbacks, mostly used for pages that only consist of blocks

Please your block in separate Empty Page's
> 0 votes

# Answer
I would do this from my custom module. I would create a men path and a page callback which renders the block.

```
/**
 * Implements hook_menu().
 */
function mymodule_menu() {
    $items = array();
    $items['my/block/path'] = array(
        'title' => 'Block As A Page',
        'page callback' => 'mymodule_block_as_page',
        'access callback' => TRUE,
    );
    return $items;
}
/**
 * Page callback the path for my/block/path
 */
function mymodule_block_as_page(){
    $block = module_invoke('module_name', 'block_view', 'module_delta');
    return $block['content'];
}

```

If you go to the path **my/block/path**, you will see your block as a page/node.
> 0 votes

# Answer
An alternative solution with hook\_menu

Provide a generic menu handler for viewing a block at `block/view/module_name/delta`

```
/**
 * Implements hook_menu().
 * Provides block view page at:
 * /block/module_name/delta
 */
function mymodule_menu() {
    $items = array();
    // Pass generic module_name and delta as args
    $items['block/view/%/%'] = array(
        'title' => 'Block page',
        'page callback' => 'mymodule_block_page',
        'page arguments' => array(2,3),
        'access arguments' => array('access content'),
    );
    return $items;
}
/**
 * Page callback the path for block/module/delta
 */
function mymodule_block_page($module, $delta){
  if (module_exists($module) && !empty($delta)) {
    $block = module_invoke($module, 'block_view', $delta);
    return isset($block['content']) ? $block['content'] : MENU_NOT_FOUND;
  }else{
    return MENU_NOT_FOUND;
  }
}

```

Alternatively, use Panels.
> 0 votes

---
Tags: nodes, routes, blocks
---


# Question
Title: How to Collapse "Locale settings" (TimeZone) in User Profile with hook_form_FORM_ID_alter();
I cannot seem to get "Locale settings" fieldset to collapse using hook\_form\_FORM\_ID\_alter().

Here is what I've tried so far.

```
function fsrsys_form_user_profile_form_alter(&$form, &$form_state, $form_id) {
    $form['timezone']['#type'] = 'fieldset';
    $form['timezone']['#collapsible'] = TRUE;
    $form['timezone']['#collapsed'] = TRUE;

    $form['#after_build'][] = 'user_profile_form_afterbuild';
}

function user_profile_form_afterbuild($form, $form_state) {
    $form['timezone']['#collapsed'] = TRUE;
    //dd($form['timezone']['#collapsed']);  // <-- shows '1'
    return $form;
}

```

The fieldset is still 'open.'

For good measure, I've cleared both the Drupal cache and the browser cache twice.

What am I doing wrong?

# Answer
> 1 votes
This is a bit of a hack but it worked for me.

My desired effect was to have the Locale Settings start out collapsed and be expandable, every other solution out there suggests just "turning it off". I still need to use the Locale settings though. Anyway!!! Execute this jquery on the edit user profile page ( I inserted it using a hook\_form\_alter):

```
(function($){
  $(document).ready(function(){
    $('#edit-timezone .fieldset-wrapper').toggle();
    $('#edit-timezone').addClass('collapsed');
  });
})(jQuery);

```

# Answer
> 1 votes
You can just add a class `collapsed` to the attributes array within the form element. So for locale settings, in your form after build function you can use `$form['timezone']['#attributes']['class'][] = 'collapsed';`

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


# Question
Title: Don't allow users to create nodes until they have at least one comment
I'm trying to create a community website using drupal where users can create accounts, login and create nodes but i don't want them to create a node until they have at least one comment on a node. I heard rules will be able to accomplish this but I don't know hw to set it to disallow users from creating a node until they have a content

# Answer
> 5 votes
You can do this is with the Rules module.

1. Remove the permission to create nodes from authenticated users.
2. Create a new role (e.g., one\_comment) and give this role the permission to create nodes.
3. Create a rule that is triggered when a comment is posted and gives the user who posted the comment the one\_comment role.

---
Tags: rules
---


# Question
Title: Views, User type page view ignoring Omega content grid
I have created a view of users with a page display. When I navigate to that page it isn't rendering Omega's usual id or grid classes. Instead it is just using Views classes.

For example here is the HTML output for a normal content type views page:

And here is the HTML output for a user type page view:

Has anyone come across this?

--

Just to add that if you add a block to the content region then the omega template seems to work normally.

# Answer
Ok so I think I have found a workaround / solution when using view pages. I think that the Context module may of had a hand in this, as another site I run, which doesn't have context installed works fine when rendering views pages.

So while poking around Context and its available blocks I noticed that there was a Main page content block. I added that to the content region and now if I use a view as a page the content region HTML is rendered.
> 0 votes

---
Tags: views, theming
---


# Question
Title: How to render complete page when overriding page--node--add--typename.tpl.php
I'm trying to add more buttons to a custom content type form. I create a page--node--add--typename.tpl.php where I modify the form then render it:

```
$form = node_add('answer');

$form['actions']['cancel'] = array(
    '#type'   => 'submit',
    '#value'  => t('Cancel'),
    '#access' => TRUE,
    '#weight' => 55,
    '#submit' => array('cancel_button_form_cancel', 'node_form_submit_build_node'),
    '#limit_validation_errors' => array(),
);

print drupal_render($form);

```

However this only renders the form. Menus and other blocks are not rendered.

THanks.

# Answer
> 2 votes
I think you would need to return the form, not print it.

```
return drupal_render($form);

```

Printing from a function will cease the theme engine which would cause the other parts of the page not rendered.

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


# Question
Title: A table was not created by _schema() function
I added this function to cleanetica\_advanced module and after this ran /update.php

```
function cleanetica_advanced_schema() {
  $schema['videos'] = array (
    'description' => 'Videos with HTML titles',
    'fields' => array(
      'id' => array(
        'description' => 'Primary key for our table of videos',
        'type' => 'serial',
        'unsigned' => TRUE,
        'not null' => TRUE,
      ),
      'urlinfo' => array(
        'description' => 'The string referring to the video',
        'type' => 'varchar',
        'length' => '255',
        'not null' => TRUE
      ),
      'title' => array(
        'description' => 'The title for a video, used in admin part only',
        'type' => 'text',
        'size' => 'medium',
        'not null' => TRUE
      ),
      'richtitle' => array(
        'description' => 'The HTML-formatted title for a video',
        'type' => 'text',
        'size' => 'medium',
        'not null' => TRUE
      ),
    ),
    'primary key' => array('id'),
  );

  return $schema;
}
```

But the table `videos` was not created.

What have I missed in order for the table to be created?

The module cleanetica\_advanced is enabled and I checked that it really loads by inserting a nonsense (non-PHP) there and seeing that the site crashes with an error. (After this I removed the nonsense.)

# Answer
> 3 votes
The hook\_schema is only run for table creation during module install.

To run it later, you'd need to install the schema from .install file with something like

```
/**
 * Implements hook_update_N
 */
function cleanetica_advanced_update_7001(){
  drupal_install_schema('cleanetica_advanced');
}

```

Add, and then run update.php

---
Tags: database
---


# Question
Title: Can't pass php variable to javascript in Drupal 7
Can somebody help me with this problem. In the body of a Basic page:

```
drupal_add_js(array('my_var' => array('orderid' => '123')), 'setting');
drupal_add_js('sites/all/scripts/printout.js');

```

In printout.js:

```
alert("Before");
alert(Drupal.settings.my_var.orderid);

```

Result: "Before" was alerted then returned to Basic page, no orderid. What have I done wrong?

# Answer
Make sure you call for jquery setting inside Drupal behaviour, you can do like this:

```
(function ($) {
    Drupal.behaviors.example_name = {
        attach: function(context) {
            alert(Drupal.settings.my_var.orderid);
        }
    }
})(jQuery);

```

or you can call inside jQuery's .ready() event (less preferable than behaviours approach in Drupal world):

```
jQuery(document).ready(function($) {
   alert(Drupal.settings.my_var.orderid);
});

```

These both approaches ensure that jQuery is loaded before calling a variable.

**P.S.** I recommend using console.log instead of alert for quick debugging, like this:

```
console.log(Drupal.settings.my_var.orderid);

```

Then go to your developer console / firebug (depending on browser you use) and you'll see an output in console.
> 4 votes

# Answer
You have to say drupal where to put the javascript like this:

```
$options = array(
'weight' => 1000, // High number to push this file to the bottom of the list
'scope' => 'footer' // This will output the JS file in the footer scope, so at the end     of   the document
);

drupal_add_js(drupal_get_path('module', 'modulename') .'/script.js', $options);

```

But like i learned a more sophisticated way would be to use Drupal.behaviors.

Look at my question: How to pass values from php to javascript properly?
> -1 votes

---
Tags: javascript
---


title: How to configure blocks per node?

text:
# Question
Title: How to configure blocks per node?
I'd like to build a Drupal 7 module that generates a block which contains (along with some static HTML to be used as template for a JavaScript library) *a node-specific value* to be passed on to a web service. (The web service will return relevant data for the contents of the node.)

How should a block receive node-specific data? Module configuration seems to be global, and blocks cannot be configured individually.

Should I modify the main content-type of the node by adding this "node-specific data" as an extra field even if this value is only used in my module?

# Answer
Use the Block API to add the blocks

i.e:

Use menu\_get\_object to get the node object for that page.

e.g:

```
function mymodule_block_view($delta){
  $block = array();
  switch($delta){
    case 'my_delta':
     if ($node = menu_get_object('node') && $node->type == 'my_type') {
       $block['subject'] = t('Example block on %node', array('%node' => $node->title));
       $block['content'] = render(field_view_field('node', $node, 'body')); // for example
     }
    break;
  }
  return $block;
}

```
> 1 votes

---
Tags: blocks
---


# Question
Title: Moving a DB table into a different module
Here is cleanetica\_advanced.install file (of a "custom" module containing particulars of the site we work on):

```
<?php
function cleanetica_advanced_schema() {
  $schema['video'] = array (
    'description' => 'Videos with HTML titles',
    'fields' => array(
      'id' => array(
        'description' => 'Primary key for our table of videos',
        'type' => 'serial',
        'unsigned' => TRUE,
        'not null' => TRUE,
      ),
      'urlinfo' => array(
        'description' => 'The string referring to the video',
        'type' => 'varchar',
        'length' => '255',
        'not null' => TRUE
      ),
      'title' => array(
        'description' => 'The title for a video, used in admin part only',
        'type' => 'text',
        'size' => 'medium',
        'not null' => TRUE
      ),
      'richtitle' => array(
        'description' => 'The HTML-formatted title for a video',
        'type' => 'text',
        'size' => 'medium',
        'not null' => TRUE
      ),
    ),
    'primary key' => array('id'),
  );

  return $schema;
}

function cleanetica_advanced_update_1(){
  drupal_install_schema('cleanetica_advanced');
}
```

I now think that it is better to create a separate module to manage 'video' database table and related things.

The trouble is that I have already created 'video' DB table. How to move/transfer a table into an other module?

# Answer
> 1 votes
The simplest way is to uninstall your existing module completely (not just disable), cut the schema definition from the old to the new, then enable both modules. The uninstall will remove the table, and the install will add it back in from the other module.

You'll also want to get rid of the `cleanetica_advanced_update_1()` function from your current module as that could cause some interesting inconsistencies if left unchecked.

---
Tags: 6, database, installation
---


# Question
Title: Place custom content field only on sidebar
i have created a custom content type "My\_Content" with some custom fields. One of the fields in "My\_field". Now, when the user is creating a content of type My\_content, he/she is asked for the fields like title, body, picture, My\_field etc...What i need is that the My\_field always displays on the right sidebar. Is there a way to achieve this?

# Answer
> 2 votes
You can do this with the Panels module. From the Page Manager configuration screen (Pages in the admin interface), enable the node edit page override. Then edit this override.

Create a new variant. Set the selection rule to be "content has type" -\> "my custom content type". Then, under Layout, choose an appropriate layout (one with a right sidebar).

Afterwards, under content, you will need to add all of the fields for the content type to be edited. Just place My\_field in the right sidebar and it will be displayed there.

---
Tags: 7, theming, entities, nodes
---


# Question
Title: How to tokenize a value in a custom field formatter for views?
I am using an custom field formatter for a view field like this:

```
function custom_fields_field_formatter_info() {

  return array(
    // the key must be unique, so it's best to prefix with your module's name.
    'custom_fields_breadcrumbs' => array(
      'label' => t('Breadcrumbs'),
      'field types' => array('entityreference'),
    ),
  );
}

/**
* Implements hook_field_formatter_settings_form().
*/
function custom_fields_field_formatter_settings_form($field, $instance, $view_mode, $form, &$form_state) {

  $display = $instance['display'][$view_mode];
  $settings = $display['settings'];
   if ($display['type'] == 'custom_fields_breadcrumbs') {
    $form = array();
       $form['active'] = array(
      '#type' => 'textfield',
      '#title' => t('Mark as active'),
      '#description' => t('You can specify a node id, which should have class "active". Yo can use replacement tokens.'),
      '#default_value' => $settings['active'],
      '#size' => 4,
      '#maxlength' => 128,
      '#required' => FALSE,
    );
  }
    return $form;
}
function custom_fields_field_formatter_view($entity_type, $entity, $field, $instance, $langcode, $items, $display) {

  $element = array();
  $settings = $display['settings'];

  switch ($display['type']) {
     case 'custom_fields_breadcrumbs':
      $ids = array();
      foreach ($items as $item) {
        $ids[$item['target_id']] = $item['target_id'];
      }
      $items = array();
      // http://api.drupal.org/api/drupal/modules!node!node.module/function/node_load_multiple/7
      $items = node_load_multiple($ids, array(), FALSE);
      foreach ($items as $delta => $item) {
        $label = $item->title;
        // modeled after entityreference_field_formatter_view() in entityreference.module
        if ($display['settings']['link'] && ($uri = node_uri($item))) {
          $otpions = array();
          if (isset($settings['active']) && $delta == $settings['active']) {
            $otpions = array('attributes' => array('class' => array('active')) );
          }
          $element[$delta] = array('#markup' => l($label, $uri['path'], $otpions));
        }
        else {
          $element[$delta] = array('#markup' => check_plain($label));
        }
      }
      break;
  }
  return $element;
}

```

Everything works as expected, but I want to be able to use replacement patterns for my custom setting $settings\['active'\]. How do I do this?

I think, I have to use the method:

```
tokenize_value()

```

from the views object. But I don't have the views object within the hook, haven't I?

# Answer
> 0 votes
I found out how to do this. We have the views object via the parameter "display", so we can use:

```
$display['views_view']->style_plugin->tokenize_value($settings['pager']['active'], 0)

```

to tokenize a field value.

---
Tags: views
---


# Question
Title: Print preview and Printer-friendly version look different
I am using a Print module with a bartik subtheme. I am trying to override the print module styles by using my theme's print.css file. Is this correc tway of doing this?

Both the print preview and preview via the printer-friendly version generated by the print module look different...

How would I go about overriding the print module styles?

This is how the print stylesheet is being called in my theme: stylesheets\[print\]\[\] = css/print.css

# Answer
> 1 votes
You have two separate stylesheets.

The 'preview' stylesheet needs to be configured in the CMS. You just enter into a field something like 'print.css' and create that file in your theme folder. This is nothing different than a typical stylesheet you would use anywhere else on the site.

The actual 'print' stylesheet (what you get when you press the print button) that you have declared in your .info file will style the resulting print.

---
Tags: theming
---


title: Returning body values only

text:
# Question
Title: Returning body values only
I have the following function that simply grabs nodes:

```
function getWords() {
    $query = new EntityFieldQuery();
    $query->entityCondition('entity_type', 'node', '=')
            ->propertyCondition('status', 1, '=')
            ->propertyCondition('type', 'wall_of_words', '=');
    $result = $query->execute();
    return node_load_multiple(array_keys($result['node']));

```

}

Right now it's working but it's returning everything, is there a way I can return the contents of the body or title field only?

# Answer
> 2 votes
You can leverage **field\_attach\_load()** for this:

```
$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'node', '=')
  ->propertyCondition('status', 1, '=')
  ->propertyCondition('type', 'wall_of_words', '=');
$result = $query->execute();

$nodes = $result['node'];

// Get all fields attached to a given node type
$fields = field_info_instances('node', 'wall_of_words');

// Get id of body field
$field_id = $fields['body']['field_id'];

// Attach a field of selected id only to get value for it
field_attach_load('node', $nodes, FIELD_LOAD_CURRENT, array('field_id' => $field_id));

```

Now you have `$nodes` array of "half-loaded" nodes, where you can get your field data from like it were a usual node, just do something like this:

```
foreach ($nodes AS $nid => $node) {
  print $node->body['und']['value'];
}

```

***Note**. I used 'und' for language here. You may want to query for node language field here to get a dynamic language data if needed.*

So this should work.

**UPD**. One note to this. field\_attach\_load() doesn't invoke hook\_node\_load(), so if some data is being manipulated via hook\_node\_load() you won't get its representation via described method. This is the only drawback of this method. But in most cases it is safe to use. Just check if it works in your circumstances.

# Answer
> 2 votes
If I were only interested in one or two fields, I would use `db_select()`, as in the following code.

```
$result = db_select('node', 'n')
  ->fields('n', array('title', 'body'))
  ->condition('type', 'wall_of_words' ,'=')
  ->condition('status', 1 ,'=')
  ->execute()
  ->fetchAssoc();

```

However, I tend to design with future modifications in mind. I think that using an EFQ to do the query and then using `entity_metadata_wrapper()` to extract the fields makes the code more readable and changeable in the future. Unless this causes large performance impacts, this is a big benefit to me.

---
Tags: entities
---


# Question
Title: Uploading from within fieldset using drupal 6 forms API not working
I've got a drupal form with a fieldset (actually, two). Inside the fieldset, there are a number of dynamically generated file fields. Unfortunately, I can't seem to access these fields' contents from file\_save\_upload. Currently, I'm attempting to use the approach described here to set the #name property of my file fields so that the files array gets built correctly. However, file\_save\_upload always returns 0. What am I doing wrong?

Form (this is an example, since the actual form is dynamically generated by a bunch of code that isn't relevant here):

```
$form['release_data_graphics'] = array(              //This has a few other random things in it
    '#type' => 'fieldset',
    '#title' => 'Brand Release Graphics',
    '#collapsed' => FALSE,
    '#collapsible' => TRUE,
    '#weight' => 11,
);
$form['release_data_graphics']['graphics'] = array(  //This has a few other random things in it
    'folders' => array(                              //This is here because I iterate through it
        'folder1' => array(
            '#type' => 'fieldset',
            '#name' => 'Folder 1',
            '#description' => 'some description',
            'graphics' => array(                     //This is here because I iterate through it
                'graphic1' => array(
                    '#type' => 'file',
                    '#title' => 'Upload graphic 1',
                    '#name' => 'files[1]',
                ),
                'graphic2' => array(
                    '#type' => 'file',
                    '#title' => 'Upload graphic 2',
                    '#name' => 'files[2]',
                ),
            ),
        ),
    ),
);

```

Then, in my submit handler, I iterate through the folders and child graphics arrays (which I won't show here) with file\_save\_upload. My code ends up running file\_save\_upload like this:

```
graphic1 = file_save_upload('1', file_directory_path(), FILE_EXISTS_REPLACE);
graphic2 = file_save_upload('2', file_directory_path(), FILE_EXISTS_REPLACE);

```

When I select a few items for upload and then print the files table in the submit callback, the files table looks good:

```
[files] => Array(
    [1] => test1.png
    [2] => test2.png
);

```

So I'm really having trouble figuring out what's going on...

# Answer
> 1 votes
Add this to beginning of your form

You need this:

```
$form['#attributes'] = array('enctype' => 'multipart/form-data');

```

Also:

```
file_save_upload($source, $validators = array(), $dest = FALSE, $replace = FILE_EXISTS_RENAME)

```

you have

```
graphic1 = file_save_upload('graphic1', file_directory_path(), FILE_EXISTS_REPLACE);

```

you should have

```
$graphic1 = file_save_upload('graphic1',,file_directory_path(), FILE_EXISTS_REPLACE);

```

One thing I've noticed in D6 with file uploads is that using only file\_save\_upload() will result in your file being purged on a subsequent drupal cron run. This happens because all files are uploaded in Drupal with a status of 0.

Therefore, you should be calling your hook\_submit more like this...

```
// Save new file uploads.
if ($file = file_save_upload('file_upload', $validators, file_directory_path())) {

// Do something with $file here.

//Make file permanent
file_set_status($file, FILE_STATUS_PERMANENT);
}

```

# Answer
> 1 votes
There is a known bug when file upload inputs are used inside fieldset in the Drupal 6 API. See these for more info:

structure of $\_FILES when more than one file input is used:

---
Tags: forms, files
---


# Question
Title: how to link a select field options with the database records
i am doing some experiments within my custom form and that is to display a table record from database only corresponding to the product code (i.e sku) is selected from the select list. The database has following structure:

```
nid | sku | orderin | orderout | created

```

I want to link the sku in select list and the sku in database table so that when i select a sku then data corresponding to that sku should only display. Below is what I have done so far.

## Query for the select list

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

  // The form we are building
  $form = array();

 $result = db_query("SELECT o.nid, o.sku FROM {formmodule_order} o ");

    $options = array();
   foreach($result as $row) {
      $options[$row->nid] = $row->sku;

    }

```

## Query for record display

```
 $query = db_select('formmodule_order', 'h')
   ->fields('h',array('nid','sku','orderIn','orderOut','created'))
   ->orderBy('h.nid', 'ASC')
   ->condition('$options[$row->nid]', array('pen-11'));

    $result = $query->execute();

```

# Answer
Check out the Form API reference, especially the part about select lists:

```
<?php
   $form['selected'] = array(
       '#type' => 'select',
       '#title' => t('Selected'),
       '#options' => array(
          0 => t('No'),
         1 => t('Yes'),
       ),
       '#default_value' => $category['selected'],
       '#description' => t('Set this to <em>Yes</em> if you would like this category to be selected by default.'),
   );
?>

```

You can also consult the examples module for more information.
> 1 votes

---
Tags: forms
---


# Question
Title: Disable email alerts when modules are out of date
How can I disable Drupal's email alerts when modules or core are out of date?

# Answer
> 1 votes
Go to http://mysite.com/admin/reports/updates/settings, and remove all the email addresses from the *E-mail addresses to notify when updates are available* textarea:

Just to highlight the pertinent of the description on that field:

> If blank, no emails will be sent.

---
Tags: updating
---


# Question
Title: Add custom class to link outputted by views
I'm using views to output a link. The user gets two fields in which to add the href and the text on the link. I wan't them to be able to put a class on the link as well. How can I do this?

In views I have set a fixed class to all those links, but I wan't to be able to add another class if I wan't to, from the backend.

# Answer
> 6 votes
You can do this on the server side with a Views field `tpl.php` file, or on the client side with jQuery.

---

**For the server side method**, go to your `view edit -> Advaced -> Theme:Information -> chose your field` you need to create a one template file (in your theme/templates folder):

For example: if your field name is title you will see something similar to this:

```
Field Content: Title (ID: title): - click on it and cope the code

views-view-field--YOURVIEWNAME--page--title.tpl.php -paste it here

```

Now you have 3 variables to play with

```
 * - $field: The field handler object that can process the input
 * - $row: The raw SQL result that can be used
 * - $output: The processed output that will normally be used.

```

Easy way - do it with `str_replace` function :D

```
<?php $output = str_replace('<a', '<a class="someclass"', $output); ?>
<?php  print $output; ?>

```

Also you can play around with`($row)` and create your own output. To easy development install devel module so you can `dpm($row)` and see what it contains. or you can `print_r($row)`. have fun \<3

---

**Fastest way to do this with jQuery** you can simple add class to your `fields` `anchor` tag.

```
$(document).ready(function() {
    $('.your-views-class-name .your-view-field a').addClass('someclass');
}

```

open firebug(int firefox) and find your view class name and field class name which contains `anchor tag` and add class to it. You can do this in YOURTHEME - scripts.js or any other js file you want.

---
Tags: views, navigation
---


# Question
Title: Filter to display articles from the last edition date only
I have a magazine type project but articles are grouped into editions(issues). So I have 2 content-types interconnected using node reference.

What I need is to create a view to display only the articles of the last edition on frontpage. I can use a criteria of edition date or edition number (need the last one). Unfortunately I cannot find how to do do it. What value of the operator to enter.

# Answer
What if you filter by **Edition Date**, order it by descending, and display only first value?

It should give you the last available edition, if I'm not mistaken.
> 1 votes

# Answer
just enter the date as the value. If you are not sure about the format just add the "field\_date" to show on the screen and copy and paste the date you want to filter by.
> 0 votes

---
Tags: 7, views
---


title: Form - Submit hidden field (select)

text:
# Question
Title: Form - Submit hidden field (select)
Should be pretty straightforward but I am kinda stuck. I am prepopulating a mandatory field's value according to the URL, so I want to prevent the field from showing up, but not in a CSS level.

hide() and #access do not seem to submit the field leading to a validation error. Any clues on how would I go about doing this?

P.S. not a field of #type =\> hidden. An actual field. A select list if you want.

Comment trail clarifications:
1) the field is an entity field, a user field
2) the field is mandatory
3) the field is prepopulated using #value and #default\_value (for safety (?))
4) the field should not be either visible or editable
5) I'd like to avoid adding a hidden and/or value field myself and write another submission/validation function since the user\_register one works just fine. I want to use the value that the field has upon the form's rendering taking into consideration point 4.

# Answer
> 1 votes
Since Drupal 7, Field API is in core so you don't have to worry about Fields when editing a node form. In Drupal 6, you have to add an `#after_build` function to do this.

You need to create a `hook_form_alter` function to alter the `user_register_form`. (or `hook_form_FORM_ID_alter`).

I can't remember the structure of form fields. Install devel module and you can see the entire `$form` array nicely.

```
 <?php
    function mymodule_form_user_register_form_alter(&$form, &$form_state) {
      dpm($form); // Make sure you have Devel module installed.
      $field_name = 'field_myfield';
      $value = $_GET['somekey']; // populate this var from the URL params as you mentioned in your question.

      if (isset($form[$field_name][LANGUAGE_NONE][0])) {
        if (empty($value)) {
          $form['#access'] = FALSE;
          drupal_set_message(t('Please use correct URL'), 'warning'); // in case the value is not set, hide the form and issue a warning.
          return;
        }
        // #options is an array like this: array('key' => 'value', 'key2' => 'value2');
        // Make sure you set the key of this array in $value. if your $value is a value, you'll need to array_flip and find the key instead.
        $form[$field_name][LANGUAGE_NONE][0]['#type'] = 'value'; // this element will not be rendered at all
        $form[$field_name][LANGUAGE_NONE][0]['#value'] = $value; // this value will be passed to $form_state['values']
      }
    }

```

Calling the form using `drupal_get_form` DOES fire all form\_alters as necessary. If you are trying to use this form with a direct menu router, set `page callback` in the menu router item to `drupal_get_form` and `array('user_register_form'),` as the `page arguments`

# Answer
> 0 votes
For some bizzare reason, both

```
  $form['field_fieldname'][LANGUAGE_NONE]['#disabled'] = true;
  $form['field_fieldname'][LANGUAGE_NONE]['#type'] = 'value';

```

needed to be done, both in the hook\_form\_alter.

Doing the same work within the page callback:

```
$form = drupal_get_form('form_id');
//same thing
$form['field_fieldname'][LANGUAGE_NONE]['#disabled'] = true;
$form['field_fieldname'][LANGUAGE_NONE]['#type'] = 'value';
return $form;

```

Does not work. The field is a select list.

---
Tags: 7, forms
---


# Question
Title: In Views, how to wrap a div around every specified number of items
I'm using D7, Views 3, and am playing around with using jQuery Cycle. What I would like to do is amend my view output so it's like in this example from the jQuery Cycle website:

```
    <div style="margin:auto;text-align:center"><div id="nav"></div></div>
<div class="slideshow">
    <div class="slide">
        <img src="http://jquery.malsup.com/cycle/images/beach1.jpg" width="200" height="200" />
        <img src="http://jquery.malsup.com/cycle/images/beach2.jpg" width="200" height="200" />
        <img src="http://jquery.malsup.com/cycle/images/beach3.jpg" width="200" height="200" />
    </div>
    <div class="slide">
        <img src="http://jquery.malsup.com/cycle/images/beach4.jpg" width="200" height="200" />
        <img src="http://jquery.malsup.com/cycle/images/beach5.jpg" width="200" height="200" />
        <img src="http://jquery.malsup.com/cycle/images/beach6.jpg" width="200" height="200" />
    </div>
    <div class="slide">
        <img src="http://jquery.malsup.com/cycle/images/beach7.jpg" width="200" height="200" />
        <img src="http://jquery.malsup.com/cycle/images/beach8.jpg" width="200" height="200" />
        <img src="http://jquery.malsup.com/cycle/images/beach9.jpg" width="200" height="200" />
    </div>
</div>

```

I was hoping to use Semantic Views for this but I'm stuck on how to wrap the div class "slide" around every 3 items. Is it possible to do this? I only seem to be able to apply a div to every item and then apply the class to every 3rd item. Any help/guidance/tips much appreciated.

# Answer
> 4 votes
In the View, there is a **Theme: Information** Link under the **Advanced Tab**. There you can theme your view with template files the way you like.

# Answer
> 2 votes
Take the html list template and change the views-view-list.tpl.php. Check the theme information to see the names you can give.

```
<?php
/**
 * @file views-view-list.tpl.php
 * Default simple view template to display a list of rows.
 *
 * - $title : The title of this group of rows.  May be empty.
 * - $options['type'] will either be ul or ol.
 * @ingroup views_templates
 */
?>
<?php print $wrapper_prefix; ?>
  <?php if (!empty($title)) : ?>
    <h3><?php print $title; ?></h3>
  <?php endif; ?>
  <?php print $list_type_prefix; ?>
    <?php foreach ($rows as $id => $row): ?>
      <?php if($id % 3 == 0){ print '<div class="row">'; } ?>
      <li class="<?php print $classes_array[$id]; ?>"><?php print $row; ?></li>
      <?php if($id % 3 == 2){ print '</div>'; } ?>
    <?php endforeach; ?>
  <?php print $list_type_suffix; ?>
<?php print $wrapper_suffix; ?>

```

# Answer
> 1 votes
The simplest way to do this is have a node with an image field that only allows for three 3 images.

In views you can add that field and specify "Display all values in the same row" and each node will display all of it's images in one row. This will allow you to add the class "slide" to each row and "slideshow" to the div surrounding the view.

If you want to do this with one node per image you will need to create your own row template and own preprocess function for that template. In the preprocess function you can loop through the fields (which will contain one image per row) creating a multidimensional array that contains 3 values for each key. In the template you can loop through those values adding 3 images inside each "slide" div.

# Answer
> 0 votes
Be sure to look at the Views Column Class module.

---
Tags: views, blocks, javascript
---


title: Rearrange Date input field rendering

text:
# Question
Title: Rearrange Date input field rendering
In a function that is a response to a drupal\_get\_form() I am constructing a form that includes a date field

```
$form['dob'] = array(
    '#type' => 'date',
    '#date_format' => 'm-d-Y',
    '#title' => 'Date of Birth',
    '#required' => TRUE,
);

```

This however displays the the input with year first then month and date. How can I change this to render the month first then day and then year?

# Answer
You need to change `#type` value to `date_select`

So your code should look like this

```
$form['dob'] = array(
    '#type' => 'date_select',
    '#date_format' => 'm-d-Y',
    '#title' => 'Date of Birth',
    '#required' => TRUE,
);

```

If you want text field instead of select dropdown menu you can change `date_select` to `date_text`
> 1 votes

---
Tags: forms, datetime, theming
---


# Question
Title: How to sum vote values from a single field?
I use a single field `Vote Results: Value` (with some relationships and contextual filters) which outputs the amount of votes every node has, in a list, like this:

* 5
* 3
* 4
* 2

However, I want it to look like this:

* 14

I tried to use the aggregation SUM on the field, but it didn't change.

# Answer
> 1 votes
Solved it by removing the sort criteria. Stupid mistake... :)

---
Tags: 7, views
---


# Question
Title: Fieldsets 'IF ELSE' based on checkboxes?
So i have a custom form with 3 fieldsets built from FORM API. each fieldset holds its own "mini" form for users to fill out. what i want is the second 2 fieldsets should not display unless either checkbox 2(fieldset B) is clicked or checkbox 3(fieldset C) is clicked. but fieldset one holds the checkbox field and i have it set up as a #tree

```
$form['Contract'] = array(
 '#theme' => 'form_panel_table',
 '#tree' => TRUE,
 '#title' => t('General Information'),
 '#collapsible' => TRUE, // Added
 '#collapsed' => FALSE,  // Added
);
$form['Contract']['first'] = array(
 '#type' => 'checkboxes',
 '#title' => t('Products applying for:'),
 '#options' => array("Product B", "Product C"),
 '#required' => TRUE, // Added
 );

```

//if statement should hide this part of form unless checkbox above is clicked /\* second fieldset starts here for product B \*/

```
    $form['Contract']['product B'] = array(
     '#theme' => 'form_panel_table',
     '#type' => 'fieldset',
     '#tree' => TRUE,
     '#title' => t('product b'),
     '#collapsible' => TRUE,
     '#collapsed' => TRUE
    );
    $form['Contract']['product B']['first'] = array(
     '#type' => 'textfield',
     '#title' => t('Zip/Postal Code'),
     '#size' => 30,
     '#maxlength' => 6,
    );

```

//one more else if statement for last fieldset should be here? /\* End of product B. Begin product C \*/

```
$form['Contract']['product C'] = array(
 '#type' => 'fieldset',
 '#tree' => TRUE,
 '#theme' => 'form_panel_table',
 '#title' => t('example'),
 '#collapsible' => TRUE,
 '#collapsed' => TRUE
);
$form['Contract']['product C']['first'] = array(
 '#title' => t('example'),
 '#rows' => 39,

```

using php how would i write the if else statement in my custom form(tried it my way didnt show up on my site) in a druapl way?

# Answer
Assuming you are looking for a `#states` based solution, which is new in Drupal 7.

First, note that you cannot use `0` as a key for `#options`. So rewrite your `first` field set as follows:

```
$form['Contract']['first'] = array(
 '#type' => 'checkboxes',
 '#title' => t('Products applying for:'),
 '#options' => array('b' => 'Product B', 'c' => 'Product C'),
 '#required' => TRUE, // Added
 );

```

Now, we hide/show the other fieldsets depending on the above checkboxes' values.

```
$form['Contract']['product B'] = array(
  '#theme' => 'form_panel_table',
  '#type' => 'fieldset',
  '#tree' => TRUE, // not necessary if parent element has #tree = TRUE.
  '#title' => t('product b'),
  '#collapsible' => TRUE,
  '#collapsed' => TRUE
  '#states' => array(
      'visible' => array(
        ':input[name="first[b]"]' => array('checked' => TRUE),
      ),
    ),
);

```

Likewise,

```
$form['Contract']['product C'] = array(
  '#type' => 'fieldset',
  '#tree' => TRUE,
  '#theme' => 'form_panel_table',
  '#title' => t('example'),
  '#collapsible' => TRUE,
  '#collapsed' => TRUE,
  '#states' => array(
    'visible' => array(
      ':input[name="first[c]"]' => array('checked' => TRUE),
    ),
  ),
);

```

What we are doing exactly is that we ask the Form API to generate necessary jQuery code that it should only show the field set in question only if the input tag (it's a specially jQuery selector that selects input, textarea, select, etc tags at once) with name "first" and its value `c`/`b` is checked. These 2 visibility settings are individual so there is no `else if` concept here.

Also note that `#tree` has nothing to do with the form's settings. if the code above didn't work, try setting if off. When you have `#tree`, `name` attribute of input fields get changed so PHP can build an array of submitted information. There is nothing to do with the visibility settings (except it can make our visibility rule never become true)
> 3 votes

---
Tags: forms
---


# Question
Title: How can I send email to user that is not logged in since 30 days?
I am using Drupal 7, and I want to send email to registered users who have not logged in to the site since 30 days; for example, an email saying:

> Hello user, you are not login since 30 days.

Is there any way?

# Answer
You can use the Rules module to do this.

Make a rule that that is triggered when a user logs in. Make this rule schedule sending this e-mail in 30 days. Let the identifier of the task be something like `30-days reminder for [account:uid]`. This way, if the user logs in within the next 30 days, the scheduled task will be overwritten - pushing the 30 days e-mail.

Make sure to activate the Rules Scheduler module.
> 8 votes

# Answer
Take a look at the User Stats module, it might be something that could work for you. From the module's project page:

> Provides commonly requested user statistics for themers, IP address tracking and Views integration. Statistics are:
>
> * Days registered
> * Join date Days since last login
> * Days since last post

etc and then, you can use cronjob to send email.
> 1 votes

# Answer
You can try the *Inactive user* module:

**Inactive user**
http://drupal.org/project/inactive\_user

> The inactive\_user module provides Drupal administrators with a way to automatically manage inactive user accounts. This module has two goals: to help keep users coming back to your site by reminding them when they've been away for a configurable period of time, and to cleanup unused accounts.
> 0 votes

# Answer
Another way would be to implement hook\_cron. like this:

```
function yourmodulename_cron() {
  $users = database query to get users that have not logged on in the last 30 days
  $queue = DrupalQueue::get('send_maillast30days');
  foreach ($users as $user) {
    $queue->createItem($user);
  }
}

```

Also you will have to implement a queue using hook\_cron\_queue\_info as shown here:

```
function yourmodulename_cron_queue_info() {
  $queues['send_maillast30days'] = array(
    'worker callback' => 'yourmodulename_send_email30days',
    'time' => 60,
  );
  return $queues;
}

```

you will also have to implement "yourmodulename\_send\_email30days" function: i.e

```
function yourmodulename_send_email30days($user) {
  //use drupal_mail function to send the mail (see http://api.drupal.org/api/drupal/includes%21mail.inc/function/drupal_mail/7)
}

```
> 0 votes

---
Tags: 7, emails
---


# Question
Title: How to override the widget of an exposed form filter?
I have a view with a single filter criteria (let's call it *category*) exposed to the user. The user can also select multiple *categories* in for this view (standard view stuff).

The *category* selection filter is rendered to the user in a big `<select>` for element. **For aesthetic reasons, this is undesirable**.

What I'm trying to do is override the display of the widget that renders out the `<select>` element. I've copied my `/sites/all/modules/view/themes/views-exposed-form.php.tpl` to my theme's folder, however, the widget itself (which contains the `<select>` form control I want to change to something else) is simply rendered by `$widget->widget;`

How can I change how the widget renders the multiple *categories* selection filter in the view?

**Edit**, for more info and clarity: This question deals with styling a widget, which is not quite what I want to do. I want to change the markup that renders the widget.

**Another edit (after answering my own question):** Turns out *widget* is not quite the correct Drupal terminology to use here for the exposed form filter.

# Answer
Ok, so after spending a day digging around the net, it seems that there are two ways to do this.

First off, for clarification, the exposed filter from the view **is not a widget**, at least in the Drupal sense of the word. In the traditional Drupal sense of the word, a widget is something used on an **edit** form or **add** form. Hooks like `hook_field_widget_alter()` and it's brethren operate on these widgets.

Just because the `views-exposed-form.php.tpl` has `$widget` as a variable, THAT DOES NOT MAKE IT A WIDGET!!!

Now that that confusion is out of the way, there are two ways to change the exposed filter.

1. Add a custom module and use `hook_form_alter` to change things about the exposed filter form. I got as far as creating a custom module (called *bypass*) and creating a hook to display some simple debugging info:

```
function bypass_form_alter(&$form, &$form_state, $form_id){
    dsm($form_id);
    dsm($form);
}

```

when I discovered the Better Exposed Filters module.

2. Use the Better Exposed Filters module to display the filters as checkboxes, radio buttons, etc. and style those.

Option 2 is what I'm doing now. Hope this helps someone :)
> 7 votes

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


# Question
Title: Remove module dependency in multi-site D7 setup?
In sites/all/modules, I have video module 7.x-2.2 installed. Within my sub-site in a single-core, multi-site setup, I have video module 7.x-2.7 installed. When I try to disable and remove the local video module (7.x-2.7) - for a lack of words, it wont' let me, nor default back to the sites/all/modules/video module. I get wsod, database errors, and funky behavior. How would I remove my subsites manual dependency on its local module? Is my last resort to go into the database? Thanks,

# Answer
Try this. Without disabling the module, remove the code for your local video module, leaving the code you want in sites/all/modules. Next, run `drush registry-rebuild` followed by `drush updatedb`. See: http://drupal.org/project/registry\_rebuild

IMPORTANT NOTE: Your globally installed video module is 7.x-2.2, but your local module is 7.x-2.7. You can't go backwards in version numbers in Drupal, so you'll have to upgrade your global video module to 7.x-2.7 and run updatedb on all other sites that use it before following the instructions above. If you can't upgrade the global module, you'll have to keep them separate until you can.
> 1 votes

---
Tags: 7, multi-sites, files
---


# Question
Title: Adding a target='blank' attribute in D7 module for Nice Menus
I'm trying to add a `target=_blank` to all of the menu items inside Nice Menus. Has anyone ever figured this out?

I suspect that it's like adding title tag but I'm unsure.

# Answer
Consider using the menu attributes module to add additional attributes with your particular menu item:

> This simple module allows you to specify some additional attributes for menu items such as id, name, class, style, and rel.

Unfortunately, I'm not sure if it integrates with nice menu. You'll have to give it a try nonetheless.
> 1 votes

---
Tags: routes
---