# Question
Title: Migrating Users from Older Versions of Drupal
I'm part of a team that's going to be migrating several older Drupal sites (Drupal 5, Drupal 6) into a new, single Drupal 7 site. I'm familiar with Drupal from a software architecture point of view, but not as familiar with the day to day running of a Drupal site as I'd like. Because of this I have a few general questions about this migration.

Are Drupal's password hashing mechanisms consistent across different versions?

If not, are there tools to support migrating user accounts and converting the passwords between versions?

If a no to migrations, are there modules that provide a standard experience for this situation that allows an old user to pick a new password?

# Answer
> 1 votes
**Are Drupal's password hashing mechanisms consistent across different versions?**

No, D7 and D8 use SHA512 with a salt. Drupal 6 uses MD5 without a salt.

**If not, are there tools to support migrating user accounts and converting the passwords between versions?**

Yes you can just rehash them.

**If a no to migrations, are there modules that provide a standard experience for this situation that allows an old user to pick a new password?**

Yes there is a really simple way (one example is). Make sure you **BACKUP** before you do anything. If this does not work for you, google how to convert drupal 6 passwords to drupal 7. There is a ton of different ways.

```
<?php
        require_once DRUPAL_ROOT . '/' . variable_get('password_inc', 'includes/password.inc');
        $res = db_query('select * from drupal.users');

        if($res) {
                foreach ($res as $result) {
                        $hashed_pass = user_hash_password($result->pass, 11);
                        if ($hashed_pass) {
                          $hashed_pass  = 'U' . $hashed_pass;
                          db_update('users')->fields(array('pass' => $hashed_pass))->condition('uid', $result->uid)->execute();
                        }
                }
        }

```

---
Tags: 7, users
---


title: Move views pager into row data?

text:
# Question
Title: Move views pager into row data?
I'm working with Drupal 7 and Views 3 to build a simple video player. The view is fields-based, and is set to display one result (video) at a time. I'd like to provide a "Next" link as shown in the attached image, to allow navigation to the next video. Ideally, the Next link would be available in the row with the other field data.

Normally, pager info is at the bottom of a view. I could use CSS and absolute positioning to move the Next link, but the site is responsive, so it would be a lot cleaner to have the Next link appear with other field data.

Is there a straightforward way to do this?

# Answer
You best bet is to write a small JS script where it will clone the pager's element content into an empty element within that field.

1. Rewrite the field you wish to insert the pager into. Add a span element or whatever you choose.
2. Write a small js script to copy one elemen'ts content to another. Use this as an example: https://stackoverflow.com/questions/3475727/how-to-copy-text-from-one-div-to-another-in-javascript
> 0 votes

# Answer
In the end, this is what I did:

1. Installed views simple pager (https://drupal.org/project/views\_simple\_pager)
2. Configured a simple prev / next pager that displays 1 item only
3. Used CSS to absolutely position prev and next links (with background images as arrows) on either side of the video

This seems to work fine for my use case.
> 0 votes

---
Tags: views, paging
---


# Question
Title: How to change template file name and destination for some blocks?
For example: I want to change default login block template.

My current template file is — /sites/all/themes/{theme\_name}/templates/block--user--login.tpl.php

But I want — /sites/all/themes/{theme\_name}/templates/**system\_blocks/login-block.tpl.php**

How can I do that?

# Answer
Check out template\_preprocess\_block. You can do this with the following code in your theme's `template.php` file:

```
function MYTHEME_preprocess_block(&$variables) {
  // Perform a check based on any parameter, e.g. block ID.
  if ($variables['block_html_id'] == 'block-system-main') {
    // This will lookup for block--system-main-block.tpl.php file in your
    // theme.
    $variables['theme_hook_suggestions'] = 'block__system_main_block';
  }
}

```

However, Drupal already looks for various template names, before it settles down for the default `block.tpl.php`. Here is the list:

1. block--block--\[block-id\].tpl.php
2. block--\[module\]--\[delta\].tpl.php
3. block--\[module\].tpl.php
4. block--\[region\].tpl.php
5. block.tpl.php

See this page for more information.
> 1 votes

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


title: The curious case of a Drupal Button

text:
# Question
Title: The curious case of a Drupal Button
The code below is used to get the word count of a field (field\_body) using ajax callback. It works great and everything functions as it should, well almost. For some reason, the click of a button is also calling the default node form submit action.

So what happens is after I update count, and suppose I don't save the content. In fact, just go to another page or refresh the page, I get something like Categories is required Tags is required Thumbnail is required....

Basically whatever I would get on form validation. It's just that the result is delayed as I am using ajax.

The problem is not with ajax, because even I comment the callback, and I click the button it tries to submit the form, when clearly it should not as executes submit callback is False.

```
function hook_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'article_node_form' || $form_id == 'q_and_a_node_form' ) {

    $form['get_word_count'] = array(
     '#type' => 'button',
     '#value' => t('Update Count'),
     '#weight' => 5,
     '#executes_submit_callback' => FALSE,
     '#ajax' => array(
      'callback' => 'count_words',
      ),
    );

    $form['body_words'] = array(
     '#title' => t('Words in Body'),
     '#type' => 'textfield',
     '#disabled' => TRUE,
     '#weight' => 5,
     '#prefix' => '<div id="replace_body_words">',
     '#suffix' => '</div>',
    );
   $form['field_length_type']['#prefix'] = '<div id="replace_field_length_type">';
    $form['field_length_type']['#suffix'] = '</div>';
  }
}

function count_words($form, $form_state) {
  $str = $form['field_body']['und'][0]['value']['#value'];
  $count = preg_match_all("/\S+/", preg_replace('/(' . chr(160) .'| )/', ' ', strip_tags(str_replace('><', '> <', trim($str)))), $matches);
  $form['body_words']['#value'] = $count;
  if ($count < 500) {
    $form['field_length_type']['und']['#value'] = "short";
  }
  else if ($count > 500 && $count < 800 ) {
    $form['field_length_type']['und']['#value'] = "medium";
  }
  else {
    $form['field_length_type']['und']['#value'] = "long";
  }
  return array(
    '#type' => 'ajax',
    '#commands' => array(
      ajax_command_replace("#replace_body_words", $form['body_words']),
      ajax_command_replace("#replace_field_length_type", $form['field_length_type'])
     )
   );
 }
}

```

Any help would be much appreciated. *Any workaround?*

# Answer
When using the `#type => 'button'` the submit callback is never executed, it already receives a `FALSE` as default value.

Even if the `submit` callback is not executed, the `validate` callback is always executed (even on ajax posts). You can bypass this validation on a trigger element by using the `#limit_validation_errors` property.

In your case, you can set it on the `body_words` form element to only validate on this scope instead of the whole form.

```
$form['get_word_count'] = array(
    '#type' => 'button',
    '#value' => t('Update Count'),
    '#weight' => 5,
    '#limit_validation_errors' => array(
        array('body_words'),
    ),
    '#ajax' => array(
        'callback' => 'count_words',
    ),
);

```
> 4 votes

---
Tags: ajax, forms
---


# Question
Title: Retrofitting CSS media queries into an existing project
I've inherited a Drupal 6 project with a custom theme based off fusion. I would like to keep the current design for screen sizes above 800. Should I wrap existing CSS in `@media screen and (min-width:800px)`? Or, might I be able to use a "reset" technique under another media query?

How would you retro fit media queries into an existing site?

# Answer
Got it. Basically we're moving `['all']` to `['(min-width: 720px)']` in the array structure. When it's loaded back in *all* of the stylesheets are effectively now wrapped into a media query.

```
function hook_preprocess_page(&$vars) {
  // get style sheet array
  $css = $vars['css'];

  // copy over the [all] to a media query key
  $css['(min-width: 720px)'] = $css['all'];

  // Remove the all
  unset($css['all']);

  $vars['styles'] = drupal_get_css($css);
 }

```

This leaves us the ability to define other style sheets in `theme.info` for other breakpoints.

```
stylesheets['(max-width: 480px)'][] = phone.css

```

Update, I turned this into a larger structure to let my content maintainers pick where the breakpoint should be.

A small idea for an add-on. I had an issue with a recent Drupal 6 site that I was trying to make responsive. I got tired of trying to override CSS from various areas so I wrote the following hook\_preprocess\_page to move stylesheets from \[all\] and move them to a logical break point. By doing this I can retro fit a mobile stylesheet into

A small idea for an add-on. I had an issue with a recent Drupal 6 site that I was trying to make responsive. I got tired of trying to override CSS from various areas so I wrote the following hook\_preprocess\_page to move stylesheets from \[all\] and move them to a logical break point. By doing this I can retro fit a mobile stylesheet into

```
/*
 * Implemntation of hook_preprocess_page
 *
 * Takes CSS files from the $vars['css']['all'] and moves them to $vars['css'][$breakpoint]. In effect, this moves all
 * existing stylesheets into a media query that you can specifiy. By default it's 480px.
 */
function wrapcss_preprocess_page(&$vars) {

  $css          = $vars['css'];
  $pixel_break  = (int) variable_get('wrapcss_breakpoint', '480');

  // Ensure that we have a value and that value is numeric
  if (isset($pixel_break) && is_numeric($pixel_break))
  {
    $breakpoint   = '(min-width: ' . $pixel_break . 'px)';
  }
  // If not, just default to 480
  else
  {
    $breakpoint   = '(min-width: 480px)';
  }

  // copy [all] to [breakpoint]
  $css["$breakpoint"] = $css['all'];

  // Remove stylesheets from [all]
  unset($css['all']);

  // Import back in
  $vars['styles'] = drupal_get_css($css);
}

```
> 0 votes

---
Tags: 6, theming
---


# Question
Title: Access $display_submitted in page template
Is there a way to access a node's $display\_submitted Boolean value from within a page.tpl.php?

# Answer
While normally done in `node.tpl.php`, if the page is a node view page, the `$node` variable is also available in `page.tpl.php`

You can then use something like:

```
if (isset($node)) {
  // Check if display submitted variable is set for this node type
  if (variable_get('node_submitted_'. $node->type, 0)) {
    // Do stuff
  }
}

```

An alternative approach would be adding the required logic instead to an implementation of

`hook_preprocess_page`

*Bonus update*: You can see the `$node` variable added to `page.tpl.php` in core `template_preprocess_page`

```
if ($node = menu_get_object()) {
  $variables['node'] = $node;
}

```
> 1 votes

---
Tags: theming
---


title: show a div before the title

text:
# Question
Title: show a div before the title
I'm using an accordion list. In my file views-views-accordion.tpl.php want to print a div before the title of each article. I'm using the latest version of drupal and views. Any idea?

# Answer
> 0 votes
You have many ways of achieving this:

1. You can either preprocess it inside template.php file. The title has a #prefix and a #suffix theme key when preprocessing it with hook\_preprocess\_node().
2. Install delta blocks and turn convert the page into block and place the block accordingly.

---
Tags: views, theming, navigation
---


# Question
Title: Handling custom parsing and importing with Feeds
I've been wading through the Feeds module and documentation, and for whatever reason have been unable to figure the best way to do this, so I'm hoping someone will be able to point me in the right direction.

I need to get video node information from one D6 site to another. I've set up a feed via Views on the source site, and I want to use Feeds to ingest the info into the target site. There are two custom things I need to do, and I can't figure the best way to do them.

1. There are two taxonomy vocabularies on the source site that I need to get to specific vocabularies on the target site. One is a tags vocabulary, and one is titled Channel (same on both sites). I've added the tid for the target Channel term to the feed as `<channel-map>` and I need to import that value into the assigned Channel term on the target node. The problem is that the core Taxonomy module dumps all taxonomy terms, regardless of vocabulary, into the source feed as `<category>`; the only way to differentiate between vocabs when importing the feed item is to look at the domain attribute, which is the URL for that term. There is a Tags target in the standard feed importer, but I need to filter out the Channel terms, as well as the terms for other vocabs that only exist on the source site.
2. The target site has a custom video formatter that plays the embedded video from the source site when you enter the source site URL into the Video field on the target node in the format http://mysourcesite.com/node/$nid. I've added the source nid to the feed as `<source-nid>`, so I just need to take that value and construct the URL the source site URL is already stored in a variable on the target site as part of the custom formatter settings), and then insert it into the Video field on the new target node.

So what I'm trying to figure out is the best way to handle these instances when importing the feed. It looks like one option is to write a custom parser and/or importer plugin. However, I don't need to rewrite the whole parsing and importing processes; I just need to handle the two cases above. There are already targets defined for the two fields I need to import into, so would it just be a matter of using the `feeds_node_processor_targets_alter()` hook and override the existing node processor? Or would I need to write my own custom plugins?

Thanks.

EDIT: I tried creating my own callback as a wrapper for content\_taxonomy\_feeds\_set\_target() using hook\_feeds\_node\_processor\_targets\_alter(), but by that point in the process, all that is provided is the term name with no additional information to indicate the source vocabulary.

# Answer
I finally got everything to work with some code voodoo and changing parsers. One thing that I didn't add to the original question above as an edit was the fact that using the common syndication parser, my custom items that I added to the source feed were never available. I then switched to using the SimplePie parser, and was able to extend that functionality to do what I need.

According to the Feeds module documentation for developers and this blog post, you can do some custom parsing by overriding the parseExtensions() method of FeedsSimplePieParser class. First, you have to declare the class with hook\_feeds\_plugins():

```
/**
 * Implementation of hook_feeds_plugins().
 */
function mymodule_feeds_plugins() {
  $info = array();

  $info['MyModuleFeedsParser'] = array(
    'name' => 'Custom Parser',
    'description' => 'Custom parser for my video import.',
    'handler' => array(
      'parent' => 'FeedsSimplePieParser',
      'class' => 'MyModuleFeedsParser',
      'file' => 'MyModuleFeedsParser.inc',
      'path' => drupal_get_path('module', 'mymodule') . '/plugins/feeds/',
    ),
  );
  return $info;
}

```

You also want to implement hook\_enable to clear caches.

```
/**
 * Implementation of hook_enable.
 */
function mymodule_enable() {
  //clear the cache to display in Feeds as available plugin.
  cache_clear_all('plugins:feeds:plugins', 'cache');
}

```

Next you create the class.

```
/**
 * Custom Feeds parser class used to parse custom info from source site video feed.
 */

class MyModuleFeedsParser extends FeedsSimplePieParser {
  /**
   * Add the extra mapping sources provided by this parser.
   */
  public function getMappingSources() {
    return parent::getMappingSources() + array(
      'source-nid' => array(
        'name' => t('Video NID - SimplePie'),
        'description' => t('.'),
      ),
      'channel-map' => array(
        'name' => t('Channel Map - SimplePie'),
        'description' => t('Target Channel tid - SimplePie.'),
      ),
    );
  }

  /**
   * Parse the extra mapping sources provided by this parser.
   */
  protected function parseExtensions(&$item, $simplepie_item) {
    if ($value = $simplepie_item->get_item_tags(SIMPLEPIE_NAMESPACE_RSS_20, 'source-nid')) {
      $item['source-nid'] = $value[0]['data'];
    }
    if ($value = $simplepie_item->get_item_tags(SIMPLEPIE_NAMESPACE_RSS_20, 'channel-map')) {
      $item['channel-map'] = $value[0]['data'];
    }
    // Filter out non-Tags terms.
    $categories = $simplepie_item->get_categories();
    // Cycle through the categories and delete any items
    // in feed item that aren't tags. The array id values
    // are synchronized between $categories and $item['tags'].
    foreach($categories as $id => $category) {
      if (!strstr($category->scheme, '/tag/')) {
        unset($item['tags'][$id]);
      }
    }
  }
}

```

This code does a few things:

1. getMappingSources() creates a couple sources that are available for mapping. You set these in your importer settings for your processor.
2. Gets the source-nid value from the feed source and add it to the item.
3. Gets the channel-map value from the feed source and add it to the item.
4. Filters out the non-tags terms from the categories (aka taxonomy terms). The scheme value is the URL to the taxonomy term (e.g. mysite.com/tag/tag-term), so I use that to identify non-tag terms and unset them.

Finally, I have to create the values for the video field and the Channel vocabulary. This is done with some custom callbacks defined in hook\_feeds\_node\_processor\_targets\_alter().

```
/**
 * Implements hook_feeds_node_processor_targets_alter().
 */
function mymodule_feeds_node_processor_targets_alter(&$targets, $entity_type, $bundle_name) {
  $targets['field_source_url'] = array(
    'name' => 'Source Video URL',
    'description' => 'The URL of the source video',
    'callback' => 'mymodule_feeds_set_source_url',
  );

  $targets['channel'] = array(
    'name' => 'Target Channel',
    'description' => 'The target video channel',
    'callback' => 'mymodule_feeds_set_channel_target',
  );
}

```

And the callbacks themselves:

```
/**
 * Custom callback to set the video source URL in field_video.
 *
 * @param $node - The node object being built.
 * @param $target - The target field.
 * @param $value - The field value from the feed.
 */
function mymodule_feeds_set_source_url(&$node, $target, $value) {
  $source_url = variable_get('emvideo_source_domain', '') . '/node/' . $value;
  $node->field_video[0]['embed'] = $source_url;
}

/**
 * Custom callback to set the target vocabulary term.
 *
 * @param $node - The node object being built.
 * @param $target - The target field.
 * @param $value - The field value from the feed.
 */
function mymodule_feeds_set_channel_target(&$node, $target, $value) {
  $term = taxonomy_get_term($value);
  $node->taxonomy[(int)$value] = $term;
}

```

You then define these as targets in your Processor mapping (to coincide with the Source values above), and you're good to go.
> 2 votes

---
Tags: 6, feeds
---


# Question
Title: Displaying static text on a view that disappears after hitting 'Search'?
I have a view with a Search block exposed to users. What I would like to achieve is:

I would like to display a text in the View's body itself under the Search box. This text should disappear once a user enters a term and hit 'Search".

Is this doable? I hope someone can help me out.

Thanks

# Answer
> 1 votes
All you need is Custom Search module.

# Answer
> 0 votes
In Drupal 7 there is an option to do it.

There are two exposed forms. By default basic is selected. there is another option called "input required" You can select that instead of Basic. This will make the result displayed only after entering the data.

You can also input the text that should be displayed before the search is made.

---
Tags: views, search
---


# Question
Title: Create a view based on node reference field
There are two content types Gallery and Image. Image has node reference field (node reference from url). Gallery doesn't have any node reference fields.

By using views I can show all related images on a gallery page (I use node reference field "field\_pers\_gallery" as a contextual filter).

At the same time I need to create a view to show all images related to one gallery (all images have the same value in field field\_pers\_gallery) on a page of every image. I would like to create a view that looks like Flickr image page with related images. I have the problem with it because I cannot choose the right contextual filter to create the view as I want.

I tried the following examples but nothing helped me, I cannot understand why.

Could anybody help me with any advices?

# Answer
I think here is a simple solution just add that the node reference field (field\_pers\_gallery) to contextual filter then all nodes (Images) which have same value in that field can be displayed on a page.
> 2 votes

# Answer
Here is a solution using the Entity Reference module to display other nodes that reference the same node that the current node references. No need for relationships, just follow these steps:

1. Make sure you're filtering the view by the content type you want to view a list of, not the one you're trying to reference.
2. Add a contextual filter using the entity reference field.
3. For the entity reference field, choose to provide a default value in PHP **¹**.
4. Adapt the following code to your field names **²** and save the contextual filter:

$node = menu\_get\_object();
$referenced\_node = $node-\>field\_YOUR\_FIELD\_NAME\['und'\]\[0\]\['target\_id'\];
return $referenced\_node;
5. Save the view and check it out.

**¹Disclaimer:** PHP should never be used in the UI due to concerns with security, performance, & lack of version control. As a result, the *proper* way to implement this solution involves writing your own simple module that creates a block that passes the argument into the view as you render it in the block. I'm still including this because whether people ignore this warning or use it to write a module, hopefully it helped.

**²** Not sure what your field names are? Install and enable the Devel module and visit a node. Click the 'devel' tab and navigate through the list to find your desired entity reference field.
> 0 votes

# Answer
I'm not sure about node reference, but since another answer proposes Entity Reference for the reference field(s) I will piggyback on that suggestion.

With Entity references in place, you'll be able to add "reverse references" within the relationship builder in the Views admin UI. These will read as

> "Entity Reference: **Referencing entity**"

(as opposed to **Referenced entity**)...

Here's what these look like:

It takes a bit of getting used to, maybe some eye strain, to establish the reverse reference you're looking for. Once working, I find it helps to give it a meaningful administrative label, like "Nodes pointing here" or, in your case "Appearing in \[Galleries\]:" or something similar.
> 0 votes

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


# Question
Title: how to render create page form & list of contents in page.tpl.php
I am theming an admin page & I require to load/render admin forms in page.tpl.php file.
The final output should be somehow like the attached screenshot. Scroll below to see screenshot & code written in page.tpl.php.

```
<h1 class="page-title">Admin Page</h1>
<div class="content-left">
  <!--load list of all contents("/admin/content") -->
  <?php print drupal_render(drupal_get_form('node_admin_content')); ?>
</div>
<div class="content-right">
  <!-- add new content form here "/node/add/page") -->
  <?php print drupal_render(drupal_get_form('page_node_form')); ?>
</div>

```

I was searching for this solution & I came across this "print drupal\_render()". Please suggest best solution for this. I have render same kind of pages in other tpl.php files.

# Answer
> 0 votes
It is recommended to render the forms either in preprocess function or in the custom module. Example of rendering the form in preprocess function:

```
function MYTHEME_preprocess_page(&$variables) {
  // Assigning node_admin_content form to the variable.
  $node_admin_content = drupal_render(drupal_get_form('node_admin_content'));
  $variables['node_admin_content'] = $node_admin_content;

  // Assigning page_node_form form to the variable.
  $page_node_form = drupal_render(drupal_get_form('page_node_form'));
  $variables['page_node_form'] = $page_node_form;
}

```

Now to render this form in `page.tpl.php`:

```
<h1 class="page-title">Admin Page</h1>
<div class="content-left">
  <!--load list of all contents("/admin/content") -->
  <?php print $node_admin_content; ?>
</div>
<div class="content-right">
  <!-- add new content form here "/node/add/page") -->
  <?php print $page_node_form; ?>
</div>

```

---
Tags: forms, theming, users
---


# Question
Title: Best practices when choosing a method of displaying content?
This is a little broad, but I have a specific example. I'm new to Drupal, with a WordPress background. I'm getting some of the core Drupal concepts down, but I'm left with some questions.

How do I *know* what method of displaying content is best for a situation? For example, I'm running Ubercart. I would like to display a single featured product on the home page. As far as I'm aware, I can't use a block because I'm not sure if I can pull node data into that. I could hard code it in the template file, maybe? Can I use a view?

Is there somewhere in the documentation where this concept is spelled out?

Thank you for the help.

# Answer
You want to display a single, featured product on the homepage. I would try using Views to create a Block which you can then include in the Content region on the homepage.

In Views, set the criteria, so you're pulling the appropriate content type. Perhaps you have some kind of "featured" or "sticky" flag. Add that to your criteria as well. Then if you want to restrict it further by taxonomy or sort it by most recently added and restrict the view to a single item, you can do that (see Pager settings; click "Display all items" and adjust settings).

Typically, Views is used to create a Page or a Block. Have yours output a block, then at sitedomain.com/admin/structure/block, locate the new Block and add it to the page wherever you want it.
> 0 votes

---
Tags: nodes, theming
---


# Question
Title: Take messages generated by module and print them inside the node teaser?
I have a Pay2Publish module, which gets no support these days, so I have to turn to the community for the help. I guess this is a simple PHP question:

I want to take the messages generated by Pay2Publish module and display them bellow each node teaser.

Here's the code from the module:

```
/**
 * Implements hook_node_view()
 *
 * Displays the Message for the author of a node
 */
function ms_paypublish_node_view($node, $view_mode, $langcode) {
  $plans = variable_get('ms_paypublish_plan_' . $node->type, array());
  $pp_node = ms_paypublish_load_node_nid($node->nid);

  if ($pp_node AND !empty($plans)) {
    if ($view_mode == 'full' AND user_access('renew own pay to publish nodes')) {
      global $user;
      if ($node->uid == $user->uid) {
        switch ($pp_node->status) {
          case 0: // Not Published
            drupal_set_message(
              str_replace(
                '!link',
                l(t('Publish'), 'ms_paypublish/publish/' . $node->nid),
                variable_get('ms_paypublish_not_published_text', 'This content is not published. To publish, please click here: !link')
              )
            );
            break;

          case 1: // Published
            if ($pp_node->expiration_date) {
              drupal_set_message(
                str_replace(
                  array('!days','!link'),
                  array(
                    ms_paypublish_get_expiration_string(ms_paypublish_get_expiration($node->nid)),
                    l(t('Promote / Extend'), 'ms_paypublish/publish/' . $node->nid)
                  ),
                  variable_get('ms_paypublish_published_text', 'This content will expire in !days days. To Promote / Extend, please click here: !link')
                )
              );
            }
            break;

          case 2: // Awaiting Admin Approval
          case 5:
            drupal_set_message(variable_get('ms_paypublish_approval_text', 'This content is Awaiting Admin Approval. It will be published shortly.'));
            break;

          case 3: // Not yet published
            drupal_set_message(str_replace('!link', l(t('Publish'), 'ms_paypublish/publish/' . $node->nid), variable_get('ms_paypublish_publish_text', 'This content has not been published yet. To publish, please click here: !link')));
            break;
        }
      }
    }
  }
}

```

What do I need to put inside my custom node--content-type.tpl.php so that these messages are displayed below each teaser?

# Answer
My suggestion is:

1. Change this line in hook\_node\_view() `if ($view_mode == 'full' AND user_access('renew own pay to publish nodes')) {` and add `$view_mode == 'teaser'` to it. Then you can create a patch and submit to community, if you think that this feature may be needed by other users.
2. You can create a template file for this content type, store the messages in a theme variable and display them in template file, just use `<?php print $VARIBALE_NAME ?>` You also have to write a template preprocess function where you will write code to get message body.

I think second option is the best. The requirement is not generic and changing the module is not right in this case. However, you can search the module's issue queue for this.

References
> 1 votes

---
Tags: theming, status-messages
---


# Question
Title: Creating Nodes Of A Content Type on-the-fly While Creating A Different Content Type
# Exposition

On a Drupal 7 site I have two Content Types with the following fields:

* **Scenes**

1. Scene Name
    2. Starring (Actor's names)
    3. Streaming Link
* **Releases** (DVD Releases)

1. Title
    2. Description
    3. *Starring* (All actor's names from all Scenes referenced)
    4. *Multiple* Scenes (Entity references to the Scene Content Type)

# My Question

Is there a Drupal 7 module or some technique that will allow me to create new Scene nodes on-the-fly *while* in the Create Release (node/add/releases) form?

# Avenues I Have Explored

* Field collection (No way to set Scene Name or Create separate nodes)
* Node Reference + noderefcreate (Creates blank Scene without prompting for the fields)
* Inline References is an abandoned Drupal 6 module that looks like it was meant for using with nodrefcreate to add the other fields like I want.

# The Solution

Thanks to Clive's Answer, I've found Node Connect which is exactly what I needed.

# Answer
If you are able to use the node reference field from the References module instead of the Entity Reference once the Node Reference Create module might be of some help:

> Node Reference Create is an enhancement to the nodereference autocomplete widget that allows users to reference non-existent nodes.
>
> When no matching node is selected, the new nodes are automatically created allowing for a seamless and intuitive user experience that is similar to free tagging.

I think the Contextual Administration module might also be useful too; there's some video documentation under the title of "Automatic Node Reference on Node Create" which will probably interest you the most.

**UPDATE**

You also might want to check out the NodeConnect module, it doesn't append the fields of the referenced node to the original node's edit form but does this instead:

> Node Connect expands the node reference (of the references project) auto-complete field by adding a add new content and edit current content button.
>
> The add a new button will all a new node to be added via a node add form and then return the user to the original form.
>
> The edit button will take the user to the edit form of the referenced node, and return them when they are done editing.
>
> Unlike other module that have provide this functionality this module does not use popups of kind, but caches the original forms when switch to child forms. This allows for multiple levels of adding and editing
> 3 votes

# Answer
It can be accomplished with entityreference \+ Inline Entity Form modules. it will allow to add/edit scene node inside releases add/edit.

Deepak
> 2 votes

# Answer
another methord: references dialog

> This module extends reference fields like the user and node reference fields by adding links to add, edit and search for references through a dialog.
> 1 votes

---
Tags: nodes, entities
---


# Question
Title: Cause for Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException: error
Currently trying to port over a Contrib module and learn the new Drupal 8 architecture.

A google search revealed a possible issue related to this.

The cause could be that there's an underscore in the file name which violates psr-0 naming standards. Looks like i had that before and have renamed it just now and still have that issue after clearing the cache.

What would likely be the cause of the following error?

> Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException: You have requested a non-existent service "\drupal\form\_example\forms\formexampleformone". in Symfony\Component\DependencyInjection\Container-\>get() (line 304 of /home/chris/workspace/d8/core/vendor/symfony/dependency-injection/Symfony/Component/DependencyInjection/Container.php).

The error occurs when i visit `/examples/form_example/tutorial/1`

**form\_example.routing.yml**

```
form_example:
  path: 'examples/form_example'
  defaults:
    # _form: '\Drupal\form_example\Forms\FormExampleForm'
    _content: '\Drupal\form_example\Controller\FormExampleController::description'
  requirements:
    _access: 'TRUE'
form_example_tutorial_1:
  path: 'examples/form_example/tutorial/1'
  defaults:
    _form: '\Drupal\form_example\Forms\FormExampleForm'
  requirements:
    _access: 'TRUE'

```

**form\_example.module**

```
<?php
function form_example_menu() {
//   $items = array();
//   $items['examples/form_example'] = array(
//     'title' => 'Form Example',
//     'route_name' => 'form_example',
//     'access callback' => TRUE,
//     'expanded' => TRUE,
//   );
  $items['examples/form_example/tutorial'] = array(
    'title' => 'Form Tutorial',
    // 'page callback' => 'drupal_get_form',
    'route_name' => array('form_example_tutorial'),
    'access callback' => TRUE,
    'description' => 'A set of ten tutorials',
    // 'file' => 'form_example_tutorial.inc',
    // 'type' => MENU_NORMAL_ITEM,
  );
  $items['examples/form_example/tutorial/1'] = array(
    'title' => '#1',
    // 'page callback' => 'drupal_get_form',
    'route_name' => array('form_example_tutorial_1'),
    'access callback' => TRUE,
    'description' => 'Tutorial 1: Simplest form',
    // 'type' => MENU_DEFAULT_LOCAL_TASK,
    // 'file' => 'form_example_tutorial.inc',
  );
  return $items;
}

```

**/lib/Drupal/form\_example/Forms/FormExampleForm.php**

```
<?php
/**
 * @file
 * Contains \Drupal\form_example\Form\FormExampleForm
 */
namespace Drupal\form_example;

use Drupal\Core\Form\FormInterface;

class FormExampleForm extends FormBase {
// form...
}

```

# Answer
> 2 votes
Looks like the namespace defined in your class file does not match the one you put into the resource, there's a "Form" sub-namespace missing.

Also make sure that the class is placed in the right folder.

The reason for that error is apparently that for *some* reason, the specified class can't be found, so apparently the router then falls back to the service. So the _ thing is just one possible reason.

Also, there are some errors in your hook\_menu(), route\_name is a string, access callback can be removed and you still need the first entry for now so that you have a menu link to it.

---
Tags: 8
---


# Question
Title: How do I send verification mail from my drupal custom module?
I have written a custom module, which can send simple mail. how do I send mail so that user should get the verification link or something similar.

```
<?php
/**
* implements hooks_menu
*/

function planet_extension_menu(){
$items['planetext']=array(
'title' => t('DEMO Planet Extension'),
'description' => 'Feeds aggregation ',
'page callback' => 'drupal_get_form',
'page arguments' => array('planet_extension'),
'access callback' => TRUE,
);
return $items;
}

// callback function
function planet_extension($form,&$form_submit){
$form['url']=array(
'#title' => 'URL',
'#type' => 'textfield',
'#required' => TRUE,
'#size' => 35,
'#description' => t('Enter the URL'),
'#attributes' =>array('placeholder' => t('www.example.com'))
);
$form['title']=array(
'#title' => 'Title',
'#type' => 'textfield',
'#required' => TRUE,
'#size' => 35,
'#description' => t('Enter the Title'),
'#attributes' =>array('placeholder' => t('Title'))
);
$form['email']=array(
'#title' => 'email',
'#type' => 'textfield',
'#required' => TRUE,
'#size' => 35,
'#description' => t('Enter you valid email'),
'#attributes' =>array('placeholder' => t('example@example.com'))
);
$form['submit']=array(
'#type' =>'submit',
'#value' => 'Submit',
);
return $form;
}

// below is the form submission function
function planet_extension_submit($form,$form_state){
//store the values entered in form into variables
$values = array(
'url' => $form_state['values']['url'],
'title' => $form_state['values']['title'],
'email' => $form_state['values']['email'],
);
//insert the variables into the table
$insert = db_insert('planet_extension')
                -> fields(array(
                        'url' => $values['url'],
                        'title' => $values['title'],
                        'email' => $values['email'],
                ))
                ->execute();

drupal_mail('planet_extension', 'planet_extension_mail', $form_state['values']['email'], 'en', array('values' => $values));

        drupal_set_message(t('Form submitted. Check your email for verification')); //custom message after form submission is successful
}

//implements hook_mail
function planet_extension_mail ($key, &$message, $params) {
  switch ($key) {
    case 'planet_extension_mail':
      $message['subject'] = t('Hello');
      $message['body'][] = t('Hello user');
      $message['body'][] = t('The main part of the message.');
      break;
  }
}

```

# Answer
I am not sure about what kind of verification emails you are sending, though I believe if you peep inside drupal core user module you can get hold of function which does the same,as for user registration process we have email verification option also.

A very simple straight custom way might go in the following way

1. How you will be generating the verification code?
    * while sending the email create a link something like www.mydomain.com/email-verification/%random\_string%
2. Create a custom table with column as email,random\_string,verified
3. once you have generated it, make a db query to insert the link you created a point back against the email user entered and set verified to 0 in the custom table.
4. send the email
5. In your custom module implement hook\_menu() with menu entry fir "email-verification" .
6. In the page callback using wild card check if the random\_string exists in you custom table, if so set verified to 1

Not exact but close to what you may need.

**Update:**

```
global $base_url;
$random_string = substr(str_shuffle(md5(time())),0,10);
// Link
$email_link = $base_url . "/email-verification/" . $random_string;

```
> 1 votes

---
Tags: 7, forms, hooks, emails
---


# Question
Title: How to add 'read more' link in Blog comments
I created blog entry pages for different subjects in a website. Each blog page displays its comments. I need to trim the comments and add read more link. I can trim the comments, but can't able to add read more link. I can't create view for the blog pages because different blog pages needs to display differently. Any ideas? Please help me.

# Answer
You can override comments template for your blog content type and in the template add the read more link.

In order to override the template simply copy the existing `comment.tpl.php` to your theme/templates and rename it to `comment--node-blog.tpl.php` and edit it to add the read more link.

on click of this you will be running jquery codes to toggle the comments below.
> 0 votes

---
Tags: comments, nodes
---


# Question
Title: How to correctly check the value of boolean in D7?
I have a boolean single check-box field. and inside my node--content-type.tpl.php Idothe following check:

```
  <?php if($content['field_hide_1st_line_of_the_addre']['und'][0]['value'] == 0): { ?>
    <?php print render($content['field_images']['#object']->field_location['und'][0]['street']) . t(', '); ?>
    <?php } else: { ?>
    <?php print t(''); ?>
    <?php } endif; ?>

```

And it returns loads of "Notice: Undefined index: und in include() (line 80 of node--content-type.tpl.php"

Any idea what is going on?

UPDATE

```
  <?php if (isset($content['field_hide_1st_line_of_the_addre']['und'][0]['value'])): { ?>
    <?php print render($content['field_images']['#object']->field_location['und'][0]['street']) . t(', '); ?>
    <?php } else: { ?>
    <?php print t(''); ?>
    <?php } endif; ?>

```

is not the doing the check correctly: the Street field disappears forallteasers,while it should only disappear for those that have the boolean check-box ticked.

UPDATE 2 This code didn't work either. Pave me a **Parse error: syntax error, unexpected $end**

```
<?php
  if (isset($content['field_hide_1st_line_of_the_addre'][LANGUAGE_NONE][0]['value'])) :
  if($content['field_hide_1st_line_of_the_addre']['und'][0]['value'] == 0): { ;
    print render($content['field_images']['#object']->field_location['und'][0]['street']) . t(', ');
  }  endif;
?>

```

UPDATE 3

I deleted that old field and created a new identical one. Tried many things,but it turns out that for some unknown reason it just didn't like the 0 and preferred 1 instead.So I used 1,and just changed the wording of the field from "Hide full address" to "Display full address". This is the code that worked for me. If you seeany syntax mistakes,pleaselet me know.

```
<?php
    if (isset($content['field_hide_address']['#items'][0]['value'])) :
    if($content['field_hide_address']['#items']['0']['value'] == '1'):
    print render($content['field_images']['#object']->field_location['und'][0]['street']) . t(', ');
    endif;
     endif; ?>

```

# Answer
> 1 votes
The error you're getting simply means that

```
$content['field_hide_1st_line_of_the_addre']['und']

```

hasn't been set. It might be that the 'und' key is missing, or it might be that `$content['field_hide_1st_line_of_the_addre']` simply hasn't been set at all. This can happen if you've added a new field to a content type that already has existing nodes (and probably in other situations too).

To remove the notice, you can just wrap your code in another condition that ensures the array element you're accessing exists. For example:

```
<?php
  if (isset($content['field_hide_1st_line_of_the_addre'][LANGUAGE_NONE][0]['value'])) :
    if ($content['field_hide_1st_line_of_the_addre'][LANGUAGE_NONE][0]['value'] == 0) :
      print render($content['field_images']['#object']->field_location['und'][0]['street']) . t(', ');
    endif;
  endif;
?>

```

I've taken the liberty of replacing 'und' with the constant equivalent (and cleared up a couple of other very minor issues), it's better practice. Even better practice would be to extract this logic out of the template file completely, and instead implement it in a preprocess function.

---
Tags: theming
---


title: Cache not clearing on expiry

text:
# Question
Title: Cache not clearing on expiry
Using the steps explained here: http://www.lullabot.com/blog/article/beginners-guide-caching-data-drupal-7 I'm storing an array with specified expiry time.

But what is happening is that even after expiry of time, the cache\_get is returning the stale cache. Even Cron run is not deleting the cache entry(I've checked the cache\_block table).

This is the code:

```
     $out = &drupal_static(__FUNCTION__);

        if ( !isset($out)) {
            if ( ( $cache = cache_get(__FUNCTION__,'cache_block'))) {
                $out = $cache->data;
                dsm("cache returned");
            } else {

//do something
//...........
  $out = '<ul style="list-style:none;padding-right:20px">' . $out . "</ul>";
            cache_set(__FUNCTION__, $out, 'cache_block', strtotime("23:59:59")+2);
        }//else ends
    }//!isset ends

    return $out;
}//function ends

```

Only cache clear all in the Performance tab is clearing this cache entry in the cache table.

I'm confused how this expired cache will be deleted.

In that article I can read this statement:

> Expired entries will be automatically discarded as they pass that date.

But does not seem to be happening. Also I've verified that "expire" value in the cache table is beyond current time.

I can clear the cache myself but then cache\_get function does not return the "expire" time in the table.

Anything I'm missing here?

# Answer
> 0 votes
As you can see in the documentation:

> $expire: One of the following values:
>
> * **CACHE\_PERMANENT**: Indicates that the item should never be removed unless explicitly told to using cache\_clear\_all() with a cache ID.
> * **CACHE\_TEMPORARY**: Indicates that the item should be removed at the next general cache wipe.
> * **A Unix timestamp**: Indicates that the item should be kept at least until the given time, after which it behaves like CACHE\_TEMPORARY.

Please note - it's not *"at most"*. It's *"at least"*. So your code works just the way it is to be expected. If you want to force-expire it, use `cache_clear_all( __FUNCTION__ , 'cache_block')`, for example in `hook_cron()` or at the beginning of your code.

Also note that it looks like you are re-saving cache at each use. That's not an usual thing, saving data is CPU and HDD expensive. It costs more than not caching at all. So consider only setting cache if it was not found in the first place, and *needs* to be regenerated. If cache is already set, let it expire and don't set it again.

---
Tags: 7, caching
---


# Question
Title: How to make user profiles editable by site administrators
For a site I'm building, Profile2 is not an option because it doesn't play with Pathauto. As an alternative, I want to extend the regular user profiles with a mugshot and a bio text field. I don't want the profile owners to have exclusive editing rights over those two extra fields; site administrators should be able to enter the profiles and edit the image and the text as required. Out of the box, this isn't workable because an administrator would need to override the user's password to make any changes to a profile, thus effectively issuing a new password for every change made. Is there a way to give administrators regular editing access to the profiles?

# Answer
> 1 votes
Yes, you can add the fields to the user entity at

*admin/config/people/accounts/fields*

While I think you can save the account form without updating the user password (don't enter a value for password when saving), if you want to move the password to a separate tab, you can use the module

password\_tab

---
Tags: 7, workflows, nodes, users
---


title: Importing epub as a node

text:
# Question
Title: Importing epub as a node
Is there a module that imports epub book as a node into drupal? Or a way to do something like this by converting epub into something else before?

# Answer
> 1 votes
It's in dev but the Epub module is probably your best starting-point.

> The new epub module for Drupal 7 provides displays for file entity and file fields and enables users to read epub/ibooks files inside their browsers like pdf module.

It doesn't import as a node, but you can take a lot of code from that module to build your own node-import version.

Interestingly, the reverse operation has already been implemented in Epub export, so you might want to have a look at the code for that one too.

---
Tags: 7
---


title: List menu and sub menu

text:
# Question
Title: List menu and sub menu
I have a "Opinions" in my main menu that appears in main menu block in first page. I want to do something that when I click to "Opinion" in goes to a page that has 2 links: "articles" and "others". I mean I click to Opinions and after that I can select articles or other and they go to article page and other page (articles and other are my taxonomy terms)

I don't know what should I do?

# Answer
If your question is not what your title says consider this: Module you need is views module.

1. Create a view of article type and keep the display of your view type as page,this view will list all nodes of article content type.Give page path as "articles" or whatever.
2. Create another view to show taxonomy terms of type all/vocab, this view will also be page display type.Give page path as "show-taxonomies" or whatever.
3. Create a menu block with two menu items "articles" and "others" link them respectively to the views page path you have set.
4. Now put this menu block in main content region with path specified for block display as "opinions".
> 1 votes

---
Tags: routes
---


# Question
Title: How do I alter the title display with hook_user_view?
```
/**
 * Implements hook_user_view().
 */
function my_statistics_user_view($account) {
    $account->content['statistics']['daily_avg'] = array(
        '#type' => 'user_profile_item',
        '#title' => t('Daily average'),
        '#markup' => 'Hello',
        '#attributes' => array('class' => array('daily-avg')),
    );
}

```

The above code renders:

```
Daily average
Hello

```

in a user's account profile. I would like to render it inline, like this:

```
Daily average: Hello

```

How is this done? Thanks.

# Answer
> 1 votes
You don't. To alter display, you have to create or edit `user-profile.tpl.php` file in your theme, or template\_preprocess\_user\_profile() function in `template.php`

# Answer
> 0 votes
You could either theme the form label inline (e.g with CSS), or include the label as part of the markup, for example something like:

```
/**
 * Implements hook_user_view().
 */
function my_statistics_user_view($account) {

  $value = 'Hello'; // for example
  $account->content['statistics']['daily_avg'] = array(
    '#type' => 'user_profile_item',
    '#title' => t('Daily average'),
    '#title_display' => 'invisible',
    '#markup' => t('Daily average: @value', array('@value' => $value)),
    '#attributes' => array('class' => array('daily-avg')),
  );

}

```

# Answer
> -1 votes
I think the simplest way here is just to use drupal\_set\_title:

```
function my_statistics_user_view($account) {
    drupal_set_title('Your desired title here');
}

```

---
Tags: users
---


# Question
Title: 7: How to cache $form[] elements in complex AJAX forms
How is it best to efficently rebuild your form on multiple AJAX requests?

That is how can I cleanly cache individual elements so I don't need to rebuild them?

Using static variables is not an option as they will not persist across form rebuilds. Using $\_SESSION is probably the best, but this needs care as potentially a single session my have to windows open with diffent copies of the form in each one - and $\_SESSION seems generally unclean.

Anyone got any best practices or boiler plates?

Background:
In order to AJAX in "proper" drupal style you need to rebuild the entire form on each AJAX call back. Your AJAx call back then just returns individual elements to replace. This is efficent for http bandwidth, but if the form elements are expensive to build this is potential an unneccessary performance hit.

The answer probably involves using $form\_state somehow...

# Answer
> 3 votes
You need to rebuild whole form, no way around it, but you can store expensive things in Drupal cache. I advise against storing parts of `$form` array if it can be avoided, but using `cache_set()` and `cache_get()` to keep things like options available for select B when there is X in select A, it should work like a charm. And it will work with APC and Memcache modules out of the box.

The key is, of course, careful selection of `$cid` building algorithm.

## $form\_state as cache

`$form_state` is kept in form cache bin, but it is not a "real" cache. Let's look at the definition from Wikipedia:

> In computer science, a cache (/ˈkæʃ/ KASH) is a component that transparently stores data so that future requests for that data can be served faster.

Now, that's pretty much what **`$form_state` is not** \- it is kept to save temporary data that needs to be consistent, and that are never stored anywhere else during form processing. It means that when someone is using APC or Memcache, he needs to take extra care to prevent their "it can be deleted without any reason, for performance purposes" approach from corrupting forms. Most Drupal admins I know simply exclude form cache bin from them. And that is not what you want for your pre-built form parts.

Your pre-built form parts **are** real cache. So you want to keep them in bins that will be treated accordingly, you want to have speed over stability - you can afford additional rebuild once and then more than you can afford slowing down each request by pulling this data from database - slowest cache possible for Drupal.

Second reason not to use it is scope. `$form_state` exists only per one form session. So if user ends filling the form and access it again, `$form_state` is build anew. If hundred of users access he same form at one time, you have a hundred instances of `$form_state`. That's not what you want when your form elements does not depend on the user of your system. By keeping them in separate cache bin, *keyed only by the things they depends on*, you can have one copy, and use it for all hundred of users, every time they need it. It is impossible to loose anything, and you can decrease load (both CPU for generation and space for storage) to minuscule fraction of what it would be, if you would keep it in `$form_state`.

---

Algorithm for using cache (if someone happens to forget, of for newbies reading in future):

1. Check if data is in cache
2. If not, build it and save to the cache
3. Use either data obtained from cache in 1., or built in 2.

---
Tags: 7, forms, ajax, caching
---


# Question
Title: How to setup hook_install to have a geometry field on a POSTGIS database?
From a module, I would like to create a table containing a POSTGIS geometry field. I guess I need to use hook\_install but can't find any definition of a geometry field anywhere. How can I achieve that ?

# Answer
> 0 votes
I have no idea if this will work (don't have a postgis install handy to test), but try

```
$schema['table'] = array(
  'fields' => array(
    'some_geom_field' => array(
      'pgsql_type' => 'geom',
      ...
    ),
  ),
);

```

If that doesn't do it I think you're out of luck using `hook_schema()`, you'll probably need to execute a custom SQL script instead.

---
Tags: 7, installation
---


title: views block display based on url

text:
# Question
Title: views block display based on url
I have a view with exposed filters which only returns results when a filter is applied and it all works fine. I also have a block underneath the view which I only want to show before a filter is applied. I have set the block only to display on a url for example

> /view

which is the path of my view, when you apply filters the url path becomes

> /view?var=arg

at this point I don't want to display the block

# Answer
> 0 votes
Turn on php filter module shipped in core, so to get option to add php codes option to set block visibility at the block configuration.

**Remember** you have to make sure, php code should be appropriate else it will not allow to access the site till you delete the added php codes from database for the block.

Code which might help you

```
<?php
  if ($_GET['q'] == 'view' && count($_GET) == 1) {
    return TRUE;  // block will be shown
  }
  return FALSE;
?>

```

---
Tags: views, blocks, uri
---


title: Unpublished Nodes and Content Access

text:
# Question
Title: Unpublished Nodes and Content Access
I have a view that relies on a specific content type to display images. The Content Type has a Title, a File Field, and a checkbox for show or don't show. The default setting for all nodes created using this Content Type is unpublished, so that users can't randomly access the node ( basically it's a slideshow that displays banner ads, accessing the actual node isn't a bad problem per se ).

This works great. As it turns out I also need a members only section for the site, so I installed Content Access. That works great for restricting access to the nodes I need restricted. However, I discovered that now the unpublished Slideshow nodes don't show.

My question is how to work around this. Will another access module work differently or is this a core feature? Could I write a small module to grant view access to the Slideshow nodes? Or barring all that, is there a module or ( I know it's probably off-topic) an htaccess recipe that would not allow direct viewing of the nodes of a certain type?

# Answer
> 0 votes
I solved this by making the Content Type nodes published again. So in my View I check to see if the checkbox is check AND if the node is Published. The slider works as it should. I was then left with the task of deciding if allowing access to the actual node was desirable. Viewing the direct node in my case was not all that bad, it's not restricted content or anything but I felt it would just be sloppy. So since I had Panels already installed, this solution https://drupal.stackexchange.com/a/19072/12881 worked out great. If someone stumbled upon one of the nodes of that specific Content Type they're just sent to the front page.

---
Tags: 7, users
---


# Question
Title: Drush site-install working with profile_name_install_tasks and forms
**Is there a way to add some arguments to the drush site-install command to set the value of some form fields introduced by a hook\_install\_tasks() in an install profile?**

I tried some arguments variants on: `drush site-install my_profile my_profile_form.my_settings.key=value`

But to no avail.

See Drush output (for the form field 'Featureset')

`WD php: Exception: Featureset field is required. in install_run_task() (line 414 of X/includes/install.core.inc). [error]`

`WD php: Warning: Cannot modify header information - headers already sent by (output started at X/drush/includes/output.inc:38) in drupal_send_headers() (line 1216 of X/includes/bootstrap.inc). [warning]`

`Exception: Featureset field is required. in install_run_task() (line 414 of X/includes/install.core.inc).`

`Drush command terminated abnormally due to an unrecoverable error. [error]`

# Answer
> 4 votes
Drush `si` command has `key=value`argument.
The key is in the form `[form name].[parameter name]` on D7 or just `[parameter name]` on D6.

```
drush site-install standard install_configure_form.site_default_country=FR

```

See more: http://www.drushcommands.com/drush-6x/core/site-install

---
Tags: drush
---


# Question
Title: When adding Content: has taxonomy term id contextual filter to view and check specify validation criteria box, why don't I see validation options?
My request is closest to these two questions:

Filter by multiple taxonomies in URL

Views contextual filters taxonomy name

I have a view which is a page and displays node titles in a table format after the user selects a state, school year, school division, and school using exposed filters. And since each resultset can have dozens of nodes (nodes about that school for that school year) in it, the results are pages of links to 10 nodes at at time. I have exposed filters for state, school year, school division, and school. The view works fine, but the urls for each page of 10 node titles pertaining to an individual school looks like this:

http://www.mydomain.com/schools?field\_state\_tid=123&field\_school\_year\_tid=456&field\_school\_division\_tid=789&field\_school\_tid=999&page=1

when I would prefer it look like this where instead of term\_ids I have terms in the url:

http://www.mydomain.com/schools/arkansas/2012-2013/little-rock/clinton-elementary/page1

I have created state, school year, school division, and school taxonomies and each node is tagged appropriately with 1 term from each taxonomy.

But when I try to follow the instructions in the above mentioned questions, I get stuck at the part where it says to "specify validation criteria".

I check that box, but I have no options - the options are unavailable.

In the second question referenced above there is a part that says:

"Make sure Specify validation criteria is checked and **you should be presented with more options**."

\[emphasis added\]

That is exactly my problem - I should be presented with more options, but I am not.

Can anybody tell me why I am not presented with more options? Am I doing something else wrong?

Thanks in advance.

# Answer
> 0 votes
Duh, in case anyone else runs in to this problem:

This really boiled down to after adding a contextual filter, if I clicked any of the checkboxes under the heading "When the filter value IS in the URL or a default is provided":

Override title
Override breadcrumb
Specify validation criteria

I did not see any of the options for any of those checkboxes appear after checking it.

Turns out I didn't have the most up to date version of the chaos tools module.

When I updated to chaos tools 7.x-1.3 (sometimes referred to as ctools) problem fixed.

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


# Question
Title: programmatically add class name to fields
I want to add custom class name to fields in user login form other than default class name. For example,

* `user-name-field` for Username field
* `password-field` for Password field
* `click-me-button` for Submit button
* c`reat-account-link` for Create new account
* `request-password` for Request new password

how to do this programmatically?

# Answer
> 1 votes
Alter the login form using hook\_form\_alter(). And use #attributes to add custom classes to fields.

# Answer
> 0 votes
Create a custom template file (e.g. block--user--login.tpl.php). Then you can add custom classes to the

```
<div id="user-login-block-container">
    <form action="<?php print $form['#action']; ?>" method="post" id="<?php print $form['#id']; ?>"
      accept-charset="UTF-8">
    <div class="form-item form-type-textfield form-item-name customclass">
        <?php print render($form['name']); // Name field ?>
    </div>
    <div class="form-item form-type-password form-item-pass customclass">
        <?php print render($form['pass']); // Password field ?>
    </div>
    <input type="hidden" name="form_id" value="user_login_block"/>

    <div class="form-item form-actions form-wrapper" id="login_button">
        <input value="Login" type="submit" class="submit-button customclass" title="Login"/>
    </div>
    </form>
</div>

```

Then put in the template.php of your theme, the function:

```
yourtheme_preprocess_page(&$vars, $hook) {
$user_login = user_login_block(array());

$form = drupal_build_form('user_login_block', $user_login);

$form['name']['#required'] = false;
$form['pass']['#required'] = false;

$vars['form'] = $form;

```

Finally include the template file in your page.tpl.php:

```
<?php include 'block--user--login.tpl.php'; ?>

```

---
Tags: theming
---


# Question
Title: How can I provided simplified custom exposed filter options for a field in Views?
On my site, users can input their nationality in a field provided by the Countries module. About half the users on my site are Japanese, and the other half come from all other countries.

I have a view that allows members to search for each other, and I want to make the nationality an exposed filter. Since there are 200+ countries in the world, I do not want to expose the entire list of countries (this would be a selection nightmare on mobile phones).

Instead, I would like to provide a select list with three options: **All countries**, **Japan**, and **Not Japan**.

The Views UI allows administrators to select options on select lists and limit the list to the selected options by checking a box. This is not what I want to do, because there is no way to create a **Not Japan** option (which should show all members from all countries except Japan).

This answer suggests writing a custom views filter handler, but I'm a bit confused about where to begin.

The Countries module provides its own custom handlers, but (I think) these are overkill for what I need (you have to add a relationship to the country, which allows you to filter by continent, etc.); I simply need to make a version of the basic select list handler with my three options.

It seems that most views handlers extend another. In the `views/handlers` folder there is a file, `views_handler_filter_string.inc`, which I think I can use, but I'm not really sure what the next step is to take.

# Answer
> 1 votes
I've done something very similar to that with the following process:

1. Implement `hook_views_api()` in a custom module

```
function MYMODULE_views_api() {
  return array(
    'api' => 3,
    'path' => drupal_get_path('module', 'MYMODULE') . '/includes/views',
  );
}

```
2. Create includes/views/views\_handler\_filter\_MYMODULE\_country.inc somewhere with code similar to this (the MYMODULE bit isn't necessary, just a bit of low-tech namespacing):

```
class views_handler_filter_MYMODULE_country extends views_handler_filter_in_operator {

  /**
  * Get value options for the select list.
  */
  function get_value_options() {
    // Replace $this->value_options with an appropriately filtered list.
    $this->value_options = function_to_build_filtered_list();
  }

}

```
3. Register that file with the autoloader by adding this to MYMODULE.info:

```
files[] = includes/views/views_handler_filter_MYMODULE_country.inc

```
4. Finally, implement `hook_field_views_data_alter()` to force Views to use your new handler, changing the `$field['field_name']` condition (and other similar strings based on `field_address`) to whatever makes sense for your site

```
function MYMODULE_field_views_data_alter(&$result, $field, $module) {
  // Limit country exposed filters.
  if ($module == 'addressfield' && $field['field_name'] == 'field_address') {
    $result['field_data_field_address']['field_address_country']['filter']['handler'] = 'views_handler_filter_MYMODULE_country';
  }
}

```

---
Tags: views
---


# Question
Title: How do I use arguments with the Path Breadcrumb module?
I am using the Path Breadcrumbs module to create breadcrumbs. I don't fully understand how to use arguments and selection rules, and thus I'm not sure how to create the following breadcrumb:

On the gallery node page (/gallery/%node), I want to use *home \> events \>\[event-name\] \> schedule* as breadcrumbs.

Every Event node contains a node reference to a gallery node. I am trying to add this event name to the breadcrumbs. I already have retrieved the event name from `$variables`, following How do I retrieve node data for a referenced node in a template file?

# Answer
> 0 votes
As an last option you can implement theme\_breadcrumb() in your theme template.php

Something like below sample code.

```
function themename_breadcrumb($variables) {
  if (arg(0) == "galery" && is_numeric(arg(1))) {

    // Get event title of the  event
    $event_nids = mymodulename_get_back_refernce_value(arg(1));

    // Note since a gallery can be referred by multiple event nodes so you have add logic which one you need to pick here, for now I am picking with array index as 0
    $event_node = node_load($events_nids[0]);

    $links[0] = l(t('Home'), '<front>');

   // inplace of 'events' add internal link path to events page.
    $links[1] = l(t('Events'),'events');
    $links[2] = l(t($event_node->title),'node/'.$event_node->nid);
    $links[3] = t('schedule');
    drupal_set_breadcrumb($links);
  }
}

```

# Answer
> 0 votes
The *Path Breadcrumbs* module works with system paths. For nodes system path looks like node/%, you can read more in the module FAQ and documentation.

The main problem with your example is that your **Gallery** content type doesn't have a reference field to **Event**, so other modules don't know if *this* Gallery node is referenced from *that* Event node.
There is a list of modules which may help with it on How do I implement two-way node references? (I didn't test them.)

Another way is to provide a computed entity property "Event" for Gallery content type with `hook_entity_property_info_alter()`. Doing so, your property will be available as a token in Path Breadcrumbs.

---
Tags: breadcrumbs
---


title: Get SQL From View to put in db_query()

text:
# Question
Title: Get SQL From View to put in db_query()
I am using views and have a query to return some data. I want to take the SQL from the view and use it in my code.

The SQL the view is creating is:

```
SELECT node.title AS node_title
FROM
{node} node
LEFT JOIN {field_data_field_order_reference} field_data_field_order_reference ON node.nid = field_data_field_order_reference.entity_id AND (field_data_field_order_reference.entity_type = 'node' AND field_data_field_order_reference.deleted = '0')
INNER JOIN {node} node_field_data_field_order_reference ON field_data_field_order_reference.field_order_reference_nid = node_field_data_field_order_reference.nid
INNER JOIN {field_data_field_service_status} field_data_field_service_status ON node.nid = field_data_field_service_status.entity_id AND (field_data_field_service_status.entity_type = 'node' AND field_data_field_service_status.deleted = '0')
WHERE (( (node_field_data_field_order_reference.nid = '110' ) )AND(( (node.status = '1') AND (field_data_field_service_status.field_service_status_value = '1') )))
LIMIT 1 OFFSET 0

```

When I try and run this code in mysql I get back some errors. Such as:

It seems not to like the `{}`.

Is there an easy way to transform this View SQl into SQL that I can run using db\_query()?

# Answer
Assuming the table and field names are valid, you can run that SQL straight through `db_query()` and it will work fine.

It *won't* work if you just put the raw query into an SQL client, as Drupal uses brackets around table names to substitute in any necessary prefix. MySQL doesn't do that, so if you want to run the same query against the server proper, you need to remove the brackets from around the table names.
> 2 votes

# Answer
If you like to get and be able to execute the query for a view you could use the `hook_views_post_execute()` hook.

The function actually converting each placeholder to its appropriate value are taken from kiamlaluno answer on this page: Print the query which is built using db\_select()

```
function _get_query_string(SelectQueryInterface $query) {
  $string = (string) $query;
  $arguments = $query->arguments();

  if (!empty($arguments) && is_array($arguments)) {
    foreach ($arguments as $placeholder => &$value) {
      if (is_string($value)) {
        $value = "'$value'";
      }
    }
    $string = strtr($string, $arguments);
  }
  return $string;
}

function YOUR_MODULE_views_post_execute(&$view) {
  print str_replace(array("{","}"),
                    array("",""),
                    _get_query_string($view->build_info['query']));

}

```

If you would like to display the query for a specific view you could check the name of the view inside the `hook_views_post_execute()` hook:

```
if($view->name == 'MY_VIEW_NAME') {
}

```
> 0 votes

---
Tags: views, database
---


# Question
Title: Drupal 7: When using the Features module and the database (e.g content type) is different than the matching Features component
Drupal 7: When using the Features module and the database (e.g content type) is different than the matching Features component (e.g the same content type) what is used when viewing this component within the Drupal webapp?

# Answer
If the Feature is overridden, then what you have stored in the database is what Drupal will be using until you revert either the whole feature, or the item in question (such as your View for example).

As an example, if you have an exported View and you make some changes, it will be read from the database. If you either update or revert your Feature, then it will go back to being read from code.
> 1 votes

---
Tags: features
---


# Question
Title: How to bypass Drupal page cache if a certain cookie is set on a shared domain?
I have a drupal web site that lives on the same domain as another non-drupal website.For instance, The site is a.example.com. When my users logs in example.com a certain authentication cookie is set. However, when the user hit a.example.com, the user gets a cache hit. I know that hook\_boot is invoked on all pages, however, how do I tell Drupal to bypass cache? Should I set a certain cookie?
I would like to now what is the proper way of doing something like this.

# Answer
I would suggest looked at the Single Sign options of Drupal or implement some code that logs you into Drupal when they login to the non-Drupal site.

**EDIT**: first, boostrap Drupal and then run this function:

```
function drupal_user_login($username, $password)
{
    $uid = user_authenticate($username, $password);
    if($uid)
    {
        $form_state = array();
        $form_state['uid'] = $uid;
        user_login_submit(array(), $form_state);

        return true;
    }
    else
    {
        return false;
    }
}

```
> 1 votes

# Answer
I did some research and came up with one implementation on bypassing cache. The idea is you cannot bypass the page cache if no hooks are invoked at all when the page is in cache. Only `hook_boot` and `hook_exit` are invoked and only if `page_cache_invoke_hooks` is set to TRUE. The default value of this hook is TRUE but many caching module, such as Varnish Module, requires this `page_cache_invoke_hooks` to be set to FALSE (I don't know why). In the case when `page_cache_invoke_hooks` is set to TRUE I was able to dynamically toggel cache on and of in the following manner:

```
 /**
 * Implements hook_boot().
 */
function somemodule_boot() {

  if (need_tobyapss_cache()) {
    // Set the proper cache header.
    header('X-Drupal-Cache: MISS');

    // Do not cache this page. Otherwise this page could be cached in a logged

    drupal_page_is_cacheable(FALSE);

    // Continue the bootstrap process.
    drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL, FALSE);

    // Execute the page callback and exit.
    menu_execute_active_handler();

    exit;
  }
}

```

Again, this relies on `page_cache_invoke_hooks` being set to TRUE. iF it is set to FALSE drupal will not invoke hook\_boot or hook\_exit.

Also, there is an ongoing core issue about allowing developer to dynamically toggle cache on/off. https://drupal.org/node/322104
> 0 votes

---
Tags: caching, users, authentication-authorization
---


title: jquery SmartMenus conflict?

text:
# Question
Title: jquery SmartMenus conflict?
I believe I've got a jquery conflict, but for the life of me I can't find it. I admit, I'm not the best with jquery.

I'm using D7 with jquery update (7.x-2.3+6-dev) and I'm trying to get the jquery based SmartMenus to work: http://www.smartmenus.org/

For the most part I've got it installed and working, but the problem I'm having is that the drop down menus will not close when I mouse off them.

The menu can be seen here: http://www.multibrand.visionmix.us/

I'm not sure what other kind of information to post, so please let me know and I'll add it. I'd really appreciate any help.

# Answer
> 1 votes
I got it, I was calling a tag not specific enough.

Once I replaced:

```
$('#mainnav ul.menu').smartmenus();
$('#main-menu').smartmenus('menuHideAll');

```

with

```
$('#mainnav ul.menu:first').smartmenus();

```

Everything was fine.

---
Tags: javascript
---


title: Crop Profile Image on upload

text:
# Question
Title: Crop Profile Image on upload
I come across different type of image crop, but the only one seems to work on the profile image is Image Javascript Crop like says this answer.

The problem so far is that i need to crop the image on upload. I can't find any way. Is there any way?

# Answer
> Imagefield\_crop doesn't work on profile picture or either i can't find a way to make it work

You could disable the standard user picture (Configuration » People » Account -\> Personalization) and instead add your own custom image field, then Imagefield\_crop will work.
> 2 votes

# Answer
The Imagefield Crop module allows a user to crop the image after upload.

Here is a quote about it (from the module's project page):

> When the user uploads an image, the image is presented inside a cropping area. A cropping box is shown inside, and the user can resize and move it. Upon clicking 'preview' or 'submit', the image is cropped and the result is saved instead of the original image.
>
> **Features**:
>
> * Seamless, intuitive cropping, almost like using a desktop photo editing app
> * All major browsers supported
> * Dynamic preview - you see how your crop will look like, in real time!
> * Original image is saved for recropping.
> * No matter what resolution the cropping area is, the original image is used for cropping (for highest quality)
> * The sizes of the cropping area, cropping box and resulting image can be controlled by the administrator
> 1 votes

# Answer
> that was not the simplest way to do. Now I have to understand how to show the custom image in comment and similar, but it works

user picture field
> 1 votes

# Answer
The best way for cropping an image: If you are the admin then you could apply an image style to the image field.

Go to configuration -\> media -\> image-styles

Either add your own image style or edit any of the default image style. And effects that you want to select like crop/rotate/desaturate/scale etc and save that configuration.

Now go to configuration -\> media -\> file-types -\> Manage file display of the image

Now select any one from original/Default/link/preview/small/large

In that check the image checkbox. there select the image-style that you did the settings and save the configuration. Now where ever you want to crop the image for eg in content type you want to add the image there select that image style.
> 0 votes

# Answer
Then you will have to make use of:

Either **imagecrop module** from http://drupal.org/project/imagecrop

Or **ESPA crop module** from http://drupal.org/project/epsacrop
> 0 votes

---
Tags: 7, media
---


# Question
Title: Adding quantity to a Commerce product's attribute
I have a D7 Commerce Store. It will be selling to wholesales.

I have a Product that has multiple attributes. An example of the attributes is as follows;

T-Shirt Printing (Product)

* Size (S, M, L, XL, etc)
* Sides (1 Side, 2 Side)
* Service Type (All over, Spot)

How can I allow the customer to add that 1 product with multiple of a particular attribute?

Example; Customer should be able to order, 10 Small, 15 Medium, 20 Large of that one product "Tshirt Printing".

The Image below is an example from jakprints.com. I would like to do something similar. How can I replicate this in commerce? Or instead of using sliders... + or - buttons.

Please provide a few different ideas or POV's towards achieving this.

# Answer
Use the Commerce Add to Cart Extras module. It provides a new product reference field display formatter that does exactly what you need.
> 2 votes

---
Tags: 7, commerce
---


# Question
Title: How to use Drush or Migrate module to create/edit/delete nodes hourly
I need to

* Create new nodes (W/12 fields) hourly from a new table/fields in the Drupal DB (x\_table).
* Update currently created nodes via current x\_table rows.
* Delete nodes once the row has been removed from x\_table.

My skill sets do not include coding, and for years I have gotten by with the great Drupal modules, although I haven't had to import/update/delete rotating 10,000+ nodes. I previously used Feeds w/out updating, and it was extremely slow.

I've been reading I should be using the Migrate module and/or Drush. (I understand that Drush is part of Migrate)?? Anyhow I have installed the migrate module, but I have been completely baffled for an hour by their UI. It seems I need to create some data/text files for it to work, which is why I was trying to use the UI.

I feel that it will likely be best to create these scripts using Drush and calling them hourly via cron.

My question is, how do I create the script?? I'm not quite sure how to map the fields either? Could someone suggest a page showing this, or put together a quick example to work off of? 30 mn's of using the search engine hasn't shown me much, mostly only using csv files, etc. and not pulling from a database.

Thanks in advance for any help/suggestions.

# Answer
> -1 votes
In your module for the migration use this code:

```
function YOURMODULENAME_cron() {
$machine_name = "MACHINE NAME OF YOUR MIGRATION";
$last_run = variable_get('YOURMODULENAME_last_cron', 0);
$interval = variable_get('YOURMODULENAME_cron_interval', 60);//60 seconds
if(time() - $last_run > $interval)
  {
   variable_set('YOURMODULENAME_last_cron', time());//track the last_run time
   $migration = Migration::getInstance($machine_name);
   $result = $migration->processImport();
  }
}

```

---
Tags: drush, migrations
---


# Question
Title: Use functions: uc_file_user_downloads function and theme function
I would like to print files user download from ubercart on a new page. I find this theme function "uc\_file\_user\_downloads" but i don't know how to use it.

To print the table i write this little code:

```
<?php

 print $user->uid;
 $account = $GLOBALS['user'];
 print theme('uc_file_user_downloads', $account);
?>

```

And the result i have:

> 26 Fatal error: Cannot use object of type stdClass as array in /code/includes/theme.inc on line 1070

Could you explain me the correct way to pass the parameter on this function. I tried to cast the stdclass to array but this is not working.

# Answer
> 0 votes
If it is drupal 6 in order to print the table you can simply do `print uc_file_user_downloads($account);` ,this function will internally call the theme function `theme_uc_file_user_downloads`

What you are trying in your code is combination of both.So in drupal 6 try witih the following code.

```
global $user;
print uc_file_user_downloads($user);

```

In drupal 7 the function `uc_file_user_downloads($account);` returns array unlike html in drupal 6. So try the following with drupal 7

```
module_load_include('inc', 'uc_file', 'uc_file.pages');
global $user;
$table = uc_file_user_downloads($user);
print drupal_render($table['downloads']);

```

---
Tags: ubercart
---


# Question
Title: Is there any module that can automatically convert a module to be used on a different version of Drupal?
I don't find many of the Drupal 6 module yet on Drupal 7 and there are many Drupal 7 module that are not available in Drupal 6. I work in High level synthesis and am sure these can be done using high level compilation techniques, but wondering if there has been already any work in this direction. My question is, is there any module /framework already developed that can automatically convert a Drupal 6 module to Drupal 7 and vice versa?

# Answer
> 6 votes
I will not say that it is fully automatic, but *Coder Upgrade*, which is a sub-module of Coder, will do a lot of the grunt work for you. However, it is not a 100 % solution, there are always some loose ends to tie up. It is a good idea to use Coder Review afterwards to highlight the areas that need special attention. After that, it should be a simple case of installing the Drupal 7 version of the module, test it, and fix the remaining nits "by hand".

You can download and install it as part of your staging site or use the web-based version: http://dupgrade.com/

It is one way: Drupal 6 to Drupal 7. I know of no tool that goes in the other direction.

See also: https://drupal.org/node/224333 for an overview of the changes from Drupal 6 to Drupal 7.

# Answer
> 1 votes
There can be major differences in the data structure between versions so many modules have to be rewritten or at least very significantly altered. if it was easy to automate this, lots of people would have done it already.

---
Tags: 7
---


title: Organic Group Setup

text:
# Question
Title: Organic Group Setup
Following the recommendation of the stack drupaler i have been looking into OG for new website, although i am a little confuse whether or not it s the way to go. Here is what i need to be available:

1. User created group: Each user can create it s own group and get "administrator privileges on it"
2. Limited number of user can then join this group
3. The Group as it s own "blog page"

Is the OG the way to go for this or should i look into other module or at worst built one custom for my needs?

# Answer
> 2 votes
OG will do exactly this right out of the box. Just add the Organic Groups join limit module to get your Join Limit. Here is an excerpt about it from the module's project page:

> This module allows to set a join limit on a specific group.

# Answer
> 2 votes
OG is will work perfectly for you. 1. User created group: in permissions give the members the permission to create group or or create a group with members having the permission to create the group( can also use role to create new role for group creator). 2. as suggested use above use group limit to limit the group size http://drupal.org/project/og\_limit . 3.just enable the blog module and in content type :blog select group content.

# Answer
> 0 votes
You can also configure the group settings to require approval to join the group if you want to leave the limit up to the group's owner/admins.

---
Tags: organic-groups
---


# Question
Title: Identifying Community Modules vs. Custom Modules
Is there a list of Drupal Community modules that's easily query-able by the module's name/folder-name?

Context: I've inherited a web application built in Drupal. This application has around 30 modules in

```
sites/all/modules

```

I'd like to identify which modules the previous team developed on their own vs. which modules the previous team downloaded from the community modules listing.

So, I'm looking for a list of community modules I could check the module identifier (as opposed it's free form name) against in an automated way. This seems easier than manually search for 30 different modules.

Happy to hear other solutions for my problem.

# Answer
I am unaware of any full list of modules that are on drupal.org for public consumption (there are *a lot*). If I were you, I would do one of two approaches.

Based on https://stackoverflow.com/questions/6136022

```
cd sites/all/modules
for module in *; do
  echo -n $module
  echo -n ': '
  wget --spider --no-check-certificate -S "https://drupal.org/project/$module" 2>&1 | grep "HTTP/" | awk '{print $2}'
done

```

Lines that print out with a 200 exists; ones that don't should give a 404.

The other option is

```
cd sites/all/modules
for module in *; do
  grep 'project = ' $i/$i.info
done

```

Only modules on drupal.org will have a project line, which gets added by the packager script.

Also, if you visit the Available Updates page (admin/reports/updates) and check for updates, only public modules will be listed.
> 5 votes

---
Tags: 7
---


# Question
Title: how to change the value of the form in the preprocess functions or get the value of the function preprocess
I need to get the value of preprocess function and write it in the form `#default_value`, while my form is a variable that preprocess functions I create custom module

```
<?php
/**
 * Реализация template_preprocess_comment()
 **/
function comment_email_form_preprocess_comment(&$variables){
    $variables['content']['email_form']['email']['#default_value'] = 'New value!';
    $variables['content']['email_form'] = show(drupal_get_form('comment_email_form'));
    dsm($variables);
}
/**
 * Создаем форму, которая будет хранить данные email адресов бригад и отправлять письмо.
 **/
function comment_email_form($form, &$form_state){
$query = db_select('comment', 'c')
    ->fields('c', array('cid', 'nid'));
$result = $query->execute();
$comments = array();
foreach($result as $value){
    $comments[$value->cid] = comment_load($value->cid);
 }
  $form['email'] = array(
    '#type' => 'textfield',
    '#access' => TRUE,
    '#default_value' => 'test123',
    '#required' => TRUE,
  );

  $form['actions']['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Send'),
  );

  $form['#validate'][] = 'comment_email_form_validate';
  $form['#submit'][] = 'comment_email_form_submit';
  return $form;
}

```

Thanks for any help.

# Answer
> 1 votes
You pass extra arguments when building the form using the `drupal_get_form`.

For example:

```
drupal_get_form('comment_email_form', 'default_value');

function comment_email_form($form, &$form_state, $default_value)
{
    // $default_value is here the string 'default_value' value passed as extra argument
    // ... rest of your form
}

```

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


title: How to print a page in drupal 7?

text:
# Question
Title: How to print a page in drupal 7?
I have a module for drupal 7 that generate reports. I want to print one of the reports with out drupal menus and footer. I want the report to be displayed on second page alone with view descriptive data? Please Help.

# Answer
You might want to check out the Print Module. I've used it successfully for print media in the past.
> 1 votes

# Answer
You should ask yourself if you really need/want to display the content on a separate page before printing it.

Providing a simple print style sheet in your theme with `display: none` for the regions that don't make sense when printed will work for all the pages on your site without the overhead of print module's approach

People that like to print things know their browser can print and will try it anyway whether you give them a print link or not.
> 1 votes

# Answer
You could use the Print Module. This module actually fixed the problem and performs the required functionality.
> 0 votes

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


# Question
Title: How to link views content nodes to custom URL
I have nodes in a view using a custom view mode (using Display Suite). I'm doing some AJAX stuff when the user clicks on a particular node, so I need to wrap the nodes in a custom URL, like somenode/nojs/(nid).

I feel like I should be able to do this in Views, since fields can link to the content. Is there a way to get the node to link to a custom URL?

# Answer
I was able to do it in Display Suite using tokens.

EDIT:

For getting my node of a particular view mode to be clickable, I was able to set it in my node's display, in the view mode, and below the fields under "Custom Wrappers", I switched the "Add Link" box to "Tokens", and entered my URL with the \[node:nid\] token.

However, that just added an onClick handler to my node wrapper, so it wasn't useful for the purpose of making my node clickable for an AJAX callback. I had to do override my template file and works fine.
> 0 votes

# Answer
I don't know if you can get the node link in a custom URL, but you can overwrite the output of the nid field.

Steps:

***1. Add NID field***

***2. Hide field (this might change depending in your setup)***

***3. Go to the overwrite section and overwrite the NID output***

***4. The rest is up to you. You can display a field as a link and add the NID field as a replacemente pattern or use it as is.***
> 1 votes

---
Tags: 7, views, ajax, display-suite
---


# Question
Title: Views not displaying on page, but show up in preview
I have a view setup to display all properties where a drop down box = portfolio 1. However, when I set up the view everything looks correct but when I go to the actual url it does not display the teaser or full content in the body.

When I set it up as a block I can add it to my right sidebar and it displays fine...

here is the export of the view:

```
$view = new view();
$view->name = 'portfolio_1';
$view->description = '';
$view->tag = 'default';
$view->base_table = 'node';
$view->human_name = 'Portfolio_1';
$view->core = 7;
$view->api_version = '3.0';
$view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */

/* Display: Master */
$handler = $view->new_display('default', 'Master', 'default');
$handler->display->display_options['title'] = 'Portfolio_1';
$handler->display->display_options['use_more_always'] = FALSE;
$handler->display->display_options['access']['type'] = 'perm';
$handler->display->display_options['cache']['type'] = 'none';
$handler->display->display_options['query']['type'] = 'views_query';
$handler->display->display_options['exposed_form']['type'] = 'basic';
$handler->display->display_options['pager']['type'] = 'full';
$handler->display->display_options['pager']['options']['items_per_page'] = '10';
$handler->display->display_options['style_plugin'] = 'list';
$handler->display->display_options['row_plugin'] = 'node';
$handler->display->display_options['row_options']['view_mode'] = 'full';
/* Field: Content: Title */
$handler->display->display_options['fields']['title']['id'] = 'title';
$handler->display->display_options['fields']['title']['table'] = 'node';
$handler->display->display_options['fields']['title']['field'] = 'title';
$handler->display->display_options['fields']['title']['label'] = '';
$handler->display->display_options['fields']['title']['alter']['word_boundary'] = FALSE;
$handler->display->display_options['fields']['title']['alter']['ellipsis'] = FALSE;
/* Sort criterion: Content: Post date */
$handler->display->display_options['sorts']['created']['id'] = 'created';
$handler->display->display_options['sorts']['created']['table'] = 'node';
$handler->display->display_options['sorts']['created']['field'] = 'created';
$handler->display->display_options['sorts']['created']['order'] = 'DESC';
/* Filter criterion: Content: Published */
$handler->display->display_options['filters']['status']['id'] = 'status';
$handler->display->display_options['filters']['status']['table'] = 'node';
$handler->display->display_options['filters']['status']['field'] = 'status';
$handler->display->display_options['filters']['status']['value'] = 1;
$handler->display->display_options['filters']['status']['group'] = 1;
$handler->display->display_options['filters']['status']['expose']['operator'] = FALSE;
/* Filter criterion: Content: Type */
$handler->display->display_options['filters']['type']['id'] = 'type';
$handler->display->display_options['filters']['type']['table'] = 'node';
$handler->display->display_options['filters']['type']['field'] = 'type';
$handler->display->display_options['filters']['type']['value'] = array(
  'property' => 'property',
);
/* Filter criterion: Content: portfolio (field_portfolio) */
$handler->display->display_options['filters']['field_portfolio_value']['id'] = 'field_portfolio_value';
$handler->display->display_options['filters']['field_portfolio_value']['table'] = 'field_data_field_portfolio';
$handler->display->display_options['filters']['field_portfolio_value']['field'] = 'field_portfolio_value';
$handler->display->display_options['filters']['field_portfolio_value']['value'] = array(
  'port1' => 'port1',
);

/* Display: Page */
$handler = $view->new_display('page', 'Page', 'page');
$handler->display->display_options['path'] = 'portfolio-1';

```

I can provide screen shots if that would help.

# Answer
Few possible things you may try to resolve the above problem are:

* Make sure the path you are accessing is same as the path you have assigned to page display.
* Not using the same path elsewhere (e.g: either in the `hook_menu`, `panels`, etc.)
* Try changing the path (adding some random chars) for testing and check if it works.
* Perform a search in the `menu_router` table for the path you are using, and if it already had an entry than you need to change the path.
> 1 votes

---
Tags: 7, views
---


# Question
Title: How to manage contrib modules composer dependencies on drupal 8
Let's say I have a module exposing a composer.json file, composer manager let me merge it with others modules composer.json.

In Drupal 8 composer.json are used from the core, so is it possible to avoid dependencies duplication with contrib modules ? Is composer-manager still used for that ?

# Answer
At the moment this is not possible, and it does not look like this will make it into Drupal 8, as Drupal is in code freeze.

Instead, try to manage your dependencies using your module's \*.info.yml file (this is for depending on other modules) or using http://drupal.org/project/libraries, which is for third party libraries.

To elaborate on why using Composer for Drupal 8 contributed modules is not a good idea right now:

1. You cannot expect site builders to know composer and do a "composer install" after having downloaded Drupal to their computer, as Drupal is not just for people who are familiar with the command line.
2. Because of that, you would have to do the composer install yourself and commit all code to your repository. While this is legally possible for any third party code that complies with the GPLv2, this makes maintenance harder, and if someone downloads two modules that both use the same library through Composer, they'll end up with duplicate code. This in turn makes class loading and debugging a whole lot less fun.
> 1 votes

---
Tags: 8, composer
---