# Question
Title: How to start views at %nid position (from path)?
I have a portfolio showing somes nodes (views3 + views slideshow using cycle). Everything works fine, I've a default path `/portfolio` to access to it.

However, I'm trying to set a path for each slide. I would like to use `/portfolio/%nid` and using `%nid` in views to default the first viewed slide to this node id.

Anyone know how it is possible ? I've tried with UI but I don't think it is enough.

# Answer
> 1 votes
In jQuery Cycle there is an option called startingSlide. By default this is set to 0, like this: startingSlide: 0

If I remember correctly there is a tab/textarea for advanced settings where you can add options to jQuery Cycle from within the Views UI. I think you can add "startingSlide: 5" for example there.

You will need to find out which is the starting slide (convert the %nid to which row in the view it is) and add it as a HTML element. When that is in place we can fetch it with jQuery and add it as a jQuery Cycle option. I'm not sure which is the best way but I think you could do something like:

```
    function MYMODULE_views_pre_render(&$view) {
      if($view->name == "MYVIEW") {
        $view->attachment_after = $startingslide;
      }
    }

```

You will have to add more code to find out $startingslide there of course. Look inside $view-\>result and find out which of the rows that is the argument, that will be your $startingslide. Use dpm() on the view to search through the object.

Hope this will help you. Let me know what you ended up doing :)

# Answer
> 0 votes
You could add an exposed filter to your view, configure it to show nids `greater than` the provided value, and mimic it's URL accordingly.

for example /portfolio?nid\_is\_greater\_than=3

You could then hide your filter with css.

# Answer
> 0 votes
Since your problem is about appearance, not about structure I suggest to not solve it on the server and not in the URL path but on the client with a URL fragement: /portfolio#slide-\[nid\].

I've not read the javascript code of views slideshow + cycle, but I guess it's quite easy to adopt it's behavior to read the URL fragment on initialization of the slideshow. Or maybe there is already such a logic implemented which you could use...

# Answer
> 0 votes
How about using 'Rewrite Output Results' option in Fields section of Views?

1. In Views, go to Configure (Image) Field \> Rewrite Results
2. Check the 'Output this field as a link' checkbox
3. Enter the Link Path (nid/) and other details
4. Click on Apply
5. Save View

Hope this helps.

# Answer
> 0 votes
Views passes off the display to `node_view()` in that case, and doesn't get involved with the markup for the row.

The easiest way to do what you want is to implement `hook_preprocess_node()`, look for a View in the current context, and if the node is being rendered as part of that display, you can make some alterations.

TAKE A LOOK AT THIS:

```
function MYMODULE_preprocess_node(&$vars) {
  if (!empty($vars['view']) && $vars['view']->view_name == 'foo') {
    $nid = $vars['node']->nid;
    $vars['extra_link'] = l('Some text', "node/$nid");
  }
}

```

In your `node.tpl.php` file you'll have access to `$extra_link.`

---
Tags: uri, javascript, views
---


# Question
Title: Display a single view in different view format
I want to display a view in both grid and list style, and allow the users to explicitly select the format in which they want to view (Like the picture below)

The JQuery which I used is

```
(function ($) {
    Drupal.behaviors.mytheme = {
  attach: function (context, settings) {
    $('#content').once('course-view', function() {

  if ($(".view").hasClass("course-view")) {
    $(".view").addClass("grid-view"); // Sets .grid-view as default class on the view

    $(".list").click(function() {
      if ($(".view").hasClass("grid-view")) {
        $(".view").addClass("list-view"); // adds .list-view to the view class
        $(".view").removeClass("grid-view"); // removes .grid-view from the view class
      }
    });

    $(".table").click(function() {
      if ($(".view").hasClass("list-view")) {
        $(".view").addClass("grid-view"); // adds .grid-view to the view class
        $(".view").removeClass("list-view"); // removes .list-view from the view class
      }
    });
  }
});
  }
    };
    })(jQuery);

```

# Answer
Try this: For this you need one instance of your view. No clone required.

**Note:** You need to set your view format to grid by default.

In view header, add Global custom text and add below HTML for toggle between grid and list.

```
<div><span>View:</span><a class="grid" href="#">Table</a> <a class="list" href="#"> List</a> </div>

```

**In template.php**

```
function mytheme_preprocess_views_view(&$vars) {
  $view = &$vars['view'];
  // Make sure it's the correct view
  if ($view->name == 'participant_list') {

    // add needed javascript
    drupal_add_js(drupal_get_path('theme', 'mytheme') . '/script.js');

    // add needed stylesheet

  }
}

```

**script.js** (add in the custom theme)

```
    (function ($) {
    Drupal.behaviors.mytheme = {
    attach: function (context, settings) {
       $(".list").click(function() {
         $( "div.view-participant-list" ).find("td").addClass("display_list" );
    });

        $(".grid").click(function() {
        $( "div.view-participant-list" ).find("td").removeClass( "display_list");
    });
  }
 };
})(jQuery);

```

**.css**

```
.display_list
{
    display:block;
}

```

**Note:** Here **div.view-participant-list** is selector in my case. You need to find your own.
> 0 votes

# Answer
I think Your Question resembles the video tutorial series in Code karate:

Multiple Views Series

Please Check It out... By adding and removing classes when clicking the grid and list icons using jQuery make this done..
> 0 votes

# Answer
I didn't got your question ? According to the javascript you used the implementation will be achieved.

However the drupal way of doing this is to create another display of the view ( extend it from master ) and render both the views on the same page and write some JS which will hide the list view when grid button is clicked and hide grid view when list button is clicked. One having display format- list having class list view and other having display format : grid having class grid.

```
$('.list').on('click',function() {
  $('.grid').removeClass('enabled');
  $(this).addClass('enabled');
  $('.grid-view').hide();
  $('.list-view').show();
});
$('.grid').on('click',function() {
  $('.list').removeClass('enabled');
  $(this).addClass('enabled');
  $('.grid-view').show();
  $('.list-view').hide();
});
$('.grid-view').hide(); //default settings
$('.list').addClass('enabled'); //default settings

```

Considering both options the first option with single view and pure js to handle it is correct way as in either case we need to change the class and generated HTML would be the same.

Moreover, If we have same view repeated twice then its useless to create one more view with the same Markup. As it will obstruct the performance and loading time of the page.

I can give you more detailed advice if you can become more descriptive.
> 0 votes

---
Tags: views
---


# Question
Title: Can I disable Toolbar in specific theme?
I have two active theme, and switching between them by themekey on specific paths.

theme #one is my main theme, and some contents load in theme #two in a modal box (lightbox2). I need disable Toolbar on theme #two because it's load Toolbar too and I don't want it there.

my question is how can I disable Toolbar in theme #two?

# Answer
You'll have to use hook\_page\_alter from within a module to unset `$page['page_top']['toolbar']` — you can't do it from within a theme.

There is a module for that: Toolbar Visibility.
> 1 votes

# Answer
Or you can disable the 'toolbar' module for this.

https://www.ostraining.com/blog/drupal/adding-the-administration-menu-to-drupal-7-and-disabling-the-default-toolbar/

Is it the best way you think? Or plan something like,

```
 1.
      if ($vars['page']['page_top']['toolbar']['#access']) {
         $vars['page']['page_top']['toolbar']['#access'] = false;
      }

```

But I don't know where could you find the '$vars' from.
> -1 votes

---
Tags: 7, theming, toolbar
---


title: Show result summary in theme table

text:
# Question
Title: Show result summary in theme table
Can we show the result summary like "Displaying X to Y of Z records" while using the "table" or "tableselect" themes? I mean just the thing we do in views header/footer using the "Global: Result summary" option.

Hope I am clear with the requirement.

# Answer
> 0 votes
On your theme's **template.ph**p override the **theme\_pager** function as below.You need to do some HTML customization as per your need.Hope this helps.

```
function themename_pager(&$variables){

$element = $variables['element'];
global $pager_page_array, $pager_total, $pager_total_items, $pager_limits;

$pager_current = $pager_page_array[$element] + 1;
$pager_max = $pager_total[$element];
$total_items = $pager_total_items[$element];
$limit = ($pager_limits[$element])?$pager_limits[$element]:10;

$start = ($pager_current-1)*$limit+1;
$end = ($pager_max != $pager_current)?$pager_current*$limit:$total_items;

$text = "$start to $end of $total_items Records";
return $text.theme_pager($variables);
}

```

---
Tags: paging, theming, forms
---


# Question
Title: Override default table template In custom module
How can I use a custom module to override views-view-table.tpl.php? I understand how to do it for a theme, but I want to provide the template using a custom module. I've already created my replacement table theme file. I've put it in a folder called "templates" inside my custom module. Now I just need to understand what hook(s) I should use to tell views to check my module for replacement templates.

# Answer
> 2 votes
Add a module path to the Drupal 7 theme registry by implementing hook\_theme\_registry\_alter().

Here's an example - replace the usual with your own data :)

```

/**
 * Implements hook_theme_registry_alter().
 */

function MYMODULE_theme_registry_alter(&$theme_registry) {

  // Get module path
  $path = drupal_get_path('module', MYMODULE);

  // Find all .tpl.php files in this module's folder recursively.
  $template_files = drupal_find_theme_templates($theme_registry, '.tpl.php', $path);

  // Itterate through all found template file objects.
  foreach ($template_files as $key => $template_file) {
    // If the template has not already been overridden by a theme.
    if (!preg_match('#/themes/#', $theme_registry[$key]['theme path'])) {
      // Alter the theme path and template elements.
      $theme_registry[$key]['theme path'] = $path;
      $theme_registry[$key] = array_merge($theme_registry[$key], $template_file);
    }
  }
}

```

# Answer
> 0 votes
Try hook\_views\_api().

```
function YOUR_MODULE_views_api() {
  return array(
    'api' => 3,
    // Place your exported views here if you have any.
    'path' => drupal_get_path('module', 'YOUR_MODULE') . '/includes/views',
    // Place your template files here.
    'template path' => drupal_get_path('module', 'YOUR_MODULE') . '/templates',
  );
}

```

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


title: Accessing node#ID in node save process

text:
# Question
Title: Accessing node#ID in node save process
I just realized `hook_node_presave($node)` does not yet have a NODE#ID associated with the new node.

**Can anyone tell me if there is a hook in the node creating process where I can access the new nodes' nid?**

# Answer
> 1 votes
`hook_node_insert()` is the one you're looking for...

> This hook is invoked from node\_save() after the database query that will insert the node into the node table is scheduled for execution, after the type-specific hook\_insert() is invoked, and after field\_attach\_insert() is called.

# Answer
> 0 votes
Some option by attaching function to submit button on node form.

```
/**
 * Implements hook_form_NODE_TYPE_node_form_alter()
 * Add some action to submit button
 */
function CUSTOM_MODULE_form_NODE_TYPE_node_form_alter(&$form, &$form_state){
    $form['actions']['submit']['#submit'][] = 'CUSTOM_MODULE_form_NODE_TYPE_node_form_submit';
}
function CUSTOM_MODULE_form_NODE_TYPE_node_form_submit(&$form, &$form_state){
    $node = $form_state['node'];
    // YOU CAN GET NID OR EVERYTHING THRUE $node
}

```

---
Tags: 7, nodes, hooks
---


# Question
Title: How to add custom Jquery in drupal module?
I have created a custom module in drupal 7. The module creates a form for user and store the form's data into database. The module is working fine. But I want to add a custom jquery for the page. I searched **Google** and find the result for adding custom JQuery for theme not for modules. I guessed and add the following in my module's info file

```
;scripts
scripts[] = js/test.js

```

Just alert a "hello" word while the module will load. But nothing is happened. Is this possible to add custom Jquery for a module or I am doing wrong? Please help.

# Answer
There are several ways of adding JS to your module, you can check them here https://www.drupal.org/node/756722

Your attempt should work fine, just don't forget to clear the caches after editing module's .info file.

Cheers!
> 5 votes

# Answer
with the drupal\_add\_js function you can add your own javascript file, it is best to call in hook\_init

Example

```
/**
 * Implements hook_init().
 */
function mymodule_init(){
  drupal_add_js(drupal_get_path('module', 'mymodule') . '/js/mymodule.script.js', array('scope' => 'footer'));
}

```

drupal\_add\_js
hook\_init

This hook is not run on cached pages. To add JS that should be present on all pages, modules should not implement this hook, but declare these files in their .info file.

```
scripts[] = js/script.js

```
> 4 votes

# Answer
You can add any no of js files and css files from your .info file. This is as simple as you modify your modulename.info file with:

```
scripts[] = js/jsfilename.js
stylesheets[all][] = css/cssfilename.css
stylesheets['specify_name'][] = css/cssfilename.css

```
> 1 votes

---
Tags: 7, javascript
---


# Question
Title: Redirect a user after the node has been saved
I'm looking for a hook to use after a node of a specific content type is created or saved, to perform a redirection to a specific page.

# Answer
In case of Drupal 6 hook\_nodeapi() will help to perform on various actions, basing on the value of the first argument passed to the hook (`$op`).

* alter
* delete
* load
* update

In Drupal 7 there is a number of hooks for this.
> 4 votes

# Answer
Form redirect after node save. This blog discusses the usually way of redirecting a form, the problem with node forms, and how to solve them for Drupal 6. I believe it should also work for Drupal 7
> 5 votes

# Answer
For the completeness of this thread, here is a link to a more detailed answer.
Either code it or add a rule using the rules module.
> 0 votes

# Answer
If "created" and "saved" mean node has been on database, here some option.

```
/**
 * Implements hook_form_NODE_TYPE_node_form_alter()
 * Add some action to submit button
 */
function CUSTOM_MODULE_form_NODE_TYPE_node_form_alter(&$form, &$form_state){
    $form['actions']['submit']['#submit'][] = 'CUSTOM_MODULE_form_NODE_TYPE_node_form_submit';
}
function CUSTOM_MODULE_form_NODE_TYPE_node_form_submit(&$form, &$form_state){
    $node = $form_state['node'];
    // CHECK NODE TYPE AND REDIRECT
}

```

Here similar case which can be done by this option.
> 0 votes

---
Tags: hooks, forms
---


# Question
Title: Daily cron job to download and email Webform submissions file
On a Webform I can download a tsv (tab delimited) file and select the 'Only last submissions since download' option.

What I want to do is have a daily cronjob which does the same thing and emails this file automatically.

How would I do this? Is there any existing Module to do this in Drupal 7?

# Answer
Using a custom module, you can implement hook\_cron() to export the csv and send an email:

```
function MODULE_cron()
{
    //this is the function that creates the csv, you'll need to research how to use it properly.
    webform_results_download($node, $export_info);
    //send email
}

```

As far as sending email, you can use php mail or drupal\_mail(), but phpMailer might be the easiest to use.
> 4 votes

# Answer
You could probably do this using Webform MySQL Views and Views Rules which will also give you flexibility of what should be in the email that you send.
> 0 votes

# Answer
i did the same functionality but my final goal is want to upload the webform results in sftp server automatically.

if you have a webform then get its node id ( $node-\>nid )

function hook\_cron()

{

```
$node = node_load(1063);

$format = 'delimited';

module_load_include('inc', 'webform', 'includes/webform.export');
module_load_include('inc', 'webform', 'includes/webform.components');
module_load_include('inc', 'webform', 'includes/webform.submissions');

$submission_information = array(
    'serial' => t('Serial'),
    'sid' => t('SID'),
    'time' => t('Time'),
    'draft' => t('Draft'),
    'ip_address' => t('IP Address'),
    'uid' => t('UID'),
    'username' => t('Username'),
);

$options = array(
      'delimiter' => variable_get('webform_csv_delimiter', ','),
      'components' => array_merge(array_keys($submission_information), array_keys(webform_component_list($node, 'csv', TRUE))),
      'select_keys' => 0,
      'select_format' => 'separate',
      'range_type' => 'all',
      'download' => 1,
 );

  $exporter = webform_export_create_handler($format, $options);

  $file_name = drupal_tempnam('temporary://', 'webform_');
  $handle = @fopen($file_name, 'w'); // The @ suppresses errors.
  $exporter->bof($handle);

  // Fill in the header for the submission information (if any).
   $header[2] = $header[1] = $header[0] = count($submission_information) ? array_fill(0, count($submission_information), '') : array();
  if (count($submission_information)) {
    $header[0][0] = $node->title;
    $header[1][0] = t('Submission Details');
    foreach (array_values($submission_information) as $column => $label) {
      $header[2][$column] = $label;
    }
  }

  // Compile header information for components.
  foreach ($options['components'] as $cid) {
    if (isset($node->webform['components'][$cid])) {
      $component = $node->webform['components'][$cid];

      // Let each component determine its headers.
      if (webform_component_feature($component['type'], 'csv')) {
    $component_header = (array) webform_component_invoke($component['type'], 'csv_headers', $component, $options);
    $header[0] = array_merge($header[0], (array) $component_header[0]);
    $header[1] = array_merge($header[1], (array) $component_header[1]);
    $header[2] = array_merge($header[2], (array) $component_header[2]);

    // Allow modules to modify the CSV header.
    drupal_alter('webform_csv_header', $component_header, $component);
      }
    }
  }

  // Add headers to the file.
  foreach ($header as $row) {
    $exporter->add_row($handle, $row);
  }

  // Get all the required submissions for the download.
  $filters['nid'] = $node->nid;

  if (!empty($options['sids'])){
    $filters['sid'] = $options['sids'];
  }

  $submissions = webform_get_submissions($filters);

  // Generate a row for each submission.
  $row_count = 0;
  $sid = 0;
  foreach ($submissions as $sid => $submission) {
    $row_count++;

    $row = array();
    if (isset($submission_information['serial'])) {
      $row[] = $row_count;
    }
    if (isset($submission_information['sid'])) {
      $row[] = $sid;
    }
    if (isset($submission_information['time'])) {
      $row[] = format_date($submission->submitted, 'short');
    }
    if (isset($submission_information['draft'])) {
      $row[] = $submission->is_draft;
    }
    if (isset($submission_information['ip_address'])) {
      $row[] =  $submission->remote_addr;
    }
    if (isset($submission_information['uid'])) {
      $row[] = $submission->uid;
    }
    if (isset($submission_information['username'])) {
      $row[] = $submission->name;
    }

    foreach ($options['components'] as $cid) {
      if (isset($node->webform['components'][$cid])) {
    $component = $node->webform['components'][$cid];
    // Let each component add its data.
    $raw_data = isset($submission->data[$cid]['value']) ? $submission->data[$cid]['value'] : NULL;
    if (webform_component_feature($component['type'], 'csv')) {
      $data = webform_component_invoke($component['type'], 'csv_data', $component, $options, $raw_data);

      // Allow modules to modify the CSV data.
      drupal_alter('webform_csv_data', $data, $component, $submission);

      if (is_array($data)) {
        $row = array_merge($row, array_values($data));
      }
      else {
        $row[] = isset($data) ? $data : '';
      }
    }
      }
    }

    // Write data from submissions.
    $data = $exporter->add_row($handle, $row);
  }

  // Add the closing bytes.
  $exporter->eof($handle);

  // Close the file.
  @fclose($handle);

  $export_info['options'] = $options;
  $export_info['file_name'] = $file_name;
  $export_info['exporter'] = $exporter;
  $export_info['row_count'] = $row_count;
  $export_info['last_sid'] = $sid;

```

}

In $export\_info we get the csv file (which is a php temp file) 1) if you want to download call webform\_results\_download($node, $export\_info) function 2) If you want to send mail you write your mail function and assign the file. 3) if you want to upload the file automatically in another server through SFTP you call your upload function (i have this SFTP upload functionality soon i publish in drupal else if you want mail me i send my code vishnumoorthy.yaso@gmail.com)

Reason for incude this files:

module\_load\_include('inc', 'webform', 'includes/webform.export'); module\_load\_include('inc', 'webform', 'includes/webform.components'); module\_load\_include('inc', 'webform', 'includes/webform.submissions');

To access the function 1) webform\_export\_create\_handler() 2) webform\_component\_feature() 3) webform\_get\_submissions()

we include this function in above code these function all available in webform so we just use the function by include the files here.

Hope this help you lot. If i did any mistake please be free to point me. This my first drupal answer . I am happy to give a correct solution. Lets rocking drupal and drupal developers.

Thanks...
> 0 votes

---
Tags: 7, webforms, cron
---


title: Reset button in Exposed Form of Views

text:
# Question
Title: Reset button in Exposed Form of Views
I have a view named `search-form`. In my view there are some fields like age, profession, education, etc. In this view I am using 2 buttons i.e. Submit & Reset. These buttons show from **Exposed Form** setting of View.

**Submit** button is working fine but whenever I click on the **Reset** button. It works like submit button. I have check through firebug. Found this `<input type="submit" id="edit-reset" name="op" value="Reset" class="form-submit">`. I think in place of 'submit', 'reset' need to set. How can I solve this. Please help. Thanks.

# Answer
> 1 votes
Try this:

Use `str_replace()` function

`$variables['page']=str_replace(your replace code);` in your template.php within `themename_preprocess_html()` fuction.

You can replace **type="submit"** with what you want i.e **type="reset"**.

Rough Example

```
$variables['page']=str_replace('<input type="submit" id="edit-reset" name="op" value="Reset" class="form-submit">','<input type="reset" id="edit-reset" name="op" value="Reset" class="form-submit">',$variables['page']);

```

# Answer
> 3 votes
Download and install the **Better Exposed Filters** module. This module provides a "Include Reset button" when you are creating a View. Hope that helps.

---
Tags: views
---


# Question
Title: Search API Saved Search tokens output [search-api-saved-search-result:url] has cron.php in urls
I'm using Drupal 7 : with Search API

In this I'm using the token \[search-api-saved-search-result:url\] which I take it should output the Url of the relevant nodes. The Urls are correct except the have 'cron.php' text in them . ie 'www.example.com/cron.php/node/1234' ; making them not work.

this is the code in the Search API module.

```
case 'search-api-saved-search-result':
  $d = $data['search_api_saved_search_result_info'];
  if (!empty($d['search']) && !empty($d['entity'])) {
    $search = $d['search'];
    $index = $search->index();
    $item = $d['entity'];
    foreach ($tokens as $name => $original) {
      if ($name == 'id' && ($id = $index->datasource()->getItemId($item))) {
        $replacements[$original] = $id;
      }
      elseif ($name == 'label' && ($label = $index->datasource()->getItemLabel($item))) {
        $replacements[$original] = $label;
      }
      elseif ($name == 'url' && ($url = $index->datasource()->getItemUrl($item))) {
        $url['options'] += $url_options;
       $replacements[$original] = url($url['path'], $url['options']); // $replacements[$original] = url('http://www.rcnbulletins.com/', $url['options']);
      }
    }
    if (($url_tokens = token_find_with_prefix($tokens, 'url')) && ($url = $index->datasource()->getItemUrl($item))) {
      $replacements += token_generate('url', $url_tokens, $url, $options);
              }
  }
  break;

```

I'm wondering if this is a bug or something i've missed in admin.

# Answer
> 0 votes
Here is the solution . thanks to these answers Formatting output of token

```
/**
* Implements hook_tokens_alter().
*/
function rcn_tokens_alter(&$replacements,  $context){
  // fix urls being outputted with cron.php in the link.
  if(isset($replacements['[search-api-saved-search-result:url]'])){
  $url = $replacements['[search-api-saved-search-result:url]'];
  $newurl = str_replace("cron.php/", "", $url);
  $replacements['[search-api-saved-search-result:url]']  =   check_plain($newurl);
  }

}

```

---
Tags: 7, search
---


# Question
Title: How to remove a Required Field based on other field value
i have a form with two fields, FieldA (Select List) and FieldB (Select List, required field).

How to set the FieldB to optional when FieldA has certain value in order to pass the form validation?

# Answer
> 0 votes
First mark the field B as not required if you have set the field as required using UI

```
if field B is not set as required then you can continue with the following code.<br/>

```

For none value in field B we can set custom form error using form\_set\_error();

```
     function hook_form_alter($form, &$form_state, $form_id) {
        if ($form_id == 'abc') {
        $form['#validate'][] = 'hook_abc_validate'
        }
        }

       function hook_abc_validate($form, $form_state) {

        if ($form['field_A']['und']['0']['value'] == 'your_value') {

        $form['field_B']['#required'] = 0;
        }
        else {
        $form['field_B']['#required'] = 1;

        }
    if ($form['field_B']['und']['0']['value'] == '_none') {
            form_set_error('field_B', 'field_B cannot be none');
            }
}

```

# Answer
> 1 votes
Try using the #states attribute: a structured array describing the different JavaScript states that can be applied to the element when certain conditions are met. Please read the extensive description of this feature at drupal\_process\_states()

---
Tags: 7, forms
---


title: hook_menu title callback on wildcard

text:
# Question
Title: hook_menu title callback on wildcard
I have two pages, the first page 'test' has links to test/%. On test/% I want to have different titles but some how this wildcard and the title callback aren't working properly.

```
/**
 * Implements hook_menu().
 */
function cjgimport_menu() {
  $items['test'] = array(
    'title' => t('Test title'),
    'title callback' => 'function_title_callback',
    'title arguments' => array(0),
    'type' => MENU_NORMAL_ITEM,
    'access arguments' => array('access content'),
    'page callback' => 'function_content_callback',
  );

  $items['test/%'] = array(
    'title' => t('Test title'),
    'title callback' => 'function_title_callback',
    'title arguments' => array(1),
    'type' => MENU_NORMAL_ITEM,
    'access arguments' => array('access content'),
    'page callback' => 'function_content_callback',
  );

  return $items;
);

/**
 * Custom callback function for title
 */
function function_title_callback($arg) {
  if($arg == 0) {
    $title = ucfirst(arg(0));
  } else {
    $title = ucfirst(arg(1));
  }
  return $title;
}

```

Can anyone tell me why the title doesn't work on the test/% pages?

# Answer
You need to provide the wildcard as `title arguments`:

```
$items['test/%'] = array(
  'title' => t('Test title'),
  'title callback' => 'function_title_callback',
  'title arguments' => array(1),
  'type' => MENU_NORMAL_ITEM,
  'access arguments' => array('access content'),
  'page callback' => 'function_content_callback',
);

```

And obviously make sure that your function is actually called `function_title_callback()` (which you've listed in `hook_menu()`), and not `cjgimport_title_callback()`, which you have listed in the question.

You should also be using the `$arg` variable, not the `arg()` function in your callback...but I guess that might be the result of debugging.
> 5 votes

# Answer
Please remember to put the loader function in the same file where your menu function is in, it usually is the .module file. In my case, my loader function wouldnt fire when i put it in the .inc file.
> 0 votes

---
Tags: routes
---


# Question
Title: Add more than 2 profile in Civicrm contribution page
I'm using civicrm contribution page to create a membership renewal page. But in the "Profile" tab, I'm only able to add two profile, one in top of the page, one in bottom of the page.

Is there any way I can add in more than two profiles in the page? Just like in event page, I can add 7 profile.

Thank you.

# Answer
> 13 votes
There's no way of doing this through the user interface.

An alternative approach would be to use a Drupal webform integrated with CiviCRM. You'll need the Webform module, the webform\_civicrm integration module, and various dependencies.

Depending on the payment processor you are using to process the membership payment, if indeed you are using any, you can then build a form that will include all the CiviCRM fields you need without needing to create profiles.

If you are using a payment processor and accepting online payments for you memberships, IPN-based processors, such as Paypal standard, aren't supported by this approach, but you can get around that by having the user taken from the webform through to a basic CiviCRM contribution page and they can make their payment there.

# Answer
> 6 votes
Another approach would be to manipulate the page via JavaScript inserted in the content fields to arrange the fields as required. I admit though it's not very elegant and somewhat hacky.

# Answer
> 2 votes
Even if the database structure allow this, it seems that there are some code logic that prevents it from working.

So, if you want it to be purely CiviCRM, what you could do is to add all the fields you want in one big profile and then add some html in Field Pre Help / Field Post Help to add the title to separate content. You can then add css and/or javascript to make it look like there are more than one profile.

# Answer
> 1 votes
A real 'cheapskate' solution is to break up a big profile by eg entering in to the 'help' field of the item above where you want the new profile to begin a horizontal rule and heading such as `<hr><h3>this is my sub-profile title.....`

It can work nicely ;-) and very easy

# Answer
> 1 votes
I think as of 4.4 ( may be 4.3 too ) you can add profile field "Formatting", which is free html content, that can be used as an separator.

---
Tags: civicrm
---


# Question
Title: How to send E-mail and SMS notifications when one user outbid another user in drupal 7?
I am new to auction idea of drupal 7. My client wants an checkbox to be implemented ,where users can select whether they require any e-mail notification /sms or both or none.I want to send e-mail and sms notification to the respective logged in user on the basis of bids placed by them!

I configured the mail and sms notifcation part .Can anyone let me know how to send notifications when user checks the checkbox in drupal 7 on the basis of bid?

# Answer
> 0 votes
To add to user28867's answer which gives a useful way to send messages to users, you seem to need a way to trigger those messages.

Assuming the trigger is based on saving a node of some kind you should look at hook\_node\_presave which will tell you when a node is saved.

Create a custom module to receive that message and act on the hook by creating a function that implements the hook.

Of course the standard warnings apply:

* Make sure you have replace 'hook' with the name of your module.
* Clear the cache before trying it out as Drupal doesn't look for hooks on boot or init.

# Answer
> 0 votes
I would look at the Message module

> The Message module is the core of the message stack. It enables logging and displaying system events in a number of different use cases. Events that are recorded over time are sometimes call activity streams. Exportable messages subtypes can be created for different use cases with custom fields and display (view) modes.

---
Tags: 7, commerce
---


# Question
Title: Move fields from additional settings to field_group on node edit forms
I try to move some settings, for example the comment or menu settings, from the "additional settings" to my own field group created with the Field Group module.

As there is no way to access the fields under additional settings via the gui I thought about moving them via a form\_alter hook, but with no success.

**Update**

Here is the code i used in a custom module to (unsuccessfully) move a field:

```
function form_tweaks_form_alter(&$form, &$form_state, $form_id) {
  if(isset($form['#node_edit_form']) && $form['#node_edit_form']) {
    // Adding the comment settings to my field group
    $form['#group_children']['comment_settings'] = 'group_sidebar_tab4';

```

My module's weight is lower then the weight of the field group module and when I use the above code on other fields added to the content type, for example an image field, it works just fine.

**Update 2**

Just to make sure, I am talking about **node forms**. I want to move certain elements that resist in the "additional settings" vertical-tab-group to other groups.

# Answer
> 1 votes
After a good amount of researching I stumbled upon the Renderable Elements module.

It is still a bit experimental, but it makes a bunch of form elements available for rearrangement that are hard-coded in the node module and therefore not accessible via manage fields.

# Answer
> 1 votes
Display Suite

-module which changes the `manage display` page to allow exactly for that and moving title, links, comments and way more useful features like changing/resetting field and views templates, linking between displays, dynamic & block fields, moving fields to a block just to name a few. It could replace views in those cases where you mainly use views to have more control over the output. Thank You.

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


title: Context Filters Views Taxonomy Parent

text:
# Question
Title: Context Filters Views Taxonomy Parent
I have a taxonomy list like this.

```
- House
 --Large house
   --- Large white house
   --- Large green house
   --- Large pink house
 --Medium house
 --Small house

```

I have a view url that looks like this

```
<url>/categories/large-house

```

My contextual filter depth is set to 1. So when I go to the above URL it displays all the nodes that have Large house and Large house children attached. What I want to achieve is to exclude all nodes that are attached to the Large house parent term directly and display nodes that are attached to Large house children.

Under Filter Criteria I thought this would work. My thinking is display all nodes except the nodes that have parent term Large house.

```
(term) Taxonomy term: Parent term (!= 0)

```

Any help would be great

# Answer
That's quite tricky because the taxonomy system doesn't seem to like looking for children. You might need to use Page Manager and the ctools context system to achieve this.

* Create a 'page' (url) at /categories/%term-id that has the term currently being viewed as a context
* Create a view pane that requires a context of parent term id which shows all nodes that have the taxonomy term subordinate to the parent term
* use the view pane in your 'page' and set the context to the term being viewed

There's a rather good example of a similar use case here (watch the whole series, it's really good).
> 2 votes

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


# Question
Title: How to add a dynamic cart link to the user menu?
Commerce already defines two menu items in the Navigation menu:

* Shopping cart - 'cart' - enabled by default, static
* Shopping cart - 'cart/my' - disabled by default, dynamic

'cart/my' uses a custom title callback, 'commerce\_cart\_menu\_item\_title' that builds a dynamic menu link in the form: Shopping cart (2 items)

If I want to add a new menu item for the shopping cart to the User Menu, what's the proper way to do this? Do I first need to duplicate a menu item, then override the duplicate?

Ideally, I would be able to set my own title callback so that I can optionally build a dynamic menu in any format I choose.

# Answer
> -1 votes
You can create a new menu programatically through menu hooks, and a great source for sample code and explanation is the menu\_example portion of the Examples Module.

For example

```
function mymodule_menu() {
     $items['cart/new_menu_item'] = array(
    'title' => 'Shopping cart (# items)',
    'title callback' => 'mymodule_new_menu_item_title',
    'title arguments' => array(TRUE),
    'page callback' => 'mymodule_new_menu_item_redirect',
    'access arguments' => array('access content'),
    'type' => MENU_SUGGESTED_ITEM,
  );
  return $items;
}

```

---
Tags: routes, commerce
---


# Question
Title: How to configure settings.php for Drupal site with Varnish and CDN?
I am completely new to the back-end issues, so I would appreciate any detailed answers with explanation.

We need to configure our settings.php file so that it works with Varnish and CDN. Currently, it's commented out by default. I read the comments over and over in the settings.php, and it doesn't make much sense, or I don't know how to provide the information.

> In the most simple scenario, the proxy server will add an X-Forwarded-For header to the request that contains the client IP address. However, HTTP headers are vulnerable to spoofing, where a malicious client could bypass restrictions by setting the X-Forwarded-For header directly. Therefore, Drupal's proxy configuration requires the IP addresses of all remote proxies to be specified in $conf\['reverse\_proxy\_addresses'\] to work correctly.
>
> ...
>
> In order for this setting to be used you must specify every possible reverse proxy IP address in $conf\['reverse\_proxy\_addresses'\]. If a complete list of reverse proxies is not available in your environment (for example, if you use a CDN) you may set the $\_SERVER\['REMOTE\_ADDR'\] variable directly in settings.php. Be aware, however, that it is likely that this would allow IP address spoofing unless more advanced precautions are taken.

Several things that concern me:

1. What comments do I need to uncomment?
2. Since I'm using a CDN, I guess I'll have to use: $\_SERVER\['REMOTE\_ADDR'\]. But what are the "advanced precautions" available that I can take to prevent IP spoofing?

Thanks

# Answer
> 1 votes
If you don't know what you're doing (and to a certain extent even if you do) it's probably better to use modules to accomplish what you're trying to do:

1. Varnish
2. CDN

This is mainly due to the extra configuration and set-up help you get with the modules

---
Tags: configuration, proxies, cdn
---


# Question
Title: Request an Ajax form through Ajax [solved]
I want to load a form through Ajax in a custom Javascript Event as it is explained in this tutorial. I receive the form, but its ajaxified behaviour is very strange.

My Javascript:

```
var address = $(location).attr('protocol') + '//' + $(location).attr('hostname');
var url_get_button = address + 'mymodule/get_button/';

Drupal.ajax.prototype.specifiedResponse = function() {
  var ajax = this;
  try {
    $.ajax(ajax.options);
  }
  catch (err) {
    return false;
  }
  return false;
};

var ajax_settings = {};
ajax_settings.event = 'onload';
ajax_settings.keypress = false;
ajax_settings.prevent = false;
ajax_settings.url = url_get_button;
Drupal.ajax['get_button'] = new Drupal.ajax(
  null, $(document.body), ajax_settings);

//the following is somewhere at the right js event...
Drupal.ajax['get_button'].specifiedResponse();

```

My php code:

```
function mymodule_menu() {
  $items['mymodule/get_button'] = array(
    'page callback' => 'mymodule_send_button',
    'type' => MENU_CALLBACK,
    'access callback' => 'user_is_logged_in',
  );
  $items['mymodule/next_ajax'] = array(
    'page callback' => 'mymodule_next',
    'type' => MENU_CALLBACK,
    'access callback' => 'user_is_logged_in',
  );
}

function mymodule_get_form ($form, &$form_state) {
  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Submit'),
    '#ajax' => array(
      'event' => 'click',
      'path' => 'mymodule/next_ajax/',
      'effect' => 'fade',
    ),
  );
  return $form;
}

function mymodule_send_button() {
  $form = drupal_get_form('mymodule_get_form');
  $form = ajax_pre_render_element($form);

  $commands = array();
  $commands[] = ajax_command_replace('#replace-this', render($form));
  $commands[] = ajax_command_invoke(NULL, "some_js");

  $button = array('#type' => 'ajax', '#commands' => $commands);
  ajax_deliver($button);
}

function mymodule_next() {
  commands = array();
  $commands[] = ajax_command_alert('works!');
  $message = array('#type' => 'ajax', '#commands' => $commands);
  ajax_deliver($message);
}

function mymodule_node_view() {
  drupal_add_library('system', 'drupal.ajax');
  drupal_add_library('system', 'jquery.form');
}

```

Well, if `Drupal.ajax['get_button'].specifiedResponse();`is called in the Javascript event, the button will be loaded, but if I click on the button, the page is reloaded with `url_get_button` (which was used to request the button) instead of getting the alert window with 'works!'.

But if I add another form builder function and call this function with `drupal_get_form()` within the hook\_node\_view() (without returning anything!!), it will work.

So I add:

```
function mymodule_get_another_form ($form, &$form_state) {
  //I have to add the following line in order that it works
  $form2['submit'] = array();
  return $form2;
}

```

and change my hook\_node\_view() to:

```
function mymodule_node_view() {
  drupal_add_library('system', 'drupal.ajax');
  drupal_add_library('system', 'jquery.form');
  $form2 = drupal_get_form('mymodule_get_another_form');
  //I don't return $form2...
}

```

Well, in summary: I want to request an ajaxified button through a custom Javascript event. I receive the button, but it is not ajaxified and on top the wrong url is linked. But if i call `drupal_get_form()` with another 'empty' form builder function during the page load, it will work and I will get the alert message after clicking on the button.

I use Drupal 7.

Does anyone have an advice for me? Why isn't it working without the second form builder function and why does it work with it?

I would welcome every advice. Thank's a lot.

Daniel

# Answer
I got it: In a sidebar, there was another form with a submit button provided by another module. This submit button has also the key 'submit'. In the form builder function I changed the key 'submit' to e.g. 'mymodule\_submit' and now it works! So I don't need this strange second form builder function anymore.
> 0 votes

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


# Question
Title: "This page was last modified on" code not displaying
I added the following code to my `node.topl.php` but nothing is displaying on my site. What am I missing?

```
<?php
if ($submitted) {
  echo 'This page was last modified on ' . date( "F j, Y",$node->changed);
} ;
?>

```

# Answer
> 0 votes
Perhaps that content type has "submitted by" information hidden.

Try just:

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

```

And clear cache at `Admin > Config > Performance`

# Answer
> 0 votes
I have a slightly different approach on this. Edit the `page.tpl.php` and add this:

```
<?php if (isset($node->changed)): ?>
  <div class="page-update">
    <time datetime="<?php echo date('Y-m-d', $node->changed); ?>">Page Updated: <?php echo date('m-d-Y', $node->changed); ?></time>
  </div>
<?php endif; ?>

```

---
Tags: 7, nodes
---


title: How to NOT show results on view page

text:
# Question
Title: How to NOT show results on view page
This is going to be a ridiculously simple question and after getting this crazy view working, I don't' know why I can't figure this out.

I have created a view from entityform and field collections. Got everything working, displays what I want. The user clicks on the link in the nav, page opens, exposed filter is displayed, along with the results of the view which is everything in the db/view.

I only want the user to see the exposed filter when they click on the link to the view/page, then the user will add the 'item number' to the filter, click search/apply and see the results. I am hoping I don't have to create another view and link things.

How can I accomplish this?

# Answer
You can set the value of the Exposed form style to "input required". This shouldn't display the items when the first view the page.

Is that what you were after?
> 3 votes

---
Tags: views
---


# Question
Title: How do I update a site after its installation profile is updated?
Say I decide to add a new module to an installation profile I've created and used to build a bunch of sites with. Can I easily use Drush to update all of those sites to the latest version of the Installation Profile?

I've just recently started to grok installation profiles, but I'm not sure if they are useful after a site has been set up. I manage 40+ sites at work, so this would be amazing if possible.

TIA.

Aaron

# Answer
I don't know if you have any problem using Drush to update the installation profile, but I use git and everything is fine.

If you have code (in the installation profile) that writes on the db and push this to production nothing will happen. So all your changes must done manually.

Finally, the installation profiles aren't the best way to maintain a site, after Drupal install nothing will happen.

About the 40sites take a look at Aegir. It's a hosting platform for Drupals.
> 0 votes

---
Tags: drush, installation-profiles
---


# Question
Title: ajax_deliver returns json instead of content
I have a panel with two columns. In the left is a views with teasers, in the right the full body text of a node. If you click on a link in the views the content in the right panel should be replaced with the body text (and images). Here the code of the module:

```
<?php
function customNews_menu() {
        $items['customNews/%/%node'] = array(
                'access arguments' => array('access content'),
                'page callback' => 'customNews_ajax_callback',
                'access callback' => 'user_access',
                'page arguments' => array(1,2),
                'type' => MENU_CALLBACK,
        );
        return $items;
}

function customNews_ajax_callback($js, $node) {
    if ($js == 'nojs') {
        drupal_goto('node/' . $node->nid);
    }
        $div_id = 'customNewsContent';
        $vnode = node_view($node);
        $vnode['is_ajax'] = true;
        $output = '<div class="panel-pane pane-node" id="'.$div_id.'">'.theme("node", $vnode).'</div>';
        $commands = array();
        $commands[] = ajax_command_replace('#'.$div_id, $output);
        $page = array('#type' => 'ajax', '#commands' => $commands);
        ajax_deliver($page);
}
?>

```

When I run it I get the following back in the browser:

```
[{"command":"settings","settings":{"basePath":"\/drupal\/","pathPrefix":"","ajaxPageState":{"theme":"seeleben","theme_token":"wdFHgqik_Sx4kvKrKXtT9tAndWxYgNr2-cO6lfT09gg"},"colorbox":{"opacity":"0.85","current":"{current} of {total}","previous":"\u00ab Prev","next":"Next \u00bb","close":"Schlie\u00dfen","maxWidth":"98%","maxHeight":"98%","fixed":true,"mobiledetect":true,"mobiledevicewidth":"480px"}},"merge":true},.........

```

What do I do wrong?

# Answer
***You are almost there!***

1. You are opening a serious security hole in your site, allowing anyone who has `access content` permission to access all nodes bypassing node access system.

Assuming you need to use ctools's Ajax framework extension, you obviously need to have ctools module enabled.

**1. Change your menu loader to this:**

`$items['customNews/%ctools_js/%node']`

This will make Drupal pass the second %ctools\_js argument to ctools\_js\_load function that returns TRUE if `nojs` was changed to `ajax`.

**2. The link.**

Ctools won't change all "nojs" occurrences in the page. You need to create a special link using `ctools_ajax_text_button` function, or by adding classes to the link.

```
<?php
  ctools_include('ajax');
  ctools_include('modal');
  ctools_modal_add_js();
  print ctools_ajax_text_button(t('Read more'), 'customNews/nojs/1'); //1 is the node ID. Replace accordingly. You need to use "nojs" here.
?>

```

**3. Almost there!**

Your code should work now. However, make sure you have proper node access checks before showing anything. `SA-CORE-2-14-005` was touch enough.

```
if ($js == 'nojs') {
        drupal_goto('node/' . $node->nid);
    }

```

Can be changed to:

```
if (!$js) {
  drupal_goto('node/' . $node->nid);
}

```

The importance of this "special link" is that ctools's JS registers all anchor tags in `Drupal.ajax` that follows the class name convention. For my own use, I have a small function that returns the proper link so I don't have to include ctools's `ajax.inc` file.
> 2 votes

---
Tags: ajax
---


# Question
Title: Create Taxonomy vocabularies and terms in installation profile
I'm creating a Drupal installation profile(drupal 6) and want to create taxonomy vocabularies and terms. How to create taxonomy vocabularies and terms in installation profile?

# Answer
'Terms' are data, so you must import them using the Migrate module or Feeds module.

It's easy to create 'vocabularies', not programmatically but using a Feature and then enable it with you installation profile.

But if you want programmatically here is a good article that describes how to create Taxonomies vocabularies and terms programmatically.
> 1 votes

---
Tags: taxonomy-terms, installation-profiles
---


# Question
Title: Change Text of Create an Account in Login Block
I want to change text of **Create an account** to

```
<div>something></div><span><a href="actual_link">Click here</a></span/>

```

When I print the form I got these values

```
[links] => Array
        (
            [#markup] => <ul><li class="first"><a href="/user/register" title="Create a new user account.">Create new account</a></li>
<li class="last"><a href="/user/password" title="Request new password via e-mail.">Forgot your password?</a></li>
</ul>
        )

```

Also, I gave a try in `settings.php` like

```
$conf['locale_custom_strings_en'][''] = array(
  '"Create a new user account' => ' <div>somethifn></div><span><a href="actula link>Click here</a></span/>',
);

```

But this prints as a text.

Anybody can help?

# Answer
The above mentioned problem can be easily solved by using hook\_form\_alter hook\_form\_alterhook\_form\_alter(&$form, &$form\_state, $form\_id) . You can use that function in our template.php of your custom theme .

In template.php write..

```
function custom_theme_form_alter(&$form, &$form_state, $form_id){
  if( $form['form_id']['#value'] === 'user_register_form'){// For registration form on 'user/register' page
    $form['actions']['submit']['#prefix'] = '<div class="test">';
    $form['actions']['submit']['#value'] = '--your text--';
    $form['actions']['submit']['#suffix'] = '</div>';
  }
  if( $form['#id'] === 'user-login-form' ){  // For login block that comes with drupal core blocks and can be assigned to any region.
    $form['links']['#markup'] = '<div class="item-list"><ul><li class="first"><a href="user/register" title="--your text--">--your text--</a></li>
<li class="last"><a href="/user/password" title="Request new password via e-mail.">Request new password</a></li>
</ul></div>';
  }
}

```

This will change your text from 'Create a new account' to your custom text. And don't forget to clear the cache :).

Reply on this thread if you still find some problem.
> 1 votes

# Answer
So lets assume you want to alter the tab-menu of the `/user` page.

First the `dpm()` doesn't work because you are logged out.

Then you must create a module, but if you are too lazy paste the code on the `template.php` of your theme and rename `module` with your theme's name.

Then debug the menu:

```
function module_menu_local_tasks_alter(&$data, $router_item, $root_path) {
  debug($data);
}

```

After you find the `title` you want to edit your function:

```
function module_menu_local_tasks_alter(&$data, $router_item, $root_path) {
  // The path of the array
  debug($data['tabs'][0]['output'][0]['#link']['title']);
  // Edit the actual array value
  $data['tabs'][0]['output'][0]['#link']['title'] = "My new title";
}

```

If you want to edit something in the login form:

```
function module_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'user_login') {
    debug($form);
  }
}

```
> 0 votes

# Answer
I have solved the same problem with just two lines at the top in my `page.tpl.php` file,

```
<?php if($title == 'Create an account'):$title='whatever title you want';endif;  ?>

```

You can also include html tags to modify the title.

Thank you.
> -2 votes

---
Tags: 7, theming
---


title: omega 4 sprites css

text:
# Question
Title: omega 4 sprites css
I am using omega 4 theme. To generate css sprites I have used following in my layout sass file

```
@import "social-icons/*.png";
@include all-social-icons-sprites;

```

It generated this file **social-icons-s8394565a36.png** in generated folder in my images folder, but I cant find the css for my icons.

Is it suppose to generate the CSS also if so where can I find that ?? I have checked almost all directories in my SASS\LAYOUT\MY-LAYOUT directory but it seems that no css is generated for sprites

# Answer
Don't be confused by the fact that you're using Omega 4, which doesn't have much to do with the spriting aside from the fact that it allows you to use Compass to compile its styles.

You can find great write-ups on Compass spriting here and here.

Once you've created the spritesheet with:

```
@import "social-icons/*.png";

```

You can use the sprites like this, where you have a file at "social-icons/facebook.png":

```
.facebook-icon {
  @include social-icons-sprite(facebook);
}

```

Alternatively (my preference), you can use spritesheets like this:

```
$social: sprite-map("social-icons/*.png");

.facebook-icon {
  background: sprite($social, facebook);
}

```

And you can get even more hands-on:

```
.facebook-icon {
  background-image: sprite-url($social);
  // Offset the facebook sprite x-position by 2px and y-position by -6px.
  background-position: sprite-position($social, facebook, 2px, -6px);
}

```
> 2 votes

---
Tags: theming
---


# Question
Title: Load Aegir's site credentials from a php function
I'm using Aegir and want to inject some data into a site's vhost. And I managed to do it thanks to this post.

My problem is I can't find an Aegir function to load a site's dabase configurations from this Aegir functions listing to do it programmatically on each site-verify.

I need to find a function or method that would return a site's data:

* db\_name
* db\_user
* db\_passwd
* etc

I tried `Provision_Config('mysite.com')` but I have a `template argument missing error`.

Does anyone know which function I should use to get the data? I usually use `drush sql-connect` in ssh, but here I'm not sure it would be a clean way as it should be in a php script.

The goal is to make Drupal work with multi-site / multi-folder (I'm aware of that post and patch, but my solution seems to work for me without having to patch anything):

```
<VirtualHost *:80>
  DocumentRoot /var/aegir/platforms/myplatform

  ServerName mysite1.com
  SetEnv db_type  mysql
  SetEnv db_name  mydbname_1
  SetEnv db_user  mydbname_1
  SetEnv db_passwd  *********
  SetEnv db_host  localhost
  SetEnv db_port  9854

  # Credentials from other Aegir's site
  # located in a subfolder /blog.
  <Location /blog>
    SetEnv db_type  mysql
    SetEnv db_name  mydbname_2
    SetEnv db_user  mydbname_2
    SetEnv db_passwd  *********
    SetEnv db_host  localhost
    SetEnv db_port  1258
  </Location>

</VirtualHost>

```

# Answer
> 14 votes
Installing sites in sub-directories is supported in Aegir 2+ without any such hacking. Just enable the "Site subdirectories" feature, under the 'experimental' group at admin/hosting/features.

That said, to answer your question, DB credentials are available via drush\_get\_context('site').

# Answer
> 1 votes
> I usually use drush sql-connect in ssh, but here I'm not sure it would be a clean way as it should be in a php script.

If I understand correctly, you are writing a custom PHP script that needs to connect to the database of a Drupal site managed by Aegir?

If yes, you can use:

```
$ drush php-script your-script.php

```

This bootstraps Drupal (and connects the database) and will call your script as if you had run `$ php your-script.php` on the command line.

---
Tags: drush, aegir
---


title: Can I call drupal_add_css from a block?

text:
# Question
Title: Can I call drupal_add_css from a block?
I'm building an HTML table in a php filter in a block. Can I/is it OK if I call drupal\_add\_css() from the block php?

Thanks.

# Answer
Although probably ok, rather than using the PHP filter, you may be interested in using

To define your blocks instead. Perfectly fine to use drupal\_add\_css there.

Eg :

```
<?php
drupal_add_css(drupal_get_path('module', 'custom') . '/css/custom.css', array('group' => CSS_DEFAULT, 'every_page' => TRUE));
?>

```
> 4 votes

# Answer
instead of using hook\_block\_view, which implies creating the block content fully by hooked functions, i am using hook\_block\_view\_alter like this. It maintains the capability to alter the content using Drupal's block admin pages in more user friendly way :

```
function font_awesome_add_css_block_view_alter(&$data, $block) {
  if (!is_object($data) && !isset($data->bid)) {
    return;
  }
  switch ($data->bid) {
    case '366':
      if (is_array($data['content'])) {
        break;
      }
      $current_content = $block['content'];
      $block['content'] = array(
        '#markup' => $current_content,
        '#attached' => array(
          'css' => array(
            'http://maxcdn.bootstrapcdn.com/font-awesome/4.1.0/css/font-awesome.min.css'
          ),
        ),
      );
    break;
  }
}

```
> 0 votes

---
Tags: 7, blocks
---


# Question
Title: Drush make Distribution throwing errors: exec() unable to fork bootstrap.inc:636
I'm using DrupalPro VM and trying to do a `drush make` on the distribution One Page CV.

I build the distribution:

```
sudo drush make onepagecv.make -y

```

But I'm getting the following errors during the make and crashes my terminal. I logged the install process and it seems to stop at the following.

Here is the log:

# Answer
This is probably related to some resources limit or temporary glitch. So first try to restart your Apache.

If this won't help, make sure that you've necessary requirements to run drush (which is either curl or wget).

Otherwise it could be some resource limitation on your environment. E.g. check for `ulimit -a` or `kern.maxprocs`.

If there is still problem, please add `-v` for verbose mode or `-d` for debug messages for `drush`, you could more easily track the issue.
> 1 votes

---
Tags: 7, distributions, drush
---


# Question
Title: Creating node in installation profile but body field stays empty
I am trying to generate nodes in my installation profile. The weird thing is that everything works except the body. First here is the code I use:

```
$date = new DateTime();
$node = new stdClass();
$node->type = 'article';
$node->status = 1;
$node->uid = 1;
$node->title = 'Test title';
$node->promote = 1;
$node->created = $date->getTimestamp();
$node->timestamp = $date->getTimestamp();
$node->sticky = 0;
$node->format = 3;
$node->language = LANGUAGE_NONE;
$node->teaser = '';
$node->revision = 0;
node_object_prepare($node);
$node->intro[$node->language][0]['value'] = 'introtext index';
$node->body[$node->language][0] = array(
    'value' => 'Body text test',
    'summary' => '',
    'format' => 'filtered_html',
    'safe_value' => 'Body text test'
);
node_save($node);

```

The weird thing is.. This code works perfect when I add it in the index.php. But when I add this exact same code in the installation profile everything works except the body(it stays empty).

I tried the next two possibilities see below:

`$node->body = 'Body text test'`

`$node->body[$node->language][0]['value'] = 'Body text test'`

I also replaced `$node->language` for `'und'` on all possibilities.

Still I find it weird that my code works in the index.php but not in the installation profile. Does anybody have a clue what I am doing wrong or what needs to change?

# Answer
I know this old, but I just came across it. It's really difficult to know what's going on without being able to look at all of the code, but my guess would be you are trying to use 'format' =\> 'filtered\_html' before you've define it in the .install. In the distributions I help to maintain, we always call filter\_format\_save as one of the first items of business...

http://cgit.drupalcode.org/cm\_starterkit\_easy/tree/cm\_starterkit\_easy.install#n14
> 1 votes

# Answer
On the lines of the following answer in the link : LINK

You can create a new content type first like shown in the webform.install file as below:

```
function webform_install() {
  module_load_include('inc', 'node', 'content_types');
  db_update('system')
    ->condition('name', 'webform')
    ->condition('type', 'module')
    ->fields(array('weight' => -1))
    ->execute();

  // Optionally create the default webform type.
  if (variable_get('webform_install_create_content_type', TRUE)) {
    $webform_type = array(
      'type' => 'webform',
      'name' => st('Webform'),
      'base' => 'node_content',
      'description' => st('Create a new form or questionnaire accessible to users. Submission results and statistics are recorded and accessible to privileged users.'),
      'custom' => TRUE,
      'modified' => TRUE,
      'locked' => FALSE,
    );
    $webform_type = node_type_set_defaults($webform_type);
    node_type_save($webform_type);
    node_add_body_field($webform_type);
  }
}

```
> 0 votes

---
Tags: 7, nodes, installation-profiles
---


title: How do I redirect to an external URL?

text:
# Question
Title: How do I redirect to an external URL?
Drupal 7 has drupal\_goto() that would allow redirecting to an external url.

The change record indicated that ControllerBase::redirect is the method to be called in D8. https://www.drupal.org/node/2023537

This seems to work with internal drupal URLs but throws an error with external http urls -

```
[12-Nov-2014 21:00:22 Asia/Kolkata] Uncaught PHP Exception Symfony\Component\Routing\Exception\RouteNotFoundException: "Route "https://www.facebook.com/dialog/oaut....." does not exist." at /Applications/MAMP/htdocs/d8/core/lib/Drupal/Core/Routing/RouteProvider.php line 147

```

What would be the ideal equivalent of drupal\_goto in D8 to redirect to an external URL?

# Answer
With a route name on a Controller:

```
use Drupal\Core\Controller\ControllerBase;

class MyControllerClass extends ControllerBase {

  public function foo() {
    //...
    return $this->redirect('user.page');
  }
}

```

With an absolute URL:

```
use Drupal\Core\Routing\TrustedRedirectResponse;

return new TrustedRedirectResponse('https://google.com');

```

On a form `RedirectResponse` doesn't work, then:

With a route name:

```
public function submitForm(array &$form, FormStateInterface $form_state) {
  //...

  $form_state->setRedirect('user.page');
}

```

With an absolute URL:

```
public function submitForm(array &$form, FormStateInterface $form_state) {
  //...

  $form_state->setResponse(new TrustedRedirectResponse('https://google.com', 302));
  // You can change the response code from 302 to whatever you need
}

```
> 26 votes

# Answer
`return new RedirectResponse($absolute_url);` seems to work
> 2 votes

---
Tags: 8, uri
---


# Question
Title: selected option on drupal form not coming up first
I added a '#default\_value to my drupal7 form , and it says

```
<option selected="selected" value="81">Service</option>

```

(this is the option I want selected) but I want it to come out first in the list and it isnt .

how can I get it to come out first?

# Answer
> 0 votes
This is only a problem in firefox, and the way to fix it so it works in firefox as well is to add this: $form\['#attributes'\]\['autocomplete'\] = 'off';

---
Tags: forms
---


# Question
Title: Can drush accept piped commands for aliases?
Can drush take piping commands for a multisite command using an alias?

I'm trying to setup a simple refresh function from my prod to dev/staging. Any pointers or tips would be welcome. just started learning this stuff.

```
drush $prodalias sql-dump --gzip >/tmp/$site.sql.gz

gunzip /tmp/$site.sql.gz | drush $devalias sqlc

```

# Answer
> 1 votes
It should be allowed to use piping in drush aliases as this feature was added recently by improving escaping options for core-exec.

So you have to upgrade your drush to the recent version (7.x).

See: Are pipes allowed in shell aliases?

---

If you prefer to use script, here is one which I'm usually using:

```
#!/bin/sh
# pull-db.sh
# Script to pull the database from remote to local environment.
[ -z "$1" ] && { echo "Usage: $0 @remote (args)"; exit 1; }
SRC="$1"
shift
drush $SRC sql-dump | drush $* sql-cli

```

# Answer
> 1 votes
I write bash/shell scripts involving Drush all the time. If it's just the variables you're interested in, that has nothing to do with Drush and works fantastically. As for piping, I i'm not too sure what all is supported.

For bash to interpret your variables, you just need to wrap them in quotes.

Example:

```
#!/bin/bash
source=$1
dest=$2

# Check if we have both a source and a destination.
if [ -z "$dest"]; then
  # Looks like at least one of our parameters are missing, notify and exit.
  echo "A source and destination Drush alias is required."
  exit 1
fi

drush sql-sync "$source" "$dest"

```

Usage:

```
./my-sync-script.sh @alias.prod @alias.dev

```

---
Tags: drush, multi-sites
---


# Question
Title: Why doesn't "drush --debug en color" show any output?
Running `drush en color` from the /xampp/htdocs/drupal directory doesn't output anything. The same happens with `drush --debug en color`. Why?

# Answer
It seems that your drush installation is broken. So you have to reinstall it again.

The easiest way would be to install Composer and follow the instructions from drush-ops (especially check Windows section). Then check How to configure Drush on Windows 7?

If this is still happening, check your PATH environment variable if it contains the correct directories (maybe you have some non-drush binary within your system list of folders which could cause some conflict).
> 1 votes

---
Tags: drush
---


# Question
Title: Entityform: email submitted form to someone who is not admin?
How do I get the Entityform module to email the contents of a submitted form to user@example.com. The owner of this email address is not the admin. Thanks

# Answer
go to admin/config/workflow/entity\_rules/entityform\_submission and clone "Entityform Notification Email Submitter" or "Entityform Notification Email Admin", edit accordingly. If that does not works, please add a custom rule (admin/config/workflow/rules):

event: After saving a new entityform submission Condition: Entity has field: \[entityform\], Field: token of your field Action: send email, use the token for your email field or any email you want.
> 1 votes

---
Tags: entities
---


# Question
Title: Will Drupal 8 Twig have template inheritance like Drupal 7?
Drupal 7 you can style down to the fields on the page will we have this type of control with twig? I have reviewed a lot of documents about twig and didn't see anything that lets you have that same inheritance as the Drupal 7 template engine. If this is not built in to twig, is Drupal 8 going to be building it in?

# Answer
> 7 votes
I think you might be confusing inheritance with granularity. Twig actually does have the concept of template inheritance (see extends), while Drupal 7's theme engine doesn't.

The short answer is yes, you can expect the same from Drupal 8 as you did from Drupal 7. Specifically for fields, the example in the docs for field.html.twig will give you some insight:

> For example, for a field named 'body' displayed on the 'article' content type, any of the following templates will override this default implementation. The first of these templates that exists is used:
>
> field--node--field-foo--article.html.twig
>
> field--node--field-foo.html.twig
>
> field--node--article.html.twig
>
> field--field-foo.html.twig
>
> field--text-with-summary.html.twig
>
> field.html.twig

These can be altered/added to using `hook_theme_suggestions_alter()`, or the more specific `hook_theme_suggestions_HOOK_alter()`.

---
Tags: 8, theming
---


# Question
Title: How to style a byline field in an article content type?
There might be a simple answer to this but it's driving me crazy. I'm working on a template for an article node and I want the byline to display this way:

> By Author Name

I don't want to change the field label in the web form, so I just want the "By" to be inserted through the node template. No matter what CSS styling I use, the byline field always displays like this:

> By
> Author Name

Is there a way to get the label and field to show up inline?

Here's the PHP I'm using in the template:

```
<div class="newsbyline">
  <?php print t('By'); ?> <?php print render($content['field_newsbyline']); ?>
</div>

```

Setting the "newsbyline" `<div>` to inline doesn't seem to be working.

# Answer
> 0 votes
It would be helpful to see the markup that surrounds the newsbyline field. I'm guessing there's a div or some other element around `field_newsbyline` that's a block element by default. If you change the CSS for that element to `display: inline` that may solve the problem.

Alternatively, if the above code is in your node template, you could adjust the markup in the field template instead:

1. Copying `field.tpl.php` from the base theme you're using or from Drupal core's `/modules/field/theme/` into your theme
2. Rename it `field--field-newsbyline.tpl.php` (assuming field\_newsbyline is the machine name of your field)
3. Edit that template to add `<?php print t('By'); ?>` in the appropriate spot.

By making the change in the field template, you should be able to get your code inside the wrapper div, rather than having it outside.

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


# Question
Title: How to add a field to the contact form in Drupal 7?
I want to add a phone field and a company field to the contact form. How to overwrite the form in `template.php`? Thank you

# Answer
> 2 votes
This module http://drupal.org/project/contact\_field will do what you want and I have know about it since D6, but the last time I try it in D7 it was buggy.

So far the best alternative I have found that works all the time like a charm is the webform module http://drupal.org/project/webform as you will be able to add or remove fields as need it and the email support works well and you also get the bonus of storing all the contacts attempts in case your email server or service was down for any reason.

# Answer
> 1 votes
Why not you use hook\_form\_alter() to add those two fields into the contact form?

```
function MYMODULE_form_alter( &$form, &$form_state, $form_id ) {
    if( $form_id == 'contact_site_form' ){
        $form['message']['#weight'] = 2;
        $form['copy']['#weight']    = 3;
        $form['phone'] = array(
            '#type' => 'textfield',
            '#title' => t('Phone'),
            '#required' => TRUE,
            '#weight' => 1
        );
        $form['company'] = array(
            '#type' => 'textfield',
            '#title' => t('Company'),
            '#required' => TRUE,
            '#weight' => 1
        );
    }
}

```

You can alter the contact mail by using hook\_mail\_alter(). The variable `$message['params']` contains the form values submitted.

```
/**
 * Implementation of hook_mail_alter
 * Override mail structure
*/
function MYMODULE_mail_alter(&$message){
    if($message['id'] == 'contact_page_mail') {
        $language = $message['language'];
        $params   = $message['params'];
        /*
        $message['to'] = $more_receipient;
        $message['subject'] = $subject_overridden;
        $message['body'][0] = $msg_body;
        $message['body'][1] = $param_to_msg_body;
        */
    }
}

```

# Answer
> 1 votes
There are the following modules which you can consider:

* Contact Forms

> Which expands the features of the site wide contact form. It eliminates the drop down category menu by generating a clean looking contact form.
* Contact form fields

However it's minimally maintained and it needs work for 7.x and it's not ready yet for the production. Please find my fork with some fixes, however still it doesn't work perfectly.

---

Alternatively this should be straight forward via Drupal API:

```
/**
 * Implements of hook_FORM_ID_form_alter().
 */
function foo_form_contact_site_form_alter(&$form, &$form_state, $form_id){
    $form['location'] = array(
        '#title' => t('Your location'),
        '#type' => 'textfield',
        '#required' => TRUE,
        );

    $order = array('name', 'mail', 'subject','location', 'cid', 'message', 'copy', 'actions');

    foreach($order as $key => $field) {
        $form[$field]['#weight'] = $key;
    }
}

/**
 * Implements of hook_mail_alter().
 * This is where the mail being sent if edited. I just add it the the end of the message
 */
function foo_mail_alter(&$message) {

    if ($message['id'] == 'contact_page_mail'){

        $message['body'][] .= t('This is their location - ').$message['params']['location'];
    }
}

```

Source: contact\_add\_fields.module at GitHub

---
Tags: 7, emails
---


# Question
Title: how to display a gallery of custom themes
I would like to set up a gallery of all my themes and when the user clicks on the item it would go to a pre-setup Drupal instance and it would set that instance with the theme they clicked so they can see the theme in action. I know how to create a photo gallery but i want to have the images when click go to a sub site that is preset to change the default theme to the one passed in the link so that the user can see the live theme. I would like to have one sub site and have that sub site have all the themes installed and simple change the enabled theme based on the request. The user clicking on the images in the gallery will not be logged in. I don't want to make a different site for each theme. That would be to much unneeded work and to many databases that do not need to be. using modules would be the best over making custom code for this.

# Answer
> 0 votes
The ThemeKey module would help you to achieve this.

> ThemeKey allows you to define simple or sophisticated theme-switching rules which allow automatic selection of a theme depending on current path, taxonomy terms, language, node-type, and many, many other properties. It can also be easily extended to support additional properties exposed by other modules.

---
Tags: theming
---


# Question
Title: Programmatically Create 'full_html' Page Node in Drupal 7
So I'm able to create a page programmatically, BUT even though I'm specifying the 'full\_html' filter, the page is being created with the 'filtered\_html' filter which means that the code I'm writing to the page after it's created is being stripped out. Here's the line I'm using to set the filter type:

```
$node->body[$node->language][0]['format'] = 'full_html';

```

Why is the filter type being ignored when the node is created?

Thanks in advance, Bryan

# Answer
OK, as it turns out, the 'body' field is not called 'body' in our Drupal installations; it's called 'field\_page\_body'. Changing that in the code made everything work.
> 3 votes

# Answer
It could very well be due to the default weight of the filter. You set this in content authoring \> input formats

just make "full html" the first option. let me know if that works as I had a similar issue before.
> 0 votes

# Answer
I'm using

```
node_save($node);
$wrapper = entity_metadata_wrapper('node', $node->nid);
$wrapper->body->set(array('value' => body_text, 'format'=>'full_html'));

```

hope it's helpful.
> 0 votes

---
Tags: nodes
---


# Question
Title: Programmatically subscribing all users to Mailchimp list with module
I've installed the Mailchimp plugin and added a field to my user profile called `field_mailchimp_test` and I'm attempting to subscribe all current Drupal users to this list programmatically (since it seems this feature was taken out of the 7.3 branch for whatever reason).

I attempted this code:

```
function module_mailchimp_subscribe() {
  $users = entity_load('user');
  foreach ($users as $key => $user) {
    if ($user->uid != 1 && !empty($user->mail)) {
      $edit = array(
        'field_mailchimp_test' => array(
          'und' => array(
            0 => array(
              'value' => true
              )
            )
          )
        );
      var_dump(user_save($user, $edit)); exit;
    }
  }
}

```

Which returns a user object with the `field_mailchimp_test` field set to true, which I would think would subscribe them, but when checking the users page and/or `var_dump`ing the user object, the field is no longer set to true.

So my question is either what is wrong with my code that it's not subscribing users, or what is a different (easier/more sensical) way of doing this?

# Answer
I'm pretty sure the MailChimp module doesn't actually store user subscriptions in the Drupal database, it picks up data from the MailChimp API when required.

What worked for me was to export all my Drupal users and import them into MailChimp through their website. This is fine for a once-off, and you should be able to handle new and updated users directly through the module.
> 2 votes

---
Tags: 7, emails
---


title: Unable to generate the derived image

text:
# Question
Title: Unable to generate the derived image
Today I uploaded my site to the server, and I get errors like the following:

> Unable to generate the derived image located at public://styles/sponsor\_image/public/TerraThermaSponsorLogo.png.

Image styles cannot generate images. I have tried to set permissions on styles/\* folders with `chmod -R 775 styles/`, and even tried `chmod -R 777 styles/`. The folder's owner is OK. I don't get what can be wrong.

The directory associated with public:// is sites/default/files, and it is OK.

# Answer
> 7 votes
Briefly, this is what I do whenever I have this problem:

Change user to the one running your web server (apache, httpd, www-data, nginx etc)

```
sudo -u [user] -s /bin/bash

```

and `cd` directly to the files directory, and try to write random data to a new file.

```
echo "Random text" > some_file_name

```

Usually this will fail and you'll get an error message from the OS, moving the problem out from Drupal at least. If this fails to work, you have file permissions issue. This question may be helpful: What are the recommended directory permissions?

# Answer
> 10 votes
You should also make sure you do have a graphical library (like php-gd) installed on your server: check /admin/config/media/image-toolkit (D7).

# Answer
> 7 votes
The error is coming from Image module (core) and the logic looks like:

```
$success = file_exists($derivative_uri) || image_style_create_derivative($style, $image_uri, $derivative_uri);
if ($success) {
  $image = image_load($derivative_uri);
  file_transfer($image->source, array('Content-Type' => $image->info['mime_type'], 'Content-Length' => $image->info['file_size']));
} else {
  watchdog('image', 'Unable to generate the derived image located at %path.', array('%path' => $derivative_uri));
  ...
}

```

Therefore error happens when Drupal has problem with generating an image derivative by applying all image effects and saving a cached version of the resulting image.

---

The easiest way reproduce the problem (for diagnosting purposes) is by drush.

1. Invoke image\_style\_create\_derivative() directly from drush:

```
drush -v eval 'image_style_create_derivative(reset(@image_styles()), "public://pictures/picture-123.png", "public://styles/test/test-success.png");

```

Replace `picture-123.png` with the existing picture from the log:

> Unable to generate the derived image located at public://styles/foo/public/pictures/picture-x.png

Or use any other existing one, e.g. `drush sqlq "SELECT * FROM file_managed"`.

If you don't have access to shell, use Devel module, go to `/devel/php` and paste the PHP code there.

Note: If the `files` folder is owned by Apache user, you should log-in as this user for testing purposes. Otherwise prefix your drush command with `sudo -u www-data`.
2. There are the following possibilities.

* Above test has been successful (file has been generated successfully in your files dir), if so, check if your failing picture from the log actually exists, maybe it was removed from the server.
    * If you have the same error message or the file wasn't created, then it's problem with your permission or missing libraries (check: `drush eval "print_r(gd_info());"`).
    * If you don't have any error and the file wasn't created, then check if you used the right existing files.

---

Debugging permission problems can be easily achieved by `strace`. Install it and just prefix any command that you're testing with `strace -f` (you don't have to be root).

In example:

```
$ strace -f drush -v eval 'image_style_create_derivative(reset(@image_styles()), "public://existing-image.png", "public://styles/test/test-success.png");' 2>&1 | grep "default/files"
mkdir(".../sites/default/files/styles/test", 0775) = -1 EACCES (Permission denied)
chmod(".../sites/default/files/styles/test", 0775) = -1 EPERM (Operation not permitted)

```

If you're logged in with different account which owns `files`, then don't forget to prefix your drush command with `sudo -u www-data` to run the whole command as Apache user.

# Answer
> 5 votes
This can also be caused by PHP being compiled without libjpeg (if the images that won't generate have jpeg sources). Check the output of `gd_info()` to see if there is PHP support.

---
Tags: 7, media
---


# Question
Title: How can I use Drush to determine if a module is being used or not in a multisite architecture?
I have a multisite architecture that has over 30 sites.

In one specific site search\_api\_solr version 7.x-1.0RC5 is installed, and I can see that it's enabled and being used in the module list.

In the common sites/all/modules folder search\_api\_solr 7.x-1.0-rc2 is there. When I do `drush pm-list | grep search` I can see that it's listed but "Not Installed."

Does this mean that none of the 30+ sites is using this module and it's safe to delete it? Or is that command simply telling me that it's not being used by the default install?

If the latter, how can I use Drush to tell me what specific sites are making use of modules in the common sites/all/modules directory?

EDIT:

@greg\_1\_anderson

I tried your solution with:

`drush @sites pm-info search_api_solr --field=status`

On each line of the output after hitting y I get something like:

`.appdrupal#mysite.example.com >> blahblah : some.description`

looks like the above output is 3 columns. Possible values for that 'blahblah' column seem to be numerous (requires, required by, type, title, description, version, date, package, 'group', files.. etc, etc..) nothing to denote if it's enabled)

I can see a couple times in the 'blahblah' "status", but it's not singled out. Ultimately this creates 1000s of lines of output. I tried to add | grep status but it hanged (I gave it 120 seconds).

Drupal is 7.26 and Drush version is 5.9 - thoughts?

# Answer
> 4 votes
This works in Drush 6.x and later:

```
$ cd /path/to/drupalroot
$ drush @sites pm-info MODULENAME --fields=status
You are about to execute 'pm-info devel' non-interactively (--yes forced) on all of the following targets:
  /path/to/drupalroot#default
  /path/to/drupalroot#other
Continue?  (y/n): y
.path.to.drupalroot#other   >>  Status   :  enabled
.path.to.drupalroot#default >>  Status   :  enabled

```

# Answer
> 0 votes
from within the Drupal installation directory:

```
drush @sites pml --status=enabled -y | grep module_name

```

# Answer
> -1 votes
You need to either set up Drush aliases, so you can run your command against all of the multisite's individual sites at once (as Clive suggests) or you can cd into each individual site (on D7, usually `drupalroot/sites/A_SITE/`) and run the command so it's checking using that individual site's configuration and not the default site's configuration (which is usually at `drupalroot/sites/default/`.

---
Tags: drush, multi-sites
---


# Question
Title: How can I use Display Suite with a Drupal Commerce view?
I am new to Display Suite and want to use it with the Drupal Commerce checkout forms. In particular for the review stage, which is made from a view.

I want to display the order summary in the left column and the customer profile address details in the right column.

I can see how Display Suite is used for regular nodes, but can not find any information about how it can be used for views fields. Is this even possible?

# Answer
> 3 votes
In the FORMAT section of the views edit page, there is a "Show:" option.

If you choose "Fields" (oftentimes the default for any Entity view, including nodes) then you cannot control the output of those fields with Display Suite.

There is an option "Rendered Entity".

You can alter the settings for this option, and select any view mode that you have created/configured with Display Suite. For example you can create a view mode "Foo", and select that view mode in the settings for the "Rendered Entity" option. This will work for any entity.

So you want to create a new view mode for your Commerce entity, select the layout of your choice, put the fields you want in the regions of your choice (maybe the two column 50/50 layout), and in your view Select "Rendered Entity" and select the proper view mode.

---
Tags: commerce, display-suite
---


# Question
Title: Warnings still show on page even after setting Error messages to None in Logging and Errors
I have set the Error messages to display to None

but still the website shows warning messages on top.

Also cleared the cache after this but the anonymous user can still see warning messages.

Is there anything else to be changed?

# Answer
> 1 votes
That's a pretty specific error message, and google says it is coming from this module:

https://www.drupal.org/project/netforum

at these lines: 808-812

```
  catch (Exception $e) {
    if (isset($cache_max)) { //this implies that we went even further back in the cache and could not connect, so call it quits
      if (variable_get('netforum_hide_error_messages', 0) == 0 || user_access('administer site configuration')) {
        drupal_set_message(t('Could not retreive data from server or cache.'), 'error');
      }

```

More specifically to your question, because the above module is using drupal\_set\_message it is not going to be effected by the 'error\_reporting' level since that only impacts errors that would go to the logs. This makes sense as you would want to be able to suppress syntax or PHP errors while still letting system messages like "node was saved" or "subscription processed" still appear to the screen.

Your options to suppress this are to deal with the underlying cause of the error from the module (best case), or remove the 'messages' functionality from your theme, i.e. remove where ever it is that it says:

```
print $messages;

```

but again, that is probably not the best course of action here.

---
Tags: 7, status-messages
---


title: Search on specific content

text:
# Question
Title: Search on specific content
Hi is it possible to make a search box which are searching only for some specific content.

it should be a search box that should look at titel, ingrediensliste, body, and who have made it.

# Answer
You're looking for the Custom Search module.

This module alters the default search box in many ways. If you need to have options available like in advanced search, but directly in the search box, this module is for you.

> # Basic options
>
> The module adds options to select:
>
> * **which content type(s) to search**,
> * which specific module search to use (node, help, user or any module that implements search),
> * which input type to use (with Elements),
> * advanced criteria
>
> For all these choices, there are options to switch between a select box, checkboxes or radio buttons, and also customize the selector label and the default - Any - text.
>
> # Advanced options
>
> There are also options to:
>
> * change the default search box label,
> * add a default text in the search box,
> * add advanced search criteria,
> * change the default submit button text,
> * use an image instead of the submit button,
> * change the order of all the elements,
> * include some elements in a popup block,
> * add a filter to the results page,
> * show/hide basic and/or advanced search in the results page,
> * show/hide meta data in the results page,
> * multiple search paths

You can also achieve that by writing a custom module. Have a look at

Build a Drupal 7 Content Type Search Block in 5 Easy Steps
> 1 votes

---
Tags: search
---


# Question
Title: Is there a module to provide node access based on Ip address?
I am looking for a module that provides node access or content type access based on the ip address of the user? So what would be ideal is that i can select the ip address range allowed for a particular node when creating it or i can define a range of ip address on a content type.

Once i select the ip address range then someone coming from outside of that range should not be able to access that page.

I have looked into several modules and couldn't find much. The closest thing i found is in sandbox https://www.drupal.org/sandbox/schlicki/1461406

Please let me know if i can clarify more?

# Answer
> 0 votes
The Restrict IP module is what you're looking for.

> This module allows administrators to restrict access to the site to an administrator defined set of IP addresses.
>
> Anyone trying to access the site from an IP address not in the list of allowed IP addresses will be redirected to an access denied page with the message "Your address is not in the list of allowed IP addresses". No blocks will be rendered, and no javascript will be added to the page. This will happen for any and all pages these users try to access.

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


# Question
Title: Membership contribution with profile required 'on behalf of' prefilled
I'm helping a nonprofit with a Drupal/CiviCRM site. They track memberships in CiviCRM which are associated with an organization as the primary member, and individuals linked to the organization by relationships to share this membership.

Using the "CiviMember Roles Sync" module, these individuals are granted access to a member role in Drupal.

I've created a contribution page in CiviCRM for membership signup or renewal, and since the primary member is actually the organization, I've checked "Allow individuals to contribute and/or signup for membership on behalf of an organization". Since it is a requirement, I've also made this required instead of optional. (Screenshot below).

The help text here indicates that "logged in users will be given a choice of selecting from a list of organizations that they have a permissioned relationship with OR entering a new organization" -- however, I am not able to produce the select/list despite assigning "view and update information" permissions in both directions on the relationship between the individual and the organization. The contribution page just allows typing in a text field for the org name, which will produce a lot of duplicates and extra work.

Am I missing a step to get the select list which will prefill the org's information?

# Answer
> 3 votes
The behaviour that you are expecting to see will work - at least it does for me - when the relationship between the individual and the organisation is "Employee of". Other relationship types appear not to work. Perhaps you are using a different relationship type?

---
Tags: civicrm
---


# Question
Title: Civicrm membership expiration date after renewal
I'm using D7, with CiviCRM 4.4.6. I had created a contribution page, with membership form included.

By now after renewal membership, the expiration date extend according to the end date. Eg:

Start Date: 1 Nov 2014
End date: 5 Nov 2014
Status: Expired

If renewal payment made on 11 Nov, for one month, the expiry date is changed to 5 Dec 2014.

But I want the expiry date to be one month after payment date, which is 11 Dec 2014.

Is there any way I can configure it to get the above result?

If not in configuration, any way I can change it in codes?

# Answer
This works in the 4.5.2 sandbox (unknown if it works in 4.4.6)

1. Set your membership type to rolling instead of fixed
2. Disable the "Grace" membership status
3. If you are having a membership period shorter than 3 months, also disable or shorten the "New" membership status

An alternative workaround, which however may be a bit too clunky, would be to create a new membership type monthly and update the contribution page, so that it forces people to sign up for a new membership rather than renewing their existing one. This would, however, lead to the potential for overlapping memberships if they sign up for the new membership before the end of their old one.
> 5 votes

# Answer
If you really need this and are ready to write some code. Here is what you could do :

```
/**
 * hook_civicrm_pre
 */
function myextension_civicrm_pre( $op, $objectName, $id, &$params ) {
  // changing end date for the monthly membership

  if ($objectName == 'Membership' && $op == 'create' && $params['membership_type_id'] == MY_MEMBERSHIP_TYPE_ID) {

    // FIXME: don't know if it's in params or if you need to get it using the api
    $contribution_date = ...

    // compute the new date
    $membershipDates = _getNewDatesForMyMembership($params['membership_type_id'], $params['join_date'], $contribution_date);

    // update the params, so it gets saved in the database
    $params['end_date'] = $membershipDates['end_date'];

  }
}

```

See also CRM\_Member\_BAO\_MembershipType::getDatesForMembershipType to have an idea of how CiviCRM compute dates for membership.
> 2 votes

# Answer
In the example you describe, where the renewal payment is made after the end date, removing/disabling the Grace period will have the desired effect. Essentially it will create a new membership starting from the date the payment was made.

This may have knock-on implications for you because the user will be immediately treated as a non-member from the end date rather than from the end of the grace period. So, if you were using the Civimember Roles Sync module in your Drupal site, and were, for example using that to manage access to content, there will be a period where your user will lose access to member-only content.

If the renewal takes place before the end date, then the grace period is irrelevant and the membership is simply extended for the period of the membership (one month, if I read your question correctly), starting from the previous end date, not the date the renewal was made.
> 2 votes

# Answer
I'm not sure, but Admin \> CiviMember\>Membership Types, Edit link beside relevant type, and changing Fixed to Rolling might impact this, as might disabling the Grace status under Admin\>CiviMember\>Membership Status rules.

More likely you will need to program this using `hook_civicrm_pre()`.
> 1 votes

---
Tags: civicrm
---


# Question
Title: Field depandancy module can not work for textfield in field collection
I am using field dependency module for use only 1 field

I have 2 fields text and image user can use only 1 field text or image if user can select text field other will be hidden or invisible same case with image to text field

here is conditions:

case 1:

```
Dependent:Image (field_image)
Dependees:Text (field_text)
Description:Image is invisible when Text is filled.

```

case 2:

```
Dependent:Text (field_text)
Dependees:Image (field_image)
Description:Text is invisible when Image is filled.

```

case 1 is working perfectly but case 2 is not working.

# Answer
> -1 votes
You can use Conditional Fields module which define dependencies between fields based on their states and values. Conditional Fields allows you to manage sets of dependencies between fields.

Thank you.

---
Tags: 7, entities
---