# Question
Title: Insert a view into a block or a node using a shortcode
I need the following:

I have a view that lists my portfolio projects the projects have a term reference field for its category. I want a shortcode for insert the view into some of my nodes and be able for apply arguments or filters for example:

* Category 1 AND Category 2
* Category 1 OR Category 2
* Or simply listing the project node IDs: 333,332,334

I found the Insert view module with that module I can make a shortcode like this

\[view:view\_name==arg1/arg2/arg3\]

but how I told you I need to be able for filter in the short code Category\_1 AND Category\_2 for example or list the given node IDs

How would you do this using Insert view module?

# Answer
> 1 votes
Your problem seems to be one of passing in context.

A better option is to install either the Display Suite Module, or Page Manger with Panels. It is great for passing context and creating custom views outputs on your node .With both of these options you have far more control, and if you invest in learning the ins and outs of at least one of them you will not be sorry.

I will walk you through using Display Suite:

Install CTools' Views content panes. Create a base view that lists whatever you need listed, then add a Content Pane (from CTools) to the view. Add a relationship to the term in question, and then any and all contextual filters that would be needed. Lastly, under PANE SETTINGS in views, click on Argument input, select From context for each of the contextual filters, and slect the required context for each of them.

Install Display Suite. In the display of your node type, select a layout (one column should be fine) to activate display suite to render that view mode. Create a new dynamic field. Drag it to wherever you want it displayed. Click on the gear next to it, and at the top would be a Edit content link. Click that, and select View panes, then the view you just created. It will then ask for you to select the context for each of your views contextual filters. Node being viewed is what you select.

Now when you view the node it pulls in that view with the required contextual filters and displays its output as a field.

---
Tags: 7, views
---


title: Views: Multiple Rows & Mutliple Columns

text:
# Question
Title: Views: Multiple Rows & Mutliple Columns
I've been twisting and turning the View module but can't get simple tasks done. Well it should be simple but yet Drupal don't have a good solution ...yet.

How to create 2 columns where column A have an image that spans from top to bottom and column B have 3 rows?

# Answer
I am afraid you will have to write custom code in this situation to get this done. What you can do here is create tpl file for your view with format as table and then in that tpl you can have your condition to make a table inside td.

You can fetch your views fields in tpl inside foreach ($row as $field =\> $content)

Make sure you have all the fields in your view which you want to display in table format.
> 0 votes

# Answer
Try Display Suite. It has an config option under Extras -\> Other -\> Views displays Manage the layout of your Views layout with Field UI.

This allows you full control to reorder the output of your views fields.

This is assuming as @Geoff rightly asks that your columns etc are for one result set.

If it is not, then I would think that you need to set the display of the image field to none, then group by the image field, and do some custom CSS.
> 0 votes

---
Tags: views, theming
---


# Question
Title: Views Exposed Filter Sort on Entity based on Term Reference Field from Entity Reference Relationship
I've been playing around with Views exposed filters on an entity. I have so far been able to create a relationship to another entity through an Entity Reference, and exposed the fields belonging to that entity.

What I needed to sort my entity by was a term reference field on the referenced entity (this is a one to many relationship, the sorted entity can have any number of reference entities). I was able to get a multiselect field to do so, but this is really not ideal. Using Better Exposed Filters I was hoping to get a checkbox list. But it seems that the nature of the relationship doesn't open that possibility up.

**So the question is, if I needed a View that allowed sorting an entity by an exposed Term Reference Field filter on all of its Entity References, what method would I use, if not Better Exposed Filters?**

# Answer
> 0 votes
So you have two relationships. One to the referenced entity to pull it in, and another on the term on that referenced entity to pull in data such as term names (to sort on term names).

This immediately brings to my mind an issue whereby you will have what seems like duplicate entries coming in. To avoid that you will have to use aggregation, and in the aggregation settings you will have to do a count on one of the fields (which will collapse the result set) and then do an exposed filter.

---
Tags: entities, views
---


# Question
Title: Feeds: Is it possible to set a unique field other than the title field?
I'm trying to create a feed importer that uses a unique ID that is NOT necessarily in the title field of the content type. For example, were I using the feeds importer to import a list of contacts, I'd like to have the unique ID be the phone number, yet I would prefer that the content title be the name of the contact rather than the phone number, for organization and aesthetic purposes. Is this possible? As of now, it seems I am limited to enabling only the title field as unique.

I realize I could simply put the contact name into the title field and set that as unique, but this is less prudent, as contacts may have identical names and similarly with my data, the duplicity of titles and/or misspellings is/are inevitable. Any help would be appreciated!

Thanks!

# Answer
> 0 votes
For most of my Feeds, I import the Node ID and make that unique.

# Answer
> 0 votes
Yes it is. Look at Support unique targets in mappers.

---
Tags: entities, feeds
---


title: uid is not taking

text:
# Question
Title: uid is not taking
I'm getting uid by $account-\>uid on rules when I wrote a query by using this id it returns 0 rows. Below is the code that i'm writing on rules

```
$uid=$account->uid;
$sql="select * from profile where uid=:uid";
$args = array(':uid' => $uid);
$row = db_query($sql, $args)->rowCount();
echo $row;

```

the output is 0. uid is there on both tables please help me why this is happening.

# Answer
The documentation for `DatabaseStatementInterface::rowCount` states:

> Returns the number of rows affected by the last SQL statement.
>
> Return value
>
> The number of rows affected by the last DELETE, INSERT, or UPDATE statement executed.

Notably, "SELECT" isn't included in there, so may not be reliable to use with selections.

Assuming `$account` is a valid user object, you may find you have a query result if you try something like:

```
// Get query result using db_select
$result = db_select('profile', 'p')
            ->fields('p')
            ->condition('uid', $account->uid)
            ->range(0,1)
            ->execute()
            ->fetchObject();
drupal_set_message('<pre>'.var_export($result,1).'</pre>');

```

It might just be the missing curly braces around the table name (profile versus {profile}).

Lastly, you might also be interested in `profile2_load_by_user($account, 'main')`.
> 0 votes

---
Tags: database
---


title: Make Views pager count rows, not items?

text:
# Question
Title: Make Views pager count rows, not items?
I have a view of events, grouped by month. Each month could have between 1 and 6 events. The pager is set to 10 items.

Example:

```
January
x x x
February
x x x x
March
x x
April
x

```

So if there are 5 events in April, the page cuts off after the first item. Even though paging can be used to navigate to the remaining events, this is misleading; it looks as though there is only 1 event in April.

So I wonder whether Views pager could work by row rather than item?

# Answer
> 1 votes
It sounds like you need a view of views. Try the module Views Field View.

I don't know if this is doable. But this is what I will investigate:

In your primary view you must create a month only field, and page on that. Then in your secondary view (which will become a field of the first view, and to which you pass the month as context) you return the dates for the passed in context of the month. You will then end up with a multi-value date field in the first view. You might have to do some rewriting of output (Views PHP?) to get the dates as text or integer fields.

And if you get it right, remember to employ views caching as Views Field View adds a lot of database queries.

---
Tags: views, paging
---


# Question
Title: Get node path for Entity Referenced in Views
I have two Content Types: Product and Offer.

Offer has a Entity Reference field to Product

I'm making a view with Offers, and I want to get the Product URL in this View. I was trying with Relations but I have no result.

# Answer
> 1 votes
You already have the Entity Reference module installed and that is sufficient.

Create a view with base table Offer. Then add a relationship as follows: Click on add relationship, select filter by Entity Reference which will only show the entity referenced endpoints. It will show the field in question from two directions. You are working from the entity that contains a reference to another entity. You therefore select the 'A bridge to the Content entity that is referenced via field\_whatver.

This pulls in the related entity. Now you just have to add the new field (URL) to your view and make sure that you set the relationship when you add it to the relationship you defined.

---
Tags: views, entities
---


title: Set select list option value

text:
# Question
Title: Set select list option value
I'm trying to set value of select list programmatically with hook form alter

I have select list with options:

```
$options = array(125 => 'USA');

```

and setting value like this

```
$form['field_news_rubrique']['und']['#options'] = $options

```

But this don't work.

if i change options like this

```
$options = array(0 => 'USA');

```

it's working

if i have multiple value in options like this :

```
$options = array(124=> 'EN', 125 => 'USA');

```

it's working too

# Answer
Do you want to set the value before submission or after?

Before submission: Use $form and set the default value for the select list using the key.

After submission: Use $form\_state\['values'\]
> 0 votes

---
Tags: forms
---


# Question
Title: How to fetch the status of profile flag?
I have a profile flag called "keep my photos private" using which user can flag his content and can keep it private. I want to fetch the status of the flag by the specific user. I have tried php code but its not working.

```
global $user;
$user_uid=arg(1);
$flag=flag_get_flag('keep_photos_private');
print "Flag Name : ".$flag->title;
print "User : ".$user_uid;
if($flag->is_flagged($user_uid)) {
  print "flagged";
}
else {
  print "not flagged";
}

```

Is my code wrong?

# Answer
I worked with Profile2 a while ago and it was not a joy for me. I remember having to implement a hook\_user\_insert and creating the profile right there and there as the profile was only created after a user saved a new profile. So if you have a flag on it and flag it without saving the profile it might just go lost as the profile does not really exist yet.
> 0 votes

---
Tags: users, flags
---


# Question
Title: Enable/Disable field values based on another field's value
I am using Drupal 7 with the Entityform and Conditional Fields modules to build a form and need to see if it is possible to disable a value in one field based on the selected value of another field. Here are the details:

Field: Source Region List (Text) - Radio Buttons

Values: US-East US-West APJ EMEA

Field: Destination Region List (Text) - Radio Buttons

Values: US-East US-West APJ EMEA

The behavior I am looking for is this: When a region value in Source Region is selected, I need the corresponding value in Destination Region to be disabled but the rest of the values to be selectable. This is to make sure the Source and Destination regions are not set to the same value.

Example: Source Region selected value is US-East, I need Destination Region US-East gets disabled.

If this is not possible with the Entityform and Conditional Fields modules, please let me know how best to obtain this functionality. If this means writing a form from scratch, I am willing to do this but need some type of tutorial or howto document to learn how to do this.

# Answer
> 1 votes
I doubt whether it is possible. You cannot hide certain radio options in a radio group. It is the whole group or nothing. I will look rather at a custom jQuery solution coupled with a server-side validation method.

The jQuery will have to: display all hidden radio options in destination, then hide the corresponding radio option in the destination when source is selected. You will have to add the jQuery to the page via hook\_preprocess\_html or something similar, or use the module JavaScript Libraries Manager.

Server-Side: You can use the Field validation module. Put the validation against both fields, and use 'Equal values on multiple fields', and set it to reverse.

---
Tags: forms, entities
---


# Question
Title: Entity metadata wrapper, get field collection in field collection
I want to get (and to set after) the value of a field collection in a field collection (multidimensional field content).

This is my code :

```
// The node is a custom content.

// I get the list of first collections fields.
$temp = field_collection_get($node,'field_top');
// Shows the structure you can see below in the screenshot.
dpm($temp->value()[0]);

// Now, I want to get the value of field_website_informations.
// I've tried several ways but I couldn't find the right way.
// The following line returns an error.
$testage = entity_metadata_wrapper($temp->value()[0], 'field_website_informations');

```

Is it possible to do with the Entity API?

The screenshot :

# Answer
> 16 votes
Yes it is possible. Let's say you have a content type with a field collection named `field_collection_parent`, which has a field collection in it named `field_collection_child`, which has a field in it named `field_child`.

```
// First you need to wrap the node with entity_metadata_wrapper
$node_wrapper = entity_metadata_wrapper('node', $node);

// To get the value of field_child:
$value = $node_wrapper
           ->field_collection_parent
           ->field_collection_child
           ->field_child
           ->value();

// UPDATE: If a field accepts multiple values, treat it like an array
// The following line would get the first value of field_collection_child in the
// first field_collection_parent.
$value = $node_wrapper
           ->field_collection_parent[0]
           ->field_collection_child[0]
           ->value();

// To set/modify the value of field_child
$node_wrapper
  ->field_collection_parent
  ->field_collection_child
  ->field_child
  ->set('Some new value');

// To save the node after modifying
$node_wrapper->save();

```

---
Tags: entities
---


title: Ajax modal form window not loading

text:
# Question
Title: Ajax modal form window not loading
I already had success in ajax loading a form into a modal window with Ctools but now it fails and I do not why. Maybe someone can help me?! The problem: I create a link on a page which should open a form in a modal window. With another (Views created) page it did work fine: I click on the link and the form is correctly rendered in a modal window. In the following case it seems to be all the same - the only difference is that another form is used and the ajax links are not created by a Views page but a custom page callback. But when I click on the ajax link the modal window is opened - but the throbber keeps rotating and nothing happens. No form is shown in the window - just the throbber graphic.

As I can see when hacking into functions like ajax\_render() that the output is correctly built into an array usable by ajax\_render()... there are no error message anywhere, neither in Drupal database logs, reports or server error logs. Additionally the browser gives no JavaScript error or warnings.

This is the menu\_hook defining the page callback for the ajax link:

```
 $items['foodlog/existing/%ctools_js/%foodlogentry/%'] = array(
    'title' => 'Edit your foodlog entry',
    'page callback' => 'foodlog_edit_form_ajax',
    'page arguments' => array(2, 3, 4),
    'access callback' =>  'foodlog_edit_form_access',
    'access arguments' => array(3),
    'type' => MENU_CALLBACK
  );

```

This is the ajax page callback:

```
function foodlog_edit_form_ajax($js = NULL, $foodlogentry, $action) {

  if ($js) {
    ctools_include('modal');
    ctools_include('ajax');
    $form_state = array(
      'ajax' => TRUE,
    );
    $form_state['build_info']['args'][] = $foodlogentry;
    $form_state['build_info']['args'][] = $action;

    $output = ctools_modal_form_wrapper('foodlog_edit_form', $form_state);

    if (!empty($form_state['ajax_commands'])) {
      $output = $form_state['ajax_commands'];
    }

    // Return the ajax instructions to the browser via ajax_render().
    print ajax_render($output);
    drupal_exit();
  }

  // go on: if no $js -> render the form
  else {
    return drupal_get_form('foodlog_edit_form', $foodlogentry, $action);
  }
}

```

And here is the code where the ajax link is rendered (just the part of the page callback, where it happens):

```
ctools_include('ajax');
ctools_include('modal');
ctools_modal_add_js();

$actionlinks = l(t('edit'), 'foodlog/existing/nojs/'. $entry['flid'] .'/edit', array('attributes' => array('class' => array('ctools-use-modal', 'ctools-modal-foodlog-modal-style') ) ) );

```

The result is the correct link like

```
<a href="/foodlog/existing/nojs/9813/edit" class="ctools-use-modal ctools-modal-foodlog-modal-style ctools-use-modal-processed">Bearbeiten</a>

```

The JavaScript files are loaded, no caching is enabled, no aggregation. As I mentioned the same is working on another Views page where I create such a link by rewriting a views field. Just the form is another one. The form is rendered when I simply call the URL directly in the browser - there seems to be some trouble somewhere when Drupal sends all the stuff to the browser.

Does anyone has an idea?

# Answer
> 0 votes
I found the error: on my page I use the jQuery Flot plugin in order to create some charts. For one of the charts there was an error on the page where I wanted to open a form in a modal window. When I solved this error the modal window was working as expected... JavaScript is a weird thing!

---
Tags: ajax, chaos-tool-suite
---


# Question
Title: I can't get the og_group_ref set in a node form rendered via a custom block
My block code is as follows:

```
mymodule_block_info() {
  $blocks = array();
  $blocks['my_contenttype_form_block'] = array(
    'info' => t('My CustomContentType Add Form'),
    'cache' => DRUPAL_CACHE_PER_PAGE,
  );
  return $blocks;
}

function mymodule_ui_block_view($block_name = '') {
  global $user;
  switch ($block_name) {
    case 'my_contenttype_form_block':
  module_load_include('inc', 'node', 'node.pages');
  // Create a node for the content type.
  $node = new stdClass();
  $node->uid = $user->uid;
  $node->name = (isset($user->name) ? $user->name : '');
  $node->type = 'my_contenttype';
  $node->language = LANGUAGE_NONE;

  $block = array(
    'subject' => t('Create New CustomContentType record'),
    'title' => t('Create New CustomContentType record'),
    'content' => drupal_get_form('my_contenttype_node_form', $node),
  );
    break;
  }

  return $block;
}

```

The "Groups audience" field is missing. It shows up in the standard add page (mysite.com/node/add/my\_contenttype).

I've tried setting this programmatically via hook\_form\_alter, and also by setting the $form\_state\['values'\]\['og\_group\_ref'\]\[0\], but nothing seems to work (although it makes sense that these approaches are failing when the field isn't even in the form.

Thanks in advance for the assist! Any thoughts as to why it's missing?

# Answer
> 0 votes
For the benefit of others, I realized the user was not a member of the child group they were trying to add content to. They were members of the parent, but that didn't allow them to add content to the child group in question, so permissions didn't propagate as expected. There is an OG subgroups module (https://drupal.org/project/og\_subgroups) which is supposed to help with this, but I wasn't able to configure it correctly for some reason before realizing that this particular application required the user to be a member of the subgroup in order for them to actually post.

---
Tags: forms, blocks, panels, organic-groups
---


title: Help with Multisite

text:
# Question
Title: Help with Multisite
We need to develop multiple websites on Drupal with the following structure. (We are migrating from DotNetNuke.)

* www.mainsite.org
* www.mainsite.org/subsite1
* www.mainsite.org/subsite2
* possibly, www.mainsite.org/subsite1/subsubsite1

Unfortunately, using sub-domains is not an option. There should be superusers who can administer all the sites and subsites, and site-specific administrators for each sub site.
We want to use the same Drupal code base and database.

Is this possible with Drupal core, or is there a Drupal module to achieve this?

# Answer
> 4 votes
All your points can be fulfilled with just the core (i.e. no need to install a module for this).

Setting up a multisite with subdirectores (even multiple levels of subdirectories) is standard fare in Drupal. How you set this up is explained in the standard documentation. You may also want to see my blog about setting up a multi-site. The article covers all three options:

* DNS alias: `example.org + example.com`.
* Sub-domain: `example.org + sandbox.example.org`.
* Sub-directory: `example.org + example.org/sandbox`.

(It also discusses setting up a shared database, but only the simplest use case, where each site has its own content, users and configuration. I've yet to write about the use case where not only the datebase, but some of the tables too are shared.)

One mis-informed individual seems to think that you can't do this with sub-directories. So just for the record, here is an example of a muli-site set up to use sub-directories:

To address your other concerns:

> There should be superusers who can administer all the sites and subsites, and site-specific administrators for each sub site.

The simplest way to do this is to have separate `{users}` tables for each site that is part of the multi-site. You then just use the standard Drupal role based access control systems to set up the superusers and and site-specific administrators. But you may also share the `{users}` table between all sites (as explained below) to have a single front-end for managing the users to all the sites.

> We want to use the same Drupal code base and database.

The whole idea behind multi-sites is that the Drupal code base is shared, so that happens by default.

As for sharing a database, there are two options, and your question does not specify which you want:

1. **Shared database, but each site has its own content, users and configuration.** This is simple to set up. Just create the database, and during installtion, pick a different *table prefix* (`site1_`, `site2_`, etc.) when you set up the database for each site (this is under "Advanced" on the db configuration panel).
2. **Shared database, where some tables (e.g. `{users}`) are shared between sites.** To have this, you need to set up your database to use multiple prefixes. The accepted answer to this question tells you the basics of how to use prefixes to share some tables between multi-site instances (in the example shown, the tables `{users}`, `{sessions}`, `{role}`, and `{authmap}` are shared). There is also a project **Domain Access** that helps you with sharing stuff between sites, but I am not familiar with it. If you try to use it, and run into problems, ask a new question about it.

Final note: If you want to share *a lot* of tables between sites, using the **Organic Groups** project to manage permissions, users and contents on a single site may be a better solution than deploying a multi-site.

# Answer
> 0 votes
The Drupal multisite feature allows you to use multiple databases using the same database. If you are trying to share as much data as possible, though, then it would be a mistake to use multiple database. The Drupal feature that allows you to share tables with prefixes should be avoided; some tables, such as the variables table, are hard to share. Going down this road requires a lot of knowledge about the internals of Drupal and all of your contrib modules, and will introduce maintenance problems.

A better solution for sharing data is to just have a single Drupal site. Use organic groups to give different users different permissions in different parts of you site. Use the context module to define specific paths in your site (e.g. subsite1, subsite2, subsubsite3) that should look or act differently. You can then user Organic Groups Theme to set a completely different appearance for your site based on the group that is being viewed.

I have used this technique quite successfully with the Domain Access module; however, in your case, you do not have multiple subdomains, so you do not need this module. Just set up your organic group paths to match your subsites, and og\_theme will provide the illusion that these areas are completely different sites.

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


# Question
Title: Safe to delete cache_form table while site is in maintenance mode?
My site has a very large database of 100MB, most of this is in a table called cache\_form.

I've tried clearing the cache. When I try and run the cron I just get a white screen.

My site is in maintenance mode, is it safe to delete the contents of this table in PhpMyAdmin? There are clearly some other issues that I need to look into but is it safe to do this as a short term measure to get the site back on its feet? I've had to put it in maintenance mode as aspects of content creation have stopped working properly.

# Answer
> 2 votes
First off, cache\_form is not really a cache table, but a temporary table used to contain data necessary to verify the form being submitted to Drupal is not forged.
If you were to empty that table, users would encounter validation errors for the data they submitted from the form they were using. Since the site is in maintenance mode, that should impact the only users who are allowed to access the site when it is in maintenance mode, which includes you. You just reload the page containing the form, and fill it again; it's not a permanent error.

# Answer
> 0 votes
You may clear(EMPTY) cache table directly from MYSQL or phpmyadmin etc. These table will filled with desired data on next request & response.

For preventation keep database backup.

---
Tags: database, cron, maintenance-mode
---


title: From theme() to drupal_render()

text:
# Question
Title: From theme() to drupal_render()
I'm a Drupal themer, learning how to develop for Drupal. Currently I'm reading a book called **Drupal 7 Module Development** in which the following code is used.

```
/**
 * Implements hook_block_view().
*/
function first_block_view($delta = '') {
  if ($delta == 'list_modules') {
    $list = module_list();

    $theme_args = array(
        'items' => $list,
        'type' => 'ol'
    );
    $content = theme('item_list', $theme_args);

    $block = array(
        'subject' => t('Enabled Modules'),
        'content' => $content,
    );

    return $block;
  }
}

```

Its a simple module that returns a ordered list of all the enabled modules. Notice they are using the `theme()` function.

As a themer, I wanted to know more about this function, so I looked it up on drupal.org, and saw this:

> Avoid calling this function directly. It is preferable to replace direct calls to the theme() function with calls to drupal\_render() by passing a render array with a #theme key to drupal\_render(), which in turn calls theme().

So I tried replacing it with `drupal_render()`, and came up with this:

```
/**
 * Implements hook_block_view().
 */
function first_block_view($delta = '') {
  if ($delta == 'list_modules') {
    $list = module_list();

    $theme_args = array(
        '#theme' => 'theme_args',
        'items' => $list,
        'type' => 'ol'
    );
    $content = drupal_render($theme_args);

    $block = array(
        'subject' => t('Enabled Modules'),
        'content' => $content,
    );

    return $block;
  }
}

```

This however, is giving an error: `Theme hook theme_args not found.` Am I missing something? I would appreciate any help, and if possible, an explanation of what I did wrong. (since I'm learning this stuff.)

I've seen a similar question posted here, and followed its instruction, but no success. How to rewrite this theme call to drupal\_render

# Answer
> 2 votes
I think there is a typo.

Just replace

```
'#theme' => 'theme_args',

```

with

```
'#theme' => 'item_list',

```

There is no theme called "theme\_args".

---
Tags: theming
---


title: Theme function cannot be found Drupal

text:
# Question
Title: Theme function cannot be found Drupal
For some reason my theme function is not being found by Drupal. I swear I have followed everything and spent hours of time trying to make this work to no avail. Plus with not a single answer in the past 48 hours, Drupal's online support forum is about as much help as a bike with no wheels. Maybe some of you can figure out what is going wrong with this code.

```
    function opti_format_results($response) {

    $results = array(

    '#theme' => 'opti_design'

    );

    if ($response) {

    foreach ($response as $key => $value) {

    $results['result '.$key] = array(

    '#markup' => $response[$key]['title'],

    // '#link' => $response[$key]['link'],

    );

    }

    } else {

    $results[] = opti_nothing_found();

    }

    return $results;

    }

    function Opti_Search_theme() {

      return array(

    'opti_design' => array(

    'render element' => 'optisearch'

    )

      );

    }

    function theme_opti_design($variables) {

    $content = $variables['optisearch'];

    var_dump($variables);

    $content = "What is going on??";

    echo "IT HAS THEMED! :D";

    return $content;

    }

```

The error is quite simple. "Theme hook opti\_design not found." Can someone please tell me what is wrong. Everything looks fine. The hook\_theme() function was set properly, and worked in an entirely other module just fine but for whatever reason will not do it's job here. I feel like it is something simple but I am not seeing it. Thanks for any and all help.

# Answer
Your logic is fine, so check these:

1. Your module is named 'Opti\_Search". If not, `Opti_Search_theme()` needs to be changed to `MODULENAME_theme()`, and the caches cleared. This one seems most likely given the error message you received.
2. You've cleared the caches since implementing `hook_theme()`.
3. The module is installed and enabled.
> 1 votes

---
Tags: theming, hooks
---


# Question
Title: Show table records in view via hook_form
I managed to get things looking a bit better, However I dont know why the checkbox below is showing like the picture. I want to select the checkbox and make it do something with the corresponding article. By the way I have it, will it work? Thanks in advance.

\`function rss\_list\_form($form, &$form\_state) {

```
$results = db_query("SELECT * FROM {rss_table}");
$i = 0;
foreach($results AS $result) {

    $form[$i] = array(
        '#type' => 'checkbox',
        '#prefix' => '<div style="float:left; margin: 30px;">',
        '#suffix' => '</div>',
    );
    $form[$result->GUID] = array(
        '#type' => 'item',
        '#title' => $result->title,
        '#markup' => $result->description,
        '#prefix' => '<div style="float:clear; background: #e0e2e6; border: 4px solid #c5c9cf; padding: 15px; width: auto; margin-left: 80px;">',
        '#suffix' => '</div>',
    );
    $i++;
}
$form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Submit'),
);

return $form;

```

}\`

# Answer
I manage to get things working like I wanted !! So I will include a screenshot and the code for people on the same boat.

```
function rss_list_form($form, $form_state) {

$header = array(
'article' => t('Article'),
);

$rows = array();
$sql = "SELECT * FROM {rss_table}";
$result = db_query($sql);
    foreach ($result as $dbrow) {
    $rows[$dbrow->GUID] = array(
        'article' =>
        '<h3>'.$dbrow->title .'</h3>'.'<br>'
        .'<p>'.$dbrow->description.'<p>'.'<br>'
        .$dbrow->date .'<br>'.'<em>'.$dbrow->link.'</em>'.'<br>',
    );
    }
$form['rss_select'] = array(
    '#type' => 'tableselect',
    '#header' => $header,
    '#options' => $rows,
    '#empty' => t('No articles found.'),
);
$form['import'] = array(
    '#type' => 'button',
    '#value' => t('Import'),
    '#weight' => 0,
);
$form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Submit'),
);
$form['delete'] = array(
    '#type' => 'button',
    '#value' => t('Delete'),
);
return $form;

```

}
> 1 votes

# Answer
Do it without the table first. Just the form with the form elements. Once you get that right and it works you then have to create a new theme function for it:

* implement hook\_theme and define a theme function for the form
* set form\['#theme'\] in the original form to that of your new theme function
* implement the new theme function. Here you need to load all of your form elements into structures as required by theme\_table, and call theme\_table on it. And then call drupal\_render\_children on the form so as to render the rest of the form (hidden elements etc that are required by Drupal FAPI).
> -1 votes

---
Tags: forms, database
---


# Question
Title: File field breaks AJAX form in Drupal 7 form API
This is a really strange one, I've created a custom form using the multi step form method. So there are various AJAX calls to handler functions that return certain sections of the form back to containers and replace the HTML.

My form works great has a lot of complexity to it and the speed is fantastic. A recent addition to said form is to be able to upload a PDF, simple I thought! Added my **manged\_file** field and all looked great. However I'd missed that now my page was reloading, AJAX requests were no longer in the Firebug console and instead seemed to be in the POST somehow. I don't fully understand how the AJAX is still working but it is slower that's for sure!

This is a problem I think we could live with a bit of slowness but then I noticed on a full form submission it was breaking a second form outside of this form. Basically it's too big of an issue to live with now.

I've tried a few things, one a standard **file** field, two a markup field with a raw

```
<input type="file" />

```

just to see what happened and I experienced the exact same issue as using the form API. This confirms to me that this is not caused by some added javascript from Drupal but a problem with the input itself.

So my question is why does a file field break the AJAX in my form?

Rather awkwardly I can't just paste all my code here as the data is protected and technically not my property. I'm not sure it's needed but I've thrown together a quick bit of code that should demonstrate my issue.

```
function vv_test_menu(){
    $items = array();
    $items['vvtest'] = array(
        'page callback' => 'vv_test_page',
        'access arguments' => array('access content'),
        'page arguments' => array(false),
        'description' => t('Test page for code.'),
        'type' => MENU_CALLBACK,
    );
    return $items;
}

function vv_test_page(){
    $content = 'This demonstrates the file field breaking the AJAX.';
    $content .= render(drupal_get_form('vv_test_form'));
    return $content;
}

function vv_test_form($form, &$form_state){
    $form['#tree'] = TRUE;
    $form['#prefix'] = '<div id="container">';
    $form['#suffix'] = '</div>';

    $form['job_number'] = array(
        '#type' => 'textfield',
        '#title' => t('Job number'),
        '#required' => TRUE
    );

    if($form_state['triggering_element']['#ajax']['callback'] == t('vv_test_call')){
        $form['result'] = array(
            '#markup' => '<div id="container">You entered: '.print_r($form_state['values']['job_number'], true).'</div>'
        );
    }

    // - Comment this field in and out to see the problem
    $form['pdf'] = array(
        '#type' => 'file',
        '#title' => t('A file field')
    );

    $form['sync'] = array(
        '#type' => 'button',
        '#name' => 'sync',
        '#value' => t('Sync'),
        '#ajax' => array(
            'callback' => 'vv_test_call',
            'wrapper' => 'container'
        )
    );

    return $form;
}

function vv_test_call($form, &$form_state){
    $form_state['rebuild'] = FALSE;
    return $form;
}

```

# Answer
I experienced the exact same: Drupal 7, custom AJAX form, multiple pages, all working fine. After adding a managed file field it broke the AJAX functionality. Or that was what it looked like...

The past couple of days I spent quite some time digging around `misc/drupal.js`, `misc/ajax.js` and `modules/file/file.js` to turn the managed file field into a single customizable "Select & upload file" button with client side file size validation and auto submit functionality.

After reading your question and remark about that the problem even occurred when manually inserting a plain non Form API file field it dawned to me that I read the following in `misc/ajax.js` \> `Drupal.ajax.prototype.beforeSend`:

> For forms with file inputs, the jQuery Form plugin uses the browser's normal form submission mechanism, but captures the response in a hidden IFRAME.

I tested this on the dev site and it appeared that AJAX only "broke" after visiting a form page which contained a plain file field. Though the requests felt less snappy and in Chrome and Firefox loading throbbers appear in the browser tabs and the status bar showed a new page was being requested, it seemed to not harm my forms.

But the jQuery Form plugin for Drupal 7.28 has version number 2.52, see `misc/jquery.form.js`. The jQuery update module 7.x-2.4 ships with `path/to/jquery_update/replace/misc/jquery.form.min.js` with version number 2.69, though the latest version is 3.51, see http://malsup.com/jquery/form/#download. This latest version appears to use another technique for file uploads which feels like AJAX (or maybe ís using AJAX), see http://malsup.com/jquery/form/#file-upload. I tried this version on the dev site and so far with success!

Download the latest version to your module or theme and use ie. hook\_js\_alter() to replace the old script for the new one. I implemented this hook for the site's theme:

```
/**
 * Implements hook_js_alter().
 */
function YOURTHEME_js_alter(&$js) {
  // Define path to old jQuery Form plugin, alter to your needs.
  $old_path = drupal_get_path('module', 'jquery_update') . '/replace/misc/jquery.form.min.js';

  // The script does not get loaded on every page, so check the $js array.
  if (isset($js[$old_path])) {
    // Define path to newer jQuery Form plugin, alter to your needs.
    $new_path = drupal_get_path('theme', 'YOURTHEME') . '/js/jquery.form.min.js';

    // Copy data from old javascript to new and remove old javascript.
    $js[$new_path] = $js[$old_path];
    unset($js[$old_path]);

    // Set new path as data property and alter version number.
    $js[$new_path]['data'] = $new_path;
    $js[$new_path]['version'] = '3.51.0';
  }
}

```

Or see how jquery\_update\_library\_alter() did it and apply this method to your module.
> 1 votes

---
Tags: forms, ajax, files
---


# Question
Title: Omega override simple-layout.tpl.php for content types
I have copied the simple-layout files and customized, the custom layout is simply mats2015.simple-layout (`mats2015.simple-layout.tpl.php`). I need to override this file for a specific content type (`plain-page`).

Before Omega 4 (and using the layouts extension) I would use the following:

* In `theme_alpha_preprocess_html()`: `$variables['theme_hook_suggestions'] = array('html__plain_page_wrapper');`
* In `theme_alpha_preprocess_page()`: `$variables['theme_hook_suggestions'] = array('html__plain_page')`;

And, together, those two template files (`html_plain_page_wrapper.tpl.php`, `html__plain_page.tpl.php`) would simply render `$page['content']` and nothing else.

If, within `mats2015.simple-layout.tpl.php` I include `get_defined_vars()` I see this:

```
'omega_layout' =>
array (size=7)
  'name' => string 'mats2015.simple' (length=15)
  'path' => string 'sites/all/themes/mats2015/layouts/mats2015.simple' (length=49)
  'file' => string 'sites/all/themes/mats2015/layouts/mats2015.simple/mats2015.simple.layout.inc' (length=76)
  'info' =>
    array (size=4)
      'name' => string 'MATS 2015 Simple' (length=16)
      'description' => string 'preview = preview.png' (length=21)
      'template' => string 'mats2015.simple-layout' (length=22)
      'regions' =>
        array (size=11)
          ...
  'theme' => string 'mats2015' (length=8)
  'attached' =>
    array (size=0)
      empty
  'template' => string 'mats2015.simple-layout' (length=22)
  'theme_hook_suggestions' =>
    array (size=0)
      empty

```

So, the question is: is there a preprocess hook I'm missing that I can use to switch from `mats2015.simple.tpl.php` to `some-other.tpl.php` based on content type? Or is there a naming convention for the layout extension files that I'm missing?

Thanks!

# Answer
So, I was able to accomplish this using the following:

tl;dr: Create another layout extension, and use `theme_omega_layout_alter(&$layout)` to switch. That's the preprocess function I had to track down.

*(assuming use of included layout \*simple-layout\* and you want to create a layout for node type plain-page \[the naming convention doesn't matter\])*

1. Copy `themes/_your-theme_/layouts/simple` to `themes/_your-theme_/layouts/plain`.
2. Modify the file names:
    * simple.layout.inc -\> plain.layout.inc
    * simple-layout.tpl.php -\> plain-layout.tpl.php
3. Modify `plain.layout.inc` (It's just like a `.info` file for a theme, self-explanatory)
4. Modify `plain-layout.tpl.php` to suit your needs (In my case, I need to remove everything except `render($page['content'])`.
5. Open `themes/_your-theme_/template.php` and add `theme_omega_layout_alter(&$layout)`:

```
// this is specific to my use case
// change 'theme' to your theme name, as you would with any
// preprocess function
function theme_omega_layout_alter(&$layout) {
  $cPath = current_path();
  if (strpos($cPath, 'invite-print') !== 0) {
    $layout = 'plain';
  }
}

```

*The following is only necessary if you want to change parent structure (`<html>`, `<head>`, etc.), which I needed to*

1. Open `themes/_your-theme_/preprocess/html.preprocess.inc` and put this in:

```
 // this is specific to my use case
 // change 'theme' to your theme name, as you would with any
 // preprocess function
 function theme_preprocess_html(&$variables) {
   $cPath = current_path();
   if (strpos($cPath, 'invite-print') !== 0) {
     $variables['theme_hook_suggestions'][] = 'html__plain_page';
   }
 }

```
2. Create `/themes/_your-theme_/templates/html--plain-page.tpl.php` and modify as necessary.

It felt like overkill for my situation (having to create entire new layouts) but I understand why it was done - it's crazy powerful for sites that need to make drastically different layouts for different pages. Think different regions, stylesheets, js, etc - completely different .info files, essentially.

Hope this helps someone!
> 6 votes

---
Tags: 7, theming
---


title: Drush alias files aren't being found

text:
# Question
Title: Drush alias files aren't being found
I'm working locally on my OSX and I have my drush alias files at ~/.drush/\[hostname\].aliases.drushrpc.php but no matter what project I'm in, only one of the alias files are being read, as confirmed through drush status. Also of note is that my main drushrpc.php file was never in that directory and I don't think it is anywhere.

I've tried clearing drush cache, and also adding a drushrpc.php and adding this php which I'm not entirely sure what it means:

```
<?php
// ~/.drush/drushrc.php
exec('git rev-parse --show-toplevel 2> /dev/null', $repo);
if (!empty($repo)) {
  $repo = array_shift($repo);
  $options['config'] = $repo . '/.drush/drushrc.php';
  $options['include'] = $repo . '/.drush/commands';
  $options['alias-path'] = $repo . '/.drush';
}

```

I found that configuration here: http://www.astonishdesign.com/blog/drush-aliases-what-why-and-how

Anyone know how I should proceed?

# Answer
> 2 votes
> I have my drush alias files at ~/.drush/\[hostname\].aliases.drushrpc.php
> \[…\]
> But my other \[hostname\].aliases.drushrpc.php files cannot be found in drush status

The filename should be `~/.drush/[hostname].aliases.drushrc.php`. not `[hostname].aliases.drushrpc.php`: Your filename contains an extra *p*. See example.aliases.drushrc.php.

---
Tags: drush
---


# Question
Title: How would I paginate to 5 results in each page this query?
I am trying to paginate the results from the table, I saw some examples but those make use of db\_select, I chose db\_query. Is there a way to get the paging with db\_query? I have been trying to translate the code into db\_select but no luck, support please! Thanks! Here is my code!

```
function rss_list_form($form, $form_state) {
  $header = array(
    'article' => t('Article'),
  );

  $sql = "SELECT * FROM {rss_table}";
  $result = db_query($sql);

  $rows = array();
  foreach ($result as $dbrow) {
    $rows[$dbrow->GUID] = array(
      'article' => '<h3>'.$dbrow->title . '</h3>' . '<br><p>' . strip_tags($dbrow->description, '<p><b><a><img><br>') . '<p><br>' . '<b>' . $dbrow->date . '</b><br><em>' . $dbrow->link . '</em><br>',
    );
  }

  $form['rss_select'] = array(
    '#type' => 'tableselect',
    '#header' => $header,
    '#options' => $rows,
    '#empty' => t('No articles found.'),
  );

  $form['import'] = array(
    '#type' => 'submit',
    '#value' => t('Import'),
    '#weight' => 0,
    '#submit'=> array('rss_list_form_import'),
  );

  $form['update'] = array(
    '#type' => 'submit',
    '#value' => t('Update'),
    '#weight' => 1,
    '#submit'=> array('rss_list_form_update'),
  );

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

  $form['delete'] = array(
    '#type' => 'submit',
    '#value' => t('Delete'),
    '#submit'=> array('rss_list_form_delete'),
  );

  return $form;

```

}

# Answer
> 1 votes
The better way to use `db_select` with called as query extender.

Here is an example

```
$query = db_select('rss_table')
  ->extend('PagerDefault')
  ->limit(5);

```

Then `theme_pager()` can be used for outputting a pager.

For more detailed example check out

Either way to use pagination

```
 function pager_array_splice($data, $limit = 9, $element = 0) {

             global $pager_page_array, $pager_total, $pager_total_items;

                $page = isset($_GET['page']) ? $_GET['page'] : '';

  // Convert comma-separated $page to an array, used by other functions.
                $pager_page_array = explode(',', $page);

  // We calculate the total of pages as ceil(items / limit).
                $pager_total_items[$element] = count($data);
                $pager_total[$element] = ceil($pager_total_items[$element] / $limit);
                $pager_page_array[$element] = max(0, min((int)$pager_page_array[$element], ((int)$pager_total[$element]) - 1));
                return array_slice($data, $pager_page_array[$element] * $limit, $limit, TRUE);
}

 $query = db_select('rss_table','t');
            $query->fields('t');

           $resultget=$query->execute();

           $result = $resultget->fetchAll();
              $limit=5;
              $output = pager_array_splice($result, $limit);
              $html='';

   foreach ($output as $dbrow) {

                    $items[]=(array)$dbrow;
                    $title = $dbrow->title;
                    $description = $dbrow->description;

$html.="         //HTML code here//       ";

 }

  $output1 = theme('item_list', array(
    'items' => $items));

    echo $html;

```

You can use it as in the form of table too or append it to the form as well. This is the way to use pagination.

Use this code to modify as per desired output.

Hope it works for you!

---
Tags: paging
---


# Question
Title: Module submission guideline - configuration storage
I am trying to finish and submit my first module project. It's a QA/tab launcher thing that is meant for multisites. Basically, I am using a few different methods to retrieve a list of sites that are part of the same multisite as the site that the module is enabled on. The piece I have a question about is a configuration page that saves a list, from that list, of "enabled" sites.

**Here is my problem:** I want a multisite-wide configuration, but I am concerned about how i'm doing it. I understand that the Domain Access module would provide more than enough functionality for cross-site database access and would probably be more up to the Drupal guidelines, but it's extremely overkill! Domain Access will scare off people that don't want to configure each settings.php file, etc.

All I need, literally, is to save 2 non-associative arrays in a way that each multisite has access. My current setup saves them in the public files directory as 2 .csv files, and works as well as I know how to code it; as far as saving .csv's and retrieving the rows go, I think i'm doing it right. It doesn't really have performance issues tied to it because it truly is a lightweight piece; the only reason i'm doing it this way is for global access.

**My question is:** is this going to get flagged as non-conformant to the Drupal way because i'm not saving it in a table? I don't see anything in the guides specifically guiding me away from doing it that way... but it's just a guess that they won't like it.

# Answer
> 1 votes
My advice to you is to submit your sandbox to Drupal.org Project Applications, and see what people say. Its fairly rare to get an outright rejection. People will inspect your code, offer suggestions for improvement, etc. Better to get started ASAP.

As for your specific issue: I think the way you are going about it is not in accordance with The Drupal Way ™. Your best bet would probably be to generate a PHP file, only allowing your module to access this sort of administrative control from the site in Default.

---
Tags: 7, multi-sites, domain-access
---


title: Save a webform as draft?

text:
# Question
Title: Save a webform as draft?
I want to save a webform as draft for logged in user. I read somewhere that this a default feature but not able to find out. I could not find this option "Allow users to save a draft" in the form settings(Using Drupal7 and webform 3.13). Please suggest.

# Answer
There is indeed a "Save as Draft" button in webforms. Check the permissions with "allow users to save draft" in the permission page.

There has been an issue reported here with the same problem as yours.
> 1 votes

---
Tags: webforms, nodes
---


# Question
Title: an entity_metadata_wrapper for a form_content in form alter hook?
There a few days ago, someone in this website advised me to use the function entity\_metadata\_wrapper. Thanks that, I can get and set fields of entity without use heavy code.

Now, I would like find the equivalent when I use a form\_content from an alter form hook. After several google research, I didn't find the equivalent... can you help me ? =)

Concretely, When I get a fields, i do :

```
$exemple = $form_state['field']['field_one']['und']['entity'][2]->sub_field['und'][0]['value'];

```

(my form content contains a collection field). It's very ugly...

# Answer
> 1 votes
If you've got a complete entity in that form, or some type of structure that the Entity API knows about, because it's been defined in hook\_entity\_info and/or hook\_property\_info, you can wrap virtually anything, for example:

```
$data = array('pears', 'apples', 'oranges');
$wrapper = entity_metadata_wrapper('struct', $data);
dpm($wrapper->value());

```

But you won't have all the goodies of the wrappers, which are the smart metadata information about the values you're retrieving, you can find how to build your own in the entity module, for example in `entity_metadata_site_wrapper`:

```
function entity_metadata_site_wrapper() {
  $site_info = entity_get_property_info('site');
  $info['property info'] = $site_info['properties'];
  return entity_metadata_wrapper('site', FALSE, $info);
}

```

site is not an entity or field structure at all, but it has been defined by a hook\_entity\_property\_info, in `entity_metadata_system_entity_property_info` so you can wrap it normally and Entity API will go and fetch the properties you define by using the callbacks you've defined:

```
function entity_metadata_system_entity_property_info() {
  $info = array();

  // There is no site entity, but still add metadata for global site properties
  // here. That way modules can alter and add further properties at this place.
  // In order to make use of this metadata modules may use the wrapper returned
  // by entity_metadata_site_wrapper().
  $properties = &$info['site']['properties'];
  $properties['name'] = array(
    'label' => t("Name"),
    'description' => t("The name of the site."),
    'getter callback' => 'entity_metadata_system_get_properties',
    'sanitize' => 'check_plain',
  );
  $properties['slogan'] = array(
    'label' => t("Slogan"),
    'description' => t("The slogan of the site."),
    'getter callback' => 'entity_metadata_system_get_properties',
    'sanitize' => 'check_plain',
  );
(...)

```

So if you've got an entity (saved or not, this only will limit how the data is accessed), you can wrap it normally and access to it, and if you have another type of structure, Entity Metadata Wrappers will still know how to deal with this if you or another module defines so.

---
Tags: forms, entities
---


# Question
Title: Create Taxonomy term with added text and date fields, then display them in "add content"
I'd like to add a date field ("date") and a text field ("notes") to a taxonomy term ("Category"). Easy enough.

When I add content, I have the taxonomy term linked using term reference, and it is working fine.

What I can't figure out is this: I'd like the "date" and "notes" field to also appear on the add content screen once the "Category" is selected, and be fully editable. How would I go about this?

Specifically, when I add content, I select the category and enter all other relevant data. I then enter a date and notes that apply to that node being created, and also apply to any other node of the same category.

Thank you for help!

# Answer
Am not familiar with any contributed module which will server your requirement. But i can help you to achieve this functionality.

Add the Date and Notes field to the specific content type using the '**Add Existing field**' option. Since you have already created the fields for taxonomy term, its not necessary to create a new fields.

While adding a new content of that particular content type, mention the category , date and notes in the respective fields.

Now what we need to do is to hack-into the node submit flow and update the specific taxonomy term with the newly entered date and notes values.

Easily do this by using a single hook : hook\_node\_presave($node)

You can using this hook in any of the custom module. The '$node' variable will contain the date and notes values. We can easily load the selected taxonomy and update the date and notes of the taxonomy via DB queries

Thanks, Vineeth
> 0 votes

# Answer
we should create a custom module. Please follow these steps:

---

Step 1: Create a folder named '**mytweeks**' inside '/sites/all/modules' folder

---

Step 2: Create 2 files \[**mytweeks.info** and **mytweeks.module**\] inside the 'mytweeks' folder

---

Step 3: Add the following lines inside mytweeks.info file and save it:

```
name = My Tweeks
description = "This module is to tweek my node actions"
core = 7.x

```

Step 4: Add the following lines inside mytweeks.module file and save it.

```
function mytweeks_node_presave($node){

/*
The $node variable will contain all the submitted node form values.
Extract the 'date' and 'notes' values from $node variable.
Below this comment, write your PHP-MYSQL logic to update those values to the respective taxonomy term field.
This function will be invoke whenever you submit a content/node add form.
*/

}

```

Hope this helped.

Thanks
> 0 votes

---
Tags: taxonomy-terms
---


# Question
Title: How to edit fields' display markup in a search view?
Working with searchapi and views. I have a view based on a search inWondering how to edit the markup for the fields? There's a general option to strip the markup elements, but how to control the markup for individual fields?

# Answer
Select the field and drop down the "Style Settings" tab, here you can select an element and create new classes for the field, label or wrapper. You can also remove the css completely
> 1 votes

---
Tags: views, search
---


# Question
Title: Where is $page['sidebar_second'] rendered? I want to edit the style of the <ul> listing of the recent comments
The comments in the block `recent comments` is styled with an unordered list. I want the points of the list beginn exactly under the `N` of `New Comments`.

Google Chrome tells me that there is a `padding-left: 40px;` attribute:

I do not know from where i get this attribute. I looked in my themes css files but there is no attribut `padding-left: 40px;`

Here is the element lookup in Firefox:

I need to set the `padding-left` attribute to exactly `15px`. This is how it should look like:

I'm using the mas Theme in markapot.

Can I define the style of the `ul` in the function `$page['sidebar_second']`? If so, where is the sidebar built? Thanks for any help!

# Answer
I think you have to look in how theme works in Drupal. However, as per your question, $page\['sidebar\_second'\] is the variable that stores the region "sidebar\_second". This region doesn't have any specific styles and this goes for all the other regions as well. If a block is created in your system it needs a region to be displayed. So The blocks are always assigned to the desired regions.

If you want to style the block then you have to find the candidate files via devel & devel\_themer module and then in the theme directory have to create the file and style. Also if you are not wiling to do that then write a overriding css for your theme that will override the styles like,

```
.class-name {
   padding: 15px !important;
}

```

But I would recommend not to use !important unless its really needed.
> 1 votes

---
Tags: theming, blocks
---


title: Open node (internal link) in new tab

text:
# Question
Title: Open node (internal link) in new tab
How can I configure programmatically a node object to open in a new tab? I thought maybe in the `$node->path` array?

I don't see where and how I can achieve this... There is nothing such as a rendered `<a>` on which I can add a `target="_blank"`.

**EDIT (more specific situation):**

I've got a content type "news". It is possible to create news in 2 different ways:

* An editor user creates **manually** through the admin interface (basic).
* A **custom module imports data** from external RSS feeds everytime a piece of news is published in it.

I've got a **view** that display the **list of news** (just title, truncated text, date, logo...). When you click on a news' title, you access the full node view (normal). If it is an internal news (created manually), it displays normally. If it is an **imported news**, however, I **redirect** using drupal\_goto to the source of the news (that I saved on node creation).

I want to make this very redirection **in a new tab**. It's quite complicated because it is originally an internal link (node/nid) that redirects to an external link (http://www.sourcesite.com).

I can make the difference between an imported/not imported node in the `hook_preprocess_views_view`. But I can't assign it something like a target \_blank or whatever it exists to make this node opened in a new tab.

# Answer
> 0 votes
I finally achieve what I wanted. I succeed to access the info (hidden very deeply) in my `template.php` file within the following hook:

```
function pwe_2014_preprocess_views_view_fields(&$vars) {
  if(isset($vars['view']) && $vars['view']->name == "pwe_news") {
    foreach($vars['view']->result as $key => $result) {
      if(isset($result->node_feeds_item_nid) && ! is_null($result->node_feeds_item_nid)) {
        $vars['view']->result[$key]->class = "external";
      } else {
        $vars['view']->result[$key]->class = "internal";
      }
    };
  }
}

```

I assigned that new class to a new div in my `views-view-fields.tpl.php`:

```
<div class="<?php echo $row->class ?>">
...
</div>

```

And target that class with JavaScript:

```
$('.view-pwe-news .views-row .external a').attr('target', '_blank');

```

Not easy to find the right theme function where I could access the right info.

# Answer
> 0 votes
This is a theming question and there's a choice to be made about whether to use a Views or a node template. By and large when displaying entities in views, I tend to use a particular view mode, because then I can display them similarly outside of Views if necessary. To do that:

1. Choose which view mode to use. In your case use the *Teaser* view mode, or if that's not an option create a new one.
2. Ensure your view's configured to display that view mode. For more info, download and install advanced\_help, and read from the Views help at least *Row styles* and its children *Fields* and *Node*.
3. Check in the node template you're using: is there a variable that would let you add a target attribute to the title link? (There isn't in core node.tpl.php but there might be in your theme.) For more info you can read Overriding themable output and Core templates and suggestions. I'd suggest using devel\_themer to see what template is actually used - *make sure you've done step 2 first*. The template should either be `node.tpl.php` or start with `node--` and end `.tpl.php`.
4. If there wasn't a variable in step 3, then modify the template to have one, eg. by adding `$title_link_attributes`.
5. Implement `hook_preprocess_node()`. *Check if the node is of the correct type and view mode* and modify the variable appropriately. (And if you created a new variable, ensure that you set it to the empty string for other view modes and content types to avoid warnings.) For more info, see Setting up variables for use in a template (preprocess and process functions).

Let me know if you have any questions, or if that approach isn't appropriate for any reason.

Btw I gave a non-JS answer because I thought that was a requirement, but now I'm not so sure.

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


# Question
Title: How to set multiple error messages with form_set_error?
I notice I can pass in a message variable to `form_set_error()`.

How can I pass in multiple messages?

I tried calling form\_set\_error() several times, but always the first one is displayed.

So, to sum up I want to show something like this:

* error 1
* error 2
* error 3

Currently, I can only get:

* error 1

Then, once the users correct it, and resubmit it, they get:

* error 2

if (strpos($form\_state\["values"\]\["body"\], "

if (strpos($form\_state\["values"\]\["body"\], "

If both of these control statements trigger an error, only the first one is shown. After the user corrects the error, the second error message is shown.

# Answer
> 10 votes
I would change the code to issue a single call to `form_set_error()` per element:

```
$errors = array();
if (strpos($form_state["values"]["body"], "<h1") === true)
    $error_messages["body"][] = "Blalalabalbal bablalbabla.";

if (strpos($form_state["values"]["body"], "<h3") === false)
    $error_messages["body"][] = "Do this do that balbablalba.";

foreach ($error_messages as $element => $messages) {
    form_set_error($element, theme('item_list', array('items' => messages)));
}

```

# Answer
> 3 votes
I've created separate function for that:

```
function form_set_error_multiple($name = NULL, $messages = '', $limit_validation_errors = NULL) {
  return form_set_error('extra][items', implode('</li><li>', $messages));
}

```

And then I can call it like that:

```
$errors = [
  'My element error',
  'Another error for the same element',
]

form_set_error_multiple('my_element', $errors);

```

# Answer
> 1 votes
Are you passing the input element name to `form_set_error()`?

According to function name you can pass one message per function call.

# Answer
> 0 votes
I solved this with a "hack":

```
$error_messages = "";
if (strpos($form_state["values"]["body"], "<h1") === true)
   $error_messages .= "Error Message on First Line <br/>";
}
if (strpos($form_state["values"]["body"], "<h3") === false){
   $error_messages .= "Error Message on Another Line <br/>";
}
// next check if there are any errors, and if so, write them to form_set_error
if(strlen($error_messages) > 0){
  form_set_error('',$error_messages);
}

```

This will display all accumulated errors as Drupal message.

---
Tags: forms
---


# Question
Title: Add a column to a Views table display conditional on argument
I have a custom View defined in a module which provides a table display of data which takes a Node ID as an argument.

```
------------------
| Col 1  | Col 2 |
------------------
| A      | B     |
------------------

```

I want to be able to check some data from the node that is the argument to see if a certain field is set to either 0 (no extra column) or 1 (an extra column).

Using `hook_views_default_views_alter()` I can add an extra column to the table using:

```
function MODULE_NAME_views_default_views_alter(&$views) {
  if (isset($views['VIEW_NAME'])) {
    // Add an extra field to the rider times view
    $handler = &$views['VIEW_NAME']->display['default']->handler;
    $handler->display->display_options['fields']['nothing']['id'] = 'nothing';
    $handler->display->display_options['fields']['nothing']['table'] = 'views';
    $handler->display->display_options['fields']['nothing']['field'] = 'nothing';
    $handler->display->display_options['fields']['nothing']['label'] = '';
    $handler->display->display_options['fields']['nothing']['alter']['text'] = 'Download';
    $handler->display->display_options['fields']['nothing']['alter']['make_link'] = TRUE;
    $handler->display->display_options['fields']['nothing']['alter']['path'] = 'download/[nid]/[number]';
    $handler->display->display_options['fields']['nothing']['element_label_colon'] = FALSE;
  }
}

```

But this adds the column to all the tables regardless of the argument.

I guess there should be a way to add the column through `hook_views_pre_render()` but I can't figure out how.

The alternative would be to set up 2 views. One with the extra column and one without and conditionally show the correct view based on a Context/Panel visibility filter.

# Answer
> 1 votes
I don't know if this is the best way to do it, but when I've needed conditional columns I've removed them in `hook_views_pre_build()` (which is before the query gets built). The code would be something like this:

```
/**
 * Implements hook_views_pre_build().
 *
 * Removes column X on condition Y from all displays of view Z.
 */
function MYMODULE_views_pre_build(&$view) {

  // Check this is the right view.
  if ($view->name != 'Z') {
    return;
  }

  // Check if the column should be removed.
  if (!$Y) {
    return;
  }

  unset($view->field['X']);
}

```

The code above will affect all displays of the view. If you want to target a particular display just check against `$view->current_display` as well.

---
Tags: views
---


# Question
Title: Not able to see < character in front end
I am running into a problem when creating content with the \< character… It is quite strange as the symbol is showed in the backend, when creating the content, but it disappear when you go to /node/%nid. Actually the whole text nodes, where the symbol is, disappears. I have disabled all the filters and the problem remains…

By the way, I have a Drupal 7 installation and cKeditor module installed, but switching to plain text editor doesn't make a difference.

Does someone has a clue of why this is happening?

Thanks in advance.

**EDIT**

After some tests, I have discovered where the problem comes from. It has to do with the "word link" module. When word link is configured to run on a field, then it seems to remove all the text within the scope of the tags where the \< appears. Now it seems it's time to surf the word link code...

# Answer
> 0 votes
At the end, I found a work around for the problem. In the word link configuration form we can find a "Disallowed html tags" input text box. We can add a tag there, so now, whenever I want to include the \< character in my text, I wrapp the tag around it.

I know it is not the cleanest solution but it is enough to keep going until they fix the module.

Hope it can help to someone else.

# Answer
> 0 votes
hey i have identified a scenario where this happens; if \< or \< is written without any space before and after this character then this ommited the whole line. Don't know why is it happening but works fine with leading and trailing space

---
Tags: wysiwyg
---


title: Remove links from the menu tabs

text:
# Question
Title: Remove links from the menu tabs
How can I remove the some links from the Tab, when we are login as a **particular user**. Please see the below picture. I want to remove the tab Items maked in red rectangle (deny access to this link).

I tried with hook\_menu\_alter, but it do not worked and also understood, hook\_menu\_alter only hide the item in the tab. Please give me a solution. I am using drupal 7 version

Please note: I am using node gallery module to this content type to attach gallery with a node. I have added roles & assigned role to a particular user. Also give permission form that this content type in permission tab. The problem is that, when we logged as user, only the edit link is disappearing, not the gallery attached with it. I want to set this in page wise. The same user want to edit the gallery in some page & also want to edit the node. I used simple access module, but no use. it only remove the edit of that page, not the gallery attached with it. I also tried hook\_node\_access(). For that also the same result. Please give any solution.

Please see: node gallery permission is separate, which is not connected with a content type. I need to deny below url based on the roles. 1) node/#/items, 2) node/#/upload 3) node/#/sort

# Answer
> 0 votes
You can give permissions to menu links according to role.give permission to the above links then they will appear as per according to roles. use the below given module for permissions as per role

Menu per Role

May this will help you.

# Answer
> 0 votes
As I understand it, you'd like the following behaviour:

* if a user with the *flexi* role is looking at their own gallery, they see the three tabs;
* when looking at someone else's gallery, the *flexi* user can't see the three tabs.

I believe you can do it with permissions. The *flexi* role:

* **needs:** *TYPE*: Create new content, *TYPE*: Edit own content
* **mustn't have:** Administer content, Administer Node Gallery Settings, Upload to All Galleries, *TYPE*: Edit any content

Replace *TYPE* with the node gallery content type(s) that *flexi* users can create.

---
Tags: users, routes
---


title: Update role with hook user update

text:
# Question
Title: Update role with hook user update
i'm updating role using hook user update like this :

```
function my_module_user_update(&$edit, $account, $category) {
  //print_r($account->field_my_field['und'][0]['value']);exit;
  if($account->field_my_field['und'][0]['value'] == 1 ) {
    $uid = $account->uid;
    $role_name = 'Spanish';
    if ($role = user_role_load_by_name($role_name)) {
      user_multiple_role_edit(array($uid), 'add_role', $role->rid);
      //print "1";print_r($role);exit;
    }
  }
  elseif($account->field_my_field['und'][0]['value'] == 0 ) {
    $uid = $account->uid;
    $role_name = 'Spanish';
    if ($role = user_role_load_by_name($role_name)) {
      user_multiple_role_edit(array($uid), 'remove_role', $role->rid);
     //print "2";print_r($role);exit;
    }
  }
}

```

but it is not working : user's role is not updating my hook\_update\_user is correctly called, i clear cache after all change in script , i have syslog and database logging enabled to see the error log, but there is no error

When i doing like this (with just one condition), it's working , i have no problem : user's role is correctly updated accoding the condition

```
function my_module_user_update(&$edit, $account, $category) {

     if($account->field_my_field['und'][0]['value'] == 1 ) {
       $uid = $account->uid;
       $role_name = 'Spanish';
       if ($role = user_role_load_by_name($role_name)) {
            user_multiple_role_edit(array($uid), 'add_role', $role->rid);
          //print "1";print_r($role);exit;
       }
    }

}

```

any ideas ?

# Answer
> 2 votes
hook\_user\_update : Modules may use this hook to update their user data in a custom storage after a user account has been updated.

So that hook is call only when you edit the user account. other things is disable you module which implement this hook.

Morever if you want to edit the role every time when user is created/edited use hook\_user\_presave.

---
Tags: users, updating
---


# Question
Title: How do I support text formats for an entity property?
I have a custom entity I've created following this basic SitePoint tutorial. My custom entity has just two properties, a name and description. My entity is not fieldable (maybe it needs to be?.

I want to make the description support text formats so it's not just interpreted as plain text. Ideally the user could choose text formats like they could for something like a text field added thru the field UI, but since my entity is not fieldable and has no UI for adding fields, I'm not sure where to go with this?

# Answer
> 1 votes
You'll need another property on your entity to hold the format.

In your entity form builder, use a `text_format` element, and use a validate to move the desired values into place:

```
$form['description_placeholder'] = array(
  '#type' => 'text_format',
  '#title' => t('Description'),
  '#format' => empty($entity->description_format) ? 'full_html' : $entity->description_format,
  '#default_value' => empty($entity->description) ? '' : $entity->description,
);

$form['#validate'][] = 'MYMODULE_entity_validate';

...

function MYMODULE_entity_validate($form, &$form_state) {
  $form_state['values']['description'] = $form_state['values']['description_placeholder']['value'];
  $form_state['values']['description_format'] = $form_state['values']['description_placeholder']['format'];
}

```

When you render, use:

```
 $formatted = check_markup($entity->description, $entity->description_format);

```

---
Tags: 7, entities
---


# Question
Title: How do I remove the “submitted by” text on Views in drupal 7
How Can I remove the "Submitted by" Text on Views in drupal 7. I know How to do this on pages, webforms. but how on views?

# Answer
> 2 votes
Since the QA didn't care to explore on his found solution.

Assuming your view displays teaser texts / full posts, go to the content type settings (e.g. /admin/structure/types/manage/page for Basic page) and disable the option "Display author and date information." under Display settings.

---
Tags: views
---


# Question
Title: How to combine Views, Rules and EVA to record submission?
I have a Drupal 7 site and I'm using Views, Rules and EVA.

I have a specific requirement that I am sure can be achieved with the modules, but I am having no joy configuring a working process.

I have an 'Application' content type, which has a submission form embedded (i.e. visitor completes submission form for the role they are applying for).

As all visitors login in order to submit an application, I would like to record each application they make into a 'My Applications' view/block, within their User (/user) page.

I see the process as something along the lines of:

1. Visitor completes application form and clicks a Submit button.
2. Via Rules, an association/reference between the user and the specific role/application is recorded.
3. Using EVA, a custom view will list the applications the user has made (showing only his/her applications, unless admin).

The part I am failing with is how to configure a Rule, triggered by the submit button, that links the user to the specific application, in such a way that it can then form the EVA view.

Has anybody implemented a similar process? Recording applications (for jobs, events, meetings etc) and allowing users to see those they have applied for must be possible?

I would be happy to use an entirely different approach if there is a better method vs. the Views/Rules/EVA idea.

Suggestions gratefully received. Thank you.

# Answer
> 2 votes
I am not familiar with EVA but it looks pretty good.

I have a similar use case with entityform.

You can embed entityforms on nodes using the entityreference field.

Now entityform comes with a view already set up that displays a user's latest entityforms.

Here is a screencap of the view configuration - it displays a user's latest form submission(s).

You can then add a 'block' version of this view (the 'add' button in the top left corner.)

You can then configure your new block to **only** show up on the logged-in-user's /user page.

Hope that helps. Incidentally let me know if you are trying to get the form-fields to be pre-populated with user details.

Based on your comments:

---
Tags: 7, views, rules, users, forms
---


# Question
Title: How to make blocks contextually aware of current webform page
I have a multipage Webform that lives at a single URL and I would like to place certain blocks depending on which page the Webform is on.

None of the webform hooks give access to page number, and the only way to do so seems to be through a hook\_form\_alter which afaict is a bit late in the page build to pass information to other modules like Views and Context.

Any ideas how this might be achieved?

# Answer
This is currently not possible through the default UI due to the URL of all webform pages being the same.

There are two possibilities as far as I know.

(1) If your blocks only show help texts or any other static information, you should probably not use blocks at all but add markup components and place them after each page break.

(2) If you are indeed using dynamic blocks (e.g. coming from views), you would need to create a custom theme file (e.g. webform-form.tpl.php) in which you may enter the logic defining which block should appear. The currently viewed page number of your webform should be available through `$form['details']`.
> 1 votes

---
Tags: hooks, blocks, webforms, forms, 7
---


# Question
Title: Migrate: What's the difference between prepare() and prepareRow()?
Using the Migrate module: I understand that prepareRow() runs a filter on the row and should return TRUE or FALSE based on some conditions, which allows a row to be migrated or not, but could someone clarify:

* when to use prepare()
* when to use prepareRow()
* why you wouldn't add a filter in the initial sql query to filter row results that you might remove/include in either of the above

Thanks!

# Answer
This is all covered in-depth in the Migrations classes documentation provided by the project. Specifically in the Commononly Implemented Migration methods page which says the following and includes further simple example function implementations. From the docs ...

**function prepare\_row($row)**

> The prepareRow() method is called by the source class next() method, after loading the data row. The argument $row is a stdClass object containing the raw data as provided by the source. There are two primary reasons to implement prepareRow():
>
> 1. To modify the data row before it passes through any further methods and handlers: for example, fetching related data, splitting out source fields, combining or creating new source fields based on some logic.
> 2. To conditionally skip a row (by returning FALSE).

**function prepare($entity, stdClass $row)**

> The Migration class prepare() method is called by the destination class prepare() method, after it has called all field-level prepare() methods and immediately before the destination object is saved. The $entity argument is the destination object as populated by the initial field mappings and manipulated by the field-level methods; the $row argument is an object containing the data after prepareRow() and any callbacks have been applied. The prepare() method is the last chance to manipulate the destination object before it is saved to the Drupal database. It is important to remember that, since it is called after the field handlers, fields will be in their fully-expanded forms (i.e., in Drupal 7 a text field value will be at `$entity->field_textual_data['und'][0]['value']` rather than simply `$entity->field_textual_data)`.

The Migrate module is a framework which allows you to encapsulate a migration process from a source piece of data to a destination location and configuration. A migration consists of:

* define where the data is
* define where the data should go
* fetch a piece of data (row)
* sanitize the data
* begin to move the data (say into an Entity)
* actually move the data
* after moving the data perform additional action(s)

The API provides hooks to affect the data being moved in this life cycle of a migration. By excluding data from the migration via your initial query you're limiting how much control you have over the total data you could move. For sub-migrations you may find this useful. But in a general content migration you would want your migration to be as all-encompassing as possible.
> 10 votes

# Answer
If you can select the right row by writing it in a query go for it, however preprareRow() can be used in more complex systems where several parameters might be required before the row gets migrated. In such a case it is easier to run through all the rows and do the logic on a per-row basis.

prepare() is ran after prepareRow() and is your last chance to alter the entity before it is saved to the database.

Some more information on this can be found here: https://www.drupal.org/node/1132582
> 6 votes

# Answer
This is a part answer and in no way complete. I'd also keen to find out more about both of these. So this may be part of a discussion; although I have written as an answer rather than comment because of the following code snippets and examples of how I've used the above classes.

Let me illustrate some of my uses prepareRow() as - which does as it says.

A recently I was giving some data to import from a non drupal database. The entity I am adding to requires fields to be entered that I do not have in my data import.

So before my source class is created I can add

```
  $source_fields = array(
    'changed' => t('Timestamp of when the change was made.'),
    'created' => t('Timestamp of when the node was Created.'),
 );

```

and then in the function prepareRow I can do the following

```
$nowtimestamp = mktime(date('Y-m-d'));
$row->changed = $nowtimestamp;
$row->created = $nowtimestamp;

```

you can also run php if/else statements here if necessary.

I've also used the prepare function in my code and am using it to assign values to the entity.

```
$account->field_job_location [und][0]['tid'] = $row->job_location_tid;

```

I've only had to use this in this scenario as I made my own custom node plugin.

Also if you need to make calculations on that then you can do it in prepareRow which runs before prepare()

For example in the import I had a value labelled 'Town' - and could turn this into a Term Id.

```
 if ($TownCity == 'London' ){
            $row->job_location_tid = '10';
      } else {
        $row->job_location_tid = '11';
      }

```

I hope this helps.
> 3 votes

---
Tags: database, migrations
---


title: add next pager to image field views

text:
# Question
Title: add next pager to image field views
I have a view created from a node with images. All images are in one field, image field content:afbeeldingen (images)

I have created my view 1 image is one page. I get the next link and previous below my image but now i want to link add a next link to my image in my view how can I do this?

# Answer
> 0 votes
Basically what you want is an image gallery or slideshow. There are many image gallery modules you can install (ie views slideshow, Flexslider).

Then you need to set the slideshow to have a pager of its own, and in the image field you need to take care of the display multiple part (as it is a multi image field) to display one image at a time.

So you will end up with two pagers. One for the view, and one for the slideshow.

Or if you want you can try the Field Slideshow module. It builds the slideshow from one multi-instance field, so half the work is done for you.

# Answer
> 0 votes
I tried the Field slideshow module, my slideshow gallery works fine, all i want is wen i click on the image itself it goes to the next image. Instead of pushing the next button on the pager at the bottom i want it to go next page when clicking on the image.

# Answer
> 0 votes
How can I add the url generated by the view (pagination) to my image as a link. I want to add ?page=1, ?page=2 ... (depending on number of pages(variable)

---
Tags: views, media
---


title: sub theme not inheriting css

text:
# Question
Title: sub theme not inheriting css
I have a theme, and many subthemes, with the goal of creating a network of sites that are different, but share some resources (like the stackexchange sites do). What I want is to include lots of boilerplate css in the master theme, and then site specific css included for each subtheme. The problem I have is the CSS of the master theme is not being loaded in the subtheme.

The master theme:

```
name = Master
description = Master theme
core = 7.x

stylesheets[all][] = css/network_style.css

```

and the sub theme:

```
name = Red Theme
description = specific theme for site in network
core = 7.x

base theme = Master

stylesheets[all][] = css/red_style.css

```

Ideally then, the master theme just has network\_style.css, and the sub theme has network\_style.css and red\_style.css.

If I enabled the master theme, then the network\_style.css is applied. If I enabled the sub theme, then only the red\_style.css is applied. There's no css conflict, and the master theme isn't visible in the page source at all.

Where am I going wrong? I'm somewhat new to Drupal. I've gone through lots of documentation on the drupal site, and checked through all the drupal 7 specific stuff on theming. I've tried clearing the drupal cache, plus my browsers cache, even turning server on and off like a mad man.

# Answer
> 1 votes
The `base theme` should be set to the machine name of the Base Theme. The machine name is the same as the name of the directory that contains it. Yours starts with a capital letter. I imagine that the folder is just `master` (all lowercase).

Because the .info file is cached, you must clear the cache before any changes are displayed in your site.

Writing theme `.info` files

---
Tags: 7, theming
---


title: Translate View footer

text:
# Question
Title: Translate View footer
I'm trying to translate a link in footer on my views .
the code is :

```
<?php
$link = l(t('Click to view all the writing categories'), 'somewhere', array('attributes' => array('class' => array('read-latest'))));
print $link;
?>

```

The problem is after tranlate it from `admin/config/regional/translate` .
the output is `<div>` no link and no `<a>` tag .
Any idea ?

# Answer
by this module String Overrides you can translate strings .
That's it
> 0 votes

---
Tags: views, i18n-l10n
---


# Question
Title: Creating Email Sending Rules in WebForm in Drupal 7
Is it possible to create rules for sending automated emails within WebForm?

Some of the examples include (all emails are separate):-

* Send an email to user if he left a field to come back and fill it later.
* Send an email if he left certain part of the form.
* Send an email if a field is updated (or not updated).

Many Thanks.

# Answer
See webform\_rules:

> Did you ever want to react on webform submission using rules but couldn't find the proper event? Webform Rules makes it possible to catch webform submissions by rules and do whatever you'd like to do with it (meaning: do whatever rules let you do with it).

It should let you perform most of the logic you've outlined here.
> 1 votes

---
Tags: webforms
---


title: views generated pager url

text:
# Question
Title: views generated pager url
How can I get the url generated by the pager in views.

drupal/project11?page=1 drupal/project11?page=2

I would like to add a link on my image to the 2nd page on my first image, to the 3th page on my 2nd image without using the pager.

# Answer
> 2 votes
I think you're asking for a link to a View like `drupal/project11/1` or `drupal/project11/2`. You can do this with Clean Pagination module.

> Clean Pagination is a very simple module that allows you to enable clean URL pagination for specified pages. The way Drupal typically works, if you had a view with the URL 'my-view', subsequent pages would normally use a query to pass the page number, as in 'my-view?page=2'. When Clean Pagination is being used for a page, it will create a url like 'my-view/2'.
>
> Currently, the module has just two settings: 1) Set the pages where you want clean pagination enabled, and 2) Enable search-engine-friendly pagination hyperlinks.
>
> The search-engine-friendly pagination hyperlinks is an experimental feature you can optionally turn on that will add the page URL to pagination links, and then remove them via jQuery. To a user, it will look like a single number, but to a screen readers and search engines it will have the url in the hyperlink text, which is usually a good thing.

---
Tags: views, uri, paging
---


# Question
Title: Schedule a rule to repeat every week at specific time not working
I am sooo close to getting this to work, but cannot figure out why I cannot get my rule to repeat. It's driving me nuts.

I created a component that has an action item to generate send a newsletter using the simplenews module. It works just fine when I execute it manually, but I need this to repeat weekly.

I've read a ton about having it repeat by using the action "Schedule component evaluation" and this makes total sense, but it just isn't firing after the initial rule. Right now I am testing it with +2 minutes so that I can see if it works or not. Eventually I want to have it be +1 week. But if it's not working with 2 minutes it won't work with 1 week.

EDIT: Right now I am running cron manually to check to see if it's working and it's just not.

# Answer
> 0 votes
Turned out that for some reason having such a short interval was the problem. After I extended it to +10 minutes it worked fine.

# Answer
> 0 votes
Make sure you're running `cron` on demand to force your process to run every those 2 minutes, the way rules scheduler works is to create a hook\_cron process that checks the dates:

```
function rules_scheduler_cron() {
  // Limit adding tasks to 1000 per cron run.
  $result = db_select('rules_scheduler', 'r', array('fetch' => PDO::FETCH_ASSOC))
    ->fields('r')
    ->condition('date', time(), '<=')
    ->range(0, 1000)
    ->execute();

  $queue = DrupalQueue::get('rules_scheduler_tasks');
  foreach ($result as $task) {
    // Add the task to the queue and remove the entry afterwards.
    if ($queue->createItem($task)) {
      db_delete('rules_scheduler')
        ->condition('tid', $task['tid'])
        ->execute();
      $task_created = TRUE;
    }
  }

  if (!empty($task_created)) {
    // hook_exit() is not invoked for cron runs, so register it as shutdown
    // callback for logging the rules log to the watchdog.
    drupal_register_shutdown_function('rules_exit');
    // Clear the log before running tasks via the queue to avoid logging
    // unrelated logs from previous cron-operations.
    RulesLog::logger()->clear();
  }
}

```

---
Tags: 7, rules
---


# Question
Title: Is there a function to return all the multisite names?
Is there a Drupal function to return all the multisite names?

I have searched a bit but have not come up with anything.

# Answer
> 1 votes
Okay, this is what I am using for now in a drushrc.php file. If you can improve upon this please post a new answer. Thanks

```
// Gets a list of all directories in /sites.
$sites = glob(drush_locate_root() . '/sites/*', GLOB_ONLYDIR);
// Strips the absolute path except for the last name.
$sites = array_map('basename', $sites);
// Removes the 'all' folder.
$sites = array_diff($sites, array('all'));

```

# Answer
> 0 votes
Another solution inspired by some team members and @marcvangend.

```
if (is_file(__DIR__ . '/../../sites.php')) {
  include __DIR__ . '/../../sites.php';
  $sites = array_keys($multisites);
  $sites[] = 'default';
}

```

---
Tags: multi-sites
---


# Question
Title: How to create node navigation to cycle through nodes of specific content type
I would like to add node navigations (prev - next) at the bottom of each node of a specific content type so that I can cycle through all the nodes for that content type. Here is an example (scroll to the bottom of the article) http://happycog.com/work/blackhills. You'll notice that there are navigation links that take you to the previous or next article.

I'd appreciate any guidance on how I can accomplish this. I've looked at various contrib modules but none have given me the result I am looking for.

Thank you,

mario

# Answer
Have a look at these two modules:

Custom Pagers is more versatile, but I found it buggy.

Another solution, more custom and flexible, would be creating a custom field in the content type (via hook\_field\_extra\_fields() or Display Suite), and creating a custom query to get the next/previous node ids. If you prefer to go with the custom way but don't want to add a custom field, you can just preprocess the node and add the variable in your .tpl file.

Previous/Next API module could be used to get the node ids without the need to create the query yourself, apparently making the solution more scalable. It's still a -dev version though.
> 1 votes

---
Tags: navigation
---


# Question
Title: Theming: when I use a smaller device, my main content goes behind my sidebar
I am making a sub-theme from the basic theme for Drupal 7. The side bar works fine on all sizes above 480px in length, but on 480px or below, my content goes behind my sidebar and there is a horizontal scrolling bar. I can see the content when I scroll, but I want all the content to fit in the main content area and not in space to the left or extra space to the right. I set my sidebar to the css code of

```
position: fixed;

```

# Answer
> 0 votes
I took out the media selection of 480px for the content, and everything seemed to be working. I narrowed it down to a width: 100%. (inside of the media entry of course) After taking this out, everything was good to go.

---
Tags: theming
---


# Question
Title: Using Feeds Tamper to convert one list to another?
I am using a feeds importer to import a number of FIPS county codes for given locations and I was hoping to use the Feeds Tamper module to convert those county codes to county names, but have thus far been unsuccessful. Any ideas? I realize that there is a "Find replace" plugin for the Feeds Tamper, but seeing as this seems only to convert a single word or phrase at a time, I'd have to do this too many times for it to be worthwhile, though it does seem to reveal that the module is capable of doing the task I desire.

Thanks in advance,

David

# Answer
For like http://www.census.gov/2010census/xls/fips\_codes\_website.xls use Feeds or Migrate modules to fill-in a Content Type with the Fields in the Excel file. The are many tutorials online of importing data from a csv or excel sheet to Nodes.
> 0 votes

---
Tags: feeds
---


title: How do I create scrolling views?

text:
# Question
Title: How do I create scrolling views?
I want to scroll my views, but I don't find a module that allows this.

Is there a module for scrolling views? How can I scroll views, if there isn't a module with that purpose?

# Answer
> 3 votes
If you're looking for scrolling similar to Twitter, try the Views Infinite Scroll module.

If you're looking for something more like this site, try the Geared Scrolling module (DISCLAIMER: which I maintain).

# Answer
> 0 votes
As Tim said Views Infinite Scroll can be used for achieving scroll based Pagination. For more info on how to set it up please follow this link: http://www.drupaldock.com/content/setup-views-infinite-scroll-drupal

---
Tags: views
---


title: permission denied when using batch

text:
# Question
Title: permission denied when using batch
I have just switched over a site live and I'm having problems regenerating the XML sitemap.

When I try, I get:

`You are not authorized to access this page.`

The URL is: `www.example.com/batch?op=start&id=207`

What could be causing this?

Thanks

EDIT: I have created a new role with every single permission and assigned the user I'm logged in with to this role. Still no luck1

# Answer
> 1 votes
Had to manually run the cron via the browser to generate.

# Answer
> 1 votes
Your issue might be related to a small value in max\_allowed\_packet parameter in your MySql configuration. Drupal cannot store correctly the batch operation data and the subsequent execution fails with a "permission denied" error.

There's an issue here, discussing the problem.

If you cannot edit your MySql configuration (like me), there's a patch at message #41 that helped me bypass that issue. It's a couple of lines that you can modify by hand.

# Answer
> 0 votes
I struggled with a similar issue and eventually realized that I had created a folder named batch in my Drupal root, which interfered with the resolution of the "/batch/" path in the request. Generally speaking, I have found that menu router entries that match actual folder names in your Drupal install seem to cause odd behavior...best to avoid that.

---
Tags: 7, batch-operations, xml-sitemap
---