# Question
Title: How to use one field with different settings
I have a field that determines which category my content belongs to, stored in a taxonomy vocabulary. The field is used in both the content type and the user profile. Users may select a category, but they can select only one and definitely not more. The content however can belong to more categories, in my case 2. So the field settings should be different, but that is impossible when using a single field. Whenever i change the maximum number of values in useraccounts to 1, the field in the nodetype changes to 1 also.

I use the same field to be able to make some views (starting from a user's perspective) to display content based on the users choice.

I see three possible solutions:

1. Somehow use a field alias, enabling me to define the same field in 2 different ways. But i haven't found a mod for field aliases;
2. Define two seperate fields with seperate settings. But i can't filter my output in a View based on the value of another field. Also, using a contextual filter won't work because there is no value to pass in the URL;
3. Set the max value to 1 and add the same node twice, one for each category. Which is not the way to go, obviously.

Any clues to avoid option #3 ? I use D7 btw.

Thanx, Cas

# Answer
> 0 votes
Set the maximum number of values to unlimited.

Then using hook\_form\_alter change the categories select to only allow 1 value on the user profile form:

```
function YOUR_MODULE_form_alter(&$form, &$form_state, $form_id) {

    //drupal_set_message("Form ID is : " . $form_id);

    switch($form_id) {

        case 'user_profile_form':

            //dpm($form);
            $form['field_category'][LANGUAGE_NONE]['#multiple'] = false;
            break;

    }
}

```

If need be you could also add an additional validation handler here to add some custom server side validation to make sure that the user is not selecting more than 1 department.

# Answer
> 0 votes
You don't specify exactly how the field is used on the User and Node Entities, but I'm assuming a User is able to pick a category of content to like/see/follow/associate with using a Term reference field, and Nodes are able to say they belong to two of these categories in the same way.

I would go with two different fields, because you really have two different use cases for a reference to one or more Terms in the same Vocabulary. I don't think it would make sense to filter users and nodes based on the same field in Views anyway, because it wouldn't work the way I think you want it to work.

Using the same Field on two different content types does not in any way actually link them together, or even imply they can be linked together. It just means those two content types needed the same *settings* for a Field, so why not create two instance of the same Field *settings* to make sure they'll always be the same.

In other words; "That's not a bug, it's a feature!"

When creating a View, one of the first things you do is to select the "base table", ie you're creating a Node (actually known as "Content" in Views) or User type View. Assume you want to display "every" item of this type (SQL's `SELECT * FROM foo`). If you create a Node/Content View without filters, you'll get all Nodes. You may link in User data (through the author or another field) through Relationships (SQL `JOIN bar ON foo.x=bar.y`), but you'll never see all users listed just once or a single row with just a User, since their data is just joined to the Nodes. The same is true for Nodes if you start with a User based View.

Filtering on the same field for more than one content type is useful when your content types are similar or closely structurally related somehow, and are both of the same base type (bundles of say Nodes). This way you can truly list all of these items just by making a Node View and filtering out other bundles, without any joins, so they're both first class items. Then you can get a subset of both types of content by adding a single filter on the \[Term reference\] field.

However, if the same field is used on Nodes and Users, you'd have to tell Views which instance of that field to filter on by, selecting the Relation to use (if any), ie which table (node or user) to use. (View generates one alias for each table a field is used on automatically, but it can still only compare a filtering value to one of them with one filter, and aliases still use Relationships/JOINs.) This means you either get a subset based on which Nodes are in a category, or which Nodes were authored by Users that have selected that category.

This is because filters currently (until Views 7.x-3.8) only filter based on a fixed value (using one of several operators), and not the value of another field.

Just to cover a corner case; if you *also* add another filter, filtering on the same Category value, but using "the other" table as the Relationship (User in a Node View or vice versa) you'll end up only with Nodes in the same category as its author has selected, or only Users which have created Nodes in the category they like. This type of very narrow subset of Users or Nodes would also be generated if you picked any other two fields (one from each of User and Node) to filter on, since the "Content" Field being instances of the same Field settings does not really matter for the result set you'll get back.

Since you want different settings for Term references, create two separate Fields. One for Nodes, allowing two Terms, let's call it "Categories". One for Users allowing one Term, let's call it just "Category". This will actually make it slightly easier to navigate in the Views UI as you can clearly see which one of the Fields belongs to Nodes or Users later on.

Now, if you're looking to fetch Nodes based on which Category the current User has picked we'll have to figure out exactly what that relationship looks like. A list of Nodes is not directly relatable to Users, unless the user happens to be the author or there are explicit User/Node reference fields linking them together, so let's break this down in steps.

Start with a Content View, add at least the Title field and the "Content: Categories" field just so we know shat we're getting back from the query. Sort by the Node title or whatever makes sense in your case.

Nodes hold the term ids in our Categories field, but we need the actual Term data, that's one Relationship in the right direction. Add a "Content: Categories" Relationship. Make it Required since we don't want Nodes without Categories set shown. By now your result set will include all Nodes with two Categories set twice, because of the JOIN this created. That's fine.

The Terms are also being referenced by a field on Users, and adding the previous Relationship between Nodes and Terms now allows us to go one step further. Add the "Taxonomy term: User using Category" Relationship and make it required as well. By now the result set will have multiplied the number of times a Node is shown by how many Categories it has, and again by the number of users which have set one of those Terms in their own Category Field. That's also fine. You can now add a "User: Name" field to see who has chosen the same category used by the Node (note that it's using the Relationship chain).

Now we have established a link from Nodes to Users. Time to limit things to the User we're interested in: the one currently logged in. By now you'll be able to filter the result set based on any User data available through the Relationship chain, including the logged in status. So add a "Current user" filter and set it to "Logged in".

By now, your query is pretty much unreadable, but it works! ;)

In this case we're lucky User can only select one Category, since that prevents multiplying the number of times a Node is shown by the number of matches between the Category and Categories fields. But if you do need User to be able to select multiple categories later, make sure you tell Views to only return unique/distinct matches.

If some of my assumptions are wrong, please comment and I'll update the answer accordingly.

---
Tags: views, entities
---


title: How to filter single field in a view

text:
# Question
Title: How to filter single field in a view
I am running Drupal 7 with the latest version of the Views module.

I have a content type called "School," which has an entity reference field for "classroom." The "classroom" content type has a radio button field for whether it has an assigned teacher.

I'd like my view to output a table which will list the total number of classrooms in each school (so school name in the first column, # of classrooms in the second column). After some messing around, I was able to get this working.

However, now I'd like to add a third column where I display the # of classrooms which have an assigned teacher. So if the classroom doesn't have a teacher assigned, it doesn't get included in the count. Anyone know how to accomplish this? It doesn't look like I can filter on individual fields...

# Answer
> 0 votes
If this were an SQL query your new column could be a subquery. I mean this new value of **\# of classrooms with assigned teachers** has its own business logic, seperate from the list of data your already returning.

You can accomplish this using Views Field View. This lets you embed a view result -- per row of your existing view. From the project 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.
>
> It's highly recommended to use this module in conjunction with views caching. Views Content cache and Cache Actions are good ways of caching views.

So:

1. Make a new view; called for instance with the human name of "sum rooms assigned teachers" (the machine name will be sum\_rooms\_assigned\_teachers).
2. For this View simply use display mode of Show Fields; and include like the NID as a field; Under advanced settings enable Aggregation for the View. For the NID value use the `Count` aggregation.
3. Add a contextual filter to this view based on the school name.
4. Save your view.

Then in your parent view:

1. After installing Views Field View. Add a new Field your view of `Global: View`.
2. select the view named `sum_rooms_assigned_teachers`. Provide the contextual filter to the view of your school name or ID; it will look like `[!field_school_entityreference_id]` or something similiar.
3. Give this field whatever label you want.

Your main view should now show a room count. In the helper view you may want to deny access to anyone but the Administrator or other role -- as this is simply a helper view for this other view; and rather useless by itself.

---
Tags: views, entities
---


# Question
Title: How do I use the form hook alt to edit fields of inline entity form?
I am trying to use the hook\_form\_alter to modify the fields of an Inline entity form in a commerce product display node.

I know how to edit a normal field but this does not work for an entity form field. How do I go about editing a field, for example changing the price field label?

Thanks Robert

# Answer
As per IEF's API docs, you've got:

* hook\_inline\_entity\_form\_entity\_form\_alter()
> Perform alterations before an entity form is included in the IEF widget.
* hook\_inline\_entity\_form\_reference\_form\_alter()

> Perform alterations before the reference form is included in the IEF widget.
>
> The reference form is used to add existing entities through an autocomplete field
* hook\_inline\_entity\_form\_table\_fields\_alter()

> Alter the fields used to represent an entity in the IEF table.
>
> The fields can be either Field API fields or properties defined through hook\_entity\_property\_info().

I think the first would be most appropriate here, probably something like (guessing at the array keys here, they might be different):

```
function MYMODULE_inline_entity_form_entity_form_alter(&$entity_form, &$form_state) {
  if ($entity_form['#entity_type'] == 'commerce_product') {
    $entity_form['commerce_price']['#title'] = t('New title.');
  }
}

```
> 8 votes

---
Tags: commerce, forms, entities
---


# Question
Title: How to add a class to a checkbox in a form?
I would like to add the class 'checkradios' to checkboxes in an entity form, is it possible do this in the theme layer?

# Answer
> 1 votes
Sure. You can copy `theme_checkbox()` from `includes/form.inc`:

```
function theme_checkbox($variables) {
  $element = $variables['element'];
  $element['#attributes']['type'] = 'checkbox';
  element_set_attributes($element, array('id', 'name', '#return_value' => 'value'));

  // Unchecked checkbox has #value of integer 0.
  if (!empty($element['#checked'])) {
    $element['#attributes']['checked'] = 'checked';
  }
  _form_set_class($element, array('form-checkbox'));

  return '<input' . drupal_attributes($element['#attributes']) . ' />';
}

```

into your theme's `template.php` file and rename it accordingly:

```
function YOURTHEME_checkbox($variables) {
  $element = $variables['element'];
  $element['#attributes']['type'] = 'checkbox';
  element_set_attributes($element, array('id', 'name', '#return_value' => 'value'));

  // Unchecked checkbox has #value of integer 0.
  if (!empty($element['#checked'])) {
    $element['#attributes']['checked'] = 'checked';
  }
  _form_set_class($element, array('form-checkbox', 'checkradios')); // <-- checkradios added in here

  return '<input' . drupal_attributes($element['#attributes']) . ' />';
}

```

along with the addition of the `checkradios` class and this will be added to each checkbox.

Now, if you want to restrict it to certain fields, you can look inside `$element` and add some additional logic to this.

---
Tags: forms
---


# Question
Title: How to discard unsaved changes to a variant?
While working on a variant for /node/%node I did something that now causes a 'The requested page "/admin/structure/pages/edit/node\_view" could not be found.' error and am unable to access any of the variants.

How do I discard all the changes since the last save?

# Answer
> 0 votes
Finally got the answer from a Drupal guru- just deleted an entry from the ctools\_object\_cache table in the database. Everything works fine now.

---
Tags: chaos-tool-suite
---


# Question
Title: Using REST API for data storage for user definable content
I might be barking up the wrong tree completely however I am trying to achieve the following.

* Drupal 7.
* Custom REST web service which can hold user definable content types.
    + These pieces of content are stored and revisioned at a entity level. (not at a field level like drupal)
* I want to be able to use Entity API + Entity Model to define Content Types to store in the REST service.
* When inserting DO NOT create the Drupal field tables.

When I hook\_entity\_insert the field tables are still being created. How can I prevent Drupal from creating these tables.

Also, does this sound like the best way to go about this? Is there an easier way to achieve using REST services and not duplicating data in the Drupal DB?

Thanks.

# Answer
> 2 votes
This is achieved by creating a custom Entity Controller class, extending either the `DrupalDefaultEntityController` or creating a `DrupalEntityControllerInterface` implementation.

Then create a field storage engine, using the Field Storage API and attach the correct fields where required.

I used the MongoDB `mongodb_field_storage` module for reference.

This all works as expected, and I do not use the Drupal database to store any Entity Metadata or field data. Only the `field_config` table is used.

The only hiccup I have is that the Drupal 7 'Per Field' storage engine actually needs to be defined in the variable table setting the `field_storage_default` to your custom storage engine. I have yet to find a way to hook into this on a per field basis without patching core. See here for more details.

# Answer
> 1 votes
It looks like there are now two (2) modules that allow for remote data storage:

There's a good write-up on these and other options over at What is the most reliable and fault tolerant way to integrate 3rd-party data structures via a web service in Drupal 7?.

---
Tags: entities, 8
---


# Question
Title: What is the most reliable and fault tolerant way to integrate 3rd-party data structures via a web service in Drupal 7?
I've seen a number of strategies for integrating remote data structures in Drupal. The strategies have seemed to evolve as certain modules have stabilized and use cases have been tried.

Imagine we have a data structure "Farmers Markets" that is represented by a number of data types (market, market\_hours, vender, stall, produce) etc that are exposed via a REST API. The IDs for the external service would need to relate in Drupal, ie when loading a "market" we would want to grab data from the 'market\_hours' and 'stall'. What would be the best way to represent that as read-only content in Drupal that is synced on a regular basis?

I'm trying to evaluate this with the following criteria:

**Data Structures in Drupal:**

Nodes vs Custom Entities

A number of scenarios involving web services I've seen use custom entities. It simplifies the CRUD ops. However, these items would be "content" in that they would be viewed publicly.

**Storage (Local vs Remote):**

I've seen a couple of examples where services are loaded as remote entities, which this module creates a library for: https://drupal.org/project/wsdata . This sounds most appealing, but haven't seen a lot of use cases. There also examples of custom code: https://drupal.org/sandbox/fago/1493180

**Syncing Data:**

Feeds vs Migrate vs Guzzle vs 'Web Service Client' vs 'Web Services Data'

There are a number of options. Feeds now supports entities. Migrate seems a lot cleaner than feeds, especially for custom scenarios. I've also seen folks using a guzzle client to grab sync with remote services: http://drupalcode.org/project/ckan.git/blob/refs/heads/ckan\_dgu\_7.x-1.x:/ckan.drush.inc#l273. I've also noticed the WS Client module https://drupal.org/project/wsclient provides an option that has been created specifically as a rest client. Web Services Data loads directly from a service and caches it locally.

Thanks for any thoughts.

# Answer
> 16 votes
# 1. Reformulating the question

Your example suggests that the data is read only on the Drupal side, with one-way syncing only. I think this is the most important factor to consider here, because in effect whatever solution you implement will be a variant of remote storage, syncing and local caching - even if the local caching ends up being entities in the Drupal database.

So the question, rather than being "local storage vs remote storage" is going to be:

* Should you cache the data locally at all ;
* Should you cache the data as actual entities, and use Feeds (or similar) to synchronise the data regularly ; OR
* Should you use some custom made module that provides the syncing and the caching.

An article you might be interested is in "Remote Entities in Drupal 7".

# 2. Caching the data

In general, caching the data is a good idea:

* You are protected against outages of the other services, or timeouts in the connection ;
* Having your data present in your Drupal database will speed up operations ;
* Having your data present in your Drupal database will mean that you are more likely to get integration with other modules, such as Views (though this is not guaranteed).

The only advantage of not caching the data is that you never get stale data, which in some cases is preferable - sometimes it is preferable to display no data rather than stale data. I do not see this as a benefit in the example you have given, so I will focus this answer on a solution that involves local caching.

# 3. Local entities + Syncing

If you go for the option of having local entities and syncing them yourself, then we come back to your original questions:

* Should you use nodes or custom entities ;
* Which module is best for syncing.

## 3.1 Nodes vs Custom entities

* The definition of what exactly is a node is one that is quite open. The documentation page on nodes suggests that nodes are "posting" that are "stored" on your site - neither of which apply to your data ;
* As a Drupal developer I would expect that if something is a node then I should be able to manipulate it on the site itself ;
* As Drupal user, I would similarly expect that nodes can be edited ;
* This Drupal 8 issue https://drupal.org/node/2019031 suggests that the concept of "read only" is one that would apply at the entity level, rather than the bundle level. If this ever gets implemented you would benefit from it by having gone down this route.

To summarise: your data being *read only* and *stored remotely* it makes more sense to use a custom entity type to represent your data.

## 3.2 Syncing

For the second part, the two main modules for this are, as you suggest, Feeds and Migrate.

The difference between Feeds and Migrate is that Feeds is build for regular importing of content, while Migrate is build for one-off porting of content from one place to another. Migrate does support updating existing data, however given that both modules are well supported it makes more sense to use the module that was build for the task at hand - Feeds is a better match.

Having used both modules myself (Feeds for syncing, Migrating for migrating) I do not find Feeds to be more messy than Migrate. Migrate has required more custom code in my experience, though migrating entire sites is more complex than importing single content types, so it's hard to compare.

# 4. Custom module for remote storage, syncing + caching

There are a number of modules out there that can help with this task.

You mentioned the Web Services Data module, and others have mentioned the Data module. Another option to consider is the Remote Entity API module. Note that the only one of those I have experience with is the Data module.

* The Web Services Data module does not yet have a release - which may indicate the code is not yet stable, the API might change and so on. It does not support Entity Field Queries (according to it's project page), and a quick browse of the code repository shows no evidence of it having Views support - so you would not be able to use Views to display your entities ;
* The Data module is more oriented, in my experience, towards non-developers who have data in a table and want to expose it to views. I have found the Drupal 6 version to be quite frustrating to use - though that might have changed since then ;
* The Remote Entity API module sounds quite promising - it supports fetching and caching of remote entities, and has Views support. It's only on alpha release - so API might still change. At first glance it does not seem to have Entity Field Query support either, and it only support one type of remote service so you would have to implement your own.

# Conclusion

Given that none of the remote storage modules support Entity Field Queries, using actual entities + feeds is the solution that will give you the best integration with your Drupal site.

If Views support is enough, and you are not worried about potential integration with other modules via Entity Field Queries, then using the Remote Entity API might be the way to go - you would need to implement your own remote interface however.

# Answer
> 0 votes
If you need views, rules, tokens, cruds hooks, search api and definitly strong system integration in my opinion they can´t be considered nodes but they must be custom entities with their own idiosyncrasy storing in the database the "entity id" and the "external id" relation and with the retrieving information calls encapsulated in the "entity properties". Finally, whatever the tool you choose for syncing data, I would process it with cron Queues.

If you just need retrieve and expose data punctually I think a better choice would be create an Interface class for retrieving external data and implement this Interface with a Class that retrieve the info from your "Farmers Markets" structure.

Regards

# Answer
> 0 votes
There's the Field Storage API, which allows for pluggable storage back-ends other than the default database engine.

---
Tags: 7, services
---


# Question
Title: Drupal commerce donate: Safely update to dev version of module on live site
I need to update my charity website to the dev version of commerce donate because we have recently discovered that donors cannot donate decimal amounts with the current recommended release (e.g donate £5.20) and this is something that we need as people need to pay in fundraising money etc.

I am weary of uninstalling the current module and reinstalling as we have several products that are created using the donation content type and don't want to lose them or the existing donations people have made from the system.

Is there a way to do this safely and (preferably) easily?

# Answer
If you go through the normal process to update the module (which for me means `drush dl --dev commerce_donate` in this case - or you might download & un-tar the module directly), no uninstall will be necessary. In general you should not uninstall a module before installing an update, for exactly the reason you fear.
> 0 votes

---
Tags: commerce
---


title: Log in without password

text:
# Question
Title: Log in without password
I am looking for a mechanism to Log into Drupal system without a Password and only with some link provided.

**My Use case is**: Intranet system *(made with ASP)* passes the Link like: http://example.com/user\_name=jhilke&user\_email=jhilke@example.com&user\_role=developer&TY89823jjkhds234.
***To break down the above link*** *separated by &*

* **URL**: http://example.com
* **USERNAME**: user\_name=jhilke
* **EMAIL**: user\_email=jhilke@example.com
* **USER ROLE**: user\_role=developer
* **HASH**: TY89823jjkhds234

Now I need to Log in the User or Create new User (if the user doesn't exists) in Drupal site with exact Username and Role but with just the link and no password.

I have used this URL Login module so far to login to Drupal site without password and with some hash/encrypted key it generates. For eg: The link that URL Login module creates is like http://example.com/l/YUb&8767GUYuiu and logs in the user exactly as the role they are assigned, but it doesn't satisfy the other criteria like username and roles in the link.

Is there any way I can achieve this.

# Answer
> 3 votes
Have a look at

`user_external_login_register`

> Helper function for authentication modules. Either logs in or registers the current user, based on username. Either way, the global $user object is populated and login tasks are performed.

The example at:

https://api.drupal.org/comment/13434#comment-13434

Is a worthwhile read too.

# Answer
> 0 votes
Quick code, not tested, but should show idea, change CUSTOMMODULENAME to you customm module name, if not - create one:

```
<?php

function CUSTOMMODULENAME_init() {
  global $user;
  $g = $_GET;
  if (isset($g['user_name']) && isset($g['user_email']) && isset($g['user_role'])) {
    $name = $g['user_name'];
    unset($g['user_name']);
    $mail = $g['user_email'];
    unset($g['user_email']);
    $user_role = $g['user_role'];
    unset($g['user_role']);
    unset($g['q']);

    $hash = reset($g);// Since you hash hasn't key we assume that's current key
    if ($hash) {
      $account = user_load_by_name($name);
      if ($account) {
        if (CUSTOMMODULENAME_checkhash($account, $hash)) {
          $user = $account;
          $edit['uid'] = $account->uid;
          user_login_finalize($edit);
          drupal_set_message(t('Successful login.'));
        }
      }
      else {
        if (CUSTOMMODULENAME_checkhash(FALSE, $hash, $name, $mail, $user_role)) {
          $pass = 111; // Generate pass here, random or from hash.
          $new_user = array(
            'name' => $name,
            'pass' => $pass, // note: do not md5 the password
            'mail' => $mail,
            'status' => 1,
            'init' => $mail,
            'roles' => array(
              DRUPAL_AUTHENTICATED_RID => 'authenticated user',
            ),
          );
          $role = user_role_load_by_name($user_role);
          if ($role) {
            $new_user['roles'][$role->rid] = $user_role;
          }
          // The first parameter is sent blank so a new user is created.
          $account = user_save('', $new_user);

          $user = $account;
          $edit['uid'] = $account->uid;
          user_login_finalize($edit);
          drupal_set_message(t('Successful register and login.'));
        }
      }
    }
  }

}

function CUSTOMMODULENAME_checkhash($account, $hash, $name = '', $mail = '' , $user_role = '') {
  // Write check hashing function here.
  // if $account empty, well it's mean check hash for new user. So use name, mail, user_role.
}

```

---
Tags: 7, users
---


# Question
Title: How to use Drupal Commerce subscription products?
I created a site which has premium membership and want users to pay for those memberships. I have installed commerce\_sp on my site but I don't know how to configure it and use it.

When a member pay for a membership for 1 year, for example: Subscription validity: 2014-09-25 13:45:00

but I don't know why, when I check this member again every once in a while. the Subscription validity has changed to: 2015-09-24 13:45:00.

And I check this member again tomorrow,the Subscription validity has changed again:2017-09-22 13:45:00.

I don't know why the subscription validity change again and again.

I was very confused, anybody know why?

# Answer
Most probably you have got issue with your rule set. Best way to use(configure) commerce\_sp or even commerce product for membership is to put proper condition & then fire the event.

Simple Config :

* Create new products (using Subscription Products).
* Create product displays for those products.
* Go to Configuration\>Rules.
* Find the Rule called "Subscription Started (update)" and clone it.
* Rename the cloned rule.
* Make the Event "Completing the Checkout Process". Add some more like "user of type" etc.
* Make the Elements "Order contains a particular product" and specify the SKUs of your subscription products.
* For Actions, use "rule set: Subscription start" with parameter as "User:\[commerce-order:owner\] and "Schedule component evaluation" as is and added "Add user role" with Parameter: User:\[commerce-order:owner\] and Roles: my subscriber role.
* Set the low weight for this rule set.

You can modify rule as per your requirement & it will work accordingly.
> 1 votes

---
Tags: commerce
---


# Question
Title: URL redirect module working fine with nodes not with alias url's
I am new to Drupal. I have installed URL Redirect module and tried the following.

Source URL: testwebsite.com/how

Redirect URL: testwebsite.com/how-to-do

Its get stored with node id instead actual URL.

Source URL: http://www.testwebsite.com/node/123545

Redirect URL: http://www.testwebsite.com/node/134566

When I tried to call with node URL its redirecting fine. But when I call testwebsite.com/how it doesn't redirect.

# Answer
> -1 votes
You can use Path Redirect module in your scenario. Module page says :

> This module allows you to specify a redirect from one path to another path or an external URL, using any HTTP redirect status.

---
Tags: 7, redirection
---


# Question
Title: Place to put patched module under contrib or custom
I am using a contrib module which has a patch in queue to be reviewed, the patch solves my issue. Where should I keep the patched module, keep it inside contrib module or should I move it under custom module directory and keep a watch on issue till it approved and then move it again to contrib? What is the preferable place to keep such module.

# Answer
You may leave it in place (a good reason for doing this is given in the reply from *alexkb*).

However, this is not all there is to working with patches. Sometimes the maintainer is reluctant to include the patch in the official branch. This means that there may be *new* releases (security fixes!, bug fixes, feature enhancements) of the module *without* the patch. You need to think about how you deal with that.

Here is what I do: I set up staging area for where I keep all my custom modules. For the patched contrib modules, I connect those to the origin repo using *git*. I also setup a `Makefile` (or some other script file) to pull from the origin repo and semi-automate the reapplication of outstanding patches. Then, when a new release of the module is issued, the `Makefile` will pull and patch, and then send an email to me with the result. If the patch applies succesfully, I test and if the test turns out OK, I manually copy from staging to production. If the patch fails to apply due to some conflict, I try to resolve conflicts and try again.

This has two advantages:

1. Even when you're using a patched module, you're able keep up with the official branch.
2. You don't have to watch the issue queue, just set up your local repo to sync with origin at regular intervals (using CLI *cron* or similar).

The above workflow assumes some familiarity with the CLI and tools such as *git, cron* and *make*. It also takes some times setting this up to run semi-automatically. But if you need to work with patches, it is - IMHO - well worth doing.
> 4 votes

# Answer
Moving modules around in the file system means you have to perform some additional tasks before Drupal picks up the new path. This can be inconvenient and take your time.

Instead what we do is leave the module in the contrib folder, apply the patch and then create a new file in the module folder called `.drush-lock-update`. Inside this file we put some notes containing the drupal issue queue page URL and a quick summary of why it was applied. Drush detects these `.drush-lock-update` files and then ignores them when you run a `drush up`.

There is some more information over on d.o about this lock file and how it works.

It should be noted that the drupal core update module still monitors the version of your locked modules so you'll know when a security update comes out and can then manually review and apply the update separately.
> 3 votes

# Answer
For applying patch go through the following links
> 0 votes

---
Tags: version-control
---


title: Views show weird SQL query

text:
# Question
Title: Views show weird SQL query
I am using Views to display some comment for specify node.

The SQL query on Views pane:

```
SELECT comment.uid AS comment_uid, comment.cid AS cid, comment.created AS comment_created, 'comment' AS field_data_comment_body_comment_entity_type
FROM
{comment} comment
INNER JOIN {node} node_comment ON comment.nid = node_comment.nid
WHERE (( (node_comment.nid = '1330' ) )AND(( (comment.status <> '0') AND (node_comment.status = '1') )))
ORDER BY comment_created DESC
LIMIT 10 OFFSET 0

```

I try to copy above sql to phpmyadmin:

```
SELECT comment.uid AS comment_uid, comment.cid AS cid, comment.created AS comment_created, 'comment' AS field_data_comment_body_comment_entity_type
FROM
comment
INNER JOIN node_comment ON comment.nid = node_comment.nid
WHERE (( (node_comment.nid = '1330' ) )AND(( (comment.status <> '0') AND (node_comment.status = '1') )))
ORDER BY comment_created DESC
LIMIT 10 OFFSET 0

```

But phpmyadmin throw an error to me:

```
Error Code: 1146. Table 'daxuebao.node_comment' doesn't exist

```

I try to search `drupal node_comment table` at google, But I get nothing.

# Answer
> 2 votes
There is no table named `node_comment`. You must do the `inner join` to the `node` table, in the same way as the Views query.

```
SELECT comment.uid AS comment_uid, comment.cid AS cid, comment.created AS comment_created, 'comment' AS field_data_comment_body_comment_entity_type
FROM
comment
INNER JOIN node node_comment ON comment.nid = node_comment.nid
WHERE (( (node_comment.nid = '1330' ) )AND(( (comment.status <> '0') AND (node_comment.status = '1') )))
ORDER BY comment_created DESC
LIMIT 10 OFFSET 0

```

---
Tags: views
---


title: Filter images by 'current page' nid

text:
# Question
Title: Filter images by 'current page' nid
I have a view with multiple fields:

Nid Title Content Image

On my page, I use the nid as a selector ( I have a button elsewhere on the page tied to it) to open my content without going to another page. The images are also loaded. Only problem I have is that I need to find a way to ensure that only the images for the view row's \[nid\] are being output, rather than all of them. The \[nid\] filter requires a hard value and I'm looking more for a "current page" ish kind of thing.

Basicaly, I want to load only the images that have the same nid as the content being displayed in each row.

How would I set up a filter for this?

# Answer
* Edit your view
* Create Block View
* Add Contextual Filter
* Add Content:Nid
* In settings choose : Content Id from URL
* Enable your block in your node pages where you would like to display images
> 1 votes

---
Tags: views
---


title: How to add capcha for node/edit form

text:
# Question
Title: How to add capcha for node/edit form
I need to add captcha for node edit form, not for the front-end form. please can any one help me?

# Answer
> 3 votes
I believe you are using Captcha module..

* Go to admin/config/people/captcha
* Enable "Add CAPTCHA administration links to forms" and "Allow CAPTCHAs and CAPTCHA administration links on administrative pages"

* Go to node edit page you see setting like below

* Enable captcha for form

---
Tags: 7, nodes, captcha
---


# Question
Title: Views: Display Total number of products in commerce kickstart shopping cart
I'm using menu badges to display the total number of products in the commerce kickstart shopping cart. However I cannot simple use aggregation to count the total number or products using line item ID because I need to multiply it by the quantity, and add it to the total. Since the shopping cart already displays the total number of items, I though it would have been easy to do some reverse engineering but I couldn't find it.

# Answer
The developers of commerce kickstart seems to have already created a menu badge view. When I clicked the drop down menu "Display menu badges", there was already a choice to select "Commerce: Cart items count"
> 2 votes

# Answer
In menu badges module check line no 335 code

```
/**
 * Drupal Commcerce cart items count callback.
 * @param array $arguments
 */
function menu_badges_commerce_cart_item_count() {
  global $user;

  if (module_exists('commerce_cart') && $order = commerce_cart_order_load($user->uid)) {
    // Count the number of product line items on the order.
    $wrapper = entity_metadata_wrapper('commerce_order', $order);
    $quantity = commerce_line_items_quantity($wrapper->commerce_line_items, commerce_product_line_item_types());
    if ($quantity > 0) {
      return $quantity;
    }
  }
  return NULL;
}

```

You can get total quantity using below code also...

```
  global $user;
  $order = commerce_cart_order_load($user->uid);
  $wrapper = entity_metadata_wrapper('commerce_order', $order);
  $quantity_total = 0;
  foreach ($wrapper->commerce_line_items as $delta => $line_item_wrapper) {
    $quantity = $line_item_wrapper->quantity->value();
    $quantity_total = $quantity_total + $quantity;
  }

```

Commerce modules does not provide view handler for Quantity Total.. If you are interested you can create one and share it with community.. Other wise you can use views php module to achieve same...
> 2 votes

---
Tags: views, commerce
---


# Question
Title: How can I allow more file extensions with file uploads?
I've got a module that let users upload files, and everything works as long as the files are in the standard array of allowed extensions. I've tried using `file_validate_extensions()`, but this doesn't seem to change anything.

This is the code I'm using to upload now (the docx extension is added to the standard allowed ones, but it doesn't seem to get picked up):

```
$fid = $form_state['values']['attachment'];
$file = file_load($fid);

if ($file != null) {
  file_validate_extensions($file, "jpg jpeg gif png txt doc xls pdf ppt pps odt ods odp docx");
  $file->status = FILE_STATUS_PERMANENT;
  file_save($file);
}

```

# Answer
You actually have to check for the return values of the file\_validate\_extensions() function in order to detect if any errors have occurred.

so your code would be something like this:

```
$fid = $form_state['values']['attachment'];
$file = file_load($fid);

if ($file != null) {
  $extension_errors=file_validate_extensions($file, "jpg jpeg gif png txt doc xls pdf ppt pps odt ods odp docx");
  if (!$extension_errors) {
  $file->status = FILE_STATUS_PERMANENT;
  file_save($file);
  } else form_set_error('attachment',$extension_errors[0]);
}

```
> 2 votes

# Answer
I think what you are looking for is here

drupal-7-handling-file-uploads

Drupal 7 forms API: File not uploading

I too have tried with below form and it worked for me

```
function video_upload_subtitles_form($form, &$form_state) {
     $form['sub_file'] = array(
            '#type' => 'file',
            '#title' => t('Upload video'),
            '#description' => t('Pick a video file to upload.'),
        );

}
function video_upload_subtitles_form_submit($form, &$form_state) {
 $validators = array('file_validate_extensions' => array());
 $file = file_save_upload('sub_file', $validators, "public://");
}

```
> 0 votes

---
Tags: 7, files
---


title: Full path in the menu

text:
# Question
Title: Full path in the menu
I've trying to setup a Drupal 7 site where I already have some content added. The content is bound to a multi-level menu, but the path's for nodes in the submenus show only the actual node's alias, omitting the parent nodes. I wish to have url's where the path contains the content structure, no matter how many levels are?

I have tried a few pathauto settings:

* `[node:menu-link:parents:join-path]/[node:title]`
* `[node:menu-link:parent:url:path]`

After each try, I have rebuilt the paths and cleared cache, but I am still not getting the paths that I need, and they haven't actually changed. All of my nodes have the "Generate automatic URL alias" setting checked on the node edit page.

How can this be achieved?

# Answer
> 1 votes
I would try the following.

Take a backup of the database. Backup and Migrate makes this easy.

Make sure core and modules are up to date, especially Pathauto and Token.

Browse to admin/config/search/path/patterns, and set the path pattern to `[node:menu-link:parents:join-path]/[node:menu-link]`. Credit to Menu path in Pathauto.

Browse to admin/config/search/path and delete the bad aliases, or admin/config/search/path/delete\_bulk and just delete all the content aliases. Be careful here, and make sure you have a backup.

Spot check a few nodes, and make sure the "Generate automatic URL alias" is set.

Double check that the nodes have a menu entry set on the node edit page, and that the parent is correct.

Double check the menus and make sure that the links have the paths set to `node/XXX`. You need to click the EDIT link to see this.

Browse to admin/config/search/path/update\_bulk to create all of the aliases for the existing nodes.

Clear Drupal cache from admin/config/development/performance

That should work.

# Answer
> 0 votes
you can change the url path to the other site by going to Structure,menus,under main menu--click list of links. .click the edit and click the page u want to change the url and lastly put it in PATH and done..

---
Tags: routes, uri
---


title: table like in admin of custom module

text:
# Question
Title: table like in admin of custom module
I have created a custom module that can add an entry into my own created tables. However, I need to display the contents of that table into the admin, a table like view. Like this one in the picture:

Can you point me to the correct documentation or what is this called?

Thanks.

# Answer
> 0 votes
You can create such tables with the Views module.

> You need Views if:
>
> * You like the default front page view, but you find you want to sort it differently.
> * You like the default taxonomy/term view, but you find you want to sort it differently; for example, alphabetically.
> * You use /tracker, but you want to restrict it to posts of a certain type.
> * You like the idea of the 'article' module, but it doesn't display articles the way you - like.
> * You want a way to display a block with the 5 most recent posts of some particular type.
> * You want to provide 'unread forum posts'.
> * You want a monthly archive similar to the typical Movable Type/Wordpress archives that displays a link to the in the form of "Month, YYYY (X)" where X is the number of posts that month, and displays them in a block. The links lead to a simple list of posts for that month.

---
Tags: 7
---


title: Adding default text to input field

text:
# Question
Title: Adding default text to input field
I was needing to add a default value to a text field that disappears when you click on the field.

I did found this question :

How to add default text that clears on focus to a form in Drupal?

However, my knowledge is pretty limited as far as creating hooks so I'm a little lost as to the solution being drawup up here.

Could someone please point me in the right direct?

Cheers!

# Answer
Since this is 2014 you're probably looking for the placeholder attribute, and not an old-school javascript solution.

Broad strokes: Implement `hook_form_alter()` and add the attribute there:

```
function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'foo') {
    $form['bar']['#attributes']['placeholder'] = t('Baz');
  }
}

```
> 1 votes

---
Tags: hooks
---


# Question
Title: How can I load a view inpage using AJAX when a node is flagged?
I have a view that gives the users the option to flag nodes. Below this view I need another view listing the results of flagged nodes to show up without the page needing a reload. My skills are limited to Front end development so I'm unsure how I can do this via AJAX.

I did find this module: https://drupal.org/project/jquery\_ajax\_load

I'm not sure how to implement this module since I need this view to commence upon the first flag event(?)

Would someone be able to help me find a solution?

Cheers!

# Answer
> 1 votes
This is actually a pretty common functionality and there is a module for it, Views Flag Refresh:

> Views Flag Refresh allows site administrators to configure which views are refreshed automatically via AJAX when certain flags are selected. This is useful when you have a view that filters by flagged content and you want the view to be refreshed automatically when content is flagged or unflagged elsewhere on the page.

If this doesn't fit your exact needs, there are lots of code snippets in the Flag Javascript API Documentation that might set you in the right direction.

---
Tags: ajax
---


# Question
Title: How can I gracefully interrupt an AJAX callback?
I have a form element that triggers an AJAX callback call when it looses focus. This callback can take a few seconds, which generally is not an issue.

If a user submits the form before the AJAX callback completes, the following error is displayed:

Here is the exact error message displayed to the end user:

> An AJAX HTTP request terminated abnormally.Debugging information follows.Path: /system/ajaxStatusText: ResponseText: ReadyState: 4

How can I gracefully terminate an AJAX callback from completing when passing control to a submit handler?

This is the relevant code from the module.

```
function a_custom_form($form, &$form_state) {
  $form['email'] = array(
    '#prefix' => '<div id="cust-email">',
    '#suffix' => '</div>',
    '#type' => 'textfield',
    '#title' => t('Customer Email Address'),
    '#required' => TRUE,
    '#ajax' => array(
      'callback' => '_user_email_ajax',
      'wrapper' => 'cust-email',
      'effect' => 'fade',
    ),
  );
  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Submit Request'),
  );

  return $form;
}

function _user_email_ajax($form, &$form_state) {
  $commands = array();
  // Doing time intensive stuff here...
  drupal_set_message(t('Some Message'), 'error');
  $commands[] = ajax_command_replace('#email-warning-message', '<div id="email-warning-message">'. theme('status_messages') . '</div>');

  return array(
    '#type' => 'ajax',
    '#commands' => $commands,
  );

}

```

I have tried the solution given for Prevent "AJAX HTTP request terminated" error on early form submit, but this seems to prevent the submit button from functioning, rather than interrupting the AJAX callback.

# Answer
> 2 votes
That's not directly possible. There is no API in the browser to manually cancel a sent request. All you can do is to register a callback to know when the HTTP response is received, or at least when the browser changes the state on the xmlHttpRequest object. Drupal's AJAX code already handles that for you. The error message you're seeing is shown because another request was sent which did interrupt the background request, but that still looked as if it was completed (`readyState == 4`). Drupal considers completely empty responses to be an error and the message is shown.

The most common and user friendly approach I've seen is indeed to disable the submit button(s) while a request is in progress. That in combination with a "spinner" animation or progressbar is a good indication that the user should keep waiting and that they will benefit from it. When the request completes (failed or successful), the buttons are unlocked again.

An input field can become unfocused at any time and for different reasons (maybe the user just wants to copy/paste something into it really quick). Triggering a long running background request whenever that happens could quickly become annoying. As you've already noticed, it interferes with the normal form submit flow as well. Maybe you can work around that and trigger the requests by some other means which more clearly indicate to the user that they need to wait for it to complete? Perhaps giving them the choice to initiate the request when they're sure to be done with manual input into the field and are more inclined to wait for automated processing of their input. Or perhaps trigger the request after a short timer which gets stopped when the field is refocused or the form is submitted.

If not, you could try overriding Drupal's AJAX response interpreting code so it won't show that message if the submit button interrupts the background request, first setting some flag to indicate AJAX errors are to be ignored. Whether this works also depends on how important it is that the AJAX operation on your field completed. If it performs some kind of correction on the \[email address?\] the user entered, they get it wrong, but the correcting routine didn't get a chance to update the field with valid input, this probably means your serverside validation fails and the user needs to submit it again - which could have been avoided if they had waited for the request to complete.

# Answer
> 1 votes
If the process is too intensive and you can wait some minutes to execute, a good approach could be to enqueue this process to be executed on the next cron.

Drupal 7 includes queue system in core, references:

In the ajax callback you only need to enqueue this process.

```
$queue = DrupalQueue::get('mycustomqueue');
$data = array(); //@TODO: include parameters
$queue->createItem($data);

```

You need to declare your queue:

```
/**
 * Implements hook_cron_queue_info();
 */
function mymodule_cron_queue_info() {
  $queues['mycustomqueue'] = array(
    'worker callback' => ''mycustomqueue_queue_callback',
    'time' => 60,
  );
  return $queues;
}

```

Callback function (drupal get all queued items and calls one by one):

```
function mycustomqueue_queue_callback($queue_item) {
  $data = $queue_item['data'];
  // DO stuff!
}

```

# Answer
> 0 votes
You can do a trick: hide the submit button on focus with jquery until the ajax response is executed ( and the show it again with an ajax command).

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


# Question
Title: Attributes are not changing in the placed order
I have a commerce site with T-shirts as products. I have added custom attributes of size and type.

By default L Size is selected. But even if the user changes the size to something else say M or S, in the order that is placed the size is still being shown as L.

I am assuming that this is because of caching. I currently have authcache enabled with Mem-cache in the backend.

I checked the XHR call that is being made. I see that the size that is being sent in the call is the one selected by the user. But however when the order is placed it still says L. Any help where to start debugging would be greatly appreciated.

# Answer
This is a known issue with page level caching system for anonymous users in Drupal. Please subscribe to the open issue on the authcache issue tracker, then you will be notified as soon as this is fixed. There is also a report in the Drupal Commerce Queue
> 1 votes

---
Tags: commerce, caching
---


title: How to create an blog in drupal 7?

text:
# Question
Title: How to create an blog in drupal 7?
We are creating a single page website responsive one. Planning to add a blog link. Can anyone specify how to create a blog page?

# Answer
> 1 votes
Enable **Blog** module under **CORE**

# Answer
> 1 votes
You can use **Blog Module** in your Drupal 7. for more info kindly visit to learn **How to create a blog site with Drupal step by step?**

---
Tags: 7, nodes
---


# Question
Title: How to get jquery switchClass working in Drupal 7
I want to use the jquery "switchClass" in a Drupal 7 Website. I already got the jquery accordion and tabs working, by adding the library in this way:

drupal\_add\_library('system', 'ui.tabs');

drupal\_add\_library('system', 'ui.accordion');

Now i'm trying to get switchClass working this way:

drupal\_add\_library('system', 'ui.switchClass');

... which is not working.

What am i doing wrong?

Thank you for helping!

Lars

# Answer
`switchclass()` isn't a library, it's a function that's part of UI Effects. So...

```
drupal_add_library('system', 'effects');

```

Should then let you use:

```
$('.foo').switchClass('foo', 'bar', 1000);

```
> 1 votes

---
Tags: javascript
---


title: How to convert PHP Logic to Views API

text:
# Question
Title: How to convert PHP Logic to Views API
I am writing a module to convert serialized value stored in database by the Composed Field Module. The serialized value is like:

`a:3:{i:1;s:14:"First Subfield";i:2;s:15:"Second Subfield";i:3;s:14:"Third Subfield";}`

The PHP Unserialize value of above serialized data returns the following array:

```
print_r(unserialize('a:3:{i:1;s:14:"First Subfield";i:2;s:15:"Second Subfield";i:3;s:14:"Third Subfield";}'));
Array
(
    [1] => First Subfield
    [2] => Second Subfield
    [3] => Third Subfield
)

```

I called the Module as **composed\_views**

So far I have made few files like: composed\_views.info, composed\_views.module,

**composed\_views\_handler\_subfields.inc** contains:

```
class composed_views_handler_subfields extends views_handler_field {
  /**
  * Render the unserialized value.
  */
  public function render($values, $index) {
    $uns = unserialize($values) // $values = serialized data from database
    return $this->get_value($uns[$index]); // $index = array index of serialized data
  }
}

```

In **composed\_views.views.inc**

For eg: The table names are **field\_one, field\_two**
The data column are **field\_one-composed, field\_two-composed** respectively

* I want to Query those tables
* and send the serialized data to render function defined in composed\_views\_handler\_subfields.inc file

So, far the structure is like this:

```
function composed_views_views_data() {
  $data['composed_views_table'] = array();
  // The actual code I am seeking help with
  return $data;
  }

```

Any help how to do with this with views would be appreciated.

# Answer
There is some discussion in several places about this, including an issue in the Composed Field issues queue.

The module author writes;

> I haven't investigated the mechanics behind it but theoretically all that needs to be done is to somehow implements the process that those modules do on retrieving the field value from the database and then unserialize and concatenate the retrieved value.

The problem of course with storing serialised data is the inability to effectively query it using any type of relational db (No indexes.)

You can always build a query using a LIKE on the serialised data ...

```
WHERE field_one-composed LIKE '%query%';

```

But that's horrible. :(

My comment on the initial question stands; do you want to achieve this using the GUI or through code? I'll update this answer based on your response.

While I appreciate this is not the question, I'm curious about why you chose this module for your use case?
> 0 votes

# Answer
As I mentioned in your other question, once views is able to fetch the data, you can change what it takes as a result by modifying the handler's `set_items` method.

However, the field handler is meant to display fields. If you're looking to change how Views filters behave, you'll have to extend and modify the filter handler.
> 0 votes

---
Tags: 7, views
---


# Question
Title: Setting automatically created taxonomy terms using rules module
I am using the rules module to automatically create a taxonomy term when i create content of a certain type. I would also like to automatically populate the taxonomy term reference in the the created content. I have tried many different configurations using the set data function in rules however it does not ever set the taxonomy term to the the new-term which is created.

Is there any way that this operation can be carried out using rules.

I have exported the rule for you to take a look at.

```
/**
 * @file
 * advertising_region_creator.rules_defaults.inc
 */

/**
 * Implements hook_default_rules_configuration().
 */
function advertising_region_creator_default_rules_configuration() {
  $items = array();
  $items['rules_auto_taxonomy'] = entity_import('rules_config', '{ "rules_auto_taxonomy" : {
      "LABEL" : "Auto Taxonomy",
      "PLUGIN" : "reaction rule",
      "REQUIRES" : [ "rules" ],
      "ON" : [ "node_insert" ],
      "IF" : [
        { "node_is_of_type" : {
            "node" : [ "node" ],
            "type" : { "value" : { "savings_viewer" : "savings_viewer" } }
          }
        }
      ],
      "DO" : [
        { "entity_create" : {
            "USING" : {
              "type" : "taxonomy_term",
              "param_name" : "[node:title]",
              "param_vocabulary" : "2"
            },
            "PROVIDE" : { "entity_created" : { "new_term" : "New Term" } }
          }
        },
        { "data_set" : {
            "data" : [ "node:field-savings-viewer-region" ],
            "value" : [ "new-term" ]
          }
        }
      ]
    }
  }');
  return $items;
}

```

I apologize if this is posted in the wrong format I am new to all of this but will keep trying to get better.

# Answer
> 2 votes
Simply add a autocomplete taxonomy field to the content type and when node saves, rule to set data into this field. Taxonomy module will then create the new term if it does not exist.

# Answer
> 0 votes
If you enable 'PHP filter' module (in the Core package) you will unlock an additional action rule 'Execute custom php code'. There you can use drupal API commands to both create and attach the terms. (Better to do the creation as well, since then you can get the ID of the created term.)

From here it depends if you have drupal 6 or 7. The code is for 7, but should get you started with 6 as well.

The final code would be something like this, but I have not tested it.

```
$term = new stdClass(); // Make a new term object
$term->name = $name; // New term name
$term->vid = $vid; // Term's vocabulary ID
taxonomy_term_save($term); // Save the term

$node->taxonomy[] = $term->tid; // Attach the taxonomy term ID of saved term
node_save($node); // Save the node again with the term

```

**Update**

* Make sure that you try to run this code on the event 'after saving a new node', otherwise there won't be a node id yet.
* If that does not work, try using only `$node->taxonomy` without the `[]`.

# Answer
> 0 votes
Neograph's answer is close, but I had two problems with it:

this is correct to create a new term (in a custom php rules action):

```
$term = new stdClass(); // Make a new term object
$term->name = $name; // New term name
$term->vid = $vid; // Term's vocabulary ID
taxonomy_term_save($term); // Save the term

```

but the below results in 1) not setting a term field on the node and 2) a pdo exception where it tries to insert a new node twice.

```
$node->taxonomy[] = $term->tid; // Attach the taxonomy term ID of saved term
node_save($node); // Save the node again with the term

```

so instead this works for me:

```
$node->field_myterm[LANGUAGE_NONE] =  array(array('tid' => $term->tid));

```

THEN instead of trying to save the node in php, add another action to the the rule: save entity (right after the php action).

---
Tags: rules
---


# Question
Title: How to add contents through block after enabling the blog module in drupal 7
Currently creating a single page responsive business website. Planning to add blog link to our site. For that we enabled the core blog module and added data. But we want to add the contents through block!!! can anyone specify me with a solution?

# Answer
Based on your comment above, you want to display blog entries in a block on your website.

I haven't used the Blog module in a long while (it's functionality can be duplicated easily without enabling it), but I think the easiest way for you to do this is to use Views.

1. Add a few blog entries
2. Create a new View that displays Content of type Blog Entry in a Block.
3. Views creates a new block, which you can place anywhere you'd like via the Block Admin page.

If you are unfamiliar with Views, you should watch or read some video tutorials. This one is recent and seems to be up your alley.
> 0 votes

---
Tags: blocks, nodes
---


# Question
Title: How would I add markup inside of page title input?
If I wanted to achieve the below, can I insert HTML markup inside of the page title on the node?

For example,

```
<h1 class="page-title">Dummy <span>page title</span> content</h1>

```

# Answer
> 4 votes
Install HTML Title. It will solve your issue.

> Drupal node titles are restrictive and do not support italicized text or superscript text (e.g., Book titles, trademark symbols). The HTML Title module allows a limited set of HTML markup (em, sub, sup, b, i, strong, cite, code, bdi, wbr) to be used in node titles.

Also take a look at Stack Overflow question *HTML\rich text in Drupal's node title?*.

---
Tags: 7
---


# Question
Title: Is it possible for a view to have two outputs
The reason I need this because I create a view to search through document and need two outputs. One being the document and the other being the files are part of the document group the file is associated with.

\*Is this possible with one exposed filter

Thanks for any help with this

# Answer
You can use an attached View. An attached View is a View display that is attached to another View display, a compounded View.

In this question is explained its purpose: What is the purpose of Views "Attachment", "Content pane" & "Context"?

> The Attachment option is to create yet another view that you can attach before and/or after any of the displays on your current view.
> 3 votes

# Answer
You can use Views Field View; allows you to embed a view as a field in a view.

It 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.
> 0 votes

# Answer
You can use attached view. Attached view have view display before or after to page or master. So u can easily attached another views on same page
> 0 votes

---
Tags: 7, views
---


# Question
Title: google analytics are killed after "cookie control" instalation
I'm new in drupal so I will write as simple as possible. I have installed the "google analytics" (GA) module. I have configured it and it worked. I was able to see live statistics on the GA web-page. Then I had quite stupid idea and I have installed "cookie control" (CC) module. After some time I have recognize that on the GA web-page I get no results... - no live-stats. So first I had disabled the CC module. But again there were no GA-live-stats :( so I have removed the CC module from the sites/all/modules, but that does not change anything. GA does not show any new stats since I have installed the CC module. How to proceed now?

Best regards, kami

# Answer
> 0 votes
That's pretty much what Cookie Control is for.

> On May 26th 2011 a new EU originated law came into effect that requires website owners to make significant changes to their sites and may fundamentally change the whole web browsing and shopping experience for everybody.This Cookie Law is amended privacy legislation that requires websites to obtain informed consent from visitors before they can store or retrieve any information on a computer or any other web connected device.
>
> Cookie Control does just that, presenting users with clear information on whether cookies are present, linking to your privacy policy (where you should have specific information about what cookies are in use), and advising users on how to adjust browser settings and what cookies mean for them.
>
> # Features
>
> * Compact pop-up with dark and light colour themes.
> * Prevent users logging in until cookie consented.
> * Other modules can integrate with cookie callbacks (see below).
> * Configurable message and read more message.
> * Link to an admin defined privacy policy node.
> * Only apply cookie consent restrictions to specified countries or whole world.
>
> # 3rd Party Module Support
>
> A sub-module is bundled with Cookie Control which **will disable Google Analytics from tracking a visitor until they give consent.** Upon accepting cookies their first visit will be logged, along with any further page loads.

Emphasis mine.

So if you want to track people who do not consent for being tracked, you need to stop obeying the law - by disabling or modifying modules that makes your site law compliant.

# If you in fact disabled CC module

and GA is silent, then if you have no (or not much) new users, or you haven't cleared your caches, or ISP caches, then yes, it can last up to a week (usually a day or two). Try uninstalling this module, not only disabling, too. If it lasts longer than about a week, and GA can't even detect you when you browse from a browser you are sure never seen CC-enabled version on your site, then you are in trouble and it might be worth to compare your site (especially HTML, JS and headers output) with a backup from before first CC installation. But **it would be a bug in Cookie Control**, and you should report them in issue queue, not here.

---
Tags: cookies
---


# Question
Title: How to allow non-admin users to create nodes of specified content type?
I've created a content type 'Product' with some fields (like title, cnk, type, ..). I can create a product in my admin theme. But now I would like to create a form that a user (NOT admin) can fill in and submit (content created). How can I do this?

# Answer
> 3 votes
Go to **Home \> Administration \> People**, Permissions tab (URL like http://example.com/admin/people/permissions ). There, find **Node** section.

For each content type you will have 5 permissions that will let you decide who can do what, liek on the screen below:

Just check "create" for roles that are supposed to be able to create.

---
Tags: forms, nodes, webforms
---


# Question
Title: How to implement an option for users to limit access to nodes/comments to users with the same role while posting it?
How can I offer users an option on all node/comment postings to limit access to their own user role group? Essentially making the conversation accessible only for the members of their own year who they are together with in person.

Each year gets its own user role. There are multiple years of group members using the site, and sometimes members would like to limit sensitive content to themselves, as old members retain access to the site otherwise.

Ideally, it would just be a single checkbox that reads '***make this content private to your peer group***' without offering any other options, which should restrict the content to their own peer group and to admins.

# Answer
The short answer is: Yes, you can do this with the Group module.

Here are some instructions on how to do so:

1. Install the Group module and its dependencies.
2. Enable the Group Node module as well (a sub-module of Group).
3. Navigate to `admin/group`, or click the new Group link in the admin toolbar.
4. Create a Group Type "Year".
5. Configure the permissions for that group type to allow members to create and/or view nodes (outsiders will not have access unless checked).

There are numerous things you could add to the mix, such as a "Year admin" group role. But giving a sitewide admin the "Bypass group access" permission will do just fine as well.

You can also delete the group\_admin role under `Group > Group Roles` should you not need it.

If you find any bugs or need support you can also use the Group module's issue queue.

Disclosure: I'm the module maintainer.
> 2 votes

---
Tags: nodes, users, comments
---


# Question
Title: How to convert a webform to a content type?
I have a long webform with about 90 textarea fields modeling a report item. Since the requirements of my Drupal site have changed, the report is now part of the content and should have workflow and other content type functionality.

So I want to convert my webform with its 90 fields to a CT. I know this will raise some problems regarding the performance, but I was thinking to overcome them by reusing some textarea fields (e.g. by putting them in different field collections in the same content type and changing their title and description only per field instance).

Is there an easy way to **convert my exported webform with its fields to a content type** with the same fields? Or should I do it manually?

# Answer
Unfortunately, there is no easy way to take a massive webform form and convert its *form fields* into a *Drupal Entity + Fields*. And yes when you want to re-architecture your website and do this for 50+ fields -- it sucks (been there).

Because some things like the Workbench module only work with things that are Nodes. And when you initially choose a webform to represent this data you've coded yourself into a corner.

This is kinda 1 place where Drupal is somewhat lacking -- interopability between similar tools (webform, entityform, entities, ECK, etc).

There are some tools to "move stuff around" such as:

But they only work within 1 kind of architechure (Entities).
> 1 votes

---
Tags: 7, entities, nodes, webforms, importing-exporting
---


# Question
Title: How to filter views results by value of profile field of currently logged in user?
When I create a user a 'supplier' must be selected. When a user creates a product a 'supplier' must also be selected. Now I would like to show all the products with supplier = supplier logged in user. I now have a table with all my products listed, but now I need to add the filter. Is there a module for this or can this be done in another way? Because when I now want to add a filter only the product fields are shown.

# Answer
> 4 votes
Instead of listing products filtered by Supplier field. You want to build your View from Users and add a relationship to Products linked through your Supplier field -- see this thread with further documentation: https://drupal.org/node/1111722

So its something like the following from my above link:

> * Create a user view.
> * Add a contextual filter on user: uid. If no filter value is present, build a default value using the currently logged in user. (This will give you exactly one user object in your view -- the logged in user.)
> * Add a relationship, using the relevant taxonomy reference field on the user accounts. This will bring you information about the "interest" term for the logged in user.
> * Add another relationship, called "term: nodes marked with term" (or something like that). This will bring you information about all nodes marked with the interest term for the logged in user.
> * Either set the view to display node teasers, or select a number of fields to display.
> * Add a display as usual. Done!

Alternatively you could use Views Global Filter to set a filter based on the profile value most likely.

---
Tags: views, users
---


# Question
Title: Why I can upload only one file at a time with multi upload widget?
I have installed the multi-upload widget module to be able to upload several files at once. I have set a file widget to multi upload, which has enabled the ability to choose several files at once however only one files uploads are there any necessary module to install for the module to work ?

Thanks for any help on this

# Answer
Probably you are using APC for upload progress:

Check your status report to see. If so, do what it suggest. Or ask / pay your sysadmin to do it.
> 3 votes

---
Tags: 7, files
---


# Question
Title: How to prevent people to ask for registration in Drupal 7?
There is no login block in my website but everyday I see lot's of strange emails are sent they ask for registration. How do I can modify Drupal to reject every registration request?

# Answer
> 2 votes
Go to Configure \> People \> Account Settings (/admin/config/people/accounts) and set it so only Administrators can register accounts.

# Answer
> 0 votes
Have you configured Drupal to only allow registation by admins? There's a setting where people can register, but administration aproval is needed: I think you have this setting and simply are receiving the notifications to aprove those registrations. Just check the registration only by admin in People settings (admin/config/people/accounts)

---
Tags: users
---


# Question
Title: Why do sub-menu items not appear on front page, but work on other pages?
I have added a link to a Panels page in my main menu. Beneath that link are items which link to a couple of Webform pages and a Basic page.

On the home page, the sub-items do not appear beneath the heading, but on all other pages, they show up just fine. If I look at Structure-\>Menus-\>Main menu, everything is set up correctly. I have cleared caches multiple times, to no avail. Any ideas?

Thanks in advance.

# Answer
> 8 votes
> I suspect your problem could be resolved by ticking the "Show as expanded" checkbox on that menu item.

This worked for me. Thanks, Adam!

---
Tags: routes
---


# Question
Title: Filter by field that only exists for some content types shown in view
We're trying to create a view with a number of exposed filters in D7. There are a number of different content types that we want to show in the same view, and to filter using the same filters. However, most but not not all of the content types have all the fields we want to filter by.

For instance, "Difficulty Level" is a field common to many of our content types, including Tutorial and Project. However, an Idea does not have this field.

Ideally, we would like to let end-users filter by a number of fields and specify whether they want the filter to be strict or flexible. Let's say the user is looking for resources that have a Difficulty Level of "Beginner" or "Intermediate":

* **strict** would mean that only nodes that fully satisfy the filters are shown:
    + no Ideas would be shown, because Ideas by definition don't have a Difficulty Level field to begin with
    + Tutorials with a Difficulty Level of null would also not show up
    + an Advanced Tutorial would not be shown
* **flexible** would mean that all nodes that don't outright disagree with the filters are shown:
    + all Ideas would be shown
    + Tutorials with a Difficulty Level of null would be shown
    + an Advanced Tutorial would still not be shown

Is this doable with Drupal? I've searched high and low and haven't been able to find anyone with such a problem...

*EDIT:* Using the and/or groups is one possible solution, however it doesn't work for taxonomy fields: these lead to joins instead of left joins, so that you can either get the items that have the requested keyword or the items that don't have any keywords, but not both at the same time.

# Answer
> 1 votes
Yes, that's doable.

I would create a separate view for strict and flexible and then tailor each to suit your needs. You may need to use hook\_views\_query\_alter if you can't get the functionality quite right with just the view UI.

A possible simpler alternative approach is outlined in this answer here.

Essentially this involves clicking on the reduce duplicates checkbox when configuring your join in the views UI.

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


# Question
Title: Change navigation (sublinks) according to main menu (headlinks)
I would like to create a main menu with some links in it. And when you click on a link in the submenu, the content of the navigation menu changes according to the link clicked in the main menu (= subnavigation elements). Here is an image to clarify:

I now have a main menu and a navigation, but the links stay the same for this moment. So now I would like to get the navigation to be dynamic. How could I do this the best way?

# Answer
> 2 votes
The easiest way will be to create a menu for each top level menu page.

Then put all those menus as blocks in your sidebar region, with a rule so they only appear on the correct page, or subpages.

E.g.

Menus:

```
Top Menu:  Home | News | Blog
    // show on all pages

Home Menu: Info | About
    // show on home and home/*

News Menu: Current | Archive
    // show on news and news/*

Blog Menu: My Blogs | Other Blogs | Archive
    // show on blog and blog/*

```

Pages

```
/home
/home/info
/home/about
/news
/news/archive
/blog
/blog/other
/blog/archive

```

So, step by step instructions would be:

1. Create a main menu for your site.
2. Add items for Home (URL: /home), News (URL: /news) and Blog (URL: /blog) to your main menu.
3. Create another menu called Home.
4. Add pages info (URL: /home/info) and about (URL: /home/about) to this menu.
5. Add this menu to your theme in a block. Set the block visibility to only appear on "home" and "home/\*". This is the clever bit because the submenu for home page will appear on the main /home page, and also any subpages of that as long as you follow the url structure.
6. Repeat same process for the news and blog menu so now each of your sub-menus only appear on their specific pages.
7. Do a little dance (can even have a sing if you want).
8. Done.

---
Tags: navigation, routes
---


# Question
Title: How to add a counter about the total number of nodes visited by a user?
I have one block that display individual user details.

How can I add a counter which counts the total number of nodes visited by a user?

# Answer
> 2 votes
Have you checked the **Node view count** module: Node View Count module allows to count node views.

> Unlike statistics module, this module records each view of node with **user uid** and timestamp.

I guess at max. you only would have need to write the correct database query to get the count of total number of nodes visited by a user as rest of the things are being done by this module.

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


# Question
Title: Is it proper to perform a db_update on an entity table?
I have a custom entity. During a save operation, under certain circumstances, I need to change the value of a specific field (not field API) of some other entities (of the same type).

If I perform a `db_update` on the entity's table, is it safe for caches or for any other reason yet unknown to me?

Alternatively, I suppose I could use a rather complicated select query to retrieve the ID's under concern. Then update each entity separately in a loop or batch.

Which causes my second similar question, is it safe to perform a select query in the middle of this operation? Are there any circumstances where entities have different content in memory or DB cache comparing to the DB values?

# Answer
> 6 votes
The thing to look out for is invalidating the correct caches and making sure the correct hooks are called if needed.

When updating entities directly you will need to flush the appropriate caches so the next time the entity is loaded it does not grab the old data from the cache.
entity\_load()
-\> DrupalDefaultEntityController::load() {uses a static cache by default}
--\> DrupalDefaultEntityController::attachLoad()
---\> field\_attach\_load() {uses the cache\_field cache bin}.

Once you have that taken care of you will then need to address any 3rd party modules that use hook\_entity\_load() or hook\_TYPE\_load() (hook\_node\_load()). Odds are you won't have to do anything in here but it is best to double check.

Once loading has been addressed you will need to address the hooks that get ran on insert/update to make sure nothing else is done in a different place that you may not know about. hook\_entity\_update(), hook\_entity\_insert(), field\_attach\_presave(), hook\_entity\_presave(), hook\_TYPE\_presave() (hook\_node\_presave()), etc... You can follow the trail of hooks in node\_save() as an example. Once again odds are nothing crazy is going to happen in here, but it is best to double check.

In regards to getting ID's entity\_load\_unchanged() might be what you are looking for.

Most people will tell you it is not "proper" to update fields in the database directly via SQL queries. This is because 3rd party modules might do something with that data or react to it in different ways; also be aware of modules added after you've done this workaround. In reality you can directly update the database as long as you know the risks and how the code works; most people do not and thus using the API is the best answer.

Now for the interesting part. My guess is you're looking to work around the entity api due to speed issues. There are some ways to fix this. Using a background worker to do the updates is my recommendation. register\_shutdown\_function() when used in combindation with HTTPRL's threading can help. I don't have a good how-to yet but here is a really quick explanation:

httprl\_qcinp - Queue Callback to run In a New Process. This takes arguments similar to call\_user\_func\_array(). I'll use a node as a example.

```
<?php
hook_node_save($node) {
  // Preform update at the end of this request.
  register_shutdown_function('my_shutdown_function', $node);
}

my_shutdown_function($node) {
  // Load other entity that needs to be updated.
  $alt_node = entity_load_unchanged('node', $node->some_field_reference_nid);
  // Update object
  $alt_node->my_field = 'updated info';

  // Queue background node_save.
  // node_save($alt_node);
  httprl_qcinp('node_save', array($alt_node), FALSE);
  // Run it.
  httprl_send_request();
}
?>

```

At this point you might not even need HTTPRL; register\_shutdown\_function might do what you need.

EDIT: Also noted that this is a handy guide for just updating a single field http://timonweb.com/how-insert-and-update-only-specific-fields-your-entity-drupal-7

---
Tags: caching, entities
---


title: Links converting to plain text

text:
# Question
Title: Links converting to plain text
I've got a function that should generate a link as such `<a href="http://linklocation">Set Password</a>`, which does happen, but it is generating as plain text.

My guess is that this is due to my use of the t() and l() functions in the manner I'm using them.

Here's my code:

```
  global $user;
  $account = new stdClass();
  $account->uid = $user->uid;
  $account->login = $user->login;
  $account->pass = $user->pass;
  $link = l('Set Password', user_pass_reset_url($account));
  $token = t(token_replace(variable_get('listing_edit_free_activated_page', 'Your free content has been activated. Thanks! @link')), array('@link' => $link));

```

As you can tell, I'm attempting to generate a one-time user login link with the text, "Set Password". The token\_replace() isn't really relevant to this problem.

Am I completely without options here? I want to use both t() and l() here - there's not really an easy way to not use both that I can see.

How do I use both while still maintaining the structure of $link as a link?

# Answer
The answer I was looking for was to change the placeholder to `!link`.

`@link` gives only the plain text

`!link` gives the raw information

`%link` HTML escapes and highlights

This example page is for Drupal 6, but has more information on the placeholders:

https://api.drupal.org/api/drupal/includes%21common.inc/function/t/6
> 1 votes

# Answer
The t function's first argument is a string, and the second is a keyed array of arguments (search =\> replace).

The string your passing in is:

```
token_replace(variable_get('listing_edit_free_activated_page', 'Your free content has been activated. Thanks!'))

```

And the replacement your searching for it `@link`.

As the string `@link` does not appear in the string your passing in no replacements are made.

Here is an example where a replacement will be made:

```
$text = t("@name's blog", array('@name' => format_username($account)));

```
> 1 votes

---
Tags: navigation, tokens
---


title: Sub menu creation

text:
# Question
Title: Sub menu creation
I need to create page level menus. User goes to a page off of the main menu and is presented with a sub menu. The menu items need to display / not display based on user roles - similar to the main menu. I researched the Book and the Blocks... but I don't know if either of these are the way to do it. It seems like a very common thing - and want to know the simplest way to do it.

# Answer
The Menu Block module provides blocks that you can place via the Block API. Menu position might also be useful - it "allows for the creation of rules that will dynamically add the current page into the menu system at the requested spots."
> 0 votes

---
Tags: routes, navigation
---


# Question
Title: How to show Checkboxes with Fulltext Search Filter Exposed?
I have created a simple search with three filter options of "Contains any of the word", "all of the words" and "none of the word", as shown in the figure below.

I used Search API, and later created a view out of it.

For an exposed filter, I just chose "FullText Search" and exposed it as follows:-

It shows me a page likes this:-

Now, it works fine, but I want checkboxes instead of the dropdowns. For that I installed Better Exposed Filters, but it doesn't show me the option to show checkboxes ... as shown:

What am I missing that this is not allowing me to show Checkboxes :(. I will be very thankful for your help. I just need to convert them to checkboxes.

# Answer
> 1 votes
Currently BEF doesn't support tweaking the display of the filter operator, only the filter itself. But this would be a great addition -- feel free to post a feature request in the BEF issue queue.

Thanks.

# Answer
> 0 votes
Normally I would suggest to do a simple form alter and change the type from select list to radio.

But since it looks like you are trying to do it only using modules I would suggest you to take a look at Dropdown Checkbox module

> Convert
>
> 1. multiple select lists into dropdown checkboxes
> 2. single select lists into dropdown radio buttons

---
Tags: views
---


# Question
Title: How to  redirect the user to a  page and show a message on the admin overlay (using drupal_set_message and drupal_goto)
I need to redirect the user to a destination and show a confirmation/error message. How can I do that? This is my code:

```
watchdog('webform', 'The user @user has been successfully created', array('@user'=> $mail));
drupal_set_message(t('Settings saved.', array()));
drupal_goto(drupal_get_destination());

```

This code redirects, but the message is not shown. Do i need some special action in the destination page?

EDIT - the problem is that i'm redirecting to an administrative page and the message is showing in the main theme, i want it to display on the overlay theme. I'll explain a little bit more in depth what i'm doing (this could be totally wrong).

I added a link that the user can click when he is viewing a submission entered through a webform (webform module). i defined a menu voice for that link in this way (i'ts only a callback, no page is shown):

```
$items ['createuser/%'] = array (
                                    'title' => 'Create users',
                                    'access callback' => TRUE,
                                    'page callback' => 'provintegra_createuser',
                                    'page arguments' => array (
                                                            1 ),
                                    'type' => MENU_CALLBACK );

```

Then i defined provintegra\_createuser

```
function provintegra_createuser($sid) {
        //save user
    watchdog ( 'webform', 'L\'utente @utente è stato creato cons successo', array (
                                                                                '@utente' => $mail ) );
    drupal_set_message(t('Settings saved.', array()));
    drupal_goto(drupal_get_destination());//This redirects you to the page of the webform submission in the overlay
}

```

I se the message "Setting saved" but it's in the main theme, not in the theme (seven) i'm using for the administrative overlay. Do i need to set some special parameter so that the message is shown in the overlay?

# Answer
I don't think this is possible with the current message system, it would require some crazy workaround do make it work anyways.

The problem is that when you use `drupal_set_message()`, the message is stored in the session variable and displayed whenever possible. When you redirect to a page with an overlay two things happens.

1. The main page is rendered and displayed.
2. The overlay page is rendered and displayed (with an iframe).

This means that whatever message you set, would always be displayed on the main page.

What you could do, is when the messages has been extracted to set them again and remove them. This could happen in your theme somewhere. The problem is that it is probably very hard to determine when you should do this, as you effectively would hide all messages if you always did this. Another side effect would be that you would constantly get more and more messages, possibly leading to a fatal memory error at worse.
> 2 votes

# Answer
@googletorp writes:

> I don't think this is possible with the current message system, it would require some crazy workaround do make it work anyways.
>
> The problem is that when you use drupal\_set\_message(), the message is stored in the session variable and displayed whenever possible. When you redirect to a page with an overlay two things happens.
>
> The main page is rendered and displayed. The overlay page is rendered and displayed (with an iframe). This means that whatever message you set, would always be displayed on the main page.
>
> What you could do, is when the messages has been extracted to set them again and remove them. This could happen in your theme somewhere.

I solved this mainly in hook\_init(). My scenario was that my moudle's .install created some drupal\_set\_messages() which would then be obscured by overlay when the user was redirected to admin/modules.

In my .install the last line of my hook\_install implementation is:

```
// Set a flag so that we know installation has just completed.  Process the flag in ucberkeley_cas_init()
$_SESSION['ucberkeley_cas_installed'] = TRUE;

```

In my .module I have:

```
/**
 * Implementation of hook_init()
 * If overlay.module is enabled, make sure that our hook_install messages are displayed
 */
function ucberkeley_cas_init() {
  if (!module_exists('overlay') || (!is_array($_SESSION))) {
    return;
  }
  if ((array_key_exists('ucberkeley_cas_install_messages', $_SESSION)) && (!array_key_exists('messages', $_SESSION))) {
    foreach ($_SESSION['ucberkeley_cas_install_messages']['status'] as $msg) {
      drupal_set_message($msg);
    }
    unset($_SESSION['ucberkeley_cas_install_messages']);
  }
  elseif ((is_array($_SESSION['messages'])) && (array_key_exists('ucberkeley_cas_installed', $_SESSION))) {
    $_SESSION['ucberkeley_cas_install_messages'] = $_SESSION['messages'];
    unset($_SESSION['ucberkeley_cas_installed']);
  }
}

```

Now the messages appear in the the overlay.

(Let's all celebrate the removal of overlay from Drupal 8!)
> 1 votes

---
Tags: 7, redirection
---


# Question
Title: Do purchased themes need to be fully built from the ground up?
Really naïve newbie question....

I am brand new to Drupal after working in Wordpress for quite a while. We bought a custom agricultural theme for $75 - it looked perfect for my project at work. The sample had all the right stuff with content placed in areas I can customize to my project.

However, now that I have downloaded it, it is just "bare bones." The structure for the content and images is nowhere to be found. The drop-down menu isn't horizontal, the whole structure is absent. I thought this would be easier. Do I have to build everything in Dreamweaver? Did I miss something? Are the themes merely "suggested formats?"

# Answer
where did you buy the theme from? Do they provide installation instructions or usage instructions? Did it ship with any additional modules to enable configuration?

A theme is basically styled blocks, views, nodes, regions. You need to place your content into Regions of the theme for it to show up like their example.
> 1 votes

# Answer
Generally when you buy a theme like that, it will come shipped with a database that will start you off with all the default content and settings. Look back in the download and see if you can find any kind of .sql.gz file anywhere.

Sometimes they would use like an install profile so when you install Drupal, you would pick the custom profile name instead of the standard or minimal installation.
> 1 votes

---
Tags: theming
---


# Question
Title: How can I add form elements in custom form on click of link?
I want to add form elements inside my custom form when some body clicks on the link outside the form. Links are like :

* Add textfield
* Add selectlist

When user click on any link it via ajax add an element to the form. I just want and idea whether it is possible or not in drupal. If it is possible then just give me some idea about this.

Thanks

# Answer
This is absolutely possible. I would highly recommend that you check out Drupals AJAX framework and Form API.

You might even be able to use the Form API's "#states' features to accomplish what you're looking to do without having to make any AJAX callbacks.

There is also the Examples for Developers project that I believe contains code that accomplishes what your hoping to accomplish.

These should help you get started with the AJAX framework in Drupal.
> 0 votes

---
Tags: forms, ajax
---


# Question
Title: CKEditor custom configuration (implemented using WYSIWYG module)
How can I set some custom configurations for the CKeditor module? I want to set spell check SCAYT on by default, and a few other things like that. Ideally, I would like to create my own custom config file somewhere sensible that won't be overwritten.

# Answer
Look at hook\_wysiwyg\_settings\_alter

> Act on editor profile settings.
>
> This hook is invoked from wysiwyg\_get\_editor\_config() after the JavaScript settings have been generated for an editor profile and before the settings are added to the page. The settings may be customized or enhanced; typically with options that cannot be controlled through Wysiwyg module's administrative UI currently.
>
> Modules implementing this hook to enforce settings that can also be controlled through the UI should also implement hook\_form\_wysiwyg\_profile\_form\_alter() to adjust or at least indicate on the editor profile configuration form that certain/affected settings cannot be changed.

Additionally this blog post by Fuse Interactive: WYSIWYG MODULE + CKEDITOR: TAMING THE BEAST goes into great depths on how to make use of this hook. From the blog post ...

```
/**
 * Implements hook_wysiwyg_editor_settings_alter()
 */
function ckeditor_custom_wysiwyg_editor_settings_alter(&$settings, $context) {

  // The $context variable contains information about the wysiwyg profile we're using
  // In this case we just need to check that the editor being used is ckeditor

  if ($context['profile']->editor == 'ckeditor') {

    // The $settings variable contains all the config options ckeditor uses.
    // The array keys correspond directly with any setting that can be applied
    // to CKEditor - as outlined in the CKEditor docs:
    // http://docs.cksource.com/ckeditor_api/symbols/CKEDITOR.config.html
    // Another way to override configuration is to use your own configuration javascript
    // file. In this case, we're going to add our own configuration file that will
    // Hold our stylesSet customizations...
    $settings['customConfig'] = base_path() . drupal_get_path('module', 'ckeditor_custom') .
                                '/ckeditor_custom_config.js';

    // We are also going to specify a custom body id and class
    $settings['bodyId'] = 'ckeditor_custom_id';
    $settings['bodyClass'] = 'ckeditor_custom_class';

    // To see what's in $settings and $context, install the devel module
    // And run the variables through the dpm() function.
  }
}

```
> 5 votes

# Answer
Here is the code inspired by @tenken

```
/**
 * Implements hook_wysiwyg_editor_settings_alter()
 *
 * @see http://docs.cksource.com/CKEditor_3.x/Howto/Enabling_SCAYT
 */
function modulename_wysiwyg_editor_settings_alter(&$settings, $context) {
  // The $context variable contains information about the wysiwyg profile we're using
  // In this case we just need to check that the editor being used is ckeditor
  if ($context['profile']->editor == 'ckeditor') {
    // Make Scayt enabled by default.
    $settings['scayt_autoStartup'] = 'true';
  }
}

```
> 0 votes

---
Tags: wysiwyg
---