# Question
Title: Admin Config page for my module is empty
I created a module (namely, "casabaca\_s3s") and set a configure entry in the casabaca\_s3s.info file:

`configure = admin/config/content/casabaca_s3s`

Now my "Configure" appears in the module.

Then, i added, in my casabaca\_s3s.module file, the following code:

And my hook:

```
function casabaca_s3s_menu()
{
    return array(
        'admin/config/content/casabaca_s3s' => array(
            'title' => 'Casabaca',
            'description' => 'Configuración de Casabaca',
            'page_callback' => 'drupal_get_form',
            'page_arguments' => array('casabaca_s3s_admin'),
            'access arguments' => array('administer casabaca_s3s pages'),
            'type' => MENU_NORMAL_ITEM,
        ),
    );
}

```

And my handler for the hook:

```
function casabaca_s3s_admin() {
    return system_settings_form(array(
        'casabaca_s3s_modelcosts' => array(
            '#type' => 'managed_file',
            '#title' => t('Modelos y kilometrajes'),
            '#description' => t("Archivo .csv con el contenido de la tabla de precios según modelo y kilometraje"),
            '#required' => true,
            '#upload_validators' => array(
                'file_validate_extensions' => array(0 => 'csv'),
                'file_validate_size' => array(32*1024*1024),
            ),
        ),
        'casabaca_s3s_extracosts' => array(
            '#type' => 'managed_file',
            '#title' => t('Costos de servicios adicionales'),
            '#description' => t("Archivo .csv con el contenido de la tabla de precios de servicios extra"),
            '#required' => true,
            '#upload_validators' => array(
                'file_validate_extensions' => array(0 => 'csv'),
                'file_validate_size' => array(32*1024*1024),
            ),
        ),
    ));
}

```

**Problem**: When I click "Configure" button in module listing (the one with the gear), it redirects to admin/config/content/casabaca\_s3s, but that page is empty, showing standard message: "No tiene ningún elemento administrativo." (trans. You have no administrative elements). What am I missing to display the form?

# Answer
```
'page_callback' => 'drupal_get_form',
'page_arguments' => array('casabaca_s3s_admin'),

```

needs to be

```
'page callback' => 'drupal_get_form',
'page arguments' => array('casabaca_s3s_admin'),

```

(underscores removed from array keys)
> 3 votes

---
Tags: 7
---


# Question
Title: URL Redirect created over SSL only works over SSL
I have added a redirect via:

> Configuration \> Search and Metadata \> URL Redirects

While accessing the site via SSL. When I add the link the from box auto fills the root of the redirect with `https://myRootURL.com/` :

This redirect works for `https://myRootURL.com/redirectedLink` but does not work for non-ssl: `http://myRootURL.com/redirectedLink`. I would expect all of these redirects to be ssl/non-ssl agnostic - and the ones auto-generated by Drupal all seem to be.

Is this a configuration issue - or known problem? I have had no luck with Google or browsing the known issues, but I am not sure I am articulating the problem correctly.

**EDIT:** I am experiencing the same functionality with URL Aliases as well... what configuration options could impact this?

# Answer
I am feeling a little sheepish here:

Caching was turned on for anonymous users. When accessing the site as `https` I was also logged into Drupal, unlike when I was accessing the site over `http`.

As such the anonymous users were not getting the redirect or alias applied until the cache was cleared. Should have been an obvious first step.
> 0 votes

---
Tags: uri, redirection
---


# Question
Title: Make top level terms un-selectable in hierarchical taxonomy?
I have a taxonomy like this:

```
Color
-blue
-green

Size
-large
-small

```

I need to use 1 vocabulary not 2. However I need 'Color' and 'Size' to not be selectable. If I create a hierarchal taxonomy is there a way to make certain (the top level) terms un-selectable by nodes?

# Answer
Using Hierarchical Select module you can do that and configure it to ***Force the user to choose a term from deepest level***, see the below screenshot.

and also take a look at this Taxonomy Term Reference Tree Widget module, I think it have the option to select only child term and I'm not sure about this module.
> 2 votes

# Answer
You can use the Taxonomy container module, it does exactly what you want. Here is a quote about it (from the module's project page):

> ... provides an extra widget called «Select list (with groups)» to term reference fields.
>
> Drupal 6 version of the module just alters taxonomy form and converts to optgroups all top-level options in the select list.
>
> Note: Chosen module can help you make select boxes much more user-friendly.
> 1 votes

---
Tags: taxonomy-terms
---


title: Login with iframe popup

text:
# Question
Title: Login with iframe popup
I have popup showing on click on a link on my site which shows a login form in iframe. i am able to login with popup iframe but when i close that popup, i am not logged in on main site and need to login again. is there a way so that i only need to login once, either from main site or from iframe?

# Answer
> 0 votes
To maintain the sessions configure htaccess to run site with consistent protocol like www, https, if urls for pages are not with same protocols they login issues comes.

---
Tags: users, sessions
---


# Question
Title: How to track location of a sign-up form in a block?
I have a newsletter sign-up form in a block that appears on many pages. When the form is submitted, I want to capture the current page.

The block and form are created in code. In the submit function, I am using drupal\_get\_path\_alias() to get the current location. The block has no explicit caching set, so I believe DRUPAL\_CACHE\_PER\_ROLE is assumed.

I had been thinking that although the block is cached for anonymous users, the submit function would still retrieve the correct location.

However, it doesn't seem to be working correctly. I always get a value for the path, but I believe it's incorrect in many cases.

What should I do to make sure I get a correct path on submit?

Update Mar 17 2014: I switched caching from the assumed DRUPAL\_CACHE\_PER\_ROLE to DRUPAL\_CACHE\_PER\_PAGE and that seems to have resolved the problem. Also, for the record, the problem looked like this: most sign-ups come from one page. But every once in a while a sign up will come from a different more obscure location on the site. What I was seeing was that "other location" repeated for the next x of signups (the number varied). So, in that respect, it did look like a caching problem.

# Answer
have you fully tested your guess? what you've described should work, AFAIK.

other options would include:

1) modifying the form to have a hidden value, set using drupal\_get\_path\_alias() ... it would set the value on load, rather than looking it up on submit.

2) a google analytics event tracker attached to the submit button the form.
> 1 votes

---
Tags: 7, forms, blocks
---


title: Module builder as drush plugin

text:
# Question
Title: Module builder as drush plugin
I thought I had installed successfully module builder as drush plugin : typing `help mb` returns complete help story...

But when I try to use it, ie typing `mb easyresponsive_panels ctools_plugin_directory menu --write`, it gives me the following error :

> Command mb-build needs a **higher bootstrap level to run** \- you will need to invoke drush from a more functional Drupal environment to run this command. The drush command 'mb easyresponsive\_panels' could not be executed. **Could not find a Drupal settings.php** file at sites/default/settings.php.

I have a multi site install, this is why no sites/default/settings.php is found.

I tried to specify root and site explicitly, as per these answers, running `--root=path/to/drupal --uri=mysite.com status`, this returns the correct complete status :

```
Drupal version : 7.24
Site URI : visages_20131224:8082
Database driver : mysql
Database username : drupaluser
Database name : visages_20131224
Database : Connected
Drupal bootstrap : Successful
Drupal user :
Default theme : neptune
Administration theme : adaptivetheme_admin
PHP executable : php.exe
PHP configuration : C:\wamp\bin\php\php5.3.13\php.ini
PHP OS : WINNT
Drush version : 7.0-dev
Drush configuration :
Drush alias files :
Drupal root : C:\Users\Thierry\Sites\visages_20131224\
Site path : sites/visages_20131224
File directory path : sites/visages_20131224/files
Temporary file directory path : c:\windows\temp

```

(my dev config : Windows 7, Acquia Dev Deskstop, Netbeans, D7)

Related Q&A didn't enlightened me yet, any help is welcome.

# Answer
Thanks to Clive comments, and as explained in Drupal, Drush aliases and how to use them, I solved it as following.

Add an alias conf file named `sitename.aliases.drushrc.php` in .drush folder in your home directory :

```
/**
 * Local
 */
// The site in sites/default/
$aliases['default.local'] = array(
  'uri' => 'default',
  'root' => '/path/to/drupal',
  'path-aliases' => array(
    '%dump-dir' => '/tmp'
  ),
);
// The site in sites/sitename/
$aliases['sitename.local'] = array(
  'uri' => 'sitename_URI',
  'root' => '/path/to/drupal',
  'path-aliases' => array(
    '%dump-dir' => '/tmp'
  ),
);

```

Don't forget to clear cache : `drush cache-clear drush`.

Test your alias : `@sitename.local status`.

Now you can run i.e `@sitename.local mb mymodule hook1 hook2 --write`

Really powerful !

See Drush multi-site aliases for complete configuration of local/remote aliases
> 1 votes

---
Tags: drush
---


# Question
Title: How to create a 3rd Ad push in a custom Omega Kickstart subtheme
I'm using drupal commerce kickstart 7x to design an experimental website to understand the layout & methods of the CMS.

I've just started using Drupal. To be precise, 3 days. This is very new to me.

I want to know how does one go about placing a 3rd Ad Push block in the "Postscript third" section. I've sub themed Omega kickstart.

I've tried creating blocks, editing the fields, editing views, reordering the blocks and contents. Yet none seem to work.

I can only create a block with text as its body. But what I want to achieve is a 3rd block with an image in it just like the preceding 2 AD Push blocks.

How do I do it?

Images for reference:

# Answer
> 0 votes
Go to Site settings-\>Visual & Layout -\> Views. You will see the View for Ad push blocks. Click on Edit for this View. Clone the Second ad push block. Be sure to:

* change the name to Third ad push block
* set the Pager to 1 item, skip 2
* save changes

Go to Site settings-\>Visual & Layout -\> Blocks and add the Third ad push block to the Postscript Third Region and click Save blocks.

Reload your page and the block should be visible on the front page.

---
Tags: blocks, advertising
---


# Question
Title: Views: how to display different buttons before/after associated date?
I've got a node that has a deadline date field. I am configuring a view that shows a list of all the nodes.

If we are past the deadline for a given node, I want to show "closed" text. If not, I want to show a link that says "Apply".

I suspect that I may have to use views\_php but I'm not sure exactly how to do this, and I also want to make sure there isn't another way to do it without the performance hit of views\_php.

# Answer
There are three ways to do this kind of conditional logic:

1. Use the views\_php module
2. Make a views field template
3. Write a views widget (or formatter, or something - what is the correct terminology?)

I ended up taking a bit of a shortcut and going ahead with views\_php for now. I'm never going to be dealing with more than a few hundred rows, so I'm not to shaken up over the poor performance of views\_php.

This module is pretty easy to use. Add a "Global: PHP" field. I found `dpm( $data )` and other variations to be very useful.
> 1 votes

---
Tags: datetime, views
---


# Question
Title: How to get view by tag sorting the same as main view sort criteria
I am new to Drupal 7. I have a view set up at /people with the sort criteria set to a field called surname. This is working fine, listing people out alphabetically by surname.

I have tags associated with people and /people/tag/x does list out just the people with tag x (I can't remember whether I had to do anything special to get that working).

However, when viewing people/tag/x, the entries are no longer sorted by surname. I'm not sure what order they are in.

How can I get the main view sort criteria (surname here) to persist when viewing a certain tag at people/tag/x?

Here is an export of the view: http://pastebin.com/8eBSkvn7

Screenshots of view config below, after I tried to add the contextual filters suggested by awm. I have also tried changing the first tag filter to 'Content: has taxonomy term ID'. I had no contextual filters originally.

Many thanks for your time.

# Answer
Your view at /people/tax/%tid is probably from the default taxonomy module. No matter how much you change your /people view, that one won't change this way.

What you need to do is enable the /taxonomy/term/% view (comes disabled by default), which overrides and mimics the default taxonomy display functionality. Now you can change the view to sort to your liking.

There is a complication here however (which you might not need to worry about). This view is used for ALL taxonomy pages (all vocabularies), it is just showing any content tagged with those tags. If you start using those tags for other content (it will start showing that content alongside the people) or if you want to show content the same way for another vocabulary, you will run into the problem that both are output through this view.

To overcome this limitation, you can use the Taxonomy Views Integrator module, which allows you to specify a view for each vocabulary. Details from project page:

> The TVI (Taxonomy Views Integrator) module allows selective overriding of taxonomy terms and/or vocabulary with the view of your choice. Using TVI you can easily create custom views to output all terms in X vocabuarly.
>
> TVI will try not to interfere with views or taxonomy/term page displays if no TVI views exist for the current page request.

Good luck!
> 0 votes

# Answer
You can add another argument/contextual filter (surename). And in the contextual filter settings you could specify the sort criteria when the filter is not in URL. You can choose the sort criteria numeric or alphabetical as in the screen shots

Then

Edit: If you have a content type called directory, and the content type has taxonomy term reference and a field called surname you can replicate the config in the screen shot below and it should work. Note contextual filter and sort criteria settings: 1. Page View config note: 2. Contextual filter taxonomy tag settings 3. How the it will display the summary: 4. How it will display the content, note how it is sorted by surname
> 1 votes

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


title: anonymous User broken

text:
# Question
Title: anonymous User broken
I just migrated the site from sqlite to Postgres, using the drush portabledb-import module

I'm getting a error page only when no user is logged in to the site.

I can get logged in using the login-link generated running

`drush user-login`

and everything works great, all the content is there and accessible, views all work, etc... however log out and I get this message at the home page again

**The website encountered an unexpected error. Please try again later.**

and The watchdog-show reports this
`ID : 8
 Date : 12/Mar 13:07
 Type : php
 Severity : error
 Message : PDOException: SQLSTATE[22P02]: Invalid text representation: 7 ERROR: invalid input syntax for integer: "not yet assigned"
 LINE 4: WHERE (base.uid IN ('not yet assigned'))
 ^: SELECT base.uid AS uid, base.name AS name, base.pass AS pass, base.mail AS mail, base.theme AS theme, base.signature AS signature, base.signature_format AS signature_format, base.created AS created, base.access AS access, base.login AS login, base.status AS status, base.timezone AS timezone, base.language AS language, base.picture AS picture, base.init AS init, base.data AS data, base.uuid AS uuid
 FROM
 {users} base
 WHERE (base.uid IN (:db_condition_placeholder_0)) ; Array
 (
 [:db_condition_placeholder_0] => not yet assigned
 )
 in DrupalDefaultEntityController->load() (line 191 of/usr/local/www/main/includes/entity.inc).`
I've checked the DB and the 0 uid looks fine but just in case I followed the "Restore the anonymous (user ID 0) user record docs located here https://drupal.org/node/1029506

any ideas or suggestions would be greatly appreciated.

# Answer
I don't think you can migrate like that. I am pretty sure the database creation during installation process is different if you're using postgres.
> 0 votes

---
Tags: 7, users, entities, database
---


# Question
Title: User uid incrementing in non sequential manner
I have a drupal site that has been running for about 1 year. there are about 1000 members in the users table

recently I have noticed something very strange the Users uid field is no longer inrementing sequentially.

It now jumps up in the 10s, for example, my last 8 users, the uids went from 7999 to 8068, 8094, 8350, 8416, 8458, 8534, 8566.

So sometimes it is jumping 100s at a time.

How can I work out what might be causing this, and should I be worried?

# Answer
> 1 votes
If it is exactly 10 then it might have to do with MySQL's Auto Increment value https://stackoverflow.com/questions/1686327/change-the-step-auto-increment-fields-increment-by

drupal.org currently uses this feature for master slave replication. Right now all users and nodes being created have a odd value. If you look further back this value was EVEN at one point.

---
Tags: 6, users
---


# Question
Title: Link url paths change from within the 'user' area
I have made a block for a footer which contains 2 simple links. The html code is as follows:

```
<div class="privacyTerms">
<a href="privacy">PRIVACY-POLICY</a>   <a href="terms">TERMS & CONDITIONS</a>
</div>

```

The links work fine as long as i click on them while being anywhere on the website BESIDES the user profile. BUT, as soon as i try to click the links while in my user profile, instead of the URL pointing to "/privacy" or "/terms", the system appends a "/user/" path before the link. So the link becomes as follows: "/user/privacy" and "/user/terms". If i try to access it i get a Access denied. I cannot for the life of me! figure out why this is happening..... What am i missing? Drupal 7

Thanks for your help!!

# Answer
Modify your `href` from

```
<a href="privacy">

```

and

```
<a href="terms">

```

to

```
<a href="/privacy">

```

and

```
<a href="/terms">

```

Notice the slash. That means the path is relative to your base url instead of being relative to your current path.
> 0 votes

# Answer
Use href value like this

```
<a href="<?php echo url('terms');?>">TERMS & CONDITIONS</a>

```

It will work everywhere.
> 0 votes

---
Tags: navigation
---


# Question
Title: How to set a banner slideshow to run if images are only fully loaded
I am new to Drupal, and not that good in Jquery. I just created a Drupal animated banner in Jquery. Each banner image is kinda large about 500kb each jpeg. My problem is, the banner images starts to run even the banner images are not yet fully loaded. Heres the code:

```
(function ($) {
  // Original JavaScript code.
var currentBackground = 0;
var backgrounds = [];
backgrounds[0] = 'http://www.site.com/sites/all/themes/layoutph/images/bg01.jpg';
backgrounds[1] = 'http://www.site.com/sites/all/themes/layoutph/images/bg02.jpg';
backgrounds[2] = 'http://www.site.com/sites/all/themes/layoutph/images/bg03.jpg';
backgrounds[3] = 'http://www.site.com/sites/all/themes/layoutph/images/bg04.jpg';

var customtitle = [];
customtitle[0] = "Welcome to Site";
customtitle[1] = "Site joined force with Site Foundation";
customtitle[2] = "Site Foundation school campaigns for 2014";
customtitle[3] = "New York visited by Site Foundation";

function changeBackground() {
    if(currentBackground > 3 ) currentBackground = 0;
    currentBackground++;
    $('.masterbg').fadeOut(1000,function() {
         $('div.slogan').text( customtitle[currentBackground] );
        $('.masterbg').css({
            'background-image' : "url('" + backgrounds[currentBackground] + "')"
        });
        $('.masterbg').fadeIn(1000);
    });
    setTimeout(changeBackground, 4000);

}
     setTimeout(changeBackground, 4000);

})(jQuery);

```

Can you give me a modification to my code, or theres a function I need to add my code to let the banner images load first before banner slideshow start.

Thank you in advance.

Note: This jquery code is for Drupal.

# Answer
> 0 votes
You can visit this post Slideshow Tutorial to create slide show On drupal site in Drupal standard way. Try to use Drupal standards.

---
Tags: javascript
---


title: D7: Form builder

text:
# Question
Title: D7: Form builder
I have multiple services I want to connect to. I would love to use the native webform within Drupal, but I need to post each webform to different APIs. For example, we have a lead management service where you can post First Name, Last Name, Email, text area to there API. I'm unclear how to accomplish this within Drupal? I cant seem to find a module or other code that will allow me to take advantage of this.

Any help would be appreciated.

Thanks, Mac

# Answer
> 0 votes
Each form using the Drupal API is just a HTML form generated with PHP.

Each form has a unique validation and submit handler if desired. Within each validation and/or submit handler you can choose what to do with the data just like any other form handler you would find in a custom PHP implementation.

So, create your form, create your submit handler, place API code in that submit handler hooking into Drupal where it makes sense and never where it doesn't.

---
Tags: forms, webforms
---


# Question
Title: Is there any way to set line item status in an order?
I want set line item status that if a line item is delivered. In an order, order status is for all the items but line item status is for each product.

Is there any module or something in UI?

I am using drupal commerce module.

# Answer
> 0 votes
Created a custom module for this, used hook\_field\_widget\_form\_alter and insert data in custom table.

# Answer
> 1 votes
You can try using Commerce Delivery module... It supports line items delivery status..

Project page says

> Provides basic functionalities and admin pages to handle deliveries.
>
> Each delivery need to be associated to an order. Each order can have zero, one or multiple deliveries.
>
> A delivery is automatically created on order save if it contains at least one shippable item. Further deliveries can be manually added from the deliveries tab under the orders menu. On the same page each order line item can be moved from one delivery to the other.

---
Tags: 7, commerce
---


# Question
Title: Image style doesn't rebuild after image style flushed
I have practically the same problem as here : https://drupal.org/node/2187443

I've flushed my image style because I edited this image style. Now when I reload the page where the image style should be shown they are missing (404).

What did I missed? shouldn't it be recreated automatically when styles are removed ?

**Edit :**

I found that images couldn't regenerate if 404 error isn't managed by Drupal. I think its very possible, then I made a change in to my `.htaccess` file to make Drupal manage 404 errors.

I am now getting the 403 error upon all my files, that are still not loading. :(

```
Failed to load resource: the server responded with a status of 403 (Forbidden)

```

Then I add +w on my files directory recursively to make sure the writing permission available for all to avoid 403 but nothing happens.

# Answer
Problem solved!!!

After checking that Drupal manages itself 404 errors by checking .htaccess file :

```
# Make Drupal handle any 404 errors.
ErrorDocument 404 /index.php

```

I had to put this line into my settings.php... This is in the Drupal 7.20 release notes :

```
$conf['image_allow_insecure_derivatives'] = TRUE;

```

This thread saved my day.

Wish helps others.
> 0 votes

---
Tags: 7, media
---


# Question
Title: Change style of custom view mode condionally
I have a custom view mode created with ds module, this view mode lists node articles, each article displays like this :

> * title
> * description
> * url
> * **term reference field**
> * some other fields...

I want to add some style condionally depending on the term reference field For example: the first article has the term reference with the value "1", I change the backgroud of the this article to "red" the second article has the term reference with value "2", I change the backgroud to "green" ...

**EDIT :**

this is an image how look like the manage display of some fields :

My interest is with the Flag field: It's a taxonomy field reference having (title, **color** (hexadecimal value), description...) This flag field as you see has the formatter 'editable' (done with editablefieds module), so editors can edit the value of this field.

Now I want to add another field next to Flag witch is the **color** field of the current Flag taxonomy term, and render for example a simple `div` with some `width` and `height` and with the `backgroun-color`, this color field

Hope it's more clear than the old post :)

Thanks in advance.

# Answer
> 1 votes
This is pretty similar to How to provide template for particular view mode? where as you can add custom php code to add further variables used in that viewmode or add simple if/ else/ in\_array to the used template (this is not limited to a custom template - you can always override the default node.tpl.php in your theme.

UPDATE: add only a css class depending on the term reference field.

```
// can also be THEME_
function MYMODULE_preprocess_node(&$vars) {
  if ($vars['view_mode'] == 'myviewmode') {
    if(isset($vars['node']) && isset($vars['node']->field_my_term_reference)) {
      // class to add a general has-term-reference-class
      $vars['classes'][] = 'has-term-reference';
      // add a specific term-reference-class
      foreach($vars['node']->field_my_term_reference as $tid) {
        // class based on term id
        $vars['classes'][] = 'term-id-' . $tid;
        // class based on term name
        $term = taxonomy_term_load($tid);
        $vars['classes'][] = 'term-name-' . $term->name;
      }
    }
  }
}

```

# Answer
> 0 votes
I would probably do this with javascript myself. However, if you want to do it with views alone, you can do this:

Duplicate all of your display fields so there are two of each.

Go into one set of these fields and add your custom CSS tags. Write the CSS in your theme for this tag that does what you want for one condition.

Go into the second set of fields and do the same thing but use new CSS tags with the CSS written for another condition.

Then, in each field of each set, set a condition on the display of these fields based on your reference field value. The fields will only show if the condition is satisfied. This doesn't scale well. If you plan to scale this for more than say, 3 conditions. Comment back and I can come up with another solution for N conditions. (The solution will not be as simple.)

---
Tags: 7, theming, display-suite, nodes
---


# Question
Title: Display node's details instead of ID with relation module
**I have create Two node ‘Partners’ & ‘Project form’.**

**I used relation module & create directional relation between two nodes.**

**Partner’s node have following fields:**

**I have to select multiple partners in Project form, so I added relation widget into project form for create relation with partner’s node. Currently that field’s display partners node id as per below screenshot:**

**Instead of that I want to display partner’s details like (partner name-dept-country-city) & also allow to search using same string as per below screen-shot:**

# Answer
> 0 votes
When you go to the reference fields there will be an option to display view as a reference option. You need to create a view and attach it there.

---
Tags: 7, nodes, entities
---


title: List of Logged out users

text:
# Question
Title: List of Logged out users
In using drupal 7

1 .Is there any way to get List of logged out users for last 30 mins?
2. can we track browser close ?

# Answer
Yes you can, you can do it with views go to admin `admin/structure/views/view` create users views, add filter last acess -30 mintures, you can import below views

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

/* Display: Master */
$handler = $view->new_display('default', 'Master', 'default');
$handler->display->display_options['title'] = 'logout-users';
$handler->display->display_options['use_more_always'] = FALSE;
$handler->display->display_options['access']['type'] = 'perm';
$handler->display->display_options['access']['perm'] = 'access user profiles';
$handler->display->display_options['cache']['type'] = 'none';
$handler->display->display_options['query']['type'] = 'views_query';
$handler->display->display_options['exposed_form']['type'] = 'basic';
$handler->display->display_options['pager']['type'] = 'full';
$handler->display->display_options['pager']['options']['items_per_page'] = '50';
$handler->display->display_options['style_plugin'] = 'default';
$handler->display->display_options['row_plugin'] = 'fields';
/* Field: User: Name */
$handler->display->display_options['fields']['name']['id'] = 'name';
$handler->display->display_options['fields']['name']['table'] = 'users';
$handler->display->display_options['fields']['name']['field'] = 'name';
$handler->display->display_options['fields']['name']['label'] = '';
$handler->display->display_options['fields']['name']['alter']['word_boundary'] = FALSE;
$handler->display->display_options['fields']['name']['alter']['ellipsis'] = FALSE;
/* Sort criterion: User: Created date */
$handler->display->display_options['sorts']['created']['id'] = 'created';
$handler->display->display_options['sorts']['created']['table'] = 'users';
$handler->display->display_options['sorts']['created']['field'] = 'created';
/* Filter criterion: User: Active */
$handler->display->display_options['filters']['status']['id'] = 'status';
$handler->display->display_options['filters']['status']['table'] = 'users';
$handler->display->display_options['filters']['status']['field'] = 'status';
$handler->display->display_options['filters']['status']['value'] = '1';
$handler->display->display_options['filters']['status']['group'] = 1;
$handler->display->display_options['filters']['status']['expose']['operator'] = FALSE;
/* Filter criterion: User: Last access */
$handler->display->display_options['filters']['access']['id'] = 'access';
$handler->display->display_options['filters']['access']['table'] = 'users';
$handler->display->display_options['filters']['access']['field'] = 'access';
$handler->display->display_options['filters']['access']['value']['value'] = '-30 minutes';
$handler->display->display_options['filters']['access']['value']['type'] = 'offset';

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

```
> 1 votes

---
Tags: users
---


# Question
Title: Increase the Length of the block title field
How to increase the length of the block title of a block?. By default its length is set to 64 characters. Please Help.

Thanks

# Answer
That will be tricky. Block titles can only be 64 character. You need to alter the database and make the title field for blocks longer.

Put this in a custom modules .install file.

```
function mymodule_schema_alter(&$schema) {
  // Change length of title field for block.
  $schema['block']['fields']'title'] = array(
    'type' => 'varchar',
    'length' => 128,
    'not null' => TRUE,
    'default' => '',
    'description' => 'Custom title for the block. (Empty string will use block default title, <none> will remove the title, text will cause block to use specified title.)',
    'translatable' => TRUE,
  );
}

```

and then alter the block title maxlength attribute in a form alter

`$form['block_settings']['title']['#maxlength'] = 128;`

Another way is that you put your long title in the content of the block instead of using the "real" block title field.

In Drupal 7 I would hint you to checkout Bean module, but as this is Drupal 6 I'm not sure.
> 3 votes

# Answer
I think this is a cleaner way of accomplishing this:

in mymodule.module:

```
function mymodule_form_alter(&$form, &$form_state, $form_id) {
  if($form_id == 'block_admin_configure') {
    $form['settings']['title']['#maxlength'] = 128;
  }
}

```

in mymodule.install:

```
function mymodule_update_1() {
  $alt_spec = array(
    'type' => 'varchar',
    'length' => 128,
    'not null' => FALSE,
  );
  db_change_field('block', 'title', 'title', $alt_spec);
}

```

Credit goes to the commentors in this thread https://drupal.org/node/664834
> 0 votes

---
Tags: 6, blocks
---


# Question
Title: Department-based web site in which users can only edit content in their own department
What would be the steps to build a web site with different departments in which the users with edit permission can only edit content in their own department? Content types would be shared, e.g. the "page" content type should be available to all of them.

I've read this can be accomplished with PURL \+ spaces, but I am not sure this is still the best option, as most posts about it are from a few years ago.

# Answer
> 0 votes
You should look at the Organic Groups (OG) modules.

With OG, departments (i.e. "groups") is set up and managed by means of the graphical user interface. It simply provides a way to delimit a department in terms of content and members. Unlike the Spaces module, there is no total separation between departments. OG modules presents an evironment where departments appear to exist side by side within a *single* website. In other words, the groups are non-hierarchical, leverage the same theme and share common modules, etc.

Within this framwork, OG can provide multiple levels of privacy and membership.

It allows one to create content types that can associate any number of nodes to a group node. Then, developers and users can create pages that only display content intended for that particular department.

Note, however, that OG does *not* provide a base URL for a department namespace (e.g. `http://example.com/startrek/` for a department named "Startrek".) If you want this, the convention approach has been to install OG + Spaces + PURL to get this.

However, this article suggests an alternative approach building on a sandbox module named OG Token. I haven't tested this tho'. There is also another bridge module, named OG Purl that may do this for you.

**Alternate, lightweight solution:** If you can relax the requirement that all departments shall have access to the same content types, you can implement this with the core alone (i.e. *without* any external module), just using Drupal's built-in ability to clone content types and built-in role based access.

For instance, let say you want to have a department named "Startrek" (for fans of the classic TV-series). Clone the *Article* content type and call the clone "*StartrekArticle*". Now create a role named "*StartrekEditor*".

Navigate to *Administration » People » Permissions* and scroll down do the *Node* section. Grant the role *StartrekEditor* the following permissions:

* StartrekArticle: Create new content
* StartrekArticle: Edit own content
* StartrekArticle: Edit any content
* StartrekArticle: Delete own content
* StartrekArticle: Delete any content

Now, just give any user that is going to be editor in the *Startrek* department the role *StartrekEditor*.

Also note creating department-specific content types have no impact on the user's ability to *view* content. The Drupal default is that any user may view any content, and users will not even be aware of the fact that they're viewing content in different departments that differ by name only.

To have a base URL for a department namespace using this lightweight solution, you still need to install PURL, but you will not have to deal with heavyweight modules such as OG + Spaces.

---
Tags: users, organic-groups, 7
---


# Question
Title: Prevent indexing the article content after 15 lines.
I am using search API and Solr . I need to index only the first 15 lines of each article . the remaining lines after 15 lines has content which i don't want to index . Please suggest if its possible .

# Answer
> 1 votes
Anything is possible :)

You can write a custom module to alter the behaviour of search api. In the search api module directory there is a file search\_api.api.php, which gives information on the functions you can use to alter its behaviour.

For this you would make a custom data alteration like this - replace modulename and ModuleName with the name of your module (case sensitive).

This part goes in your .module file:

```
/**
 * Define available data alterations.
 *
 * Registers one or more callbacks that can be called at index time to add
 * additional data to the indexed items (e.g. comments or attachments to nodes),
 * alter the data in other forms or remove items from the array.
 *
 * Data-alter callbacks (which are called "Data alterations" in the UI) are
 * classes implementing the SearchApiAlterCallbackInterface interface.
 *
 * @see SearchApiAlterCallbackInterface
 *
 * @return array
 *   An associative array keyed by the callback IDs and containing arrays with
 *   the following keys:
 *   - name: The name to display for this callback.
 *   - description: A short description of what the callback does.
 *   - class: The callback class.
 *   - weight: (optional) Defines the order in which callbacks are displayed
 *     (and, therefore, invoked) by default. Defaults to 0.
 */
function modulename_search_api_alter_callback_info() {
  $callbacks['modulename_character_limit'] = array(
    'name' => t('Character limit'),
    'description' => t('Limit the number of characters that get indexed for a field.'),
    'class' => 'ModuleNameCharacterLimit',
    'weight' => 100, // Probably better for this one to run later than others so they get to run on the full content before you trim it. Can still be reordered via the UI though.
  );

  return $callbacks;
}

```

This goes in a file named modulename\_processor\_character\_limit.inc that goes in a sub-directory of your module called 'includes':

```
<?php

/**
 * @file
 * Contains ModuleNameCharacterLimit.
 */

/**
 * Processor for limiting the number of characters of a field that are indexed.
 */
class ModuleNameCharacterLimit extends SearchApiAbstractProcessor {

  public function configurationForm() {
    $form = parent::configurationForm();
    $form += array(
      'char_limit' => array(
        '#type' => 'textfield',
        '#title' => t('Character limit'),
        '#description' => t('The maximum number of characters of the field that will be added to the index.'),
        '#default_value' => $this->options['char_limit'],
        '#required' => TRUE,
        '#element_validate' => array('element_validate_integer_positive'),
      ),
    );

    return $form;
  }

  protected function processFieldValue(&$value) {
    // Chop unwanted characters from the value.
    $value = substr($value, 0, $this->options['char_limit']);
  }

}

```

This goes in your module's info file:

```
files[] = includes/modulename_processor_character_limit.inc

```

This will add a data alteration you can configure via the search api UI where you do things like configure the HTML filter. You can set the number of characters to limit indexing to for our fields. - In your case, set to 15 and away you go.

(Full disclosure - I haven't tested this :))

**\[Edit\]**

As per your comment below, if you want to remove all text after a specific string (in this case "The below lines are confidential" you can do away with the char\_limit setting and have a setting where you configure the text to check for (I'm calling it search\_text) then change the processFieldValue() function to be:

```
protected function processFieldValue(&$value) {
  // If the text is found anywhere in the value.
  if (($pos = strpos($value, $this->options['search_text'])) !== FALSE) {
    // Cut off everything after that.
    // The $pos is the start of the string so if you want to also
    // exclude the string itself use $pos, otherwise to include the
    // string use $pos + strlen($this->options['search_text'])
    $value = substr($value, 0, $pos);
  }
}

```

Note that strpos() will return the position of the first occurance if the string occurs multiple times, which I would think is what you would want in this case.

See PHP string functions for more info on these and other string manipulation functions.

---
Tags: search
---


# Question
Title: How to generate a list of all valid URLs served by my site
Is there a way to generate a list of all valid URLs that a site will resolve, including redirects?

Specifically, all views, nodes, and redirects (the *from* and *to*.)

The list is required for record reasons by a college in another department.

An answer would be especially useful if it didn't require a code change, as it's production site, and a code change would have to go through code review and require a release, but if it's necessary then it's necessary.

Module wise, among many others, xmlsitemap, redirect, path redirect import, pathauto and pathologic are installed. I'm not sure if any of those might be of any use.

As a second question, if there isn't a way of automatically generating all of the URLs in a pleasantly formatted list, then besides manually collecting all of the views URLs and the redirects urls, where else should I be looking?

# Answer
There exists a number of website checking tools (aka. robots or spiders) that will crawl a given website and generate a number of reports, including a report of all URLs found on that site by recursively crawling the site from some starting point (crawl foundation page).

Below are links to three such tools that I've used for this purpose:

Note that these will only report URLs that are *reachable* from the crawl foundation page. If your site consists of sub-sites that are *not* reachable from each other, you need to set up more than one crawl foundation.
> 2 votes

---
Tags: 7, uri
---


# Question
Title: Non-CRUD resource action with Drupal 7 / Services 3
I can't get this simple example working with a custom action.

I had to move it form here How can I create a simple non-CRUD resource action with Drupal 7 / Services 3? to an own question.

The example looks like this for CRUD retrieve:

```
function mymod_services_resources() {
 $api = array(
   'test' => array(
     'operations' => array(
       'retrieve' => array(
         'help' => 'Drupal 7 Services 3 test',
         'callback' => '_mymod_test',
         'access callback' => 'user_access',
         'access arguments' => array('access content'),
         'access arguments append' => FALSE,
         'args' => array(
           array(
             'name' => 'fn',
             'type' => 'string',
             'description' => 'Function to perform',
             'source' => array('path' => '0'),
             'optional' => TRUE,
             'default' => '0',
           ),
         ),
       ),
     ),
   ),
 );
  return $api;
}

function _mymod_test($fn) {
  return "Test is working";
}

```

This works fine and returns for http://myhost.dev/endpoint/test/retrieve

`Test is working`

But when i try a custom action like this

```
function mymod_services_resources() {
 $api = array(
   'test' => array(
     'actions' => array(
       'custom' => array(
         'help' => 'Drupal 7 Services 3 test',
         'callback' => '_mymod_test',
         'access callback' => 'user_access',
         'access arguments' => array('access content'),
         'access arguments append' => FALSE,
         'args' => array(
           array(
             'name' => 'fn',
             'type' => 'string',
             'description' => 'Function to perform',
             'source' => array('path' => '0'),
             'optional' => TRUE,
             'default' => '0',
           ),
         ),
       ),
     ),
   ),
 );
  return $api;
}

function _mymod_test($fn) {
  return "Test is working";
}

```

http://myhost.dev/endpoint/test/custom returns just a 404

When i try it like this

```
function mymod_services_resources() {
 $api = array(
     'actions' => array(
       'custom' => array(
       ...

```

It is not shown in the Services list.

@Clive Yes, i tried to GET that resource. But when i try to POST

```
curl -i -X POST --header "X-CSRFToken: p2BMMItuM6QD9HvdPulxS5IBnXDBnczT46VoLLSqJLM" http://myhost.dev/endpoint/test/custom

```

i get a HTTP/1.1 404 Not found: Could not find the controller.

But this solution - see the comments new user have to last 8 hours to answer own question :) yields to an other question.

How can i get the whole path, not just index 0 'source' =\> array('path' =\> '0'),

I like to get all path segments after the controller. in my case

myhost.dev/endpoint/test/foo/bar/1/2/3

i liked to get foo/bar/1/2/3 with index 0 i can get just foo.

# Answer
I got it. I don't have to use myhost.dev/endpoint/test/retrieve in the first example. It is posible to use myhost.dev/endpoint/test/Whateveryouwant. So i understand, i can use the retrieve action and it is not mandatory part of the resource path.
> 2 votes

---
Tags: services, 8
---


# Question
Title: How do I iterate through images using file_create_url()?
I am trying to add Lightbox feature to images. This is the code I used in the node template.

```
<p>
<a class="lightbox" href="<?php echo file_create_url($node->field_images['und'][0]['uri']); ?>" data-plugin-options='{"type":"image"}'>
 <?php print render($content['field_images']); ?>
</a>
</p>

```

This works fine if I have the "field\_image" limited to 1 value, but in my case the field\_image can have several values (the user can upload several images).

For the first image `$node->field_images['und'][0]['uri'])` is correct; for the second image the path would be `$node->field_images['und'][1]['uri'])`.

So how should I iterate through multiple images?

**UPDATE**(per @Clive feedback): Here is my updated code:

```
<?php if ( ($items = field_get_items('node', $node, 'field_images')) ) {
  foreach ($items as $item) {
   $uri = $item['uri']; ?>
 <p>
<a class="lightbox" href="<?php print $uri ?>" data-plugin-options='{"type":"image"}'>
<?php print render($content['field_images']); ?>
</a>
</p>
<?php
}
}
?>

```

I have 2 issues with it: The URL is not correct per my comment below. Second on every iteration it prints all images. For example if I have 2 images: it prints {img1/url1, img2/url1} and then on the next iteration it prints {img1/url2, img2/url2} instead of img1/url1 on the first iteration and then on the second iteration img2/url2.

How would I modify the 'print render($content\[\]);' to print partial content?

How would I modify the $uri to print the full URL path?

**UPDATE2**(per @Rupesh feedback): Here is my updated code:

```
<?php if ( ($items = field_get_items('node', $node, 'field_images')) ) {
  foreach ($items as $item) {
   $uri = $item['uri']; ?>
 <p>
<a class="lightbox" href="<?php print file_create_url($uri); ?>" data-plugin-options='{"type":"image"}'>
<?php print render($content['field_images']); ?>
</a>
</p>
<?php
}
}
?>

```

Now the only issue I have is that on every iteration it prints all images. For example if I have 2 images: it prints {img1/url1, img2/url1} and then on the next iteration it prints {img1/url2, img2/url2} instead of img1/url1 on the first iteration and then on the second iteration img2/url2.

Now I need I modify the 'print render($content\[\]);' to print a partial content on every iteration. For example on first iteration it will be `print render($content[][0]);` and on second iteration it will be `print render($content[][1]);` etc.

Something like that (it does not work, with a blank page )

```
<?php for ($i = 0; $i < count($content['field_images']); $i++):
 print render($content['field_images'][$i]); ?>
 endfor;
?>

```

The count is wrong, it outputs 17 instead of just 2 images. What would I change in in the code above to get it to work?

Thanks.

# Answer
> 0 votes
After couple of hours of frustration. Here is my solution to my question.

```
<?php for ($i = 0; $i < 8; $i++):  ?>
<p>
<a class="lightbox" href="<?php echo file_create_url($node->field_images['und'][$i]['uri']); ?>" data-plugin-options='{"type":"image"}'>
<?php print render($content['field_images'][$i]); ?>
</a>
</p>
<?php endfor; ?>

```

I hardcoded $i (not ideal), since I am limiting the number of images that can be uploaded. Not ideal, but it works. Also `count($content['field_images']);` returns 17 instead of the actual number of images of 2.

# Answer
> 1 votes
You're probably looking for a for loop, but Drupal has a specific function for this, `field_get_items()`:

```
if ( ($items = field_get_items('node', $node, 'field_images')) ) {
  foreach ($items as $item) {
    $uri = $item['uri'];
  }
}

```

---
Tags: 7, media
---


title: Renaming a Content Type Machine Name

text:
# Question
Title: Renaming a Content Type Machine Name
I have a really annoying typo right through my Drupal install (db table names, modules...you name it it's right through). Ideally I would like to fix the typo and not recreate the content type/modules etc.

The process I have gone through so far:

Find/replace all instances of the typo in the Database using this Script https://gist.github.com/leewoodman/9544808

I then renamed all the tables where the typo occurred using this:

RENAME TABLE field\_data\_field\_accomodation\_ref TO field\_data\_field\_accommodation\_ref, field\_data\_field\_offer\_accomodation TO field\_data\_field\_offer\_accommodation, field\_revision\_field\_accomodation\_ref TO field\_revision\_field\_accommodation\_ref, field\_revision\_field\_offer\_accomodation TO field\_revision\_field\_offer\_accommodation;

Then I ran this ruby script to replace all instances of the typo in my files/file/folder structure: https://gist.github.com/dvdsgl/4600317

Then I deleted all caches manually in the DB using:

```
SELECT
  CONCAT('TRUNCATE TABLE ', TABLE_SCHEMA, '.', TABLE_NAME, ';') AS table_name
FROM information_schema.TABLES
  WHERE TABLE_SCHEMA = 'my-db-name'
    AND TABLE_NAME LIKE 'cache_%'
    AND TABLE_TYPE = 'BASE TABLE'

```

I am pretty confident I fixed all the typos but I then get an entityreference error.

Am I missing another step here somewhere?

# Answer
> 2 votes
It is impossible to tell whether you've missed something without having complete access to your schema. The fact that you get an entityreference error after clearing all caches is not a good sign.

A safer approach to renaming a content type machine name is to recreate the bundle with the correct machine name, and then use Node convert to convert it from the old machine name to the new one.

> Node Convert ... gives the ability of converting the node from its current node type to another node type. Also it gives the ability of transfering all the custom CCK field values of the current node type to the destination CCK fields, or discard them. As of 5.x-1.4 you can bulk convert many nodes of the same type, to another one that can be accessed in Administer → Content → Convert Nodes.

It allows both single node a and multiple node conversion. Here is a link to the documentation.

I've used the module for a similar use case as yours, with success.

# Answer
> 0 votes
You will have to edit all the entity reference fields that reference that content type or use a changed field name. The quickest way I found to do this is manually.

Here's what I did: in PHPMyAdmin, MySQL Workbench or similar, I ran this query:

```
SELECT * FROM field_config WHERE type = 'entityreference'

```

This shows all the entityreference fields configured in the site. I then edited the values of the 'data' column of the appropriate fields, changing the instances of the old content type/field names with that of the new. Note that the text is actually a serialised PHP array, so since the new values are longer, the number in front of each string must be changed to match the real length of the string.

For example, **s:12:accomodation** will become **s:13:accommodation**.

You will get a WSOD if you made a mistake, so save a copy of the original data text somewhere (ie., a text editor) to work from in that case.

# Answer
> 0 votes
You will at least need to update the two tables "field\_config" and "field\_config\_instance" as they save the field name in the database. But as you can see in the "data" column, there are some serialized datas that also contains the field name.

So I just think it's impossible/really hard to update a field name programmatically. Read Jovean answer for more explanation.

I would suggest to use Gisle solution.

Otherwise, you can also create a new field in your content type, and make a script to loop over all nodes of the content type, and copy the value to the new field. Afterwards delete the old field.

---
Tags: 7, caching, entities
---


# Question
Title: How to map user/password to a mobile theme?
I'm working on a mobile version of a forgot password page, the problem I have is the mobile theme is triggered when users are on a page with a URL like:

`example.com/m/about`

Here, `about` would be a node and it's a mobile version of the `example.com/about`.

So I read through drupal documentation and looked at Customizing and Overriding User Login page...but the issue I have is, how do I go about mapping `example.com/user/password` to a mobile version since it's not a node it's a template (`node--user.tpl.php`)?

# Answer
You should be able to get around your problem (I say should because I haven't actually tried this):

Make a custom module that creates a menu item for the required url and makes it call the user password form.

```
/**
 * Implements hook_menu().
 */
function MODULENAME_menu() {
  $items = array();

  // A replica of the password reset page for mobile.
  // Based on the original menu item in user_menu().
  $items['m/user/password'] = array(
    'title' => 'Request new password',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('user_pass'),
    'access callback' => TRUE,
    'type' => MENU_NORMAL_ITEM,
    'file' => 'user.pages.inc',
    'file path' => drupal_get_path('module', 'user'),
  );

  return $items;
}

```

I foresee you having to do this for some other pages too.

Personally I would probably not make a mobile site in this fashion, I would use the same pages for mobile and non-mobile and then make them look different based on screen size.
> 2 votes

---
Tags: users, theming
---


# Question
Title: Does drupal create new file in image styles?
There are many images with 3000X2000 dimensions and I created a view of their content type. I also created a new image style, it is 90X70. This view displays the images in this size, but here is my question, which image size is loaded on the page load?

# Answer
> 2 votes
When you create an image style, a folder is created in `/sites/default/files/styles/` that holds processed versions of your image. When you select to use that style in views or anywhere else, only the processed image is loaded. It wouldn't load the full size image if you have it set to the 90x70 style.

# Answer
> 0 votes
use Chrome Developer Tools or Firebug and simply right click on an image in your webpage and see the image URL and Dimensions with `Inspect this Element`.

People can give you an verbatim answer -- but if you find the answer yourself you'll learn more.

# Answer
> 0 votes
You can create your own image preset or re-size the existing one by configuring the option under:

```
admin/config/media/image-styles

```

Then use this image style accordingly by selecting the required style in configuration of image field

---
Tags: views, media
---


# Question
Title: Custom action to create a new entity based on a fields of an existing entity
There are two entity types on my site: 1) an application for participation (entityform) and 2) a participant profile (node). At first user creates an application for participation. And then site administrator must create somehow a new participant profile and fill its fields from an entityform created by user.

How to create such an action "Create participant profile from application"? The action must be accessible to administrator as a button or a menu tab item on a entityform view page.

# Answer
> 0 votes
If I have to do that, I would take these steps to achieve what you want here :

* Make a custom module for it.
* Add a path by help of hook\_menu.
* Make a custom function for menu callback & mention the same in there.
* Inside function, get current node ID (entityform submission, where admin is there) by something like `if (arg(0) == 'node' && is_numeric(arg(1))) $nodeid = arg(1);`
* Then write code to load a entity by ID by help of entity\_load & take all the values in custom vars as per requirement for new node(profile).
* Save the node of type profile by help of node\_save.
* Insert a link(CREATE PROFILE) mapped with created path(by above hook\_menu) to the node view of entityform submission by help of hook\_node\_views.

Now when ever your inserted link will be clicked, a profile will be created.

You can restrict the access of created path by implementing hook\_permission & give access to admin only.

You are free to do some other stuff as well, like if profile node exist for entityform submission them make link disappear as well. It all depends upon your need & plan :)

# Answer
> 0 votes
Thanks, RajeevK! I think I've found a simpler solution. Add an edit/add link to an entityform view page:

```
function MODULE_menu_local_tasks_alter(&$data, $router_item, $root_path) {
  if ($root_path === 'entityform/%') {
    $entityform = $router_item['page_arguments'][0];
    if ($entityform->type === 'onfit_awards2014_join') {
      // Check whether a participant profile was created already.
      // field_application_form is a back reference from a participant profile
      // to a source appication form
      $participant_id = NULL;
      $query = new EntityFieldQuery();
      $query->entityCondition('entity_type', 'node')
        ->entityCondition('bundle', 'onfit_awards_participant')
        ->fieldCondition('field_application_form', 'target_id', $entityform->entityform_id)
        ->range(0, 1);
      $result = $query->execute();
      if (is_array($result['node']) && count($result['node'])) {
        $participant_id = array_shift(array_keys($result['node']));
      }

      // Create either an edit link or an add link
      if (!empty($participant_id)) {
        $link = menu_get_item('node/' . $participant_id . '/edit');
        $link['title'] = 'Правка профиля участника';
      }
      else {
        $link = menu_get_item('node/add/onfit-awards-participant');
        $link['title'] = 'Создать профиль участника';
        $link['localized_options']['query'] = array(
          'entityform' => $entityform->entityform_id,
        );
      }
      $data['tabs'][0]['output'][] = array(
        '#theme' => 'menu_local_action',
        '#link' => $link,
      );
      $data['tabs'][0]['count']++;
    }
  }
}

```

Copy field values from an application form to a new participant profile:

```
function MODULE_node_prepare($node) {
  if (empty($node->nid)) {
    // Find a query parameter of the form:
    // ?entity_type=entity_id
    $params = drupal_get_query_parameters();
    $entity_types = entity_get_info();
    $entity_type = NULL;
    $entity_id = NULL;
    foreach ($params as $key => $value) {
      if (is_numeric($value) && !empty($entity_types[$key])) {
        $entity_type = $key;
        $entity_id = $value;
        break;
      }
    }

    // If entity_type and entity_id were specified, copy all field values
    // from the source entity to a current node
    if (!empty($entity_type) && !empty($entity_id)) {
      $entityform = entity_metadata_wrapper($entity_type, $entity_id);
      $entityform_type = $entityform->type->value()->type;
      $node_wrapper = entity_metadata_wrapper('node', $node);
      $src_fields = field_info_instances($entity_type, $entityform_type);
      $dest_fields = field_info_instances('node', $node->type);
      foreach ($dest_fields as $name => $desc) {
        if (!empty($src_fields[$name])) {
          $value = $entityform->$name->value();
          $node_wrapper->$name->set($value);
        }
      }

      // Some custom logic
      if ($entityform_type === 'onfit_awards2014_join' &&
          $node->type === 'onfit_awards_participant') {
        $last_name = $entityform->field_last_name->value();
        $first_name = $entityform->field_first_name->value();
        $node_wrapper->title->set($last_name . ' ' . $first_name);
        $node_wrapper->field_application_form->set($entity_id);
      }
    }
  }
}

```

---
Tags: entities, actions
---


# Question
Title: how to put permission to only paid users can print something in my drupal site
I have a Drupal site which I plan on putting a print pdf function to its contents. How do I manage this so that only paid users can print the pdf?

# Answer
> 5 votes
If you mean controlling who can *view/download* (i.e. be 'served') the PDF then you need to read up on the private file system (Working with files contains a pretty good introduction).

If you mean showing the PDF to anyone who requests it, but only allowing paid users to *print* from it, you can't. That would be controlling a user's browser, which you can't do for obvious security reasons. It's the nature of the web; if you want to distribute content, you have to face the fact that it can be copied unless you go down the DRM route.

The only DRM solution I know of for PDFs is Adobe Content Server; it's written in Java and is a real pain in the proverbial but it does work. You can control the number of times a person can print or even copy/paste data from the PDF.

It does introduce a really annoying workflow, though, that you'll need to explain in detail to your users; and it ain't cheap.

# Answer
> 2 votes
The Adobe PDF format allows installation of several types of DRM (Digital Rights Management) that may limit what viewers may do with it.

(For the record: This is a feature of standard PDFs that people normally view with the free Acrobat reader. It has nothing to do with Adobe Digital Editions or the Adobe Content Server).

You can set the security of any PDF document when you create the PDF document by means of Adobe Acrobat Professional . To set the permissions security, type ctrl-D for "Document Properties" and select the security tab. Select "Passord Security" and pick a password. Then set the "Printing allowed" permission to "None" as shown in the screen capture below. The password will not be required to view the document, but will be required to print it.

To integrate this with Drupal, install the Field Permissions module. Store the password used to protect the PDF permissions in a text field in the node the PDF is attached to. Use Field Permissions to restrict access to the field containing this password to premium users (i.e. to user that has paid for access printable PDFs).

This means that everybody can view the PDF, but only those granted the right to view the password text field will be able to print it.

---
Tags: users, files
---


# Question
Title: dev site reverts to production site url when clearing cache
I have moved a copy of my production site to a development box. When I clear cache at `admin/settings/performance` or save settings on a theme, all of a sudden the URL jumps from `localhost/example/admin/build/themes/settings/theme` to `www.example.com/admin/build/themes/settings/theme` for instance. I have cleared all of my cache tables manually via phpmyadmin and for the browser (chrome, cleared everything "from the beginning of time"). I can't successfully run cron .

EDIT: If I had enough reputation, I would downvote myself. I had the "base url" setting enabled in settings.php.

# Answer
@Clive's suggestion jarred my memory and I figured it out. I have a multisite setup that I was migrating and had the `base url` setting in settings.php set to `www.example.com` and I had forgotten to change it to the localhost url. When I commented out the base url setting, everything was fine.
> 1 votes

---
Tags: caching, uri, migrations, configuration
---


# Question
Title: How can I get the filesize of an image with an image style programmatically
I need to make two links for an image, one link points to a low res version the other to the original file.

I'm creating the link for the low res with image\_style\_url

```
<?php print image_style_url('img-lib', $data->field_field_photo[0]['raw']['uri']) ?>

```

How can I print out the filesize of the image with `img-lib` style?

# Answer
> 7 votes
You can get the size of the original image easily:

```
$size = filesize($data->field_field_photo[0]['raw']['uri']);

```

But the size of an image file behind a derivative path is impossible to get reliably. The files aren't generated until the URL is first visited, so the file may simply not exist yet.

For those that *do* already exist, you can use `image_style_path()`:

```
$path = image_style_path('img-lib', $data->field_field_photo[0]['raw']['uri']);
if (file_exists($path)) {
  $size = filesize($path);
}

```

If it's 'mission-critical' to get the file size, you can always force-create the derivative there and then with `image_style_create_derivative()`:

```
$path = image_style_path('img-lib', $data->field_field_photo[0]['raw']['uri']);
if (file_exists($path)) {
  $size = filesize($path);
}
else {
  if (image_style_create_derivative('img-lib', $data->field_field_photo[0]['raw']['uri'], $path) === TRUE) {
    $size = filesize($path);
  }
}

if (!isset($size)) {
  // Something went wrong creating the derivative...
}

```

It's worth noting that you shouldn't do all (or any really) of the above directly in a template file. Instead, move your logic out to a preprocess function and pass variables in.

And if you're looking for full-on 'best practice', instead of accessing the field data directly through the array (e.g. `$data->field_field_photo[0]['raw']['uri']`), prefer `field_get_items()` for procedural-style, or an `EntityMetadataWrapper` if you're comfortable with OO.

---
Tags: media
---


title: Output Field value in field.tpl

text:
# Question
Title: Output Field value in field.tpl
I have a content type "Produkte" with the field "field\_produktmerkmale" which is a term reference field addressing the taxonomy vocabulary "Produktmerkmale". The terms have a title, a description and an image field.
When I display "field\_produktmerkmale" it shows only the title with a link to the taxonomy, but I want to display the images instead of the title. So I created the "field--field\_produktmerkmale--produkte.tpl.php" to modify the output.
**But how do I know address the image from this template?**
var\_dump($items) gives me the following result: **(Just an excerpt of the first element)**

```
[1]=> array(4) {
    ["#type"]=> string(4) "link"
    ["#title"]=> string(15) "Batteriebetrieb"
    ["#href"]=> string(16) "taxonomy/term/89"
    ["#options"]=> array(3) {
        ["entity_type"]=> string(13) "taxonomy_term"
        ["entity"]=> object(stdClass)#154 (11) {
            ["tid"]=> string(2) "89"
            ["vid"]=> string(1) "9"
            ["name"]=> string(15) "Batteriebetrieb"
            ["description"]=> string(68) "Batteriebetrieb: Mit automatischer Abschaltung zur Batterieschonung"
            ["format"]=> string(8) "php_code"
            ["weight"]=> string(1) "0"
            ["language"]=> string(3) "und"
            ["i18n_tsid"]=> string(1) "0"
            ["vocabulary_machine_name"]=> string(15) "produktmerkmale"
            ["field_icon2"]=> array(1) {
                ["und"]=> array(1) {
                    [0]=> array(15) {
                        ["fid"]=> string(3) "805"
                        ["uid"]=> string(1) "1"
                        ["filename"]=> string(6) "CE.gif"
                        ["uri"]=> string(21) "public://icons/CE.gif"
                        ["filemime"]=> string(9) "image/gif"
                        ["filesize"]=> string(3) "525"
                        ["status"]=> string(1) "1"
                        ["timestamp"]=> string(10) "1394787947"
                        ["type"]=> string(5) "image"
                        ["rdf_mapping"]=> array(0) {
                        }
                        ["image_dimensions"]=> array(2) {
                            ["width"]=> string(2) "50"
                            ["height"]=> string(2) "50"
                        }
                        ["alt"]=> string(0) ""
                        ["title"]=> string(0) ""
                        ["width"]=> string(2) "50"
                        ["height"]=> string(2) "50"
                    }
                }
            }
            ["rdf_mapping"]=> array(5) {
                ["rdftype"]=> array(1) {
                    [0]=> string(12) "skos:Concept"
                }
                ["name"]=> array(1) {
                    ["predicates"]=> array(2) {
                        [0]=> string(10) "rdfs:label"
                        [1]=> string(14) "skos:prefLabel"
                    }
                }
                ["description"]=> array(1) {
                    ["predicates"]=> array(1) {
                        [0]=> string(15) "skos:definition"
                    }
                }
                ["vid"]=> array(2) {
                    ["predicates"]=> array(1) {
                        [0]=> string(13) "skos:inScheme"
                    }
                    ["type"]=> string(3) "rel"
                }
                ["parent"]=> array(2) {
                    ["predicates"]=> array(1) {
                        [0]=> string(12) "skos:broader"
                    }
                    ["type"]=> string(3) "rel"
                }
            }
        }
        ["attributes"]=> array(2) {
            ["typeof"]=> array(1) {
                [0]=> string(12) "skos:Concept"
            }
            ["property"]=> array(2) {
                [0]=> string(10) "rdfs:label"
                [1]=> string(14) "skos:prefLabel"
            }
        }
    }
}

```

**The data I need would be in field\_icon2 with the filename and in description** (as a tooltip). But how do I address ut correctly?

I tried:

```
<?php print $item['#options']['entity']['description']; ?>

```

But I get and error:

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

```

# Answer
`$item['#options']['entity']` is an object, so you should be accessing "description" this way:

`$item['#options']['entity']->description`

But as Adam stated, you should render it the right way with `field_view_field` method. The error you mentioned it's just a problem with sending the right parameters to the method.
> 0 votes

---
Tags: entities
---


title: How to output a field as a link in D7

text:
# Question
Title: How to output a field as a link in D7
On the user/edit pages I would like to display a link based on a (text?)'field' The link should only be displayed to users with the proper permission. For this, I'll use the Field Permissions module.

My problem is that I don't to know how to output the field as a link.

I have tried the Link module but this seems to give users the ability to input a link.

In my case users should only see the link on their account page.

Any help appreciated.

# Answer
> 2 votes
it sounds like you aren't trying to add a field, but rather, are trying to DISPLAY a field (link, more specifically) on the user account page.

What you need to do is simply edit the user profile template of your theme to show the link you need in the footer/header or wherever else you need.

Something like the below should work:

* Go into our drupal root folder and from /modules/user/ copy the **user-profile.tpl.php** file and paste it into your theme's /templates folder
* It should just have code that looks like this to begin with:

> ```
> <div class="profile"<?php print $attributes; ?>>
>    <?php print render($user_profile); ?>
> </div>
>
> ```

Add your link at the bottom, making the template file something like

> ```
> <div class="profile"<?php print $attributes; ?>>
>     <?php print render($user_profile); ?>
>     <?php if (in_array('my_role', $user->roles)): ?>
>        <p><a href="http://www.example.com">My link</a></p>
>     <?php endif; ?>
>    </div>
>
> ```

* Make sure you clear your caches, visit a user account page, and make sure it's all working.
* Adjust the HTML above as you see fit...

---
Tags: navigation
---


title: Adding a linked table to user profile

text:
# Question
Title: Adding a linked table to user profile
I have a business case need to add a linked content type or table to a user's profile. Basically, when they register an account, we want to know the make, model, and year of any recreational vehicles that they own. I would like them to be able to enter as many vehicles as they currently own, each on their own row. We will eventually be reporting on this data. The make, model and year will be drawn from taxonomies, and the table or content type would basically consist of UID, Make, Model, Year.

I'm still relatively new to some of the more advanced features of Drupal, how would I accomplish this?

# Answer
> 0 votes
Sounds like a job for Field Collection:

> Provides a field-collection field, to which any number of fields can be attached.

and Field Collection Table:

> Provides a table formatter for the Field Collection module.

# Answer
> 0 votes
You could try Inline Entity Form:

> Provides a widget for inline management (creation, modification, removal) of referenced entities.

---
Tags: users, entities
---


title: How does decode_entities() work?

text:
# Question
Title: How does decode_entities() work?
Let's say `$node->field_description[LANGUAGE_NONE][0]['value']` contains `'We're in this together'`.

This code doesn't output what I expect.

```
$node = menu_get_object();
if (isset($node->field_description[LANGUAGE_NONE][0]['value'])) {
  $text = strip_tags($node->field_description[LANGUAGE_NONE][0]['value']);
  $text = decode_entities($text);
}

```

instead of `'We're in this together'`, I get `'We're in this together'`.

The full hook implementation is the following.

```
function MY_MODULE_page_alter($page) {
  // Provide list description.
  $node = menu_get_object();
  if (isset($node->field_description[LANGUAGE_NONE][0]['value'])) {
    $text = strip_tags($node->field_description[LANGUAGE_NONE][0]['value']);
    $text = decode_entities($text);
  }

  // Add metadata to describe site's content.
  $description = array(
    '#type' => 'html_tag',
    '#tag' => 'meta',
    '#attributes' => array(
      'name' => 'description',
      'content' => $text,
    ),
  );
  drupal_add_html_head($description, 'desciption');
}

```

# Answer
The function `decode_entities` works as you expect. It converts the HTML entity (`'`) into a single quote and returns the decoded string.

However, that single quote will be expanded into an entity again at some point downstream, when the page is rendered. This is what inserts (provided you spell "description" correct) the following into your page's `<head>`:

```
<meta name="description" content="We're in this together" />

```

I would not worry about this. The above is a perfectly valid HTML meta-tag and will be interpreted correctly for SEO purposes, etc.
> 1 votes

---
Tags: 7
---


# Question
Title: drupal 7, db_select(), strange behavior : malformed query
I have a table: mantenimiento\_extras.

I want a query like this: select * from mantenimiento\_extras where id in (7, 9).
(this case assumes passing array(7, 9), but it could be variable, even including the case for "in ()".

I execute this query:

```
db_select("mantenimiento_extras")->fields("mantenimiento_extras")->condition("id", $values, 'IN')->execute();//$values is guaranteed to be an array.

```

I get this query, and an error:

```
SELECT mantenimiento_extras.* FROM {mantenimiento_extras} mantenimiento_extras WHERE (id IN ()); Array( )

```

I modify the dynamic query:

```
db_select("mantenimiento_extras")->condition("id", $values, 'IN')->execute();

```

I get this query, and an error:

```
SELECT FROM {mantenimiento_extras} mantenimiento_extras WHERE (id IN ()) ; Array ( )

```

Now I bang my head against the nearest object in my desk.

Why is it generating malformed queries?

# Answer
If the array is *empty*, you'll get `WHERE foo IN ()`. That's invalid SQL syntax.

To prevent, use a conditional:

```
if (!empty($values)) {
  // Run the query.
}

```
> 0 votes

---
Tags: 7, database
---


title: Close webform error messages

text:
# Question
Title: Close webform error messages
I'm using the webform module for a contactform. But when the submission doesn't validate the user can't click away the alert box.

```
<a href="#" class="close">×</a>

```

Look's like there is no js function attached. Is there a setting in the module for closing the alert box or should you implement it yourself?

# Answer
> 0 votes
I found a neat little module the other day called Message Close which once installed, adds a simple close icon to every message, whether status or vaildation. It also resets all margins and padding so once a message is closed, the page looks exactly as it does on a fresh load.

In the js of the module, you can use jquery to make the message fade out, or slide out.

This would be perfect for closing webform validation messages without needing a page reload.

---
Tags: webforms, javascript
---


# Question
Title: How to Post JSON data to Cart service in Drupal Commerce Services
I'm uses Drupal commerce services for mobile commerce. But I don't know how to Post jSON to REST service Cart or Order. With Comment services I"m post JSON successful as below:

```
URL: [http://myserver.com/services/comment/][1]
METHOD: POST
JSON BODY:
{
    "comment":{
      "comment_body":{
        "und":[
          {"value":"Good job"}
        ]
      },
      "nid":"23",
      "subject":"Drupal Services Comment"
    }
}

```

I don't know what is JSON Body to POST to Cart or Order Service like that? Anyone Please help me? Thanks

# Answer
> 0 votes
I found JSON structure for Cart or Order Services. It's something as below:

```
{
   "type":"commerce_order",
   "commerce_customer_billing":"10",
   "commerce_line_items":
       [
           "11",
           "13",
           "14",
           "15",
           "16"
       ]
}

```

---
Tags: commerce, 8, services
---


title: Persisting URL params on form_set_error

text:
# Question
Title: Persisting URL params on form_set_error
# Scenario

I have a page which looks like http://notfound.stackexchange.com?a=1&b=2

After validation, i use **form\_set\_error** to display a drupal error message on the same page(url) but end up without the url params http://notfound.stackexchange.com

# Question

* Is there a way to preserve/persist the url params on **form\_set\_error** ?
* Is using **drupal\_goto** the correct way (since i can send the url params again) to redirect to the same page ?
* **hidden form elements** to store the params for use on different pages in the process flow, but as a last resort if there is no other way ?

# Answer
`$form_state['redirect'] = FALSE;`

This works like a charm since the form is not rebuilt or reloaded. Below link contains more info https://drupal.org/node/1850410
> 0 votes

---
Tags: forms
---


# Question
Title: Change the confirm_form message of an entity made with eck
I have an entity created with eck module, and when I want to delete an entity the message is :

> Are you sure that you want to delete %id ?

I want to change this message to show me the title of the entity and not the id. I find where this is implemented, is in the code below in `eck.entity.inc` file located under the eck module folder:

```
function eck__entity__delete_form($form, &$form_state, $entity_type, $bundle, $id){
  $path = eck__entity_type__path();

  $entities = entity_load($entity_type->name, array($id));

  $form['entity'] =
      array(
        '#type' => 'value',
        '#value' => $entities[$id],
  );

  $form['entity_type'] =
      array(
        '#type' => 'value',
        '#value' => $entity_type,
  );

  $form['bundle'] =
      array(
        '#type' => 'value',
        '#value' => $bundle,
  );

  $form['submit_redirect'] =
  array(
    '#type' => 'value',
    '#value' => "{$path}/{$entity_type->name}/{$bundle->name}",
  );

  $message = t("Are you sure that you want to delete %id",
          array("%id" => $id));

  $caption = t("This action cannot be undone.");

  return confirm_form($form, $message, "{$path}/{$entity_type->name}", $caption, t('Delete'));

}

```

Is there a way to change this confirm message without changing the code of this module ? thanks in advance

# Answer
You can use hook form alter to change a piece of the form, see this answer by Clive:

https://stackoverflow.com/questions/8111034/altering-title-on-drupal-node-delete-confirmation-form
> 1 votes

---
Tags: 7, entities
---


# Question
Title: Unable to import date from csv with Feeds module
I have a simple csv file I'm trying to import with feeds. Most of the fields are going in just fine, but the dates are failing. And after following the process through in a debugger, I cannot see why this fails - ***the date exists when Feeds saves the node, so why does this fail?***.

Above: This screenshot of my debugger shows that entity has date information immediately after entitySaved is called. I cannot detect anything unusual about the object format - looks kosher. The date was added as the `field_deadline_proposals:end`. A date can be a range, so I assume this is the proper way to save a single date (non-range).

Above: This is a screenshot of the database table for field\_deadline\_proposals immediately after node save. Node 258 does not have the information I expect.

This is the relevant excerpt from my csv doc, with headers:

```
id,rfp_num,description,title,published,rfp_filename,response_deadline,QA_deadline,mod_date,create_date
4,034-009  Robinson Pkwy,"Robinson Pkwy -Walkthru 6/22/09  9:30am.  Log onto the website for more information. Due date has been moved to 7/6/09  11:00am",TRUE,RFP_034-009  Robinson Pkwy_034-009_doc.pdf,7-6-2009 11:00,29-06-2009 13:00,7-1-2009 13:50,19-06-2009 9:29

```

My dates are currently in `d-m-yyyy hh:mm` format, which seems to work just fine and was recommended in this related post. Frankly, I don't think the date format it much of an issue - I have had success with other formats, including using feeds\_tamper to convert the date to UNIX timestamps. In all cases, though, the save fails, so I suspect some other issue :-/

# Answer
Got it. Turns out that adding a new mapping that used the same date field with the `Deadling for Proposals: start` target solved things.

This wasn't particularly intuitive for me, so maybe this will be helpful for someone else too.
> 2 votes

---
Tags: feeds, datetime, importing-exporting
---


title: Adding error class to Webform fields

text:
# Question
Title: Adding error class to Webform fields
I have a Webform which I'm validating implementing the \_validate event (i.e. altering $form\["#validate"\] by adding a custom validator which accepts &$form and &$form\_state).

In my code I have something like this:

```
if ($nombre && !CasabacaS3SValidaciones::validarLongitud($nombre, 30))
{
    form_set_error('columnas][datos_personales][nombre', t('El nombre no debe superar 30 carácteres'));
    //what should I put in THIS LINE, replacing this comment, to add the error class?
}

```

I **have no clue** about adding the "error" class (e.g. fields marked as required have class "required", and also class "error" when the field is not set). How can I alter the field (take this example field in the form\_set\_error and assume input variables are &$form and &$form\_state) so I can add the error for display?

**NOTE**: I'm seeking to add the "error" class to the fields, and **NOT** to the wrapping divs (i.e. those divs having form-item class).

(If a quick solution involves themes, please attach a link so I can read about because i'm banging my head about drupal yet, i'm a total n00b :s).

# Answer
You could use a preprocess functions in your theme for this. You can add preprocess in your template.php.

```
function mytheme_preprocess_textfield(&$vars) { // OR preprocess_field.

  $vars['#attributes']['class'][] = 'test' ;
}

```

Check the `$vars` parameter for values that may help you determine the logic. For examples, just search your code base for `preprocess_textfield` or preprocess\_field. For more inf
> 1 votes

---
Tags: 7, webforms, forms
---


title: Multiple Voting in One Node

text:
# Question
Title: Multiple Voting in One Node
I couldn't come up with much constructive title, as
The Title could also be: **Separate Voting system for Fields in same Node**

In a Content Type I have 3 fields

* Mind
* Body
* Soul

all are Longtext as in the picture below.

At the moment in this content type, I am using Plus1 Module with VotingAPI for vote, but this doesn't seem to fulfill my need.

What I am trying to acheive is to have **3** voting system, one for each field (***Mind, Body and Soul***), so, any individual can vote in any of these field.

I have tried using the Fivestar Module and adding it as field, but it breaks my Page Layout due to JavaScript Conflict. I will post that as different question.

My question is: is there any readymade module which can help me acheive this, so, I can have Voting system for Individual Field item and store the votes in Database.

# Answer
I've not had much luck with the plus1 module. The 7 version is wonky. If you're just looking for a plus 1 or like function and your fixed on the voting api then vote up/down May work for you. You can create multiple voting fields and they are tracked separately as a field. The widget may cause some layout issues so may I suggest using flags instead.

Why? It's easy to add a plus1 type feature and flags can be formatted using views or flag\_create\_link() so you can put it every where and wrap it in any CSS div or span. You can have as many as you'd like and it's all in the db and available to views. You can even use rules so the system can react on a flag. I've moved away from voting api in favour of flags.
> 0 votes

# Answer
Did you consider structuring your display differently?
1. Mind, body and soul = 3 different content types with taxonomy term "persons"
2. Use taxonomy term "persons" to link them together (person 1, person 2, etc.)
3. create 3 views, 1 for Mind, 1 for body, 1 for soul with contextual filter taxonomy term "persons" and full content display
4. create a 4th content type "full person" with the taxonomy field and 3 viewsfield and choose the person/entity in the taxonomy field (person 1 for example)
5. The views will pick the taxonomy term for each "full person" content type and display the Mind, body and soul views tagged with "persons" taxonomy and will be displayed in "full content" mode.
6. In that way you should be able to have the 3 voting system visible and usable.

I didn't tried it, it is just a guess.
> 0 votes

---
Tags: 7, rating
---


# Question
Title: using ajaxComplete with drupal quicktabs
I am trying to use `.ajaxComplete()` on my quicktabs but i cant seem to get it to hit. Would anyone have any ideas?

```
jQuery('#quicktabs-tab-find_a_doctor-1').click(function(){
  console.log('CLICKED');
  jQuery('#quicktabs-tab-find_a_doctor-1').css({
      "float":"left",
      "padding-right":"5px"
    });
  jQuery('#quicktabs-tab-find_a_doctor-1').parent().append('<div id="loading-icon"><img src="sites/all/themes/contributed/holyspirit/images/4.gif" /></div>');

  //jQuery('#loading-icon').ajaxComplete(function(){
     // jQuery(this).hide();
    //});

  Drupal.behaviors.LoadingIcon = {
    attach: function() {
      jQuery('#loading-icon').ajaxComplete(function() {
        jQuery(this).hide();
      });
    }
  }
});

```

I have tried both ideas, but i still cant get it to hit. Any help would be much appreciated!

# Answer
Of course after posting on here I was able to figure out my mistake.

```
jQuery('#quicktabs-tab-find_a_doctor-1').click(function(){

  // Making room for loading icon
  jQuery('#quicktabs-tab-find_a_doctor-1').css({
      "float":"left",
      "padding-right":"5px"
    });

  // Adding the loading icon to tab
  jQuery('#quicktabs-tab-find_a_doctor-1').parent().append('<div id="loading-icon"><img src="sites/all/themes/contributed/holyspirit/images/4.gif" /></div>');

  // Once ajax is complete remove loading icon from page
  (function($) {
    Drupal.behaviors.LoadingIcon = {
      attach: function() {
        $(document).ajaxComplete(function() {
          $('#loading-icon').remove();
          $('#quicktabs-tab-find_a_doctor-1').css({
            "padding-right":"0px"
          });
        });
      }
    }
  }(jQuery));
});

```

According to http://api.jquery.com/ajaxcomplete/ You need to attach the `.autoComplete()` onto the document as stated right here:

> As of jQuery 1.8, the .ajaxComplete() method should only be attached to document.
> 1 votes

---
Tags: 7, ajax, javascript
---


# Question
Title: drush "The drush command 'self-update' could not be found."
I'm trying to figure out why many drush commands aren't working.

`drush theme list` also reports:

> The drush command 'theme list' could not be found. Run `drush
>  cache-clear drush` to clear the commandfile cache if you have installed new extensions.

I'm mildly certain I installed drush via brew install drush.

Any tips?

# Answer
`self-update` was removed a while ago. I'm not sure what the official replacement is, but a simple `git pull; composer install` does the job for me with the latest version (run it in the drush lib folder, probably in /usr/local/Cellar if it was brewed).

`theme list` (and `theme`) don't appear in the list of available commands (although `self-update` does, ironically). Maybe you're looking for

```
drush pm-list --type=theme

```
> 6 votes

---
Tags: drush
---


# Question
Title: How to stop / hijack a infinite redirection loop with a redirecting rule
I'm using Rules and Detector module to prevent IE \< 7.0 users from browsing the site.

I've setted up a rule, executed when UA (Detector) properties are loaded. Dependings on user agent value, the rule have an action, which consists in redirecting user to a particuler node (explanation).

This works well, so well that redirection is always active, even on my destination node. So it lead me to kind of 'Too much redirection error'.

I don't manage to put another condition, like Path has url alias; that will prevent all undesired redirections.

Do you know what I'm doing wrong? Please, don't hesitate to suggest me another way to achieve this redirection properly.

# Answer
You might want to consider a simple redirect in .htaccess

To redirect based on user agent, if not already on redirected page.

```
RewriteEngine On
RewriteCond %{HTTP_USER_AGENT} MSIE [1-7]
RewriteCond %{REQUEST_URI} !^/upgrade/
RewriteRule .? upgrade [L]

```
> 2 votes

# Answer
I was not able, for mysterious reasons, to implement David Thomas solutions. So I decided to write a really dirty solution :

Assuming that I have an existing node with "upgrade" alias :

## page.tpl.php

```
<!--[if lt IE 9]>

    <script type="text/javascript">
     if (window.location.pathname != "/upgrade") {
        window.location.pathname = "/upgrade"
     }
    </script>
<![endif]-->

```

Once again, it's quite dirty:

* conditions are only available for IE
* it's static and imply to deliver this additional code (would be quite better with configuration / module)
* I must have and existing node (not too much important).

I'm really not proud of myself, but you know ... client is requiring this feature RIGHT NOW ! I hope I'll have time to found a better solution later (at least, it's planned).
> 0 votes

# Answer
Give this a try - not sure if it'll help in your case but it has worked for me.

Add /#r=off after every link in mobile that links to the main site (desktop);

i.e. http://yoursite.com/#r=off

This will direct you to your main site while preventing redirect back to mobile.

Hope this solves your problem.
> 0 votes

---
Tags: 7, rules, redirection
---


# Question
Title: All of my pages have class "page--node-" on the body element. This doesn't seem right
I'm trying to track down the source of some CSS issues I'm having on my site and I noticed that every page has class "page--node-" added to the `<body>` element. The theme hook suggestions seem to include `page__node__%`.

This looks weird. Is it supposed to be like this, or is there a problem in a theme hook suggestion generated somewhere? I'm using a subtheme of Zen 5.

# Answer
Classes beginning with page generally come from drupal core in template\_preprocess\_html(), which calls theme\_get\_suggestions() to do the heavy lifting.

That function makes a bunch of suggestions for the classes or template suggestions based on the path of the current page. The % is used as a wildcard for numeric arguments (in this case the node id).

Then back in template\_preprocess\_html() it passes the suggestions through drupal\_html\_class(), which in turn runs them though drupal\_clean\_css\_identifier(), which strips out characters not allowed in a class, including the %, so you get a class of page-node- (this seems like a bug but there is a use for it I will explain below).

This theme\_get\_suggestions() code is the same reason you have the template suggestion with the percent symbol.

This means you can affect all node pages by using the template name page--node--%.tpl.php.

That might not seem necessary because you also have page--node.tpl.php, however if you want a different template for the path /node than you do for individual node pages you need to use both page--node.tpl.php and page--node--%.tpl.php.

This same reason is why the unusual class is useful. If you want to style the /node page differently from individual node pages you can style page--node differently from page--node-

I agree it is a silly looking class though with pretty limited (or maybe none) documentation.

Also, something I found after writing this that is useful is How Drupal determines page theme hook suggestions based on path, from the "Drupal 7 Template (Theme Hook) Suggestions" documentation page.
> 1 votes

---
Tags: theming
---


# Question
Title: Access callback return true, but still is: you are not authorized to this page
```
function updatable_news_menu() {
    $items['updatable_news/test'] = array(
        'title' => 'Updatable news',
        'page callback' => 'updatable_news_test',
        'access callback' => 'updatable_news_permission',
        'access arguments' => "hello",
    );
}
function updatable_news_permission() {
    return true;
}

```

I have used a similar implementation and the permission is ok in another module. However, it fails in this module which defined a brand new entity.

```
function updatable_news_menu() {
    $items['updatable_news'] = array(
        'title' => 'Updatable news root',
        'page callback' => 'updatable_news_root',
        'access arguments' => true,
    );
}

```

I have to add new menu item with access should always be true. But it only succeed for administrator instead of anonymous user and logged in user.

# Answer
'access arguments' must be an array. Like `'access arguments' => array('access administration pages')`
> 1 votes

---
Tags: users, entities
---


# Question
Title: How to place one region below the other while reducing the width in drupal 7?
Currently, I am creating a single page responsive website in Drupal 7. After making the page responsive, I added a block with two regions: *about us* and *ethics* side by side that is in two columns. When reducing the browser width, the content still remains in two columns!!! I want the region *about us* to be below *ethics*, but I am not aware how to do it!! Can anyone guide me with the aforestated question.

# Answer
> 1 votes
You can either use float:left on both elements with fixed widths that will automatically stack when the page width is reduced enough.

Or use a CSS media query to make the regions adapt once a certain screen width is reached.

HTML:

```
<div class="container">
    <div class="region1">CONTENT1</div>
    <div class="region2">CONTENT2</div>
</div>

```

CSS:

```
.container {width:100%}
.region1 {width:50%}
.region2 {width:50%}

@media only screen and (max-width: 767px) {

.region1 {width:100%}
.region2 {width:100%}

}

```

---
Tags: theming
---


# Question
Title: 'Userpoints Transactions: Description' doesn't appear in Views
I am building a site using Drupal 7 and the User Points module.

I have an original user points page. There I have table with the column "reason".

The HTML code for the "Reason" field (same as description?):

```
<td class="userpoints-transactions-field-reason">
<a href="/comment/41#comment-41" title="Commented on New Question for Comments
 6/2/2014.">Commented on New Question f...</a></td>

```

But, I tried to create a new table for transactions in Views. For some reason, the "Userpoints Transactions: Description" is not showing in views.

Below you can see that the "description" column is empty:

This is the HTML code I see in the view:

```
<div class="views-field views-field-description">
<span class="views-label views-label-description">Description: </span>
<span class="field-content"></span>  </div>

```
* why the "Userpoints Transactions: Description" does not shows up through views?

# Answer
There is no 'Reason' field: it is named 'Description'. When you're creating a new 'Userpoints Transaction' view, you can simply add a 'Userpoints Transactions: Description' field and everything should work out fine.

**Edit:** I've imported your view and everything works fine on my website. Try reinstalling the User Points and the Views modules and clear caches. Hopefully that solves your problem.
> 0 votes

---
Tags: 7, views, userpoints
---