title: Views object model

text:
# Question
Title: Views object model
I am having trouble understanding how Views fit into the Drupal 7 object model. (I've seen responses that Drupal doesn't have an object model but since it is a computer program, I am not at all buying that.)

At the end of the Views UI it asks if I want to create a block to go with my view (or is it that the View I'm creating IS a block?). This seems like a classic case where a convenience function (creating a block as a side-effect of creating a view) might be handy but makes it hard to understand what's really going on.

I know a view is a content query. That part seems pretty straight-forward. It is the mechanism by which the content gets added to a block, a page, or what else? Is a view a query that lives within these objects but doesn't have a life of its own?

I am NOT looking for an operational explanation or a tutorial on how to create a view. There are plenty of sources for that kind of info. Instead I am trying to understand views from a data structure and object model point of view. Any links to relevant explanations would be helpful. I've spent hours searching and have found nothing very satisfying.

# Answer
A View can (very basically) be considered a 'list of data'. There are various interfaces to let it know what data to display, and how, but the idea behind a View is simply to get a list of data from somewhere and get it out to the screen. It *executes* queries, but is not *itself* a query.

At its heart a View relies on a single 'base table' to query against. It can pull in data from different tables as long as relationships are appropriately described in code, but can only operate on one base table at a time.

These base tables are described to Views using `hook_views_data()`. The Views module comes with implementations for all core entities (node/user/taxonomy term), and many contrib modules that define custom entities provide Views support (the Entity module can help there too). But it's not limited to content, or even entities, Views can display data from any table it knows about.

A View contains one or more *displays* (e.g. page, block, rss feed, etc.), which are responsible for augmenting the database query and providing format/meta/other contextual information that is needed for the query and rendering processes. Each View has a default "master" display that newly added displays will inherit from.

Views uses information from these displays to hook into various things. For example, Views implements `hook_block_info()` and `hook_block_view()` in order to let Drupal know about the blocks that have been created as displays for all Views. That's why when you create a block in Views, you'll see it available straight away for use in the block admin page. Something similar happens with `hook_menu()` for pages/rss feeds.

Sorry if some (or all) of this isn't what you were looking for, this is a bit of a brain dump; wasn't sure exactly what you needed to know.
> 1 votes

# Answer
See Clive's answer about how views module hooks into the blocks, pages, etc. I rather thought you are looking for "How come Views is object-oriented, and has classes, while other Drupal functionality is mostly procedural code.

The best way to start the answer is probably by explaining a View instance.

See that, each "View" is actually an instance of view class. This class is the base class of all views. Modules do not extend or implement this base `view` class.

Furthermore, Views module, at least until Drupal 7.x-3.x, do not use all object-oriented functionality. You will not see interfaces or abstract classes to enforce specific methods or properties, but the convention is extend a parent class. You *could* create a completely new **handler** or **plugin** without extending or implementing any other class.

You will note name, description, tag, base\_table, etc are basic properties of the View. These values are directly stored in the `views_view` table.

Then, each View can have one or more `displays`. Now that we are talking about **displays** keep in mind that every block, page, attachment, RSS feed, slideshow, map, etc is technically a **plugin** of type `display`.

Views module comes with basic displays, such as block, page, that Views module provide classes for. Modules can introduce new plugins by implementing `hook_views_plugins`.

There are other types of plugins, such as pager plugin, style, query, etc. In the Views module folder, take a look at the available plugins in `./plugins` folder.

These plugins simply introduce new functionality: for example, create a slideshow from `handlers`, show rows in a map, create block content and a subject, check access, etc. When a module is introducing a new query, chances are most of the core logic already exists in the default query plugin class. Modules can simply extend this existing class and make adjustments in the new class of its own.

These plugins are not responsible about the actual data. This is where `handlers` come into play. A handler is basically, a set of instructions on how to handle a field, filter, argument or a sort criteria".

Handlers are responsible about actual data and instructions on how to handle data. Each and every field, filter, argument or sort criteria known to Views has a `handler` class. Views module comes with simple handlers for each of these `handler types`.

These basic handlers include handling a field as a number, using an IN query for node table's `type` field, a node ID argument, sorting rows by the node created date, etc.

Node ID and created date both fields are integers in the database. But, in the Views UI, you can configure which date format you want to display the created date in, but you can't do it for the node ID. Notice the difference here. Node ID column is handled by some class, and it is not the exact same as the handler responsible for node created field. However, you will notice some similarities in both fields.

See views module folder's `handlers` folder for views-provided handlers. Again, modules do not need to introduce new handlers to the View, but they must be available in the run time (this is taken care by Drupal class autoloading with .info file).

In `hook_views_data`, you can define which filters must be used to handle a particular table column. Views will then call `query()`, `render()` and other methods of the specified handler class and perform that action. If your table column's data type can be handled with an existing class, you simply define that existing class. Otherwise, you can create new handle, *ideally* extending an existing one that is the closest to what you need, and make adjustments to it. I used "ideally" here, because it's not necessary to make the classes an implementation of another class, but they must have methods to satisfy the plugins used in the View.
> 1 votes

---
Tags: views
---


title: Render tokens in hook_node_view

text:
# Question
Title: Render tokens in hook_node_view
I am creating the following pseudo field in hook\_node\_view:

```
function user_guides_node_view($node, $view_mode, $langcode) {
    $node->content['field_mytest'] = array('#markup' => '<p>This is my test</p><p>[current-page:title]</p>');
}

```

This is the rendered result:

```
This is my test
[current-page:title]

```

How can I get the value of the token to be displayed instead of the token itself?

# Answer
You can use `token_replace()` for that. As you're using a global token (no context required) it's very simple:

```
$markup = token_replace('<p>This is my test</p><p>[current-page:title]</p>');
$node->content['field_mytest']['#markup'] = $markup;

```
> 2 votes

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


# Question
Title: Drupal 7 - Trying to get term reference node, from html.tpl
I am trying to access the value of a term reference (field\_test), from a node, in html.tpl.

First I need to load a specific node, check if the term reference of this node is the same as another value that i have already in the page.

Is someone knows how to access that term reference, with ne $node object?

I have get already the $node, but i cannot access the "field\_test" which is inside the $node.

Thanks

emb

# Answer
> 1 votes
Ok, so you'll want to test for a node, then check for the field and then print it to your template. This should work for you:

```
<?php

if(arg(0)=='node' && is_numeric(arg(1))) {
        $node = node_load(arg(1));
        if(isset($node->field_test['und'][0]['value'])) {
            print $node->field_test['und'][0]['value'];
        }
}

```

?\>

That's code for Drupal 7

---
Tags: taxonomy-terms
---


title: Web services for specific node

text:
# Question
Title: Web services for specific node
I know you can enable Web services for content in Drupal8. You also need to set permissions to make a GET request to content.

But I was wondering if it's possible to set for each node if it can be accessed by GET request or NOT. How can I do this? Because now they can access all nodes ... .

# Answer
You need to implement a route subscriber and an access handler. Assuming that that should be able to see the nodes via HTML but not via json. If they shouldn't be able to see via HTML either, swap out the node access controller by implementing an alter hook to modify the entity type info. If they should be able to see HTML, go the route subscriber path and alter the rest resource routes to add a new access requirement. Then implement your logic in an the access handler.
> 1 votes

---
Tags: nodes, 8, services
---


# Question
Title: How can enable multiple contact form in drupal 8?
I want multiple contact forms(different fields) in my drupal 8 site Like Webform module drupal 7.

I have tried to add multiple contact forms and i am able to number of contact forms with different different fields but at time only one form i can able to enable. Can i enable different contact form with different menu link?

Is there any alternatives to achieve this or i need to go for custom form?

Thank you

# Answer
Each has their own URL. Check contact.routing.yml but pretty sure they are of the form contact/{contact\_form} where contact form is the machine name. You can create menu links and aliases to these like any other path.
> 2 votes

---
Tags: webforms, 8, emails
---


# Question
Title: How to modify the header <ul> in superfish menu?
I am trying to convert a html theme into drupal theme using superfish module. I can't figure out what to edit so that my menu has a different ID. So, instead of

\< ul id="supermenu-1"\>I'd like to have \< ul id ="jMenu"\>. Which files do I have to edit? Here is the code

```
    <ul id="superfish-1" class="menu sf-menu sf-main-menu sf-horizontal sf-style-none superfish-processed sf-js-enabled"><li class="active-trail sf-depth-1 sf-no-children" id="menu-218-1"><a class="fNiv sf-depth-1 active" href="/">Home</a></li><li class="sf-depth-1 menuparent" id="menu-443-1"><a class="fNiv sf-depth-1 menuparent" href="/?q=who-we-are">Who we are</a><ul style="float: none; width: 12em;" class="sf-hidden"><li class="sf-depth-2 sf-no-children" id="menu-444-1" style="white-space: normal; float: left; width: 100%;"><a class="fNiv sf-depth-2" href="/?q=project" style="float: none; width: auto;">Project</a></li></ul></li></ul>

```

# Answer
> 1 votes
I'm not sure that this is a good idea because changing that ID may break the scripted functionality of a Superfish menu but that said, here goes...

* I'm assuming you're on Drupal 7.

It's not a template that you'll be doing anything with. It is a theme function. When the Superfish menu is generated by drupal it is in response to a call to the theme\_superfish() function. You can find detailed info info on it here: http://api.drupalhelp.net/api/superfish/superfish.module/function/theme\_superfish/7

So with that in mind, you would want to override that funtion in your template.php file in your theme folder by copying the function to your template.php file, renaming it to YOUR\_THEME\_theme\_superfish($variables) and changing the part at the end where it builds the menu.

If you have several Superfish menus and only want to affect one of them (ie: superfish-1), you can add a conditional to the function so that it only changes the ID of the menu when the conditions match.

Hope that works for you.

---
Tags: 7, navigation
---


# Question
Title: Writing functional tests for a controller that makes call to external service?
I'm working on the D8 version of the CAS module. To integrate with a single sign on CAS server, this module will have to redirect the user to the CAS server often, and occasionally make cURL requests to that server for validation of various tokens. I'm struggling to write functional tests because of this.

I have a Drupal controller that will redirect the user to a number of places and invoke actions on a number of services, some of which may make cURL requests to the CAS server.

When the controller redirects to the server, I can just tell my web test to NOT follow redirects by overriding the property `maxiumRedirects` and setting it 0, then inspecting the response to make sure it was a redirect.

But, **Since this controller may invoke services that make cURL requests to the CAS server, how would I handle that in a functional test, where that external service does not exist?** In a unit test, I can mock the response from `Guzzle`, but can I do that in a functional test? Is my only option to create a test "server" module (with all the routes defined that CAS client makes requests to) that is enabled only for testing and would be used for testing my CAS client module?

# Answer
Depending on what exactly you want to do, what we've done multiple times is make the domain/URL to which you redirect to configurable, and then configure it to redirect back to your site.

Then implement dummy routes there in a test module, do whatever you want and redirect back.

This was already possible in 7.x and hasn't really changed. It is sometimes more complicated to set up, but has the advantage that you are testing much more of your actual code and integration.

if you use @larowlan's approach, you could also just write unit tests for your service but I like to have most code covered with functional tests (too). I've seen it in core already many times that unit tests and their mocks get out of sync with how things really work, and then they are testing something that no longer exists. The more you have to mock, the bigger that risk becomes.

Note that, no matter which approach you chose, moving as much logic as possible into a service or even multiple services makes sense anyway and allows you to use unit tests for things that they are good at. Testing all possible cases, error handling/conditions and so on.
> 4 votes

# Answer
Make the requests performed by another service (let's call it a connector service) and inject that into the controller. This service would have guzzle client injected. Create an interface for the service and type hint that. Create a test module inside your module and make it hidden. In the test module use the service alter pattern to swap out the real connector service with a test one. The test one can implement another interface called mock connector which has extra methods to set the expected return or can just be wired to return fixed data. In your simple test make sure the rest module is enabled. Then you can test. This is where decoupling shines.
> 3 votes

---
Tags: 8, testing
---


title: Paid Registration with Paypal

text:
# Question
Title: Paid Registration with Paypal
I have visited related questions here but i need more specific answer.

I have hooked into the user registration form and i have added a custom submit handler for user registration before the user drupal core registration function.

I want to implement paid registration. I have visited Paypal IPN documentation but they said the require a return url.

Actually i am confused in the whole process. I want to know actual steps to implement payment api of paypal then if the user has paid the drupal core submit function should run otherwise i'll die the script.

Thanks

# Answer
Rather than try to sell access to site registration, it might be worth considering allowing users to create a basic account and then pay for access to content based on role. Whether you are using Ubercart or Commerce, you should be able to create a Rule that will grant a user a role if their order contains a specific product and payment has been made. You can also use Rules Scheduler to create a time-based registration. Initially this might not sound like what you want, but the effect is the same - an anonymous user enters their email on the checkout page and is redirected to PayPal. On their return, they are granted a role that allows them access to content. If payment failed, they just have a user account that has no access to content.
> 1 votes

# Answer
If this is an activity that you'll be repeating, like hosting events on a regular basis, I would step it up a notch and add CiviCRM to the Drupal installation. It will increase the complexity of your site by adding a new administrative area where you would manage the CRM components (at this point events and Payment Processors) but that additional complexity will simplify managing them.

Out of the box it's set for managing events with PayPal; During setup you're prompted to go through a checklist. One of those items is Payment Processor. Set it to PayPal, follow the prompts and it just pretty much works.
> 3 votes

# Answer
It turns out you don't even need to get to grips with Rules. They've made it very easy for you: http://www.ubercart.org/docs/user/30477/selling\_site\_access\_roles
> 0 votes

---
Tags: users, payment-gateways
---


# Question
Title: Variables in templates don't use the language key
I have a multilingual website using Drupal 7. I installed the i18n modules (entity translation, etc). In templates, I use variables like `$vars['und']`.

I think Drupal ran updates. Now the template system uses `$var` without the language as key. I think I activated block translation. Templates still work for anonymous users, but they don't work for the administrator user.

Do you know what happened?

# Answer
> 1 votes
Once you are logged in, another language is requested and the 'und' key no longer works: https://www.deeson.co.uk/labs/programatically-access-field-data-using-entitymetadatawrapper-drupal Try replacing your use of $vars\['und'\]\[0\]\['value'\] with Entity metadata wrappers. More examples here: https://www.drupal.org/documentation/entity-metadata-wrappers

---
Tags: 7, i18n-l10n
---


title: drupal commerce calculator

text:
# Question
Title: drupal commerce calculator
I have a webshop made with drupal commerce kickstart and use it as a POS in a bar. The people pay with cash. What i want is a calculator with 2 input fields: field 1: the "Order total" from checkout automatic comes in this field. Field 2 is the amount of cash the customer pays with. So i can see how much i have to return to the customer. I have webform calculator installed. But the big question is how to automatic place the value from Order total in the calculator.

# Answer
If you already have a calculator that you like and the commerce portion is working the way you want it, the best thing to do is probably to change as little as possible. My first thought is to use a simple javascript that looks for the field where commerce stores the order total and copy it into your webform field. In my kickstart staging environment, there is a field called "ajax-item-price". So you could do a jquery one-liner like

```
$('#name-of-your-webform-field').val($('#ajax-item-price').html());

```
> 0 votes

# Answer
I found a solution myself. I have 3 fields in the webform calculator: Field 1: payed with (the amount the customer pays with, for example he pays with 20 Euro) Field 2: with token: \[site:current-cart-order:commerce-order-total:amount\_decimal\] it fills the field automatic Field 3: a formula {payed-with}-(name of field 2} Thats it. Now i have a working cash register for a Drupal webshop.
> 0 votes

---
Tags: commerce
---


# Question
Title: Theming property non-object when transversing the $node object
I'm getting this error when I run the code below, in reference to $color module:

```
Notice: Trying to get property of non-object in cotyhouse_preprocess_html()

```

---

```
function cotyhouse_preprocess_html(&$vars){
  // Check if on an article node page
  $node = menu_get_object('node');

  $color = $node->field_title_color;

  print $color;

}

```

When i output it via dpm, it says its an object, so im a bit confused why it would throw an error. The field value does indeed come through.

# Answer
> 0 votes
menu\_get\_object('node') should be: menu\_get\_object()

No need for node as its implied when you call that function.

Also you need to put it in a conditional:

if($node = menu\_get\_object()) { }

---
Tags: theming, debugging
---


# Question
Title: How do you render a table within a custom module in drupal?
I have a page on my Drupal module that is responsible for the input of goals to be completed by an admin. What I would like to happen is have all of the goals within the database table render below the input form. However the only thing that gets outputted is the description tag. Using the DBA module I can plainly see a populated achievements table so I assume that the code to call and render the table must be wrong. Does anyone see where I went wrong?

I have the following code...

```
function achievementList_form($form, &$form_state) {
$form['generateList'] = array(
    '#type' => 'item',
    '#description' => 'This is the achievements table',
    '#value' => achievementList_generate_table(),

);

return $form;
}

```

and

```
function achievementList_generate_table() {
$query = db_query('SELECT * FROM {achievements}');

$table = array(
    '#theme' => 'table',
    '#header' => array('NID', 'Name', 'Description', 'Points'),
    '#rows' => array(),
);
foreach($query as $row) {
    $table['#rows'][] = array($row->achvmntID, $row->achvmntName, $row->achvmntDesc, $row->achvmntPts);
}

return $table;
}

```

# Answer
Here's a tutorial which should answer your question: https://www.drupal.org/node/156863

It's difficult to say much about the way you're querying the database without knowing more about how your data is stored. I will say that you might benefit from defining an Entity type for your achievements.

When it comes to rendering the table you should be returning the output of the 'theme' function, passing 'table' as the first arg, then the header and rows as the second and third:

```
return theme('table', $header, $rows);

```

The API page for your version of Drupal will tell you how to structure those variables: https://api.drupal.org/api/drupal/includes%21theme.inc/function/theme\_table/7
> 1 votes

---
Tags: theming
---


# Question
Title: Drupal Commerce Kickstart 2 Mysql problem: "Table XYZ is marked as crashed and should be repaired"
My drupal kickstart 2 site occasionally cause Mysql errors. This is what Drupal Logs say:

`"PDOException: SQLSTATE[HY000]: General error: 145 Table './MYSITE/field_revision_body' is marked as crashed and should be repaired: INSERT INTO {field_revision_body} (entity_type, entity_id, revision_id, bundle, delta, language, body_value, body_summary, body_format) VALUES (:db_insert_placeholder_0, :db_insert_placeholder_1, :db_insert_placeholder_2, :db_insert_placeholder_3, :db_insert_placeholder_4, :db_insert_placeholder_5, :db_insert_placeholder_6, :db_insert_placeholder_7, :db_insert_placeholder_8); Array ( [:db_insert_placeholder_0] => node [:db_insert_placeholder_1] => 1953 [:db_insert_placeholder_2] => 1953 [:db_insert_placeholder_3] => breaking_news [:db_insert_placeholder_4] => 0 [:db_insert_placeholder_5] => und [:db_insert_placeholder_6] =>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Morbi vehicula condimentum placerat. Curabitur vehicula pharetra felis, quis feugiat magna imperdiet non..
 [:db_insert_placeholder_7] => [:db_insert_placeholder_8] => formato_xxxxxx_calcio ) in field_sql_storage_field_storage_write() (linea 452 di /var/www/MYSITE.it/modules/field/modules/field_sql_storage/field_sql_storage.module).`"

In this case general error was on table field\_revision\_body but sometimes it's another table. Hosting Service say that mysql are all ok. So what happend? This site has been online for several months, and only few days ago give me problem.

It seems that mysql dropped, then after a few minutes he recovers tables. There are specific tools for debugging to see what makes me go down the site?

Pls someone help me.

# Answer
> 1 votes
I have run into this problem a few times. It is indeed not directly Drupal related. However, since we are looking at MySQL through a Drupal lens, I guess we might as well answer it here.

The real source of the problem is a performance problem for your MySQL server. Drupal might have contributed to the problem by adding too much load. When I ran into a similar problem, I found out that a module I had written was making a huge amount of inserts into the access\_log table, which then caused the table (and sometimes other tables) to crash. I ended up migrating to stronger hardware, which made the problem occur less frequently. Then I cleaned up my code to insert only what I really needed and the problem was gone.

I suspect, you will probably see this problem first on the tables that have the fastest growth rate. If so, take a look at which Drupal module inserts into them and find out, if you can optimize your insert strategy. If you can't, you might have to move your MySQL server to a separate machine or upgrade the hardware you are running on.

---
Tags: database, commerce
---


# Question
Title: Views entity reference based on passed in value
I have a set of taxonomies that are related to a role- each member of the role gets their own set of values, plus a default value that is common to everyone. For example:

```
uid | tid | taxname
20 | 200 | name1
20 | 201 | name2
20 | 202 | name3
21 | 203 | name4
22 | 204 | name5
0  | 205 | default
```
So users 21 & 22 each have 1 term plus the default term, user 20 has 3 terms plus the default term.

I am trying to figure out how to setup an entity reference View that would display the terms available to each user. I know how to setup the entity reference View based on the uid as a contextual filter, but can't figure out how to bring in the default value as well.

# Answer
> 0 votes
Ended up doing a somewhat convoluted hack with a custom module.

1) Used 2 Conditional Filters in the View (A- uid of logged in user, b- uid=0)

2) Used regular filter of the taxonomy type (C). Since Conditional Filters are ANDed together as well as ANDed with any normal filters, the derived WHERE logic of View is (A AND B) AND C (which would never return results unless the logged in user was user 0, but the query isn't available to anonymous users).

3) Created a custom module and used the following in hook\_views\_query\_alter: $query-\>where\[0\]\['type'\]='OR' So the WHERE logic of the altered view becomes (A *OR* B) AND C, which gives me the results I wanted.

---
Tags: views, entities
---


title: View sorting on hidden ID not Name

text:
# Question
Title: View sorting on hidden ID not Name
I have a field in the View called Dealer Name. Dealer Name is populated from a list that looks like this:

```
#111 | Dealer 1
#112 | Dealer 3
#113 | Dealer 3

```

I need this field to be Alphabetically Sortable but when I apply sortable it sorts on the ID. What befuzzles me is that in the HTML only the Name is printed not the ID so how does it know to sort on the ID? (see below)

```
<td class="views-field views-field-field-da-dealer">
    Dealer Name
</td>

```

How can I change this behaviour to sort on the Name?

# Answer
In the end I had to use a hack to get the Dealer Name field to be sortable alphabetically. The Title field was working so I used Rewrite Results on that to display the info from Dealer Name. It isn't an ideal solution but it works.
> 0 votes

# Answer
When you edit your view, you should see "Sort Criteria" at the bottom of the left column. I think it defaults to "Updated date". If anything is in this section, you'll probably want to delete it and then click on "Add" to pick the id as your real sort criterion.
> 0 votes

# Answer
It sounds like the view is sorting on Post Date currently (as pictured below), so you will need to edit the view, and in the sort criteria section, click "Add" to add the "DA Dealer" field. Then you need to remove the "Post Date" sort item, which you can do by clicking on the small downward arrow beside the "Add" link and choose "Rearrange" in the dropdown that appears -- this will allow you to rearrange or delete the sort criteria.
> 0 votes

# Answer
To answer the "why?" part of your question:

Drupal Views sorts the contents of your view long before constructing the HTML for it, so it does not need the id within the HTML to know which order to put it in.

As for "how can I fix it?"...

I think Laryn is on the right track. Are you using any plugins for Views? I have found some in the past that get the sorting wrong, notably Pivot Tables for Views.
> 0 votes

---
Tags: views
---


# Question
Title: Update existing nodes with fields from XML or CSV
There are 2 greate modules for importing nodes Feeds and Feed Import. Is there a way to update fields of existing nodes on import from XML or CSV file?

For example, there is an XML feed from another website with products (id + price) and file with additional data for the same products (id + description). How to import both sources into the same node in Drupal?

# Answer
You need to set up feeds and feeds\_xpathparser. You could found a good start for configuring all this here : http://www.drupalprogrammer.co.uk/2012/12/use-feeds-module-to-import-xml-data-in.html

Concerning your concern about updating, you can do this by configuring the guid as your external unique id. In the screenshot provided, you can see in my case the xml tag used for unique id is simply `<id>`.

Then, you just have to configure the node processor so that it will "Update existing node" when it found a duplicate as shown on the screenshot below.
> 2 votes

# Answer
You should know the nid to be able to import this product.

In node import when you add the nid to the csv it understand that there is an update, but you should try it, maybe it delete all the content but not the information from the csv.

The best options in this case should be to make a bacthapi process to update all the nodes.

Oskar
> 0 votes

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


# Question
Title: is it possible to add a class to header found in page.tpl based on a node id?
first off, i’m using Adaptive Theme so maybe this won’t make sense using a different theme. but here i want to add a class to

```
<header id=“main-content-header” class="someclasses">

```

which is found in page.tpl but based on node id. this would have to be done in mysubtheme\_preprocess\_page(). i have part of the code working.

```
 $variables['content_header_attributes_array']['class'][] = 'about'

```

but don’t know how to ascertain the node id that is contained on the page. is it possible? my pseudo code would read something like

```
if (nodeId == 1){
 $variables['content_header_attributes_array']['class'][] = 'about'
}

```

by the way, i find myself needing to do this constantly so i can style these headers differently, at least for this project i do. maybe there’s a better way to accomplish,..?

i can use conditional stylesheets but then there’s the issue of adaptive design and you’d have to put media query’s in these conditional stylesheets. don’t know if that’s such a good idea or not.

# Answer
> 5 votes
You probably already have a specific class for the page on the `<body>` tag.

For example :

```
<body class="html not-front not-logged-in page-node page-node- page-node-5 node-type-page">

```

Then a css should work for you :

```
body.page-node-5 #main-content-header { ... }

```

or

```
body.node-type-page #main-content-header { ... }

```

---
Tags: theming
---


# Question
Title: HTML Form that Passes Information to Hidden Fields Through URL
I am trying to build an html form that is stretched across several pages. My intention is to use the GET method to send all of the fields data in the query string (URL parameters) and then store this data in hidden fields on the next page. I need to know how to append the data to the URL and how to retrieve it on the next page. I think I will need to send information across at least three pages. I have searched for a way to do this but I haven't really gotten a clear explanation. I am somewhat new to HTML coding. This is the most difficult thing I have attempted to code. Also, (this is not strictly necessary) but I would like to show this information as dynamic text as well. So I can show that certain pieces information have been added to the form. This needs to be separate from the actual form though. Thank you in advance. Any help is greatly appreciated.

# Answer
You need to write a multistep form with the Form API and CTools.

The Form API allows you to write forms: See Creating a builder function to generate a form.

Because your form is multistep you need CTools to implement it, and handles issues like carry those values over the different steps.

This two subjects are too broad to explian in an answer, but there's lot of documentation about them.
> 0 votes

# Answer
Actually, you have multiple option to achieve what you want:

1. As previously suggested, you could use CTools to build a multi-page form. This tutorial has a pretty decent step-by-step.
2. You can create a form that uses collapsible tabs. It will look like a multi-page form without the complications of having to pass parameters through.
3. You can hand-code a succession of forms, each with its own menu path so that you can redirect from one to the next upon clicking submit. In this case you don't have to explicitly fill the GET parameters since each form submits its values in the POST and you can harvest them using drupal\_get\_query\_parameters() and store them in hidden fields in the subsequent form.

Which approach works best for you depends on how your data is structured and whether you need to store intermediate status of the form. For example, is filling out only the first part a valid response? Can users skip step 2 and only do 1 and 3?
> 0 votes

---
Tags: theming, forms
---


# Question
Title: Product price not showing up in views without Disable SQL rewriting
I got a Commerce Product set up in Drupal 7 with a content-type Product Display that have a product reference to it. Users have read access to Product Display but not direct access to the Commerce Product.

I am now trying to set up a Pane in Views 3 that list Product Display nodes in a table. I want to include the Price in every row. I have added the referenced product in relationship and were about to add the price field from the product.

This view however does not display at all for normal users. I suspected that normal users don't have access to the Product entity, so turned on Disable SQL Rewriting and now Views displays the table as intended for normal users.

I am wondering if this is the right way to get the price to show up in Views? I can see that the Product Display node can actually display the price on its page without giving access to the Product to normal users, but cannot find how to access that display field within just the node in Views.

# Answer
This has been discussed in a lengthy thread on drupal.org. The recommendation apparently is indeed to disable SQL Rewriting. There is a pretty good explanation of the ramifications in the middle of the thread along with alternative suggestions. But it appears that you got it right for now.
> 1 votes

---
Tags: views, commerce
---


# Question
Title: Enable new content types to use as newsletter
I am using the simplenews module in order to create newsletters and enable users to subscribe to those. By following the instructions in the readme file it says:

Enable new content types to use as newsletter: Structure \> edit content type \> Publishing options

What I did, I created a new content type and in the Publishing options I enabled the "Use as a simplenews newsletter" option.

Is this correct? Or should I have gone into one of the existing content types and selected this checkbox instead?

Also, ENABLE SIMPLENEWS BLOCK

With the Simplenews block users can subscribe to a newsletter.

Enable a Simplenews block per Newsletter category: Structure \> Newsletters \> edit newsletter category

In my block structure I have the following available to me: Newsletter: Multi Subscription Newsletter: Newsletter

Enabling Newsletter: Newsletter displays nothing. SHould it? Enablinb Newsletter: Multi Subscription displays an option of subscribing to available newsletters. But I only have one newsletter so it's a bit misleading.

What settings have I stuffed up in order for the Newsletter: newsletter block to not display anything, but to instead have a multi subscription block?

# Answer
> 1 votes
The main options are the defaults. So when you edit a content type all the options you turn on/off are the defaults for newly created content. Any content that has already been created will need to be edited and re-saved with that option selected. If you have a lot, I suggest using VBO.

# Answer
> 1 votes
It doesn't matter if you create new content types or make existing ones to newsletter issues. That's up to you.

If you checked the block checkbox and displayed the block and it doesn't show anything, then something is not working correctly. Can't say what exactly that would be, if you are sure that you followed the instructions directly, try open a support or bug report in the module. Before you would do that, I suggest you try to do the same on a clean, new Drupal installation to see if it works there or not. If it does, then probably something else on your site conflicts.

---
Tags: emails
---


# Question
Title: Reply for comment redirects to the next page
I am using advance forum module and having commenting functionality for the forums. But the problem is when I use to reply to the comments it redirects me to the next page. Where I want to display a comment form exactly below to the comment to which I am replying. Where should I configure for this? With comment module or just with advance forum module?

# Answer
> 0 votes
It seems the AJAX Comments module is what you're looking for.

I've installed it it's working good without Advanced Forum module.

> **Features:**
>
> Provides ajax comments to Drupal sites. Features:
>
> * Makes AJAX submits
> * Allows replies to comments on the actual thread page
> * AJAX comments deleting
> * Works with CAPTCHA
> * Cool jQuery sliding
> * views integration

---
Tags: comments, nodes
---


# Question
Title: Multisteps Webform loses current page when refreshing browser
I've created a Webform with three steps. When I refresh the browser (F5) on step 1 and 2, I correctly remains in the same page.

If I do the same in step three, I go back to step 2. For ALL the steps \> 2, when I refresh the page I go back to step 2.

I tried to change same Webform settings ("Allow cookies for tracking submissions" and "Automatically save as draft between pages"), but with no results.

I'm using an anonymous user to browse the Webform's pages.

Anyone has a solution?

# Answer
> 1 votes
For this purpose I use Multi-step forms module. This does all the heavy lifting for you. It allows you to use a session storage so if the page gets refreshed or the browser gets closed, it saves the current step.

**Multi-step forms:**

> Mforms module is a set of tools that help to create advanced multistep forms in Drupal. It can be modified and extended so a developer has full control of the way how individual form steps will be handeled, how and where will data be between form steps stored, which step will follow, how form controls will act and how the output will be displayed.
>
> The main differences from existing multistep solutions for Drupal are robustness, flexibility and extensibility. You can even dynamically change the steps sequence and jump from one step to another regardless of their order.
>
> Read documentation.

---
Tags: webforms, forms
---


# Question
Title: How to get a node object/id from theme functions when the form is ajaxified?
I used theme\_radio() hook to change the html code of my radio buttons in ubercart attributes form to get something like that:

The code I used in theme\_radio function to display this is:

```
//We modify only radio input in ubercart attributes forms
  if(isset($variables['element']['#parents'])){

    if(($variables['element']['#parents']['0']=='attributes')&&($variables['element']['#parents']['1']=='8')&&($variables['element']['#type']=='radio')){

      $node = menu_get_object();

      $position = $variables['element']['#return_value'];

      //We load content from field collection
      $field_collection_entity = field_collection_item_load($node->field_colors['und'][$position]['value']);

      //We extract color name from field collection
      $color_code = $field_collection_entity->field_color_code['und'][0]['rgb'];

      $pellet_html = '<span class="attributes-pellet" style="background: none repeat scroll 0% 0% '.$color_code.';"></span>';
    }else{
      $pellet_html = '';
    }
  }else{
    $pellet_html = '';
  };

```

So everything works well when I load the page.

The problem occurs when I select something in form. As the form is ajaxified, actually when I click either on colors or sizes inputs, the form reload and my function is no more able to retrieve the node object with:

```
$node = menu_get_object();

```

or with:

```
if (arg(0) == 'node' && is_numeric(arg(1))) {
  $nid = arg(1);
  if ($nid) {
    $node = node_load($nid);
  }
}

```

After I clicked in a option, the color inputs get back to initial state:

So how to retrieve node object/id from a theme function when form is ajaxified??

You can check the form there:

http://www.zanonymes.krown.ch/collections/les-accroch%C3%A9s

# Answer
You can try to store the node-\>nid in a hidden field on page load. When your ajax call is executed, you can load the node from the hidden field instead of the menu\_get\_object.
> 1 votes

---
Tags: theming
---


# Question
Title: Ubercart Authorize.Net checkout loops back to cart page
I am trying to process an Ubercart order using Authorize.Net. I go through the Checkout and Review pages. When I submit the cart for credit card processing, I get returned to the Checkout page.

The only error I can find is: page not found 09/23/2014 - 17:39 cart/sites/all/themes/metroblocks/images/int.png

I think maybe the cart solution has an incorrect relative path somewhere to go to cart/../sites/all....

At one time I tried getting Commerce to work, but couldn't install Kickstart. I deactivated Commerce, but didn't uninstall it. Don't know if there is a conflict between Commerce and Ubercart.

Could someone please explain how I might troubleshoot/resolve this issue?

Using Drupal 7.32, Ubercart 3.7 on a shared hosting server, Apache2.

# Answer
I reinstalled Drupal, and it was able to identify the missing image files. It was an issue with Drupal after all. Good thing I don't get dismissed so easily.
> 0 votes

---
Tags: ubercart, payment-gateways
---


title: Block print on page.tpl file

text:
# Question
Title: Block print on page.tpl file
I have created a block for adding image from drupal backend with title name "image". Now i want to add this block into page.tpl. How can i do that by using code.

# Answer
Here is the sample code

```
$imageblock = block_load('block', '155');
$output =  drupal_render(_block_get_renderable_array(_block_render_blocks(array($imageblock))));

```

$output will have the generate html for the block . This can be rendered in the template file using

```
 print $output;

```

If the block is created using views, you may have to use `$imageblock = block_load('views', 'block_name');` instead of loading the block using the block id.
> 0 votes

---
Tags: views, theming
---


# Question
Title: how to validate email id is already register or not
```
 function lawyer_register_form_submit($form,&$form_state)
{
$mail = $form_state['values']['mail'];
$new_password = user_password();
$edit = array(
  'name' => $form_state['values']['name'],
  'pass' => $new_password,
  'mail' => $mail,
  'init' => $mail,
  'status' => 1,
  'access' => REQUEST_TIME,
  );
  if(!db_query("SELECT COUNT(*) FROM {users} WHERE mail = :mail;", array(':mail' =>  $mail))->fetchField())
  {
  $to = $form_state['values']['mail'];
  $subject = 'Lawandmoney New account created';
  $headers = "From: admin@lawandmoney.info\nContent-type: text/html";
  $body = 'A new user account has been created for you at <a  href="http://us.lawandmoney.info">us.lawandmoney.info</a>.<br /> Your login details are as  follows:<br />Username: <b>'.$form_state['values']['name'].'</b><br /> Password:  <b>'.$new_password.'</b> <br /><br /> Please login to <a  href="http://us.lawandmoney.info">us.lawandmoney.org</a> and change your password.<br />';
     user_save(drupal_anonymous_user(), $edit);
     if($form_state['values']['send_message'] == 1)
     {
     mail($to,$subject,$body,$headers);
     drupal_set_message("Sussessful register.Please check your Email for login   deatils.");
     }
     else
     {
     drupal_set_message("mail not send.");
     }
     }
     else
     {
     drupal_set_message("You are already register.");
     }

```

we created a custom user registration form.now we have to checked if user is already register then its give error like You are already register, data will not inserted into database and mail not send to user.

# Answer
> -1 votes
```
  function module_form_submit(&$form, &$form_state) {
  $new_password=user_password();
  $edit = array(
  'name' => $form_state['values']['name'],
  'pass' => $new_password,
  'mail' => $form_state['values']['mail'],
  'init' => $form_state['values']['mail'],
  'status' => 1,
  'access' => REQUEST_TIME,
  );
  $mail = $form_state['values']['mail'];
  if(!db_query("SELECT COUNT(*) FROM {users} WHERE mail = :mail;", array(':mail' =>  $mail))->fetchField())
  {
  $to = $form_state['values']['mail'];
  $subject = 'test';
  $headers = "From: test@test.info\nContent-type: text/html";
  $body = 'test';
  user_save(drupal_anonymous_user(), $edit);
  drupal_set_message("Sussessful register");
  }
 else
 {
 drupal_set_message("Please check your Email for login deatils.");
 }
 }

```

# Answer
> 3 votes
This can be done with `hook_form_alter`:

```
function module_(&$form, &$form_state, $form_id) {
  $user_login_forms = array('user_login', 'user_login_block');
  if (in_array($form_id, $user_login_forms)) {
    $form['#validate'][] = 'my_validate_function';
  }
}

function my_validate_function(&$form, &$form_state) {
  $name = $form_state['values']['name'];
  // Drupal 6:
  if (!db_result(db_query("SELECT COUNT(*) FROM {users} WHERE name = '%s';", $name))) {
    // User doesn't exist
  }
  // Drupal 7:
  if (!db_query("SELECT COUNT(*) FROM {users} WHERE name = :name;", array(':name' => $name))->fetchField()) {
    // User doesn't exist
   }
}

```

It's better to query the DB directly in this case than than using user\_load as it hooks into other modules as well.

# Answer
> 0 votes
You can use https://api.drupal.org/api/drupal/modules%21user%21user.module/function/user\_load\_by\_mail/7 to check if a user already exists, if so display a message with

```
drupal_set_message

```

Otherwise, register the user

# Answer
> 0 votes
if you're getting the blank page(or error) it's probably because of this - `$mail = $form_state['values']['mail']` line. You're passing `$form_submit` to the `lawyer_register_form_submit`, but getting the mail from `$form_state` which is giving `undefined variable` error, after that you're passing undefined `$mail` to the `db_query`...

EDIT:

ok, here is the solution: (this goes to `_validate($form, &$form_state)` function):

```
$exist = db_select('users', 'us')
        ->fields('us')
        ->condition('mail', $mail, '=')
        ->execute()
        ->rowCount();

if ($exist) {
  form_set_error(null, 'You are already register');
}

```

submit callback, just create a user, send a mail:

```
...
mail($to,$subject,$body,$headers);
...

```

# Answer
> 0 votes
I do not really know why you have developed a new user registration form, as you can customize the one Drupal has, by going to:

> Administration » Configuration » People » Account settings

Moreover, the code you have written is likely doing the thing you want! But by the Drupal practices, you're not following the recommended way.The following line is checking the repetition of **user email**:

```
if(!db_query("SELECT COUNT(*) FROM {users} WHERE mail = :mail;", array(':mail' =>  $mail))->fetchField())

```

Try to check the values in the hook\_form\_validate and set the error by form\_set\_error function.

---
Tags: users
---


title: Drupal mkdir folder permission

text:
# Question
Title: Drupal mkdir folder permission
When creating directory using function drupal\_mkdir in custom module, how to set folder permission access to "Create and delete files"?

```
drupal_mkdir('public://myfolder/');

```

# Answer
> 3 votes
The second parameter is `$mode`, which you can provide. e.g.

```
drupal_mkdir('public://myfolder/', 0755);

```

By default the 'file\_chmod\_directory; will be used, which, by default, is 0775.

Exactly what mode you use will obviously depend on your server set up. If you're not sure, ask your sysadmin what it should be.

---
Tags: 7
---


# Question
Title: Why are available updates of CKeditor not visible in the update report in Drupal 7?
`/admin/reports/updates` lists a few updates, but the ckeditor module is missing here. It runs in version 1.9, since then a few security updates have been released, but it does not matter how often I run the cron or update the list manually, the updates for ckeditor wont be listed here.

The module itself works perfectly fine. How come?

# Answer
As it turned out, the module's .info file was broken, downloading the 1.9 release and copying the .info file's content fixed this issue.
> 0 votes

# Answer
Drupal only check for drupal modules. The CKEditor module is https://www.drupal.org/project/ckeditor and the latest version is 7.x-1.16. This information should appear in admin/reports/updates.

I suppose you are talking about the CKEditor library which is not handled by the page admin/reports/updates.
> 0 votes

---
Tags: updating
---


title: Cumulative user ratings

text:
# Question
Title: Cumulative user ratings
I am trying to set up a user to user rating system where users can rate nodes and the average is the users rating / total feedback.

I was thinking about using fivestar to create a field on the user profile, then create a fivestar reference (which doesnt exist to my knowledge) to that field so when a user rates a node they aren't rating the node, but the user's rating field attached to their user profile.

Is their a way to get users to rate nodes authored by a user and have it total up to give the user the average rating? I wanted something easy and light without having to create a feedback content type with a fivestar field and using entity prepopulate to pull the user in to link the user to the review content type. Or do it with entityforms/webform.

Would this be doable with flag since I am already using it pretty extensively?

Thanks.

# Answer
Ok here is what you can do:

1. Attach a Five Star field to the user
2. Create Views block that shows the users. Select to show fields and only show the Five star field.
3. Use a contextual filter in the View to filter by User Id(uid). Select "Provide a Default Argument" -\> "User id from URL" -\> "Also look for a node and use the node author"
4. Place this block on the page. Restrict it by content type if you want.
5. When someone Views a node then they will see the Views block also and can rate the user.

You could put Header text area in text in the View to give the user instructions. You could also display the user name, picture or other information if you wanted.

This is way I could think of with the least amount of modules. If you were already using Panels you could use Panels to place the Five Star field on the node page but I won't suggest installing Panels just for this use case.
> 0 votes

---
Tags: 7, flags, rating
---


# Question
Title: I can't set a data value using rule on a custom entity
I have created a custom entity "Project" with this fields: `id, name.`

I have created a rule and added an action "`create entity`" and selected "Project".

I have added another action "`Set a data value`" and selected "`name`" of the newly created entity project and I had this message : "`The selected data property doesn't support writing`."

Here is the entity property info

```
 /**
 * Implements hook_entity_property_info().
 */
function project_entity_property_info() {

  $info = array();

  $info['project']['properties']['id'] = array(
    'label' => t('Project ID'),
    'description' => t('The ID of the project.'),
    'type' => 'integer',
    'schema field' => 'id',
  );

  $info['project']['properties']['name'] = array(
    'label' => t('Project name'),
    'description' => t('Name of the project.'),
    'type' => 'text',
    'schema field' => 'name',
  );
  $info['project']['properties']['description'] = array(
    'label' => t('Project description'),
    'description' => t('Description of the project.'),
    'type' => 'text',
    'schema field' => 'description',
  );
  $info['project']['properties']['deadline'] = array(
    'label' => t('Deadline'),
    'description' => t('Project deadline.'),
    'type' => 'date',
    'schema field' => 'deadline',
  );

  return $info;
}

```

# Answer
> 4 votes
In the provided hook, You need to add the **setter callback**.

So it will be like:

```
function project_entity_property_info() {
  // .... rest of code removed for brevity.

  $info['project']['properties']['name'] = array(
    'label' => t('Project name'),
    'description' => t('Name of the project.'),
    'type' => 'text',
    'schema field' => 'name',
    'setter callback' => 'entity_property_verbatim_set', // -> this is it!
  );

```

Now rules knows how to set the value on entity.

More information about the `hook_entity_property_info` can be found here. If `name` requires a complex workflow to be set, you can write your own setter similar to `entity_property_verbatim_set` (for validating purposes, or ...).

If you are benefiting from the power of Entity API you may declare it in your EntityMetadataController class. There is a default class called EntityDefaultMetadataController you can extend it and introduce it as your entity type's metadata controller.

Another option is to use entityspice to declare your entity type which takes care of it all.

---
Tags: 7, entities, rules
---


# Question
Title: How to open the view and edit page inside the colorbox?
I am using an full calendar with event as a node.
I have disabled the overlay module.
In the full calendar settings-\>colorbox options, I have enabled 'open events in a colorbox'

Now when I click on any events in the full calendar it opens the node view page in colorbox which has two tabs **view** and **edit** .

When I click on **edit** tab , it opens into a new page instead of loading inside the colorbox. How can I achieve loading of **view** and **edit** tab **inside the colorbox** and prevent the redirect which occurs when clicked on edit page? .

# Answer
> 2 votes
You need to specify more precise which html elements of the destination page (the page containing the event) should be rendered.

i guess changing the id selector to

#content .content

will do the job.

---
Tags: 7, modal-dialogs, javascript
---


# Question
Title: Can't edit Main menu block in sidebar by clicking on "gear"
Today on one of my websites I encountered something strange. I have my "Main menu" block in my left sidebar, and when I hover over that block, the "gear" to edit it shows up, but clicking on it does nothing. Also, on pages that the block wouldn't show up on, it does (rather, the blank space does) with nothing in it, and the gear still shows up and is not clickable.

I tried moving the block out of the region, saving, refreshing, moving it back, saving, and refreshing again to see if that would fix anything, but that has not.

Any help would be greatly appreciated!

**Updates:**

* What I mean by "nothing" is that there is the empty region with my main content area pushed over as if there actually was block content there.
* And 3 errors in the console: Uncaught TypeError: Cannot read property 'msie' of undefined panels.js?ndi45m:6.... Uncaught TypeError: Cannot read property 'msie' of undefined admin\_menu.js?ndi45m:223.... Failed to load resource: net::ERR\_CACHE\_MISS

# Answer
It is caused by legacy functionality in old versions of jQuery no longer being supported in more modern versions. In this particular case I think it has to do with browser version detection, which has fallen out of favour for feature detection.

Add the jquery-migrate script to your theme's javascript folder and load it via your theme's info file.

If you continue to have issues you might need to make sure this file loads directly after the jQuery main file.
> 0 votes

---
Tags: routes, blocks
---


# Question
Title: Separate domain for specific content type
I haven't worked with multi-domain setups in the past so I did some research regarding the options for altering my website to accommodate for specific multi-domain needs.

My immediate need is to have a specific content type appear in links like:

```
http://my-content-type.my-website.com

```

According to what I've found so far, the Subdomain module fits my use case exactly however, there are 4 things that keep me from installing it:

1. Very small user base (272 sites using it according to drupal.org)
2. It's a beta version since 2011 and the latest dev seems to be 4 months old
3. It does not work with Global Redirect module (which I happen to use in my site)
4. I will most likely need full sub-domain support in my website in the near future (different theme, custom user paths in separate domains etc).

Based on that, I came across the Domain Access module which seems to be the way to go for my future needs having the added benefit of a large user base, frequent maintenance releases and a stable version.

My question is the following:

Is there a way to minimally setup the Domain Access module to suit my needs for now (give me the option to setup a custom content type as a separate domain) and configure any advanced settings later? Is there any other solution that my research did not reveal?

# Answer
I had the exact same choice to make 1 year ago and Domain Access was the best way to go.

To answer your questions:

* You can always configure what content is available on each domain (basically you will set the new subdomain and set your specific content type to be available only there)
* You can worry about advanced settings later; keep in mind now that almost all setting throughout the whole site can be differently set for each subdomain
* A good recommendation would be a multi site install like Karel suggested
* Another approach would be to just put some rewrite rules in your server, and have multiple themes set on each path which can contain a view that serves your content (this is pretty limited depending on what you want)
> 2 votes

# Answer
Have you considered just using the basic Drupal multisite setup using sites.php and a subdirectory for each site's settings file? This is the way to go if you want fully separated databases, but with a shared repository of modules and themes (and you can add site-specific ones too if you wanted).

Look at the file sites/example.sites.php, that should be enough to get your started.
> 0 votes

---
Tags: 7, domain-access, subsites
---


# Question
Title: drush inheritance, site-ssh and site-list
It's possible I'm going about this all wrong, and I should be setting up my aliases file differently.

We have a set up with 4 load-balanced production servers running the same code and accessing the same database. I want to set up a drush aliases file to access them by a short name and also allow commands to be run on all of them simultaneously. Here's what I have so far, in `~/.drush/cust.aliases.drushrc.php`:

```
<?php
$aliases['production'] = array (
  'root' => '/var/www/cust',
  'uri' => 'www.example.com',
  'databases' => array(
    'default' => array(
      'default' => array(
        'database' => '...',
        'username' => '...',
        'password' => '...',
        'host' => '...',
        'port' => '3306',
        'driver' => 'mysql',
      ),
    ),
  ),
  'site-list' => array(
    'production.1',
    'production.2',
    'production.3',
    'production.4',
  ),
);
$aliases['production.1'] = array (
  'parent' => '@production',
  'remote-host' => '...',
  'site-list' => array(),
);
$aliases['production.2'] = array (
  'parent' => '@production',
  'remote-host' => '...',
);
$aliases['production.3'] = array (
  'parent' => '@production',
  'remote-host' => '...',
);
$aliases['production.4'] = array (
  'parent' => '@production',
  'remote-host' => '...',
);
?>

```

Now the problem I have is that the `site-list` variable is being added to the individual definitions, so the `site-ssh` command thinks that they are a list. I've tried a few things to sort this out, including adding `'site-list' => NULL`, `'site-list' => array()` and `'site-list' => ''` to the the `production.x` definitions, but this doesn't work since `site-ssh` just uses `isset`. Neither do my attempts to use the `unset` function because the inheritance happens after I've tried to unset it.

# Answer
> 2 votes
The problem here is that Drush will always prefer the non-empty 'site-list' in @production over any empty value you provide in the specific site aliases. This is regrettable, as it makes it Hard to delete values.

There are a couple of alternatives, though. The most straightforward solution is to just take advantage of the fact that Drush alias files are executable php. You can refactor your alias definitions like this:

```
<?php
$common = array (
  'root' => '/var/www/cust',
  'uri' => 'www.example.com',
  'databases' => array(
    'default' => array(
      'default' => array(
        'database' => '...',
        'username' => '...',
        'password' => '...',
        'host' => '...',
        'port' => '3306',
        'driver' => 'mysql',
      ),
    ),
  ),
);
$aliases['production'] = array (
  'site-list' => array(
    'production.1',
    'production.2',
    'production.3',
    'production.4',
  ),
);
$aliases['production.1'] = array (
  'remote-host' => '...',
) + $common;
$aliases['production.2'] = array (
  'remote-host' => '...',
) + $common;
$aliases['production.3'] = array (
  'remote-host' => '...',
) + $common;
$aliases['production.4'] = array (
  'remote-host' => '...',
) + $common;

```

Your second option is to take advantage of a Drush feature that automatically creates group aliases for all aliases that are defined in a single alias file. Start with your alias file definition as you show it in the question above; then:

1) Delete 'site-list' from the 'production' alias.

2) Move the 'production' alias to a different file (I use servers.aliases.drushrc.php to store aliases to all of the servers that I have sites on).

3) Keep the individual site aliases as they are, with `'parent' => '@server.production'`.

Once you have done that, you may use `@cust` as an alias list for all of the aliases defined in cust.aliases.drushrc.php.

---
Tags: drush, ssh
---


# Question
Title: Action when a comment has been replied to
I have a unique case where we need to do something, namely a behavior where a user Comments on a node, and when a new comment is made in response to him, we need to "alert" the user in a variety of ways. Right now, lets say we need to send him an email.

I'm not sure of the best approach to implement this logic, but it looks like it may be possible to extend the Rules module to do so. What would this logic look like? Are there other approaches that can be used here?

# Answer
> 1 votes
I've got something similar in setting up a forum, where all posts on a topic are really just comments. We've set it up to allow people to "subscribe" to the topic via the Flag module and then have a Rule set up to notify all subscribers after a new comment is added. Here's the Rule (from /admin/config/workflow/rules )

And here's how it looks when you click "Edit" in the screen above:

So basically, I've set up an event for a comment being added to a forum topic, then under actions, fetch all the users who have flagged that node and loop through, sending them an email (which can be customized with tokens based on the newly added comment). You can automatically flag a user to a node when they create it or comment on it.

# Answer
> 0 votes
You can try Comment\_Notify module, check the feture section of the module if it satisfies your need.

OR

You can try configuring the rules for your need.

Here is the Demo link to configure Rules.

---
Tags: 7, rules, comments
---


# Question
Title: DIsplay Block content after certain time delay
I need to show the block content to users after certain delay of page load . Initially the user will see only the article , but after certain time the block content will be revealed . Can it be done ? any pointer is appreciated .

Thanks Pankaj

# Answer
* Create a block and set it to the region and page you'd like it to appear at
* Use CSS to hide the contents of the block
* Use JavaScript to override the hiding and display at a specific interval

The CSS would look something like this:

```
.block-DELTA {
  display: hidden;
}

```

And then just use JavaScript to display the block after a specified interval. You could also add some animation to your CSS property to make it fade in. (That's just one example tutorial on animating, google and you'll find hundreds more)

You can add the CSS and JavaScript to the block in a number of ways. The quickest and dirtiest is in the block content itself. I'd strongly recommend storing any code in either a module or theme. See `drupal_add_css()` and `drupal_add_js()` for more information on implementing.
> 1 votes

---
Tags: views, blocks
---


# Question
Title: List of parent nodes with a sublist of child referring nodes on a single content type
I have a content type Article with an Entity Reference to himself.

Demo content:

```
Article 1 -> No ref
Article 2 -> No ref
Article 3 -> Ref to 1
Article 4 -> Ref to 1
Article 5 -> Ref to 2
Article 6 -> Ref to 1, Ref to 2

```

Step 1: I want a View list to display every node that doesn't referring to anybody. So: `Filter criteria: RefField = Is empty` works nice and the results:

View list results:

```
Article 1
Article 2

```

Step 2: Display the title of every node that is referring to the ‘parent’

View list results:

```
Article 1
   Article 3
   Article 4
   Article 6
Article 2
   Article 5
   Article 6

```

I'll break my head! The same architecture works fine if I have 2 content types, but I can't figure out with a single content type.

Edit: When I create a relationship: *Entity Reference:* Content referencing Content from field\_Article\_Ref and then add a *Field and use the above relationship:* (Content referencing Content from field\_Article\_Ref) Content: Title (Title). It displays the childs but the results are not grouped (even I use query settings-\>Distinct) and looks like:

```
Article 1
   Article 3
Article 1
   Article 4
Article 1
   Article 6
Article 2
   Article 5
Article 2
   Article 6

```

How I can group the results?

After that point go to Format-\>Settings-\>Grouping field Nr.1 and group by the desired field.

# Answer
> 0 votes
## Recapitulation

1. Relationships-\>Add-\>Entity Reference: Referencing entity of the Field that reference to himself. Also check Require this relationship.
2. Fields-\>Add-\>Content: Title.
3. Fields-\>Add-\>Content: Title and use the relationship.
4. Format-\>HTML list (makes a wrapper element).
5. Format-\>Settings-\>Grouping field Nr.1-\>Content: Title.
6. Fields-\>Edit Content: Title-\>Exclude from display (it will be displayed by the grouping).

---

PS Also check the Views Field View module mentioned by @tenken here

# Answer
> 0 votes
I find it's easiest to do this with Views Field View module. And then enable views caching for the sub-views related queries on the page.

> This module allows you to embed a view as a field in a view. A new field handler is made available, so this can also be used in area (header/footer/empty) handlers as well as rows.
>
> This view handler can accept arguments from fields of the parent view using tokens and pass them into the child view for each row. Raw or rendered token values can be used, as well as static values.

---
Tags: nodes, entities, views
---


# Question
Title: Drupal View 3 / CiviCRM integration - block update depends on user authorization
All,

In my CiviCRM installation, I support both Individual Contacts and Organization Contacts. For the Drupal site, there is a block based on a view that exposes some information about Organization Contacts. This view is configured with a Global: Random sort criteria in order to expose three different Organization on each page visit.

When I am logged into the site (as an Authenticated User or Administrator), the block works properly. When I am not logged into the site, the block does not update. Just to be clear: When logged in, reloading the same page results in three different Organization Contacts being displayed. When not logged in, the same three Organization Contacts are displayed each time.

The issue seems to be tied to the cache. When I cleared the Drupal caches, the Organization Contacts for the non-logged in user changed (but then remained the same as described above).

Would you please suggest a fix for this problem. Thank you!

# Answer
> 2 votes
I'm not sure if there's a way around this. Drupal will cache the output of Views to anonymous users, as it does for most pages. Drupal rarely caches content for authenticated users. On top of that, your host may be using a reverse-cache such as Varnish, since it greatly improves performance of Drupal sites for anonymous users.

A workaround could be to reduce the cache time of content. First try by changing the cache settings on the specific View, and if not, try the global setting in /admin/config/development/performance.

However, assuming that the list of contacts you are displaying is a sort of "randomly featured members" type of block, if your cache expires every 15 or 30 minutes, it's still usually pretty sufficient for that type of requirement, unless you have a really high traffic site and you must rotate faster.

If you do have a *very* high traffic site, I would probably load the block dynamically with Ajax to avoid killing the cache (and cache that block in a more efficient cache such as memcached, which a short expiration time of perhaps 5 minutes).

# Answer
> 1 votes
> The issue seems to be tied to the cache.

You are perfectly right, it is. It may be block cache, but more probably it is page cache or even Boost. Instead of various workarounds like short cache or DRUPAL\_NO\_CACHE that can be ignored by Boost, Varnish etc, I prefer different way:

* I create an empty place for data that is supposed to be random. This means that page may be cached, no problem.
* Using AJAX, I fill it with random data. Page is already rendered, user sees no delay. I use some nice effect for first portion of data to appear.
* Additional bonus: Using timer, I can shuffle data even if user is not reloading my page.

# Answer
> 0 votes
In hook\_block\_info I would try using https://api.drupal.org/api/drupal/includes%21common.inc/constant/DRUPAL\_NO\_CACHE/7

---
Tags: views, caching, civicrm
---


# Question
Title: How should I configure the wysiwyg filter to align the images?
This is how my configuration in the wysiwyg filter looks like (in Drupal7):

```
a[!href|target<_blank|title],
img[src|align<bottom?left?middle?right?top|alt|border|class|height|width|float],
div[align<center?justify?left?right],
p[align<center?justify?left?right],
br,span,em,strong,cite,code,blockquote,ul,ol,li,dl,dt,dd

```

However my configuration does not work for aligning images.

I have reviewed my code and the alignment is done using the "style" tag:

```
<img src="" alt="" style="float:right" />

```

I tried the following configuration for the image but that does not work either:

```
img[src|align<bottom?left?middle?right?top|alt|border|class|height|width|float|**style**],

```

Here is another attempt that did not work:

```
@[style]

```

And I also tried like so:

```
img[*],

```

Another attempt is what is detailed in this alternative: http://screencast.com/t/jUOwMxmpu

So what is the right configuration for the images to be aligned? What is my error?

# Answer
> 1 votes
Some people forget to turn off the built-in HTML Filter when they enable the WYSIWYG Filter. If you double-filter, you will lose your img attributes.

For my part, though, I prefer to not put the `float` on the `img`; instead, I float the div that surrounds the image and caption, allowing them to float together. (Example image, with floated caption "A battle...": http://www.westkingdom.org/content/new-members). To give the content editors a good user experience, I allow them to set floats on images with ckeditor, but I move the markup to the div in a render hook when the content is displayed. In this scenario, I don't need to allow floats on the image at all.

I have a writeup of how I achieved responsive images with captions using media 2.0, wysiwyg filter, and a couple other modules, and a couple of custom hooks.

# Answer
> 0 votes
You need to whitelist the style attribute on your image tag `img[!src|style]` and then you need to *also* whitelist the style properties that can be used. You should see a "Layout Properties" group of checkboxes, check the one that says "float."

---
Tags: 7, wysiwyg
---


# Question
Title: Drupal doesn't output list of children on custom module page
I am on Drupal 7. I want to create a page that lists its children, the same way you see the list of links in 'admin/structure' (Blocks, Content types, Entity types ...).

I have modified child 1 and child 2. They aren't really important for this example.

on mymodule.module I have inside function mymodule\_menu():

```
  $items['admin/mymodule'] = array(
    'title' => 'My module parent page',
    'page callback' => 'mymodule_admin_page',
    'access callback' => 'mymodule_admin_list',
    'access arguments' => array(1),
    'file' => 'mymodule.admin.inc',
  );

  // Child 1
  $items['admin/mymodule/child1'] = array(
    'title' => 'Child 1',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('mymodule_something_01', 1),
    'type' => MENU_NORMAL_ITEM,
    'file' => 'mymodule.admin.inc',
  );

  // Child 2
  $items['admin/mymodule/child2'] = array(
    'title' => 'Child 2',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('mymodule_something_02', 1),
    'type' => MENU_NORMAL_ITEM,
    'file' => 'mymodule.admin.inc',
  );

```

Then, on mymodule.admin.inc, I have this function:

```
function mymodule_admin_page() {
  $item = menu_get_item();
  if ($content = system_admin_menu_block($item)) {
    $output = theme('mymodule_admin_list', array('content' => $content));
    // This gets printed on the page
    drupal_set_message('This gets printed on the page');
  }
  else {
    $output = t('You do not have any administrative items.');
    // This doesn't get printed on the page because my base page has children.
    drupal_set_message('This doesnt get printed on the page because my base page has children.');
  }
  return $output;
}

```

Finally, according to documentation I have read, I should add a function like the one below:

```
function theme_mymodule_admin_list($variables) {

  $content = $variables['content'];
  $output = '';
  // This doesn't get printed on the page...
  drupal_set_message('this doesnt get printed... Why???');

  if ($content) {
    $output = '<dl class="node-type-list">';
    foreach ($content as $item) {
      $output .= '<dt>' . l($item['title'], $item['href'], $item['localized_options']) . '</dt>';
      $output .= '<dd>' . filter_xss_admin($item['description']) . '</dd>';
    }
    $output .= '</dl>';
  }

  return $output;
}

```

Check my drupal\_set\_message above. Messages on function mymodule\_admin\_page get printed, but messages on theme\_mymodule\_admin\_list don't get printed... Actually, admin/mymodule responds as a page, but instead of displaying links to its children, it will display a blank page...

I must be missing something, but I really don't know what. Thank you!

========

# SOLUTION

I am posting the solution below. Thank you, Geoff, for your comment. It did the trick! I was missing one of the pieces in this puzzle, which was the mymodule\_theme function.

```
function mymodule_theme($existing, $type, $theme, $path) {
  return array(
    'mymodule_admin_list' => array(
      'variables' => array('content' => NULL),
      'file' => 'mymodule.admin.inc',
    ),
  );
}

```

# Answer
> 0 votes
Another Solution here would be to do what the admin pages do for those pages

```
$items['admin/somemodule'] = array(
 'title' => 'My Module Section',
 'description' => 'Manage My Module',
 'page callback' => 'system_admin_menu_block_page',
 'access arguments' => array('access administration pages'),
 'file path' => drupal_get_path('module', 'system'),
 'file' => 'system.admin.inc',
);

```

---
Tags: 7, routes, theming
---


# Question
Title: How to add Autocomplete to a Views Custom Textfield Filter
I have created my own custom views filter handler which works perfectly with a simple textfield for the value form. However, I am unable to add autocomplete to that textfield (ie: the blue circle denoting autocomplete doesn't show up in the textfield and in the page source, autocomplete is not mentioned for that element).

What am I missing? Does Views re-write my value form somewhere as implied in Making text fields autocomplete in views exposed filters and if so, how do I plug into the after build within a custom filter handler class? (The question linked to involved altering an existing exposed form as opposed to creating a custom filter which I am.)

NOTE: I am using Drupal 7 and Views 3.

## My Code

Here is my custom filter class:

```

/**
 * The Germplasm Genotyped views filter handler class (autocomplete textfield).
 */
class views_handler_filter_germplasm_genotyped_name extends views_handler_filter_string {

  /**
   * So that the value form is not inherited.
   */
  function value_form (&$form, &$form_state) {

        $form['value'] = array(
            '#type' => 'textfield',
            '#default_value' => $this->value,
            '#autocomplete' => 'tripal_ajax/nd_genotypes/genotyped_germplasm/name_to_id/Phaseolus/only'
        );

  }
}

```

I've defined my autocomplete in hook\_menu():

```

  // Name autocomplete (display only the preferred organism -in path).
  $items['tripal_ajax/nd_genotypes/genotyped_germplasm/name_to_id/%/only'] = array(
    'page callback' => 'nd_genotypes_germplasm_name_to_id_callback',
    'page arguments' => array(4, FALSE),
    'access arguments' => array('access content'),
    'type' => MENU_CALLBACK
  );

```

And created my callback:

```

function nd_genotypes_germplasm_name_to_id_callback($organism_genus, $all_organisms, $string) {
  $matches = array();

  // custom table select
  $query = db_select('nd_genotype_germplasm', 'g')
    ->fields('g', array('name', 'genus'))
    ->condition('g.name', '%' . db_like($string) . '%', 'LIKE')
    ->condition('g.genus', $organism_genus, '=')
    ->orderBy('char_length(g.name)','ASC')
    ->orderBy('g.genus','ASC');
  $result = $query->execute();
  foreach ($result as $row) {
      $key = $row->name;
      if (!$all_organisms) {
        $matches[$key] = $row->name;
      }
      else {
        $matches[$key] = format_string(
          '@genus: @name',
          array(
            '@genus' => check_plain($row->genus),
            '@name' => check_plain($row->name),
          )
        );
      }
  }
  drupal_json_output($matches);
}

```

## Testing I've done

I have tested the autocomplete callback directly by entering the path in my browser (ie: tripal\_ajax/nd\_genotypes/genotyped\_germplasm/name\_to\_id/Cicer/only/CDC where "CDC" is the $string) and it works perfectly. By that I means it returns a json array outside my drupal theme with the elements I expect:

```

{
"CDC Xena 454 DNA Extraction": "CDC Xena 454 DNA Extraction",
"CDC Frontier 454 DNA Extraction": "CDC Frontier 454 DNA Extraction"
}

```

But as I said, my exposed fitler textfield in my view doesn't have autocomplete functionality. I know my value form is being executed because I can dpm() from within the handler and see it in my view, #autocomplete and all. However, when I look at the page source I see a plain textfield input with no autocomplete mentioned.

Note: Working autocomplete fields seem to have the class "form-autocomplete" on the input tag and an addition hidden input with the callback path and class "autocomplete autocomplete-processed".

# Answer
So it turns out that I just had a small typo :( Anyway, I'm keeping this question up in case others are having troubles since it outlines completely how to do this and I was personally unable to find any tutorials.

In the above code it needs to be `#autocomplete_path` instead of `#autocomplete`.

Furthermore, if you are trying to create your own custom autocomplete filter, remember that you have to indicate the file containing your handler class in your .info file (ie: `files[] = views/handlers/name_of_my_handler.inc`) and that you need to assign your handler to a field using hook\_views\_data() or hook\_views\_data\_alter().
> 1 votes

---
Tags: ajax, views
---


# Question
Title: How to put description on top of the input box, for a new field added to comment form?
I have added a new field to my comment form and this is how my comment form look liks:

So you can see it does not look nice, I want to have the description on top of the input box, where I say: Which paragraph do you want to put comment on?(Enter 0 if you ant to put comment on the whole article). So How can I do it?

This is the function that I have used to add the new field to comment form:

```
  function Annotations_form_comment_form_alter(&$form, &$form_state, $form_id) {
$form['paragraph_id'] = array(
    '#type' => 'textfield',
    '#title' => t('Which paragraph you want to put comment on?(Enter 0 if you want to put comment on the whole article.)') . "<br>",
    '#required' => TRUE,
    '#size' => 10,
    '#maxlength' => 2,
    '#default_value' => !empty($form['#entity']->paragraph_id) ? $form['#entity']->paragraph_id : NULL, // set the default value to the current paragraph value
    '#weight' => $form['subject']['#weight'] + 1, // place after the subject field by setting the weight to +1 of subject weight
);

$form['#validate'][] = 'annotations_form_comment_form_validate';
$form['#submit'][] = 'annotations_form_comment_form_submit';

```

}

# Answer
> 1 votes
You need to add a description field to your array:

```
$form['paragraph_id'] = array(
    '#type' => 'textfield',
    '#title' => t('Your Title'),
    '#description' => t('The paragraph you would like to put a comment on (enter 0 if you want to put the comment on the entire article'),
    ...
);

```

This way the explanation will show up under the field.

---
Tags: forms, comments
---


# Question
Title: Adding steps, breadcrumbs, or navigation to multistep webform
I have a multi-step webform (about 10 pages), and I want the user to simply be able to skip ahead of their current location *if* they have had more progress previously.

I've been trying to use the Webform Steps module, but it's totally inaccurate and it shows the same button name for every form i.e. Step 1, Step 1, Step 1, not Step 1, 2, 3 etc. There's no customisation options for it, and I'm not comfortable with hacking it.

I've tried a couple other Modules, and they have similar behaviour, or they cannot actually link to other pages, as in the anchor tag is empty.

Is there a Module capable of doing this? Or do I need to do it myself? I'm relatively new to Drupal, and my PHP isn't *that* strong.

Any help is extremely appreciated!

# Answer
> 1 votes
It seems the issue of the Webform steps module.

> webform\_steps-7.x-1.x is the currently stable version. It works with **webform-7.x-3.x** only.

Webform steps module doesn't work well with Webform 7.x-4.x version. see the issue

If you're using webform-7.x-3.x version. Here are the steps to make it work.

Webform steps module uses *pagebreak* labels as Step labels. So go to your form webform settings and change the *pagebreak* labels as you want to use as steps

For example if you want to use label steps as Step-1, Step-2 .. Step-10. Change the page break labels like Step-1... Step-10

---
Tags: webforms, navigation
---


# Question
Title: Load all nodes from content type on front page without views
I want to create a one-page website. What I hope to be able to do is load all the created pages from one content type under each other, prefably in a for each loop.

So in page.tpl.php it would be something like:

```
foreach($pages as $page){
    print $title;
    print render($page['content']);
}

```

This way I could also bind views/blocks to certain pieces of the page. The reason I'm looking for this kind of approach is to keep the website manageable.

The structure would be as follows:

```
home
about
 - slide one (view)
 - slide two (view)
 - slide three (view)
other page
 - slide one (view)
 - slide two (view)

```

So the mentioned slides are items from a different content type, loaded from a view.

If someone can point me in the right direction, or if some pieces of the question need clearing up, please let me know.

---

If people are still interested in this, I will give my solution here:

```
$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'node')
  ->propertyCondition('status', 1) /* Status to make sure it is published */
  ->propertyCondition('type', array('page', 'webform')) /* get pages and webforms */
  ->fieldOrderBy('field_volgorde', 'value', 'ASC') /* a custom field to set the order */
  ->range(0, 9999); /* amount of pages to get */
$result = $query->execute();
$nodes = node_load_multiple(array_keys($result['node']));

foreach($nodes as $node):
    // Do your code magic
endforeach;

```

Within the foreach, fields can be echoed by using the following code examples:

```
echo $node->title;
echo $node->body['und'][0]['value'];
// ['und'] = language undefined

```

If there are any questions, feel free to let me know.

# Answer
Create a custom content type with a textarea field for each section of the page (home, about, other).

Create a custom template for you content type and output all of the fields in the proper places. You can add your views as blocks.

Make sense?
> 0 votes

# Answer
I use the following code to retrieve all nodes of a type:

```
$type = 'example';
$query = db_select('node', 'n')
  ->fields('n', array('nid'))
  ->condition('type', $type)
  ->condition('status', 1);
$nids = $query->execute()->fetchCol();
$nodes = node_load_multiple($nids);

```
> 2 votes

# Answer
I ended up using the following code to get all pages:

```
<?php
$type = "page"; // machine name for Basic Page
$nodes = node_load_multiple(array(), array('type' => $type));
foreach($nodes as $node):
    // code here
endforeach;
?>

```
> 1 votes

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


# Question
Title: How to add sorting option to a field in views bulk operation
I have created one view with the help of views bulk operations and now I want one of the field to able to sort records according to the field value.

I am attaching image

How can I make the "credits" field as sorting field.

# Answer
This has nothing to do with VBO. It is simply a setting in the "Table" format. To achieve this:

1. Click "Settings" besides "Table" format.
2. And select which field you need to make sortable.
> 1 votes

---
Tags: views
---


# Question
Title: Collect submitted data in a cookie to prefill form on next visit
I have a webform but it's very long and users are going to use it a lot of times so they requested to have sort of like a cookie storage that remembers submitted data on some fields. For example I have a country field `country: text_field` (user inputs something).

I want to collect that country input from that user so when the next time user visits this form it will already have that country input in place so the users dont need to re-type it. I thought about having a cookie to store this but it feel likes it should be done in a different way.

Suggestions?

# Answer
The webform module has the options to store incomplete webforms. You can enable the option 'Show "save draft" button' (this can be found on the advanced fieldset of the webform config). I haven't completely tested it but my best guess is that it only works for authenticated users.

When the user saves the webform and comes back to the webform, the supplied values are filled and the user can continue with the webform. It's olso possible to make the webform a multistep webform. When a users is going to a next step, webform saves the previous step. This also allows the user to continue where it left off.

I'm currently using Webform 7.x-3.18 for the features described above. I'm using a multi step form. At each stap the submitted values are saved as a draft.
> 1 votes

# Answer
There could be two cases either registered user or anonymous.

If user registered then:

1. create a custom module let called "MYMODULE".
2. In `MYMODULE.module` file do the following:

---

```
/**
 * Implements hook_form_alter().
 */
function MYMODULE_form_alter(&$form, $form_state, $form_id) {

  switch ($form_id) {
    case 'your_webform_id':
      if (user_is_logged_in()) {

        global $user;

        // Select data from table as you need.
        $query = db_select('webform_submissions', 'ws');
        $query->leftJoin('webform_submitted_data', 'wsd', 'body.entity_id = n.nid');
        $query->fields('ws', ['nid', 'uid'])
          ->fields('wsd', ['data']);
        $query->condition('ws.uid', $user->uid);

        $result = $query->execute();

        while ($record = $result->fetchAssoc()) {

          // Set your $form field #default attribute here.
        }
      }
      else {

        // If user not registered yet and have data in COOKIE.
        if (isset($_COOKIE['webform_id']['field_name'])) {

          // Set your $form field #default attribute here.
        }
      }
      break;
  }
}

/**
 * Call submit hook here.
 */
function MYMODULE_webform_id_submit($form, &$form_state) {

  if (!user_is_logged_in()) {
    $COOKIE['webform_id']['field_name'] = $form_state['values']['field_name']; // set your cookie here
  }
}

```

**NOTE**:- please note above code is just an example and not tested code. please modify as per your requirement. above code is just for explaining purpose.
> 0 votes

---
Tags: webforms
---


# Question
Title: Change mailsystem used on webforms on a per email basis
I'm using the mailsystem module to send webform notification emails using mandrill.

However, for some of our webforms we need to use mandrill for the notification email sent to the users, but send the admin notifications *without* mandrill, using normal text based emails.

From what I can tell you can only change the mailsystem on a per module or per-key basis, and it seems like all webform emails use the same key -- "submission".

Is there any way to achieve what I want here?

Thanks,

# Answer
I think you can do this via hook\_mail\_alter you'll need to write your own implementation but should be possible.

From what I can see in webform.submissions.inc inside webform\_submission\_send\_mail()

```
// Build the e-mail headers.
    $email['headers'] = theme(array('webform_mail_headers_' . $node->nid, 'webform_mail_headers'), array('node' => $node, 'submission' => $submission, 'email' => $email));

```

It should be possible to use hook\_mail\_alter to choose the right submission and also the e-mail address it's being sent to.
> 3 votes

# Answer
It sounds like its not possible. If I'm right mandrill is a SMTP-like server and it works with the drupal\_mail function, right?

If so than it's not possible because you only can set a SMTP address once in your apache settings.

Possible solutions are make a callback to an other folder where the apache settings are different. But if it doesn't use the drupal\_mail function than you perhaps are able to do this in a if statement. Something like this...

```
if ($admin) {
    drupal_mail();
} else {
    mandrill_mail();
}

```
> 0 votes

---
Tags: 7, webforms, emails
---


title: what does $styles means in drupal?

text:
# Question
Title: what does $styles means in drupal?
I am new in drupal.. please let me know what is the meaning of

$styles

in drupal html.tpl.php file.. If we want to add new css and js from where we can add this..

PLeas help me..

# Answer
> 2 votes
`$styles` is a variable. It's initialised and made available to the template via the core `template_process_html()` function.

To add CSS you can use `drupal_add_css()`, and to add JS you can use `drupal_add_js()`. Either can also be accomplished using the `#attached` property in a render array (which is actually the recommended approach these days), or by including `scripts`/`stylesheets` keys in your theme's .info file.

*Where* you can add it depends on what context you need to add it in. This could be page callback, one of many alter hooks, a process or preprocess function, and so on. If your new CSS applies to every page, it might make sense to use the info file method.

Alternatively, if you want to override the CSS of an existing theme, you can create a sub-theme and simply modify the appropriate CSS files without having to use the API.

If you're brand new to Drupal there are a few concepts you need to understand before any of this will make sense. I recommend reading the following:

---
Tags: commerce, theming
---


title: Drupal distro for landing pages

text:
# Question
Title: Drupal distro for landing pages
At my current work we do often landing pages (with their own domain) I was wandering if someone already thought to do them with Drupal:

A multi-site (only one database) with several landing pages, each of them with their own domain. Anyone did it already?

How to face the multidomain feature? Which are the best modules for accomplish this?

# Answer
> 1 votes
Have yo check the domain module? I think is the best option to solve this.

Another option, but more complex will be to create a Drupal as publisher backend and also Drupal as front end to the differents domains, you can share the content with feeds.

Oskar

---
Tags: 7
---


# Question
Title: Permission tmp problem: Change of tmp directory
I recently installed one new Drupal (7.32) on a server that doesn't belong to me. Since then, I have a permission problem, I can't edit CHMOD rights and when I try to add new content (with image(s)), I can't. Here's the mistake returned by Drupal:

```
Warning: move_uploaded_file(): open_basedir restriction in effect.
File(/home/tmp/php/phpBKRRLYL) is not within the allowed path(s): (/home/tmp/sessions/:/home/XXX/public_html/:/home/XXX/shared) in drupal_move_uploaded_file() (line 1639 of /home/XXX/www/public_html/YYY/drupal-7.32/includes/file.inc).

Warning: move_uploaded_file(): open_basedir restriction in effect.
File(/home/tmp/php/phpBKRRLYL) is not within the allowed path(s): (/home/tmp/sessions/:/home/XXX/public_html/:/home/XXX/shared) in drupal_move_uploaded_file() (line 1639 of /home/XXX/www/public_html/YYY/drupal-7.32/includes/file.inc).

Warning: move_uploaded_file(/home/tmp/php/phpBKRRLYL): failed to open stream:
Operation not permitted in drupal_move_uploaded_file() (line 1639 of /home/XXX/www/public_html/YYY/drupal-7.32/includes/file.inc).

Warning: move_uploaded_file():
Unable to move '/home/tmp/php/phpBKRRLYL' to '/home/XXX/www/public_html/YYY/drupal-7.32/sites/default/files/anime.jpg' in drupal_move_uploaded_file() (line 1639 of /home/XXX/www/public_html/YYY/drupal-7.32/includes/file.inc).

```

As we can see, Drupal apparently uses the server's tmp directory (in which I have no rights) and I would like it to use another tmp directory in "/home/XXX/www/public\_html/YYY/drupal-7.32/" so that I can add/edit content properly. How could I do this? By editing the "/includes/file.inc" file (if so, which line(s) shall I modify to do this?)? Something else?

NB: The system administrator is unavailable for an extended period so he can't change my rights for now. That's why it's important that I could change this tmp directory. Thank you!

# Answer
> 1 votes
You can edit the relevant setting in Configuration \> Media \> File system \> Temporary directory (`/admin/config/media/file-system`).

You can choose any directory in your document root skipping the forward slash. I would recommend you to specify `tmp`. Take care of the permissions.

---
Tags: files
---


# Question
Title: Views - how to create a chart AND a table from the same filter selection
I know how to create a chart using Views and I also know how to create a table. How do I used the same set of filters to create both but on the same page I am looking at?

I have embedded views inside views as well but that doesn't seem to do the job. Anyone got any idea?

# Answer
> 0 votes
I can do that in the following ways: a. Create View page to generate table with exposed filter b. Clone the view page (table), and change the title name and the path c. Change the cloned page from Table to Chart, set the field for the chart setting to display, then save d. Open the original table page view, the add footer -\> global view -\> select the view chart that you created in (b)

Now you have table with filter on top, and the chart below (also with the same exposed filter). The chart follows the results of the filter on the table. I use CSS to hide the filter for the chart on the footer.

---
Tags: views, charts
---