title: Replace strings with new strings

text:
# Question
Title: Replace strings with new strings
I have a page with list of teasers. It contain links like 1 comment, 1 new comment, add your comment. I want to change 1 comment to 1 response, 1 new comment to 1 new response and add new comment to add new response. I used **string overrides module** and tried to change the strings, but i was able to change only add new comment to add new response. How to change 1 comment and 1 new comment? please help.

# Answer
> 1 votes
There is another solution to implement `hook_preprocess_node` to modify the comments links.

You can follow the answers in the Modifying teaser node comment links

# Answer
> 0 votes
If you need only few strings redefined, String Overrides is a good solution. If you want to redefine most of them, or if your site is multilingual anyway, there is a better way:

* Be sure that internationalization modules are installed and enabled
* Go to *Administration » Configuration » Regional and language*
* Click *Add language*, and create something like *English GB*
* "Translate" strings you want to have changed

---
Tags: 7, string-overrides
---


title: What is the use of @db_query?

text:
# Question
Title: What is the use of @db_query?
I have used db\_query to retrieve table rows from database. Recently I noticed, some people use **@db\_query** instead of **db\_query**.

I dont see any difference with the two. Is it doing any special functionality that normal **db\_query** doesn't?

# Answer
`@` is the error control operator, what it does is suppress notices/warnings and even script halting errors. You see it most commonly used with variable comparisons where the person coding didn't bother to check if a variable is set first.

```
if (@$unsetVar != $var) {
  @$unsetVar .= $non_existent_variable';
}

```

Suppresses the warning that $unsetVar is not initialised.

The proper way of doing this though would be using `isset($unsetVar)` to check that this variable is in fact initialized first, if not don't do anything with it, or assign it a default of some kind. Then neither the comparison or the concatenate will throw errors. Keeping this in mind can prevent some show stopping bugs later down the line as your applications become more complicated.

I'd personally advise against using `@` wherever possible, if there's a notice/warning/error it's usually for a reason, using `@` is a lazy fix and can make debugging a pain if something does go wrong.

Tl;dr, I'd avoid using `@` where possible.
> 0 votes

---
Tags: 7, database
---


title: User configured VIEW fields

text:
# Question
Title: User configured VIEW fields
Curious, is there a module or technique I can use to easily allow my clients (who log in with a limited role) to manage fields visible in any given view?

Actually there are two specific content types and two specific page views -- which I would love to give them the capability to customize to their liking.

# Answer
> 0 votes
Sounds like something you can do with Views Dynamic Fields. Unfortunately there's only a D6 release atm, but perhaps you can port the module to D7 when it seems to fit your needs.

---
Tags: views
---


# Question
Title: How to Use Exposed filter of Taxonomy term with depth in Taxonomy View
I have a question which is similar to How to use taxonomy terms(with depth) on a views exposed filter?

But problem in my case is that I am using views of type Taxonomy, here I don't get option in Filter "Taxonomy Term: Has content with depth".

I have my Taxonomy like : -Country -State 1 -City 1 -City 2 -City 3 -State 2 -City 4 -City 5 -City 6

I want exposed filter which has 3 select boxes like : -Country- -State- -City- \- State and City boxes fillup by Ajax based on Country selected.

Then the view should be updated based on the selected filters. i.e If I select State 1 then I should get results of all the Cities below it and even of State 1.

Please note that I am not using View of type content, My view type is Taxonomy.

Can anyone suggest me how should I get this working?

Thanks in advance!

# Answer
> But problem in my case is that I am using views of type Taxonomy, here *I don't get option in Filter "Taxonomy Term: Has content with depth"*.

You can bring that option into scope if you add a **Relationship** of "Taxonomy term: Representative node" or "**Taxonomy term: Content using MY\_VOCABULARY**" and general any relationship that will join the node (or other Entity) table with the taxonomy table.
> 3 votes

# Answer
If you want to have nodes show in your Views results, you need build a view of type node. If you want taxonomy terms to show up in your results, then you build a view of type taxonomy.

If you want to use the taxonomy term with depth filter, you'll need to rebuild your view as a node view.

For example, you have a real estate site with listings -- node type is "listing" and it was a location taxonomy term associated with it that says what city each listing is in. Build a node view and add a filter of taxonomy-term-with-depth with a depth of 10 so that selecting a state will also show listings for all the cities in that state.

Hope that helps.
> 0 votes

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


# Question
Title: Add html to li for active-trail menu links
Ive used the theme override below to add a span to the end of the li of my menu links. This is working but I need it so the span is only added to the active-train li.

```
function MYTHEMENAME_menu_link(array $variables) {
  $element = $variables['element'];
  $sub_menu = '';

  if ($element['#below']) {
    $sub_menu = drupal_render($element['#below']);
  }
  $output = l($element['#title'], $element['#href'], $element['#localized_options']);
  return '<li' . drupal_attributes($element['#attributes']) . '>' . $output . $sub_menu . ' <span>Something</span> ' . "</li>\n";
}

```

# Answer
> 0 votes
You can check if `$element['#localized_options']['attributes']['class']` contain `active-trail` class and create your custom span based on this information.

```
function MYTHEMENAME_menu_link(array $variables) {
  $element = $variables['element'];
  $sub_menu = '';
  $span = '';

  if ($element['#below']) {
    $sub_menu = drupal_render($element['#below']);
  }

  if (isset($element['#localized_options']['attributes']['class'])) {
    if (in_array('active-trail', $element['#localized_options']['attributes']['class'])) {
      $span = '<span>Something</span>';
    }
  }

  $output = l($element['#title'], $element['#href'], $element['#localized_options']);
  return '<li' . drupal_attributes($element['#attributes']) . '>' . $output . $sub_menu . $span . "</li>\n";
}

```

---
Tags: theming
---


# Question
Title: Multisite, shared users, own databases, own files, how to deal with profile picture?
I'm in the middle of implementing a multisite setup. Each site will have it's own database, and files directory, but they will share the user table from the default database.

Because the profile picture field in the user table is set to a fid, am I right in thinking this will break a user picture if they look at their profile on a different site?

fid 26 might be their picture on the main site, but fid 26 in another site might be for a completely different image, or not even an image at all.

How do you normally address this issue?

Cheers

# Answer
You need a single sign on approach. You could implement your own approach just like this one https://drupal.org/node/1043724 or try to find some contribute module to handle it. Hope this help. Regards
> 0 votes

---
Tags: users, files, multi-sites
---


# Question
Title: Prevent a user from viewing another user's profile based on a field value
I'm a Drupal veteran, but this one has me stumped . . .

I have two Profile2 profiles, one for a company and one for a job seeker. In the job seeker profile, there is an entity reference field where they add companies they don't want to view their profile. The way companies finds people is by searching via Search API. Another way, would be by browsing. I need to block both ways. Basically, the job seeker should be invisible to the companies that they've blocked.

I have Panels, Panelizer, Rules, and Views all at my disposal and know how to use them, just not in this case. Or am I better going with my own custom module?

I saw this answer Hide Profile2 fields depending on it's value when viewing user profile and that's only for specific fields, I want to block the whole profile.

This question is along the same lines of mine, but I don't see a complete answer -How to filter a view based for the current user based the value of custom fields in his profile and fields in the list of items viewed

# Answer
> 2 votes
You can control profile2 access with

`hook_profile2_access`

Views listens to node access so you might be able to use to exclude rows from the view.

```
/**
 * Implements hook_profile2_access
 */
function MY_MODULE_profile2_access($op, $profile = NULL, $account = NULL) {
  if (isset($profile)) {
    // Use wrapper for field access
    $profile_wrapper = entity_metadata_wrapper('profile2', $profile);
    // Check if $account uid is set in field_invalid_users
    if(isset($profile_wrapper->field_invalid_users)){
      if(in_array($account->uid, $profile_wrapper->field_invalid_users->raw())){
        // Deny access
        return FALSE;
      }
    }
    // Example: Explicitly deny access for a 'secret' profile type.
    if ($profile->type == 'secret' && !user_access('custom permission')) {
      return FALSE;
    }
    // In other cases do not alter access.
  }
}

```

One consideration is caching. Cache will need to vary enough to not serve the same cached content to valid and invalid users. Perhaps those pages aren't cached at all, it depends on your application.

# Answer
> 1 votes
You can add an 'access callback' function to the menu hook for the pages you want to block and inside that function perform your own checks against the currently logged in user. This also means you must block the page for anonymous users or the company can just logout and view the profile anyway.

For hiding in search results I see two options:

## Easy solution

In search-result.tpl.php or hook\_preprocess\_search\_results you check access and don't show it. Drawback is that the count of the total results wouldn't be correct anymore.

## More advanced

Add an extra indexed field *blockedcompanies* which contains all ids of the blocked companies in Solr with hook\_apachesolr\_index\_document\_build. When searching: add a check on this field with hook\_apachesolr\_query\_prepare.

---
Tags: views, rules, panels, users, search
---


# Question
Title: Unable to get through to the custom form using hook_menu page callback?
Inside the hook\_menu I have ,

```
$items['abc/def/%node'] = array(
    'page callback' => 'drupal_get_form',
    'page arguments' => array('heart_form',2),
    'access arguments' => array('modify  heart status'),
    'type' => MENU_CALLBACK,
  );

```

Inside my custom form I have the foll code..

```
function heart_form(&$form_state, $node) {
   $form['notes'] = array(

    '#type' => 'textarea',
    '#required' => TRUE,
    '#description' => t('Please give an explanation'),
  );
  $form['submit'] = array('#type' => 'submit', '#value' => t('Save'));

  return $form;
}

```

But when I try to go on the link , `www.example.com/abc/def/18` I get a page not found message What is the error ?

# Answer
> 0 votes
Sanity checks first:

* Make sure you're returning `$items` from `hook_menu()`
* Make sure you've cleared the caches since making changes to code in `hook_menu()`
* You probably don't mean to have two spaces between the first two words in your permission string.
* Make sure there's a node with an ID of 18 in the system; if not the `%node` load argument will fail and you'll get a 404.

The only other problem (but not one that would causes a 404) is the signature for your form function; it should be

```
function heart_form($form, &$form_state, $node) {

```

---
Tags: 7, forms, routes
---


title: call a js function on loading a page

text:
# Question
Title: call a js function on loading a page
is it possible to call a javascript(jquery) function once a particular page is loaded. It should be hacking the of the whole site and to detect what the current page is and call the function. How can I actually do this?

So in a non-drupal php site, I would add a js file and have a start\_product\_content() function there. In the head.php file it would be something like this:

```
...
<head>
    ...
    <?php if $current_page = "product" ?>
    start_product_content()
    ...
</head>
...

```

I have explained in a different post about what I really want to achieve, long story: footer link to a page with hash changed content ready

I have achieved this when I was doing a non-drupal website, now I just want to be able to do this so that I can be closer to the target.

Thanks

# Answer
If you want to add arbitrary code to the `<head>` element you need to:

1. Take a copy of the core html.tpl.php file and put it in your theme somewhere
2. Clear the caches so it gets added to the theme registry
3. Implement `hook_preprocess_html()` in your theme's template.php file like so

```
function MYTHEME_preprocess_html(&$vars) {
  $vars['some_var'] = 'Something';
}

```
4. In the html.tpl.php file, use

```
print $some_var;

```

wherever that might be appropriate.

If you want to add structured code to the `<head>` tag then use `drupal_add_html_head()`.

Finally, specifically to add JS to the page, you can use `drupal_add_js()`. But that needs to happen *before* the HTML template is processed. `hook_preprocess_page()` would be one option, but there are many, depending on the context that makes up your page.

You'll find the Theming guide, and questions already asked on this site, invaluable if you're learning the theme system from scratch.
> 1 votes

# Answer
Drupal has is own way to add a specific .js file :

Use drupal\_add\_js()

There also a module (with an UI) to add .js file without creating a custom module. Take a look at JS injector
> 0 votes

---
Tags: javascript, 7
---


# Question
Title: Starting a views list from the nth element
I have two views blocks. One displays the latest news item. I would like the other block to list 4 next latest news items starting from the second latest (as I have already displayed the first one).

Can I achieve this via the view's admin interface?

# Answer
> 0 votes
Yes you can, Under pager settings, offset first four items. Click on the number of items to get this option

and on the page option settings change the offset.

---
Tags: 7, views
---


# Question
Title: In code alter user registration and override approval to no approval required
In my module I want to override the approval for certain users so that they are immediately approved and get the corresponding email.

The module looks at the subdomain to decide if approval is required. If it is, then the register-with-approve email should be sent. If no approval is required, the account should be activated and the no-approval-required email should be sent.

I have looked for hooks that I could use for this, but haven't got anything working yet. I'm using Drupal 7.

# Answer
I suggest you to code this directly in your module :

use \_user\_mail\_notify()
> 0 votes

---
Tags: 7, hooks, users
---


title: how to get data in views templates

text:
# Question
Title: how to get data in views templates
I am trying to use the field data inside of a views template to modify its output. I looked at the available fields with devel, and, inside of a field template, I used the following code:

```
$row->field_field_twitter_screen_name[0]['rendered']['#markup']

```

and many more like this. It worked fine. The only issue is that the page was giving me a lot of notice message from this code:

```
*   Notice: Undefined offset: 0 in include() (line 28 of [path-to-file].tpl.php).

```

Is this not the correct way to get data? If so, what is it?

# Answer
It shows you the `Notice` because somewhere in your data `array` you have missing data for a specific node. As for being correct, yes, it is a good way to alter the output. Try checking the data before printing it.

Something like

```
if(isset($row->field_field_twitter_screen_name[0]['rendered']['#markup'])) {
  //do custom action here
}

```

Edit: You can also make good use of `$content` variable here.
> 2 votes

---
Tags: views, theming
---


# Question
Title: Programmatically load the uid of the owner of a viewed profile2 entity
Using Display Suite together with Profile2 and Flags. I want one of my flags to be visible on the profile2 page, but only to the owner of the profile page and to the administrator.
I try adding a code field with Display Suite. I can get the field to display, I can get it to display to only administrators, but I don't find a way to allow only owner and administrator to view the flag.
What I need is the uid of the user viewing a profile (I've got that one), and then I need the uid of the owner of the profile being viewed, and compare them.
The profile2.module source has the following lines:

```
$account = isset($account) ? $account : $GLOBALS['user'];<br>
    if ($account->uid != $profile->uid) {<br>
      do something here.<br>
    }

```

That looks like it is what I need, but I don't seem to be able to implement it. Any help would be appreciated.

# Answer
Try with :

```
global $user; //is the current user

// you can get the viewing user id :
$user_id = arg(1);

if ($user->uid != $user_id){
}

```
> 1 votes

---
Tags: users
---


# Question
Title: "Please select category" as default value in a select list
Similar to how the search box on many sites has a default value of "search", how do I give a select list a default value without making that value a valid option in the list of options. See example below:

# Answer
> 2 votes
For adding text to your input field, write a custom module and place the code in there

```
function yourmodule_form_alter(&$form, &$form_state, $form_id){
    if($form_id == "your_form"){
     $form['some_element']['#attributes']['placeholder'] = t('Select Category');
}

```

# Answer
> 2 votes
you are looking for #empty\_value attribute

If #required is TRUE and there is no #default\_value, an empty option is added to the select control to force the user to make an active choice.

If #empty\_value or #empty\_option is set and #required is FALSE (default), an empty option is added to the select control, allowing the user to choose nothing.

If none of #required, #empty\_value, #empty\_option, and #default\_value are set, then no empty option is added to the select control. This leaves the control in a slightly illogical state, since all user agents automatically preselect the first available option. There's no way for the user to select nothing, and the user is also not forced to make an active decision.

https://api.drupal.org/api/drupal/developer!topics!forms\_api\_reference.html/7#empty\_value

---
Tags: forms
---


# Question
Title: jQuery.js not loading after enabling custom module
I have written my custom module for Drupal 7. In my `page_change.module` file I have only:

```
<?php
    drupal_add_js(drupal_get_path('module', 'page_change') . '/page_change.js');
?>

```

In my `page_change.js` file I have only:

```
Drupal.behaviors.page_change = {
    attach: function (context) {
        console.log("text");
    }
};

```

As soon as I enable my module, Drupal doesn't load `jquery.js`. It does not even appear in html source in `<head>` section. When I disable my module, or delete the only line from `page_change.module` file everything works fine.
I have also tried to load my javascript file by adding

```
scripts[] = page_change.js

```

In my `page_change.info` file (and leaving `page_change.module` with only `<?php ?>`) but it doesn't seem to work either.
Why does that happen? What am I doing wrong? Am I missing something?
edit: I have even tried to add inline javascript by adding

```
drupal_add_js('console.log("text");', array('type' => 'inline', 'scope' => 'footer'));

```

and it writes `text` to console, but `jquery.js` is still missing.

# Answer
Ok, somehow I forced it to work, but I still have no idea why it hadn't work before.

I have changed my `page_change.module` contents to:

```
<?php
function page_change_preprocess_page(&$variables) {
    $file = drupal_get_path('module', 'page_change').'/page_change.js';
    $options = array(
      'weight' => 1000,
      'scope' => 'footer'
    );
    drupal_add_js($file, $options);
}
?>

```

then I disabled and enabled my module and miraculously it works.

If you have any idea why I had these problems, please post your answer.
> 0 votes

# Answer
Your custom JS should be wrapped in:

```
(function($) {
  // custom Drupal behaviors here
})(jQuery);

```

Give that a shot.
> 0 votes

---
Tags: javascript
---


# Question
Title: Edit Block body content directly in database
I've used some php code in a block that appears on all pages and now receive a fatal error and cannot access the site. In what table and field can I find the Block body content in the database for a Drupal 7 site? I plan to edit the Block body content directly in phpMyAdmin.

# Answer
> 4 votes
block\_custom table is what you are looking for.

Regards

---
Tags: 7, blocks, database
---


# Question
Title: How best to implement a custom variable in the content creation form in D7?
I'm creating a sports league site.

I want to have a variable behind the scenes containing the current league standing. In a content type 'result', upon saving, I first want a field (previous standing) to be populated with this variable, and then for the variable to be updated with the new standing. But I have no idea where to even begin with this!

# Answer
I believe your best bet is to create your own module, with a custom form hook and the form submit which will process your data and do all your calculations and save the new value. The form tutorials in the Form API Examples can give you a lot of good insight how to do this.
> 0 votes

---
Tags: nodes, entities
---


# Question
Title: Elysia cron stuck in (w) state (wating to be executed)
I have a few crons set up to run every 15 min. My system cron is set to execute every 5 mins. However one cron keeps getting stuck in the (w) state. I updated its setting to run every minute (\* * * \*) and still every time the cron run all jobs get executed except for one `homepage_extensions_cron (w) - [run]
* * * * * 09/06/2013 - 15:14 7s 4 3s / 7s` This is really troubling me.

When I run the cron manually ( replicating what the system is doing) the cron runs fine. I do it through curl. When I execute the curl through command line, the task runs. I am suspecting there is some timing tricky stuff here. Can someone please explain how this work? Also, I am trying to clear a certain cache id in the cron task and do an http request. Could this cause an issue?

# Answer
Ok, the problem was not with elysia cron but rather with our over-engineered system. The cron runs on a different box that did not have the uptodate code. Therefore, when I visited the UI, I was able to see the cron because I am connected to a certain box the load balance designates (again some over-engineered stuff). We synced the code using cfenging and now the cron is recognized and runs.
> 0 votes

# Answer
The "(w)" flag means only that the job is ready to be executed (waiting for the system crontab to start and execute it).

If a job has a rule like "`* * * * *`" (= execute it EVERY minute), it's quite normal that the "(w)" is always on.

If you use a rule like "`* * * * *`", assure that system crontab is set to "`* * * * *`" too. That way you minimize the (w), because system crontab runs every minute too and executes the job as fast as possible.

(However, a little time with (w) is normal and not to be considered a problem).
> 2 votes

---
Tags: cron, caching
---


# Question
Title: how to use image styling on a image url field
I understand that on an image field, you can create a image style. However, I have a field which is a url and I use that url in a template to produce a picture. Is there any way for me to use the image style ui to style this?

# Answer
> 1 votes
Try using the Imagecache External drupal module: https://drupal.org/project/imagecache\_external

In your template file you could then call (from the drupal project example) and replace 'path' with your path from your url field:

```
<?php
  print theme('imagecache_external', array(
    'path' => 'http://larsjung.de/h5ai/sample/screenshots/h5ai-v0.7-icons.png',
    'style_name'=> 'thumbnail'),
  );
?>

```

# Answer
> 0 votes
Insert Module will support for all major WYSIWYG editors, including tinyMCE, CKeditor. You can choose image style before upload.

> Insert is a utility that makes inserting images and links to files into text areas or WYSIWYGs much easier. It adds a simple JavaScript-based button to FileField and ImageField widgets. When used with ImageField and ImageCache, images may be inserted into text areas with a specific ImageCache preset.

---
Tags: media
---


title: Post data to view

text:
# Question
Title: Post data to view
If I have a form that posts data to a view page, how do I go about setting the contextual filter in my view?

Here is sample code I tried running but it's not working:

```
$data = 'name=value&name1=value1';

$options = array(
            'method' => 'POST',
            'data' => $data,
            'timeout' => 15,
            'headers' => array('Content-Type' => 'application/x-www-form-urlencoded'),
    );

 drupal_http_request('http://www.mysite.com/companylist', $options)

```

# Answer
> 1 votes
Your POST might be accessible at contextual filters -\> Provide default argument -\> PHP code -\> $\_POST.

---
Tags: 7, views
---


# Question
Title: How to input search terms via a separate form on a content page to a Views Exposed Filter on a different page?
When visiting a content page (node), I want users to be able to input search terms into a form from there which will be fed into a View via its Views Exposed Filter.

The View I have is contained within Panels in a Panels-based page and it's Views Exposed Filter is made available as an external block. This approach allows me to layout this View and Views Exposed Filter with other separate items in other Panels.

Given that the Views Exposed Filter is made available as an external block, I can display it on other pages such as content. However, entering search into this form on these content pages results in the just the View being displayed - I need it to display the Panels-based page as mentioned above with the View results.

So I would somehow need to feed the input supplied by the user into the form on the content page, as a parameter into the Panels-based page.

**My initial thoughts and questions on implementaton**

Is it a case of using something like `dpm()` (which I have found useful in the past) to understand the form data being input so that input from the form can be fed to the Panels-based page and 'routed' to the Views Exposed Filter? I think the form data needed by the Views Exposed Filter is understood but how would I know where to submit the data i.e. can I give the URL for the Panels-based page as the `form action` URL and is there anything else I need to do so that the Panels-based page will convey the form input data to the Views Exposed Filter in the panel?

# Answer
It is possible to use dpm() to understand the form data. In a custom module, you can use hook\_form\_alter() to act on the exposed filter form.

It would look something like this:

```
function example_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'views_exposed_form') {
    dpm($form);
  }
}

```

You can then set the action.

```
function example_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'views_exposed_form') {
    $form['#action'] = '/path-to-panel';
  }
}

```

Just beware that this will alter all the exposed filters on the site. You can create a different if statement to target them more specifically if you have more than one.
> 1 votes

# Answer
Another option might be to Render view's exposed form anywhere in a theme/module Credit: timonweb

Quoted here for convenience (and in case entry gets deleted):

> ```
> /**
>  * Returns rendered exposed form for a given view.
>  * $view_name
>  * - A string with a view name,
>  * $display_id
>  * - A string with a name of view display,
>  * @return
>  *  Rendered exposed form.
>  */
> function MY_MODULE_render_exposed_form($view_name, $display_id = 'page') {
>   $view = views_get_view($view_name);
>   $view->set_display($display_id);
>   $view->init_handlers();
>   $form_state = array(
>     'view' => $view,
>     'display' => $view->display_handler->display,
>     'exposed_form_plugin' => $view->display_handler->get_plugin('exposed_form'),
>     'method' => 'get',
>     'rerender' => TRUE,
>     'no_redirect' => TRUE,
>   );
>   $form = drupal_build_form('views_exposed_form', $form_state);
>   return drupal_render($form);
> }
>
> ```
> 0 votes

---
Tags: 7, forms, views, panels
---


# Question
Title: Additional Configuration to disable anonymous session cookies?
I am running a clean install of Pressflow 6.28. I have set the following configurations:

Cache Mode: Normal; Min Cache Lifetime: 5 minutes; Page Cache Max Age: 1 day;

I have installed no contributed modules and have disabled all optional modules that ship with Pressflow.

I am seeing inconsistent behavior with setting session cookies with anonymous users. Sometimes a session is not set, but most of the time it is. When I login and logout, session remains set. If session is not being set and I run 'drush cc all' it begins to be set. I am wondering if there is perhaps some additional configuration I may be missing.

# Answer
> 0 votes
Make sure the $cookie\_domain is set properly in settings.php, often if it's not set to the correct domain, particularly in proxy situations, you'll see inconsistent login behaviour.

---
Tags: sessions, cookies, 6
---


title: Dynamic Form Field Submit Handler

text:
# Question
Title: Dynamic Form Field Submit Handler
This form creates dynamic fields. I am trying to build a submit handler for each of the dynamic field values. So for each of the $form\['items\_fieldset'\]\[$i\]\['serial'\], (amount, and description) I could have many fields. How would I pass those to my database?

Here's what I have thusfar:

Form excerpt:

```
$form['#tree'] = TRUE;

$form['items_fieldset'] = array(
'#type' => 'fieldset',
'#title' => t('Shippment Inventory Items:'),
'#prefix' => '<div id="items-fieldset-wrapper">',
'#suffix' => '</div>',
);

 if (empty($form_state['num_items'])) {
$form_state['num_items'] = 1;
}

 for ($i = 0; $i < $form_state['num_items']; $i++) {

$form['items_fieldset'][$i] = array(
'#prefix' => '<div class="two-col">',
'#suffix' => '</div>'
);

$form['items_fieldset'][$i]['amount'] = array(
  '#type' => 'textfield',
  '#size' => 30,
  '#title' => t('Amount:'),
  '#required' => FALSE,
  '#prefix' => '<div style="float:left; padding-right: 50px;">',
  '#suffix' => '</div>',
);

$form['items_fieldset'][$i]['description'] = array(
  '#type' => 'textfield',
  '#size' => 50,
  '#title' => t('Description:'),
  '#required' => FALSE,
  '#prefix' => '<div style="float:left; padding-right: 50px;">',
  '#suffix' => '</div>',
);

$form['items_fieldset'][$i]['serial'] = array(
  '#type' => 'textfield',
  '#size' => 30,
  '#title' => t('Serial Number:'),
  '#required' => FALSE,
  '#prefix' => '<div style="float:left;">',
  '#suffix' => '</div><div style="clear:both;"></div>',
);
}

$form['items_fieldset']['add_items'] = array(
'#type' => 'submit',
'#value' => t('Add more'),
'#submit' => array('_nnreport_shipping_new_add_one'),
'#ajax' => array(
    'callback' => '_nnreport_shipping_new_callback',
    'wrapper' => 'items-fieldset-wrapper',
    ),
);

```

Handler to pass to database (not including all the static form values):

```
 function _nnreport_shipping_new_submit($form, &$form_state) {
    $submission = new stdClass();
    //This doesnt work, but I think it's kinda what I'm after...??
     for ($i = 0; $i < $form_state['num_items']; $i++) {
          $submission=>amount.$i = $form_state['values']['$i']['amount'];

          };
          _nnreport_shipping_new_update($submission); }

```

After that I submit the values of $submission to the database, like this:

```
function _nnreport_shipping_new_update(&$submission){

     db_insert('nnj_shipment')
        ->fields(array(
            'hotshotId' => $submission->carrier,
            'driver' => $submission->driver,
            'driverPhone' => $submission->driverPhone,
             //lots more of those...
              ))
             ->execute();

```

I've unsuccessfully tried a few variations to get the dynamic fields into the object...I would be very grateful for someone to point me in the correct direction.

# Answer
Well after ignoring this problem for a while it was time to find an answer.

The issue was with using $form\['#tree'\] = TRUE; I didn't use the full array references after that...eg: $form\_state\[$i\]\['description'\] needed to be $form\_state\['values'\]\['items\_fieldset'\]\[$i\]\['description'\] = 'foo'; (

After that I just used a foreach to grab my values from the dynamic field values...like: foreach ($form\_state\['values'\]\['items\_fieldset'\] as $v){ $submission-\>description\[\] = $v\['description'\]; }

And last was to dump them into my DB, and life is good.
> 0 votes

---
Tags: forms, ajax
---


title: Blocks and CSS Grid Systems

text:
# Question
Title: Blocks and CSS Grid Systems
How do I achieve the following in Drupal:

```
<div class="row">
    <div class="col-xs-4 col-md-4">[MY BLOCK HERE]</div>
    <div class="col-xs-4 col-md-4">[MY BLOCK HERE]</div>
    <div class="col-xs-4 col-md-4">[MY BLOCK HERE]</div>
</div>

```

I can use the "Block Class" module to assign the grid system classes to the block, however this does not allow me reuse blocks in another layout (changing the grid system classes).

Im also limited to where I can put these blocks. At the moment i have a specific region setup that is wrapped in the "row" class. This prevents me for having a few different rows and from placing the blocks anywhere...

```
<div class="row">
    <div class="col-xs-4 col-md-4">[MY BLOCK HERE]</div>
    <div class="col-xs-4 col-md-4">[MY BLOCK HERE]</div>
    <div class="col-xs-4 col-md-4">[MY BLOCK HERE]</div>
</div>
<div class="row">
    <div class="col-xs-4 col-md-4">[MY BLOCK HERE]</div>
    <div class="col-xs-4 col-md-4">[MY BLOCK HERE]</div>
    <div class="col-xs-4 col-md-4">[MY BLOCK HERE]</div>
</div>

```

Basically I need to:

1. Add grid system classes to blocks
2. Reuse blocks in a different grid system class configuration
3. Freedom to define rows of blocks and assign them to any region, not just one that is wrapped in a single "row" class.

Any help would be much appreciated, at the moment I have to style each individual block to work responsively and I know that there must be a better way of doing this.

Thanks

# Answer
We primarily build our sites using Bootstrap with this same technique, so here are 3 modules that will make your life a lot easier.

Block Class \- add classes to blocks.

Block Group and/or Region Class \- group blocks together in faux regions, add classes to regions.

Blocker \- places blocks on specific pages in different regions, alternative to using the core block placement system. Really useful for site building and putting blocks on basic pages.
> 6 votes

---
Tags: theming, blocks
---


# Question
Title: How do I control the visiblity of an exposed filter in a taxonomy term view?
I've activated the "taxonomy term" (the one that has the description "A view to emulate Drupal core's handling of taxonomy/term.") view and I need to use it to:

1. expose a filter to the user
2. only display it on certain taxonomy pages

My example is this: I've got two vocabularies that are both being controlled by this view. We'll call them Restaurants and Working Locations. Both are "places" with phyical locations and I use the taxonomy display pages to list the various locations. I've also added an exposed filter that users can use to select a particular region for different "restaurants", but I do not want that filter to be on the "working locations" at all. I'm not sure how to achieve this. I've looked at Views Dependent Filters, but I can't get it to work the way I'd like.

So my question is how can I use the exposed filter to show on some taxonomy view pages, but not on others? The traditional filters of content type have not worked.

I'm looking at Rules, and or Contexts to see if this might be an option but I've still not found anything.

Any reason why the "exposed filter as block" option is not available to me in this view?

Thanks in advance.

# Answer
> 2 votes
There is an option in views to display your exposed filters in a block. In this usecase, if you only have one exposed filter, it might work for you to put the exposed filter in a block and then identify the pages you want to display it on in the block administration page.

You could use url aliases and a wildcard * to isolate all terms of a certain vocabulary to save you listing each page in the block admin form.

To put the exposed view in the block: Click on the advanced tab over on the right of the views pane and change 'Exposed form in block:' from No to Yes.

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


title: Preprocess Field: CSS Style per page

text:
# Question
Title: Preprocess Field: CSS Style per page
Trying to set up a `preprocess_field_hook()` to send a different css style depending on the node that is loaded for simpler theming. Will not work and been beating my head.

Have this set inside my `template.php`and have my tpl pages named correctly (exam: node--node\_page\_one.tpl.php), which is loading fine with other functions already working. I feel like I need to have it point to the actual element somehow? Or should I be doing this somewhere else like in the `preprocess_node_hook()`?

Sorry for my noobness.

```
 function mytheme_preprocess_field(&$variables, $hook) {
      $variables['fieldclass'] = '';
      switch ($variables) {
        case 'node_page_one':
          $variables['fieldclass'] = 'tiny-blue';
          break;
        case 'node_page_two':
          $variables['fieldclass'] = 'large-green';
          break;
        default:
          $variables['fieldclass'] = 'black';
          break;
      }

```

# Answer
Rather than $variables\['fieldclass'\] use $variables\['classes\_array'\]

Based on the docs
> 0 votes

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


# Question
Title: Populate fields when a checkbox is clicked on a form
I have a regular drupal 7 form (based on a content type called guests) where I need a "Bring my partner" checkbox. When the checkbox is clicked, a field collection field (first name/last name/address) needs to be prefilled basing on the details for the currently logged-in user. (Partner details are in my user account details.)

Can this be done in `hook_form_alter()`? Is there any other way to achieve this?

# Answer
You could do this with hook\_form\_alter and add a state to the field that needs to be hidden.

```
$form["first_name"] = array(
    "#states" => array(
        "invisible" => array(
            ":input[name='bring_parter']" => array(
                "checked" => FALSE,
            )
        )
    ),
);

```

What this does is hides the "first\_name" unless "bring\_partner" is checked. More info here
> 1 votes

---
Tags: 7, forms
---


title: Pathauto and taxonomy

text:
# Question
Title: Pathauto and taxonomy
I use the default taxonomy view (with default path: /taxonomy/term/%) to display videos that have been categorized at the time of their upload. The viewer has access to an exposed filter that allows him to select like 10, 30 or 40 video thumbnails per page (default is 10.)

The Pathauto taxonomy pattern for all video paths is: \[term:vocabulary\]/\[term:name\] Token is enabled.

The url of the landing page is correctly displayed *www.example.com/videos/sports* when the vocabulary "videos" and the term "sports" are selected through a menu.

But if, on that same page, I select to view 30 video thumbnails per page instead of 10, the url changes to:

*www.example.com/taxonomy/term/1989/0?items\_per\_page=30*

This appears normal since the the view path is /taxonomy/term. The content displayed is correct, but the page theming is totally out of wack.

How do I keep the url at *www.example.com/videos/sports/0?items\_per\_page=30* ?

Shouldn't Pathauto handle this?

# Answer
Again, I will give my own answer here:

After reading about tokens, pathauto and views, it appears that exposed filters DO NOT work with path (dixit *Merlinofchaos* in https://drupal.org/node/1257952#comment-4898854 .) So what I am experiencing is normal.

However, views have a "Use Ajax" option that is specifically there for exposed filters. Enabling it solves the issue and keep the url clean (without the \*0?items\_per\_page=30\* part.)

It does so because ajax does not refresh the page, so the url remains the same (*www.example.com/videos/sports* in this case.) :)
> 2 votes

---
Tags: 7, taxonomy-terms, path-aliases
---


# Question
Title: Search system based on two taxonomy vocabulary for Local Business Directory for Drupal 7
I am new in drupal

I am making a Local Business directory. every business entry is a node (content type "Profile") and I make two taxonomy vocabulary name as "Business-city" and "Business-category" . every node is tagged with two taxonomy term.

Now I want to make search system where user can select "Business City" and "Business category".

Please tell me how can I do this.

Thanks in advance

# Answer
> 0 votes
You need to familiarize yourself with Views module. Simply create a view of nodes of your particular content type, add two filters, one for each taxonomy, expose them and you are done.

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


# Question
Title: PDOException: SQLSTATE[42S22]: Column not found: 1054 Unknown column
I am tring to perform the following sql query to check if the name that was inserted to the form already created as taxonomy name. But I keep getting this error message:

> PDOException: SQLSTATE\[42S22\]: Column not found: 1054 Unknown column `'test'` in `'where clause'`: `SELECT COUNT(*) FROM {taxonomy_term_data} WHERE name = test;` Array ( ) in `get_google_map_api()` (line 79 of /Applications/MAMP/htdocs/Drupal/sites/all/modules/toodate/toodate.module).

my function is:

```
function get_google_map_api($item){
    $city_name = $item;
    $chack_if_is_taxonomy = (db_query("SELECT COUNT(*) FROM {taxonomy_term_data} WHERE name = ".$city_name));
    var_dump($chack_if_is_taxonomy);
    drupal_exit();
}

```

# Answer
> 1 votes
Quick fix would be adding the missing single quotes around your variable. Forgetting the quotes can throw odd errors from this function, such as mixing a string for a column, like in your case.

There are less error prone ways to make short queries like this. See also Molot's answer.

# Answer
> 1 votes
Don't use `db_query()` unless you really have to. Build your queries with `db_select()`. It's harder to make SQL errors using it. Your query would look like this:

```
// SELECT COUNT(*) FROM {taxonomy_term_data} WHERE name = $city_name
$chack_if_is_taxonomy = db_query('taxonomy_term_data', 'ttd');
$chack_if_is_taxonomy->addField('ttd', 'COUNT(*)', 'count');
$chack_if_is_taxonomy->condition('name', $city_name, '=');

```

As you can see, no place to make SQL errors, and PHP bugs should be easier to spot in your favourite IDE.

---
Tags: taxonomy-terms, database
---


title: How to highlight views result?

text:
# Question
Title: How to highlight views result?
I have a view that shows me a list of images on the front page. Each of those images has its category. Now i need to add exposed filter with categories that allow users to choose images by categories. BUT I want to show all images and just to highlight (by adding CSS class for example) the exposed filter results. Is it a way to do it?

I'm using Drupal 7.

# Answer
> 1 votes
You will need jQuery to make this work but it shouldn't be too complicated. Basically the exposed filter acts as the degraded (non-javascript) version as well as giving you all the possible category options.

```
$('.views-exposed-form .views-submit-button input').hide();
$('.views-exposed-form select').change(function(event) {
  // Clear previous highlights
  $('.highlight').removeClass('highlight');

  // Get the selected category
  var selectedCategory = $(this).find('option:selected').text();

  // Use the category name to find items on the page
  $('.views-field-term-node-tid .field-content a:contains(' + selectedCategory + ')').parents('.views-row').addClass('highlight');
});

```

I made this example with a view with fields and the "Content: All taxonomy terms (All taxonomy terms)" field limited by taxonomy. If you use a different method of creating the view you will want to change .views-field-term-node-tid .field-content and probably also the .parents('.views-row') which is what gets highlighted.

You'll also probably want an additional selector in front of all the .views-exposed-form selectors in case you add more exposed forms to you sight such as $('.my-view .views-exposed-form')...

I also made this to trigger on the select change, but you could do it when clicking the Apply button (which you would obviously not want to hide then).

If you exposed filter is a multiple select you can add an each() to the end of $(this).find('option:selected') and loop through getting the text and setting the highlight.

# Answer
> 0 votes
Try adding the category names of the images to the classes the view outputs for each image, by rewriting the output of the image field and the use jQuery to addClass to items with classes matching those in your filter. For example:

Your views output

```
<div class="views-row category4"><img src="#"/></div>

```

Your filter

```
<ul>
    <li id="category4">Cat4</li>
</ul>

```

Your js:

```
$('#category4').click(function(e){
    e.preventDefault();
    var cls = $('this').attr('id');
    $('views-row'+.cls).addClass('highlight');
});

```

---
Tags: views
---


# Question
Title: Drupal Internationalization / Translation
When you translate a website using the i8ln module it doesn't automatically translate all the words in fields correct?

Also, what do you need to do to efficiently translate all the words ?

Is it a process that requires manually translating all the text with the i8ln module?

I reviewed some drupal documentation about this but it seems to only be germane to contributing local translations to the server: http://drupal.org/node/11130

I'm looking to have the localization server automatically translate it for me.

# Answer
> 4 votes
I don't know if I completely understand your question correctly, but I think there's some confusion. The Drupal translations from localize.drupal.org and the locale core module, will only help you translate the interface. If there's something missing or you want some custom translations you can always use: http://drupal.org/project/l10n\_client \- and to keep it up-to date: http://drupal.org/project/l10n\_update

The i18n module allows users to translate the content into different languages, but it does not auto-translate. There are some modules that uses Google's APIs to auto translate but one violates Google's TOS and the other one will stop working when google pulls there translation API

# Answer
> 0 votes
I found this:
https://drupal.org/project/translation\_management
https://drupal.org/project/i18n

More explanations available in this post:
http://www.icanlocalize.com/site/tutorials/howto-translate-drupal-sites/

---
Tags: i18n-l10n
---


# Question
Title: Keep submenu expanded when parent or children are active
I have a two-tiered menu system using the Nice menus module, which I've adapted to run horizontally with the children beneath the top level, as in the following menu.

> Home - About - **Adopt an animal** \- Events - Get Involved - Contact
>
> Cats - Dogs - Small Animals - Birds

At the moment, the second tier is showing only on hover of the parent. After clicking through or landing on a page I need the children to be expanded when their parent or siblings are active and I'd like the parent to be highlighted as active in this case too - so in this example if I'm on Adopt an animal page or dogs / small animals / birds then I need that expanded.

I'm not sure where to even start on this, I don't really want to hack it by duplicating false second tier menus and using context or block to display them on certain pages because I need to be able to hand over the menu administration so the integrity is important. Thanks for any suggestions.

# Answer
> 1 votes
Menu Trail By Path sets the active-trail on menu items according to the current url.

For example if you are at yoursite.com/blog/category1/article1 Menu Items with these paths will get the active-trail class on them and expand accordingly.

```
blog
blog/category1
blog/category1/article1

```

This is particularly useful if you want a lot of nodes to appear as children of certain nodes / taxonomy term / views / referenced nodes / etc, but do not want to add them all to the menu. eg. hundreds of blog articles.

---
Tags: routes, navigation
---


# Question
Title: Taxonomy Term View not showing image field
Drupal 7, Views 3

I have created a Taxonomy Term View for a particular vocabulary. If I set the Format Show option to "Fields", and add the Taxonomy name and image fields, then for some reason only the name shows. If I change it to "Rendered entity" then everything works fine. Another weirdness: this is only for some vocabularies - for some other vocabularies, the fields option works just fine (it shows the image). Any thoughts on why this might be? Any ideas how to debug this? Thanks guys.

# Answer
Heh, well, as said in the comment, be sure to either have the same field or add all image fields :)
> 0 votes

# Answer
A detailed doc on exposing term images is available here https://drupal.org/node/1224916
> 0 votes

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


# Question
Title: What are the steps to be undertaken while writing a .install file for drupal 7 module?
I want to add an table to the database using .install file of a module. I am
creating a completely new module which has not been enabled till now.
Which are the functions required in the .install file

```
function [HOOK]_install() {
  switch ($GLOBALS['db_type']) {
    case 'mysql':
    case 'mysqli':
//Should I write my query to create table inside this ...
    case 'pgsql':

   break;
}
}

function [HOOK]_uninstall() {
//Should I write the code here to remove the table after installation

}

```

# Answer
> 1 votes
as Clive says you should use hook\_schema for creating your custom tables and then hook\_update\_N https://api.drupal.org/api/drupal/modules!system!system.api.php/function/hook\_update\_N/7 for the updates of your tables module.

---
Tags: 7, installation
---


title: How to set format of date in date field

text:
# Question
Title: How to set format of date in date field
I have a content type in which I used a date field and for the same i have used this field -\> https://drupal.org/project/date

My problem is I want to set the date format as " September 13, 2013 | 3:39 UTC |" , so I overrode the format and made it 'F j, Y | H:i e' (refering to https://www.php.net/manual/en/function.date.php)

but it is only showing the year (e.g. 2013| ), not other things.

Can anyone help me with this?

# Answer
> 0 votes
Path: Home » Administration » Configuration » Regional and language Or
Path : admin/config/regional/settings

In the above path there will be tab called 'format' where you can create your own custom format where format string is **F j, Y, g:i a e**.
Now you can change the date format of the field from the manage displays tab of the admin/structure/types path.
In the respective field you will have settings options where you can set your custom date format

---
Tags: entities, datetime
---


# Question
Title: Hook_form_FORM_ID_alter problems with custom validating
I have created a custom module for altering the user\_register\_form and with custom validating I have an error: Notice: Undefined index: values in custom\_register\_validate\_password() (line 17

This is the 17 line:

```
if (in_array($form['values']['pass'], $badpasswords)) {

```

I cannot understand what I'm doing wrong. Here's the full code:

```
<?php

    /*
     * Implements hook_form_FORM_ID_alter().
     */
    function custom_register_form_user_register_form_alter(&$form, &$form_state, $form_id) {

        $form['#validate'][] = 'custom_register_validate_password';
        //krumo($form);
     }

     /*
      * Custom password validation
      */
    function custom_register_validate_password($form, &$form_state) {
        $badpasswords = array('pass','password');
        if (in_array($form['values']['pass'], $badpasswords)) {
            form_set_error('pass', t('Please use a more secure password!'));
        }
        krumo($form_state);
    }

```

# Answer
> 1 votes
I think you need to write

```
    if (in_array($form_state['values']['pass'], $badpasswords)) {
        form_set_error('pass', t('Please use a more secure password!'));
    }

```

`$form_state['values']['pass']` instead `of $form['values']['pass']`

---
Tags: forms
---


# Question
Title: Change title of a node programmatically before displaying it
I am a newbie at Drupal tweaking. I have copied Bartik theme into sites/all/themes and am modifying it as per our requirement.

One such requirement now is to programmatically modify the node title by appending value of some other field in the node to it before displaying the node. I have identified that the right way to achieve it is by updating the variables in `hook_process_page()` or `hook_preprocess_node()` function in `template.php` file of the theme.

For testing purpose I have done the following change:

```
/**
 * Override or insert variables into the page template.
 */
function MyThemeName_process_page(&$variables) {
    // Raj: Experimenting
    $vars['site_name'] = 'New title';
    drupal_set_title('Test changed title');
    echo "<script type=\"text/javascript\">alert('MyThemeName_process_page');</script>";
.
.
.
}

```

I could see that none of the changes are affected. Since I am just beginning to tweak, I have no idea how to debug a php function as it is a server side script. For the same reason I have tried to display alert which fails to display too!

I thought that the function is not being triggered at all, so I intentionally induced error in the 'echo' line by removing a character:

```
ech "<script type=\"text/javascript\">alert('MyThemeName_process_page');</script>";

```

The interpreter complains with this error:

> Parse error: syntax error, unexpected T\_CONSTANT\_ENCAPSED\_STRING in /Applications/XAMPP/xamppfiles/htdocs/MyWebsite/cms/sites/all/themes/MyThemeName/template.php on line 48

This means that the interpreter is triggering the function, but why does not it echo and put out the alert?

Also, what is the approach to update the node title? I am assuming that there is some variable which I should be interested in the array `"&$variables"` and conditionally update it, am I right?

Awaiting help!

# Answer
To modify the node title while displaying, I had to do changes in the theme.

Implement the hook (don't remember if it was already there) in template.php file:

```
function themeName_process_page(&$variables)

```

And then had to add this part of custom code at the end of the function:

```
// Raj: To Append the scientific name and it's desciber to the title
$nodesArray = $variables['page']['content']['system_main']['nodes'];
if (!empty($nodesArray))
{
    foreach ($nodesArray as $speciesNode)
    {
        if (!empty($speciesNode['field_common_names']))
        {
            $scientificNameArray = $speciesNode['field_scientific_name_1'];
            if (!empty($scientificNameArray))
            {
                $theScientificName = '<span id="ScientificNameDIV" class="ScientificNameSuffixClass">' . $scientificNameArray[0]['#item']['first'] . '</span>';
                $theDesciber = '<span id="ScientificNameSimpleDIV" class="ScientificNameSimpleClass">' . $scientificNameArray[0]['#item']['second'] . '</span>';
                $prominentName = $variables['title'];
                $sciFiNameAndDescriber = $theScientificName . ' ' . $theDesciber;
                $variables['title'] = $prominentName. ' ' . '<span id="ScientificNameSimpleDIV" class="ScientificNameSimpleClass"> ( </span>' . $sciFiNameAndDescriber . '<span id="ScientificNameSimpleDIV" class="ScientificNameSimpleClass"> ) </span>';
                $variables['title'] = '<div id="CommonNameAndScientificName" class="CommonAndScientificClass">'.$variables['title'].'</div>';
                break;
            }
        }
    }
    unset ($speciesNode);
}

```

Please see that in the above code, most of it belongs to the context of my website where I had to append the scientific name of the species to the title of the species inside brackets. The point here is, you need to modify the `$variables['title']` inside `process_page()` hook.

Also most important, to see the changes in affect, clear the cache. I had a rough time thinking that the changes are not working, only very late did I realize that I was doing everything right but did not clear cache. It's a learning experience for me.
> 6 votes

# Answer
Page title or node title?

1. **To construct page titles** (which show on the element on the head section), try to install the page\_title module, which allows to make patterns for page titles based on any tokens (install the token module first).
2. **To construct node titles**, there is the auto\_nodetitle modules which allows to construct the node title in a similar way, using a token-based pattern.

Doing it programmatically is possible, but less maintainable and takes lots more effort, so try to find a module which works before taking the hard way.
> 2 votes

---
Tags: nodes, theming
---


# Question
Title: Unable to override views-view-unformatted.tpl.php
I have a view page named `latest` and try to override the template `views-view-unformatted.tpl.php` by creating below templates in the theme folder

`views-view-unformatted--latest.tpl.php` `views-view-unformatted--latest--page.tpl.php` `views-view-unformatted--page.tpl.php` `views-view-unformatted.tpl.php`

but none of them works. I clear the caches, rescan template files. I use views 3 and Drupal 7.23.

Can anyone please help me override this template `views-view-unformatted.tpl.php`

# Answer
> 2 votes
In the "Advanced" section of the views configuration, click in "Theme:informaction" and you will see all the possible templates

Regards

---
Tags: views, theming
---


title: hook_libraries_info() doesn't work

text:
# Question
Title: hook_libraries_info() doesn't work
I have a custom almost empty module where I'm tring to insert a js file using hook\_libraries\_info(). But when I load the home I don't see my script inserted. It works when I use a simple drupal\_add\_js.
What I'm doing wrong? I've seen other examples like masonry and nivo-slider and those are similar. Do I need to init somehow? I'm new at module development, so probably is something simple.

**DETAILS**
Libraries module is enabled:
\- Libraries 7.x-2.1

The location of the library folder is this:
\- *sites/all/libraries/test/test.js*

**test.module**

```
<?php
//drupal_add_js('sites/all/libraries/test/test.js'); when uncommented it works

/**
 * Implements hook_libraries_info().
 */
function test_libraries_info() {  // it never works
  $libraries['test'] = array(
    'name' => 'Test',
    'vendor url' => 'http://www.example.com/',
    'download url' => 'http://www.example.com/',
    'files' => array(
      'js' => array(
        'test.js',
      ),
    ),

  );
  return $libraries;
}

```

# Answer
`hook_libraries_info()`, documented in libraries.api.php, is just a hook that informs the *Libraries API* module of any existing external library. Its purpose is not loading those libraries when a Drupal page is shown; for that, the module needs to call `libraries_load()` (defined in libraries.module) when necessary.

`libraries_load_files()` is the function that actually load in the page the CSS and Javascript files, respectively with `drupal_add_css()` and `drupal_add_js()`.

```
  // Load both the JavaScript and the CSS files.
  // The parameters for drupal_add_js() and drupal_add_css() require special
  // handling.
  // @see drupal_process_attached()
  foreach (array('js', 'css') as $type) {
    if (!empty($library['files'][$type])) {
      foreach ($library['files'][$type] as $data => $options) {
        // If the value is not an array, it's a filename and passed as first
        // (and only) argument.
        if (!is_array($options)) {
          $data = $options;
          $options = array();
        }
        // In some cases, the first parameter ($data) is an array. Arrays can't
        // be passed as keys in PHP, so we have to get $data from the value
        // array.
        if (is_numeric($data)) {
          $data = $options['data'];
          unset($options['data']);
        }
        // Prepend the library path to the file name.
        $data = "$path/$data";
        // Apply the default group if the group isn't explicitly given.
        if (!isset($options['group'])) {
          $options['group'] = ($type == 'js') ? JS_DEFAULT : CSS_DEFAULT;
        }
        call_user_func('drupal_add_' . $type, $data, $options);
        $count++;
      }
    }
  }

```
> 5 votes

# Answer
You are missing the version part which is necessary:

```
version arguments' => array(
      'file' => 'readme.txt',
      // Best practice: Document the actual version strings for later reference.
      // 1.x: Version 1.0
      'pattern' => '/Version (\d+)/',
      'lines' => 5,
    ),

```

http://drupalcontrib.org/api/drupal/contributions!libraries!libraries.api.php/function/hook\_libraries\_info/7
> 2 votes

---
Tags: 7, theming
---


# Question
Title: Webform submission via URL supplied data
Is it possible to submit data to a webform by providing the data in the URL of the webform page - or some other means of remotely providing data?

I have no idea if anything like this is possible but I am trying to keep email records within Drupal rather than use a simple script.

# Answer
> 0 votes
Webform MySQL Views

> These views may be useful when you need to access this data from an external application in an automated fashion without exporting, importing, or the use of a web-based API.

View will be automatically updated whenever you add, remove, or reorder the components for that Webform.

---
Tags: 7, webforms
---


# Question
Title: How do I apply cufon.js only for Internet Explorer, in template.php?
I have some font problems in Internet Explorer, so I am trying to apply `font-family` through JavaScript. It works, but the JavaScript code runs for every browser.

How do I run JavaScript code only on Internet Explorer?

This my code.

```
drupal_add_js('sites/all/themes/blogbuzz/js/cufon-yui.js');
drupal_add_js('sites/all/themes/blogbuzz/js/Helvetica_CE_35_Thin_100.font.js');
drupal_add_js('(function ($) {
  $(document).ready(function() {
    Cufon.replace("#content-header");
    Cufon.replace("#client_tle");
    Cufon.replace("#block-block-16");
  });
})(jQuery)', "inline");

```

# Answer
> 1 votes
You can't apply JS only to one browser using Drupal functions. What you can do is:

* CSS workaround:

+ apply CSS only to IE
    + assign some style that will not be visible, but also will not be present in non-IE, like white 1px border on white background
    + use `css()` jQuery method to test if element has property you expect it to have in IE, and if true, execute your code.
* JavaScript way: Use jQuery Browser Plugin or similar solution to identify browser inside your js file. Execute your code if it's the browser you need it executed in.

# Answer
> -1 votes
Something like this is what you are looking for:

```
function yourtheme_preprocess_html(&$variables) {
  // Add conditional stylesheets for IE
  drupal_add_css(path_to_theme() . '/css/ie8style.css', array(
    'group' => CSS_THEME,
    'browsers' => array(
      'IE' => 'lte IE 8',
      '!IE' => FALSE,
     ),
    'every_page' => TRUE,
    'weight' => 10,
   )
  );
}

```

---
Tags: theming, javascript
---


# Question
Title: Setting the default value for a text field as a variable in Form API
I thought this would be straight forward but my lack of drupal knowledge is holing me back. I want to grab the email from the logged in user, and set it as the default value of the form. I can grab the email from the global user logged in, but cannot pass this to the form?

The email field is blank, but I have the email stored in `$email1` I want to place this value in the text box, as the default field.

```
global $user;
    $user_full = user_load($user->uid);
    $email1= $user_full ->mail;
    echo $email1;

 $form['admin_email'] = array (
 '#type' => 'textfield',
 '#title' => t('Admin Email need email validation!!!'),
 '#description' => t('Please enter an Email'),
 '#default_value' => $user_full->mail,
 );

```

# Answer
You don't need to use `user_load($user->uid);`. You already have a complete object inside `global $user;` variable. And don't forget PHP is *not* a natural languages. You can't just put whitespaces where you want them. In method call or property access, there should be no spaces around `->`, it should be right next to object, and property should be right after arrow.

This line is sufficient for me:

```
'#default_value' => $user->mail,

```
> 0 votes

---
Tags: forms
---


# Question
Title: How do I set up a shipping condition that accesses the value of a specific field in product?
I have a term reference field in product called "Weight" with values "Light", "Medium" & "heavy". I am using flat rate shipping service and trying to check the value of "Weight" field in Calculation rules.I know that I need to expose it by using "entity has field" but I end up having

```
commerce-line-item:order:commerce-line-items:0
commerce-line-item:order:commerce-line-items:1
commerce-line-item:order:commerce-line-items:2
commerce-line-item:order:commerce-line-items:3
commerce-line-item:order:commerce-line-items:0...
commerce-line-item:order:commerce-line-items:1...
commerce-line-item:order:commerce-line-items:2...
commerce-line-item:order:commerce-line-items:3...

```

I was able to get to the weight field by using any of them and then did a Data Comparison

```
commerce-line-item:order:commerce-line-items:0:commerce-product:field-product-weight

```

this condition worked ok first time but not after that. can anyone please help me on this or if you think of another solution please let me know. Thanks

>

# Answer
> 1 votes
What you can do is loop through the line items and each line item is passed through a rule component where you can check the line item's weight. If you want to get the shipping fee for line item, you would need to set a rule set component. If you just want the component to provide the weight of the line item, a rule component will do.

I am not sure what you are trying to achieve with the rule or how your flat rate shipping works. Are you looking for the heaviest weight present in the order and apply to the order the shipping fee of that weight? Or does the fee accumulate according to how many line items and their weight? Regardless of how your shipping rate works, it's still the same concept: Loop through the line items. Pass the line item to a rule component that checks the weight of the line item.

The rule will look like this (assuming your shipping condition is: if product is light - add 0.25$ to shipping fee, 0.5$ for medium, and 1$ for heavy.)

Rule:

```
  /* ACTIONS*/
  // Add a variable: total_shipping_fee; set to 0.
  // Loop through line items
     // For each line item, trigger get_shipping_fee component passing line item and providing the prod_shipping_fee for the product
     //  Calculate value: total_shipping_fee + prod_shipping_fee
  // Set shipping fee to total_shipping_fee

```

For the rule set component: (get\_shipping\_fee), create three rules that checks the weight of the product; each rule returning or providing the shipping fee. For instance:

```
/* SETTINGS */
Parameter: line_item
Provided: shipping_fee

/* CONDITIONS */
// If product is light

/* ACTIONS */
// Set shipping_fee to 0.25$

```

The provided variable or variable returned by the rule component depends on how your flat rate shipping works. Also, you might need to pass another variable to the rule component.

Also, if you're new to drupal and rules, you can read the documentation to make it easier for you.

Hopefully, this will give you ideas to the actual solution of your problem.

---
Tags: rules, commerce, database
---


# Question
Title: Adding a new content type programmatically in .install file or .module file?
There are 2 different ways to create a new content type programmatically.

I am preferring the first method, since my feelings say that is better to maintain (i.e. adding/updating new fields via `hook_update_N()`) and it suits better in `.install` file. But, I keep myself asking why it is done other way in Node Example module.

Does anyone know the CONs and PROs of using both methods to create a new content type in code?

# Answer
Some hooks, like `hook_delete` are only called on the module that defines the node's content type. If you save content type to a database using `node_type_save()`, it might not be recognized as "defined by module" - it acts as content types created by user. Unless, of course, you will set `$info['module']` to point at your module - in that case created entries should work the same way.
> 5 votes

# Answer
A third method, which is often easier to maintain, especially if your node type will change over time, is to use Features to export the node type, fields, and field instances. You can still add custom code to the exported Features module, and Features will preserve that custom code (and any additional files) in future exports.

I used to use the .install file method for a long time, but Features' stability and UI/drush integration is good enough now that it saves me a lot of time manually getting the field info and node type info.

If you make changes to the node type/fields/etc., and re-export the feature module, you can update the feature in the UI or using drush `feature-revert` or `features-revert-all`.
> 4 votes

# Answer
There will be no issue with that...with update method you can create the new content types...
> -3 votes

---
Tags: 7, nodes
---


# Question
Title: breadcrumbs not displaying correctly for views
I'm pretty new to the world of drupal so I'm hoping this will be a quick fix.

Anyhow here's the situation: my breadcrumbs work correctly when hitting a node for example when i go to "contact" it prints out home \> contact. Now I have a view and when I go there things look ok. I go to events and it prints out home \> events \> view all. When I go to a subview like "tech events" however it spits out home \> events \> events \> view all.

The code below is what is currently in place so I was wondering how to alter it to handle views or if anyone could point me to a good solution.

thank you

my code:

```
function custom_breadcrumb($variables) {
  $currentTitle = "";
  $trail = menu_get_active_trail();
  $currentNode = array_pop($trail);
  if( $currentNode ){
    $currentTitle = $currentNode['title'];
  }

  $breadcrumb = $variables['breadcrumb'];
  if (!empty($breadcrumb)) {

    $output = '<ul class="breadcrumb"><li>';
    $output .= implode('</li><li class="breadcrumb-seperator"><!--»--></li><li class="breadcrumb-seperator-border"></li><li>', $breadcrumb);

    if( $currentTitle ){
      $output .= '</li><li class="breadcrumb-seperator"><!--»--></li><li class="breadcrumb-seperator-border"></li><li class="active">';
      $output .= $currentTitle;
    }
    $output .= '</li></ul>';

    return $output;
  }
}

```

any help would be awesome guys. thank you.

# Answer
> 0 votes
Okay so it still needs some work to be a little more generic but this basically handles the case. It checks to make sure that the content-type is not a node we check to see if there's an additional argument and append that to the breadcrumbs. if it is a node we just print out hte breadcrumb trail checking to make sure that we don't repeat things. If you use a page jump, fragments, or redirects you might get a repeat, i.e. home \> stories \> stories. So here it is.

```
function custom_breadcrumb($variables) {
  $currentTitle = "";
  $trail = menu_get_active_trail();
  $currentNode = array_pop($trail);
  if( $currentNode ){
    $currentTitle = $currentNode['title'];
  }

  $breadcrumb = $variables['breadcrumb'];
  if (!empty($breadcrumb)) {
    $lastCrumb = NULL;

    $output = '<h2 class="element-invisible">' . t('You are here') . '</h2>';

    $output .= '<ul class="breadcrumb"><li>';

  for ($i = 0; $i < count($breadcrumb); $i++) {
    $curCrumb = strip_tags($breadcrumb[$i]);
    if ($i == 0) {
      $output .= $breadcrumb[$i];
      $lastCrumb = strip_tags($breadcrumb[$i]);
    } elseif (strpos($breadcrumb[$i], $lastCrumb) === false) {
      $output .= '</li><li class="breadcrumb-seperator" data-test="testing"><!--»--></li><li class="breadcrumb-seperator-border"></li><li>' . $breadcrumb[$i];
      $lastCrumb = strip_tags($breadcrumb[$i]);
    }
  }

  if (arg(0) != 'node' ) {
    $output .= '</li><li class="breadcrumb-seperator"><!--»--></li><li class="breadcrumb-seperator-border"></li><li class="active">';
    $output .= arg(1);
  } elseif( $currentTitle ){
    $output .= '</li><li class="breadcrumb-seperator"><!--»--></li><li class="breadcrumb-seperator-border"></li><li class="active">';
    $output .= $currentTitle;
  }
  $output .= '</li></ul>';

  return $output;
  }
}

```

# Answer
> 0 votes
To be honest, I'd probably skip all the custom stuff and just use Path Breadcrumbs

> This module is a solution for all problems with the breadcrumbs on your site!
>
> Path Breadcrumbs module helps you to create breadcrumbs for **any page** with **any selection rules** and load **any entity** from the URL!

They're also exportable, so if you want them in code you can either export them and implement the default hook, or use Features.

---
Tags: breadcrumbs, taxonomy-terms
---


title: Prevent caching of ajax loaded forms

text:
# Question
Title: Prevent caching of ajax loaded forms
Trying to make a custom page to add taxonomy terms. The page contains one drop-down menu that lists all enabled vocabularies. Full taxonomy add form loaded after I select some from that menu.

This is menu callback:

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

      module_load_include('inc', 'taxonomy', 'taxonomy.admin');
      $vid = $form_state['values']['vocabulary'];
      $vocabulary = taxonomy_vocabulary_load($vid);

      $form_state['values'] = array();
      $form_state['build_info']['args'] = array(array(), $vocabulary);

      $form_state['rebuild'] = TRUE;
      $form_state['no_cache'] = TRUE;
      $form = drupal_build_form('taxonomy_form_term', $form_state);

      return $form;

    }

```

...and form

```
    function add_term_form($form, &$form_state) {

      $options = array();
      $options[0] = t('- Select -');
      $vocabularies = taxonomy_get_vocabularies();
      foreach ($vocabularies as $vocabulary) {
        $options[$vocabulary->vid] = $vocabulary->name;
      }

     $form['vocabulary'] = array(
       '#type' => 'select',
       '#title' => t('Select vocabulary'),
       '#options' => $options,
       '#default_value' => $selected,
       '#ajax' => array(
         'callback' => 'add_term_form_callback',
         'wrapper' => 'container',
         'event' => 'change',
       ),
     );

      $form['container'] = array(
       '#type' => 'container',
       '#prefix' => '<div id="container">',
       '#suffix' => '</div>',
      );

      return $form;
    }

```

So the problem is that the form remains in the same state after first load. How to refresh the form properly?

# Answer
> 2 votes
According to the documentation:

> Changes to the form must only be made in the form builder function (ajax\_example\_autocheckboxes() in the example here), or validation will fail. The callback function must not alter the form or any other state.

You have been changing the form\_state and the form in the callback.

Based on how I understood the documentation, you should be just returning the whole form in your ajax callback and then do the change in your form in the form builder function. You can just check the form\_state value of the drop down to know which form to render. I imagine it'll be something like this:

```
function add_term_form_callback($form, $form_state) {
  return $form;
}

 function add_term_form($form, &$form_state) {

 // If vocabulary has value
      // do stuff
      // $form = drupal_get_form('taxonomy_form_term');
 // else :
  $options = array();
  $options[0] = t('- Select -');
  $vocabularies = taxonomy_get_vocabularies();
  foreach ($vocabularies as $vocabulary) {
    $options[$vocabulary->vid] = $vocabulary->name;
  }

 $form['vocabulary'] = array(
   '#type' => 'select',
   '#title' => t('Select vocabulary'),
   '#options' => $options,
   '#default_value' => $selected,
   '#ajax' => array(
     'callback' => 'add_term_form_callback',
     'wrapper' => 'container',
     'event' => 'change',
   ),
 );

  $form['#prefix'] = '<div id="container">';
  $form['#suffix'] = '</div>';
  );
  // endif;

  return $form;
}

```

EDIT: I just noticed that you weren't wrapping the form but a container in the form. you would have to wrap the form if you want the whole form to be reloaded.

---
Tags: forms, ajax, caching
---


title: Media Gallery – Gear menu unavailable

text:
# Question
Title: Media Gallery – Gear menu unavailable
I created a Media Gallery on my Drupal 7 site and I am using views to output the teaser of all my galleries. Everything works as expected, but the gear menu is missing, that enables the user to delete images from the gallery. The documentation page describes this menu:

Does anybody has an idea what to do?

# Answer
> 2 votes
Check if the Contextual links module enabled. That could be doing it, or if Contextual links is enabled check that you have permission for your account.

This may be related: https://drupal.org/node/1450840

Also check if Views UI enabled. (if needed, may not be relevant)

---
Tags: media
---


# Question
Title: Rendering a field in a custom print template
I'm using the Printer, email and PDF versions module to render a custom print page in Drupal 7. I'd like to theme the fields individually and have worked that out to the point of using nasty php in my custom template itself.

So, I have a content type called `ecard` and following the module's documentation, I'm using `print--node--ecard.tpl.php` (based on the modules's core `print.tpl.php` file) for my custom print template. That works fine but the usual ways of rendering individual fields like in a node template don't.

I can do this within `print--node--ecard.tpl.php` to render an indivdual field called `field_ecard_logo`:

```
<?php
$ecard_logo = field_view_value('node', $node, 'field_ecard_logo', $node->field_ecard_logo[$node->language][0]);
print render($ecard_logo);
?>

```

... works but kind of nasty. I'd rather put all the logic in my theme's template.php and simply print a variable I've created. Looking at what preprocess functions the Print module uses, I see `preprocess_print` and `preprocess_node`. So I tried this in template.php:

```
  function MYTHEME_preprocess_print($vars) {
      $node = $vars['node'];
      $vars['ecard_logo'] = field_view_value('node', $node, 'field_ecard_logo', $node->field_ecard_logo[$node->language][0]);
    }

```

and then in `print--node--ecard.tpl.php`, I simply do:

```
<?php print $ecard_logo; ?>

```

but that does not work. I tried different incarnations of all this but no joy so at this point I'm stumped.

# Answer
> 7 votes
After a few days of working on this, it ended up being pretty trivial to accomplish this so I'll answer my own question for those who need help in the future. I had most of the solution working but in my custom print template, the key was to have:

```
<?php print render($ecard_logo); ?>

```

*NOT:*

```
<?php print $ecard_logo; ?>

```

So the full function in `template.php` is:

```
/**
  * Renders the content of the print page using the theme api.
  */
function usfig_preprocess_print(&$vars, $hook) {

// Global node.
$node = $vars['node'];
// Compartmentalize only for ecard content type.
if($vars['node']->type == 'ecard') {

// Create a var and render using field_view_value, we don't need anything special for this, otherwise use field_get_items for data parts.
$vars['ecard_logo'] = field_view_value('node', $node, 'field_ecard_logo', $node->field_ecard_logo[$node->language][0]);
}

}

```

... and then in my custom print template I do:

```
 <?php print render($ecard_logo); ?>

```

and it works!

***Extra credit:***

You can create and render an image style with `field_view_value` as well like so in your theme's template.php file:

```
 $vars['ecard_image'] = field_view_value('node', $node, 'field_my_image', $node->field_my_image[$node->language][0], array(
      'type' => 'image',
      'settings' => array(
      'image_style' => 'my_custom_image_style',
      'image_link' => 'none',
      ),
      ));

```

Then just render the variable in your custom template file! What's the advantage to all this? It allows for ultra minimalist markup and precise themeing where layout and exactness are crucial. It cuts way down on the "divitis" that drupal tends to have.

# Answer
> 0 votes
From personal experience in these situations it's better to incorporate all the logic into a custom module, so basically you create there your functions for processing data, and these functions are available throughout the whole site by calling the function.

In your current code i think that the variable can be accessed by defining it in your tpl through `GLOBAL $ecard_logo;` . I haven't tested this so let me know if this helps.

Cheers

---
Tags: 7, theming
---


title: Number of Front Page Nodes Variable?

text:
# Question
Title: Number of Front Page Nodes Variable?
I'm aware of how to change the number of nodes displayed on the front page. My question is whether there is a variable in Drupal, or a way of calculating the numbers of nodes displayed per page of front page content?

I've got a block module that prints out information according to the nodes that are being rendered in the main content area of the front page, so it needs a list of the nodes. If there is an array of nodes that can be accessed that would also work, but I can't find information on that, so I've been trying to calculate the items per page, but merely dividing the total number of front page nodes divided by the number of pages gives inconsistent results of course.

I could of course hardcode the number, but I'd prefer a programatic way for determining this value.

# Answer
This value can be set in the site information admin settings form.

```
$count = variable_get('default_nodes_main', 10);

```

This should work for both Drupal ,  and .
> 3 votes

---
Tags: 7, blocks, paging, nodes
---


# Question
Title: How to show a field from the current node in quicktabs
I have a quicktabs block on the node page which will have several tabs with different views/content related to the current node. How can I show a field from that node in a separate tab?

# Answer
> 1 votes
Depend from requirements in the project, but Field Group can be an option too.

# Answer
> 1 votes
1. Install the Field As Block module (https://drupal.org/project/fieldblock)
2. In the Manage Display section of your content type, check the "Display As Block" checkbox next to the field you want to display in a quicktab
3. Add a tab to your quick tab with a tab type of block then select your field from the list of blocks.

The Field As Block module will create a block from the node's field.

# Answer
> 0 votes
Seems a little overkill for just showing only one field but here's how I 'd do it. Create a view block with a nid contextual argument. Add the desired field you want to display to the views fields. Then from the quicktabs administration create a tab that will use the view you just created.

The block should grab the nid from the node you are and display accordingly the content of the field.

---
Tags: 7, blocks
---


# Question
Title: Filter taxonomy terms in common to nodes related to the viewed node
I want to filter taxonomy terms in common to nodes related to the viewed node, but I cannot figure out how. What I am getting are all the terms that the related nodes have (with repeated terms too). Please take a look at this recipe page, side block STAG RICETTA

I am filtering *seasonality* terms (months) in common to *ingredients* nodes (the ones related to the node being viewed) used in a *recipe* node (the viewed one).

How can I achieve this?

# Answer
> 1 votes
To show a list of season terms on the ingredient nodes related to the recipe node:

1. Create a view of taxonomy terms of type season.
2. Add a relationship: `Taxonomy term: Content with term`
3. Add a relationship: `Entity Reference: Referencing entity (A bridge to the entity that is referencing Content via field_recipe_uses_ingredient)` via the relationship created in step 2.
4. Check "require this relationship".
5. Save.

---
Tags: views, entities
---


# Question
Title: Is there a way to have a views filter value be determined by PHP?
I need to search for fields that are equal to the value of a visitor cookie. How do I get $\_COOKIE\[somecookie\] as the criterion value in the views filter? (I know that I could use views\_php to grab all the records and filter out after the fact but that's a lot of records and would be far too slow.)

It would be preferable to be able to do this without writing a custom module. It seems like this would be a common request by admins so I feel I'm missing something obvious.

# Answer
Setup the page to use a `contextual filter` per `field` you want to be searchable. Then for the contextual filter set it to look for the value `provided by the URL`. Then select `PHP Code` for `WHEN THE FILTER VALUE IS NOT IN THE URL`.

In that PHP blob supply code that pulls the field argument from `$_COOKIE`, if any or return `NULL`.
> 2 votes

---
Tags: 7, views
---


# Question
Title: group same fields in views using custom template
drupal 6 user here. I am sure that this is basic views question but I can not figure answer to it. I have a simple view with 2 fields - node title (field\_title) and node author (field\_author). I want to print all data separate so that node titles would be printed inside ONE single separate div and node authors would be printed in another div. This can not be achieved using rewrite option as far as I know. Can anybody help me with this? Thank you.

# Answer
> 0 votes
1. Go to your view: admin/build/views
2. Edit your view: admin/build/views/edit/view\_name
3. Look at your fields node title (field\_title) and node author (field\_author) and click on Node:Title for instance
4. Once editing the view output of the Node:Title field, check "Rewrite the output of this field"
5. You should see replacement patterns: \[title\] == Node: Title

In the Rewrite this field section called "Text:" enter

```
    <div class="some-class-name">[title]</div>

```
1. Repeat 3,4 and 5 for the Node:Author field.

```
<div class="some-class-name-author">[author]</div>

```
2. You can put anything else in the rewrite field here.

(note: D7 has more options that using the rewrite method)

---
Tags: views, 6, theming
---


# Question
Title: Create Products with overlayed images from the default images
I'm using D7 and Commerce. I want the ability to create products based off a default image for a product type & image that our designers will upload to create the final product. Think of something like zazzle.com.

Imagecache\_Actions I've used this module before for the 'overlay' feature butit didn't work as desired. Its Possible I didn't set it up correctly. (This might be the key to the answer)

How can I create a product that uses the combined 'default image' & an uploaded design used to overlay and combine as the final image for a product?

Would also like the ability to place to adjust the position and size of the overlay image.

# Answer
Image Cache Actions will allow you to set up image styles that overlay images onto another preset image, such as a T Shirt template.

For your own designers, using Photoshop to place the designs on a template is probably a much better option than having them mess about with a web app.

For customers, Commerce Custom Product looks like it might be the submission flow you're looking for, but you'll need your customers to submit high res designs for you to work with on the product you're shipping - and you'll need to test this to destruction on different browsers and devices.
> 3 votes

---
Tags: 7, commerce, media
---


# Question
Title: Alter entity_translation vertical tab access
**How can you set #access to false for the vertical tab "Translation" (entity translation) on the node edit form?**

When using entity translation and a user has the permission to edit a node and edit translations, a new vertical tab is injected in the node edit form:

> **Translation**
> *Translation is published. Do notflag translation as outdated*
> \[x\] This translation is published
> \[ \] Flag translation as outdated

Since I have editors that need to edit translations but shall not have access to this v-tab (it is being confused with the *Publishing options* for the node, leading to people altering the translation status where the node in its entirety should be unpublished/published instead).

Using `hook_form_alter()` in a custom module, I do not find any trace of the above form element in the `$form` array. According to a grep search, it is defined in the file `/modules/entity_translation/includes/translation.handler.inc:1051`. I assume it is being cached somehow, as that part of the code is not being executed when the form is built (breakpoints do not trigger).

Worst case, I could use Javascript to hide the form element, but I would rather not have to rely on such a hack. If possible, I would like to set #access to false for the editor role (or similar).

# Answer
The reason you cannot use hook\_form\_alter() to modify the tabs is because the hook you implement in your custom module is being fired before entity translation injects the tab.

If you use hook\_module\_implements\_after() you can change the order of the execution of the hooks.

```
function CUSTOMMODULE_module_implements_alter(&$modules, $hook)
{
    if ($hook == "form_alter")
    {
print_r($modules);
        // save off hook
        $temp = $modules["testing"];

        // remove it
        unset($modules["testing"]);

        // add it to the end
        $modules["testing"] = $temp;
print_r($modules);
    }
}

```

The first print\_r outputs:

```
Array
(
    ...
    [CUSTOMMODULE] =>
    [entity_translation] =>
)

```

The second print\_r outputs:

```
Array
(
    ...
    [entity_translation] =>
    [CUSTOMMODULE] =>
)

```

Now that the custom module fires after entity translation, use hook\_form\_alter() to hide the tab:

```
function CUSTOMMODULE_form_alter(&$form, &$form_state, $form_id)
{
    // make sure you set the form_id in this conditional properly.
    // I am using the edit form of a "page" node type.
    if ($form_id == "page_node_form")
    {
        $form["translation"]["#access"] = FALSE;
    }
}

```
> 2 votes

---
Tags: forms, i18n-l10n
---


title: HTML: formatting instead of WYSIWYG

text:
# Question
Title: HTML: formatting instead of WYSIWYG
I personally tend to hate WYSIWYG editors. They take time to load and just love plain old HTML, so I just disable the editor entirely. However, I would like to have HTML from the database to be prettyfied or beautified or ... well, loooking sexy for the time of editing with indents, newlines, etc. Any module out there that does that?

# Answer
> 1 votes
There's a patch here to provide support for Ace code editor in wysiwyg module.

From Ace's website:

> Ace is an embeddable code editor written in JavaScript. It matches the features and performance of native editors such as Sublime, Vim and TextMate. It can be easily embedded in any web page and JavaScript application. Ace is maintained as the primary editor for Cloud9 IDE and is the successor of the Mozilla Skywriter (Bespin) project.

I'm not aware of any other source code wysiwyg editor supported by wysiwyg.module.

# Answer
> 2 votes
You're looking for HTML Tidy module.

> This module tidies Drupal's HTML output with HTML Tidy by optionally sanitizing it when it is saved or when it is displayed, like a traditional input formatter. Missing and mis-ordered tag components are replaced and reordered automatically so that user input doesn't break site structure with open tags and the like.
>
> User interface configuration supports:
>
> Code indenting: Automatically format HTML for easier reading, or strip indenting for proper parsing and display in the less compliant browsers. Word wrapping: Automatically wrap lines in an intelligent fashion once they get to a specified length Info/Warning/Error information: Optionally appended to pages and includes details about the wrong HTML attributes and W3C validation info.

---
Tags: wysiwyg
---


title: Does Redis make Authcache redundant?

text:
# Question
Title: Does Redis make Authcache redundant?
Currently my D6 site relies heavily on Memcache and apc to deal with high load of a busy social site. The memcache is on a single webserver and the database on another server.

So I am wondering, apart form being persistent (hence no need for a warm-up), whether Redis makes authcache redundant and hence avoids security issues?

# Answer
> 9 votes
No, it unfortunately does not.

Redis and Authcache are two completely separate systems/concepts, one cannot be used in place of the other.

Redis is a key/value store, primarily used in Drupal as a cache backend.

Authcache provides the *mechanism* to store/serve cached pages to authenticated and un-authenticated users alike. It *uses* a cache backend such as Redis for storage, but it is not *itself* a cache backend.

On the flip-side, Redis is a dumb key/value store, that has no concept of authenticated/unauthenticated users. It cannot be used to replace the functionality provided by Authcache, which is necessary to (amongst other things) build appropriate cache ids based on the user's authentication status, and persist rendered pages, or parts of pages.

The How does Redis compare to Authcache? thread you linked to, in the (now deleted) comments, puts it nice and succinctly:

> the question isn't about Authcache, it's really "Memcached vs Redis".

Which I agree with, and is actually what the original revision of your question was asking. So it kind of all makes sense.

Just in case you're basing the question on this obsolete bit of information from the Pantheon docs:

> "Redis adds caching for authenticated users, which can greatly alleviate request bottlenecks..."

Please note that advice has now been removed as it was misleading. Redis does not provide caching for authenticated users in and of itself, but it can be a part of that process if Authcache is enabled over the top.

BTW I should add that I wish Redis *did* make Authcache redundant - I'm right in the middle of converting a large social site to use authcache, and it's not an easy process. The above 'knowledge' has been gathered through extensive reading and back-and-forth with the Pantheon engineers.

Also, slightly off topic but possibly relevant to your decision making process: the Pantheon engineers recommend the authcache approach over something like ESI, because of the increase in the number of app-server bootstraps. So if you're looking for an advanced caching solution for auth'd users, authcache is probably the best way to go.

---
Tags: 6, caching
---


# Question
Title: Which hook is used to alter a field's description?
Which hook should I use to alter description of a field?

I want to add some descriptions to fields in several content types. because number of fields and content types are too many, I prefer to add descriptions programmatically.

# Answer
To the best of my knowledge there's no hook for that. Instead you'll want to use the following API functions in whatever context makes sense in your site:

* `field_info_instance()`

> Returns an array of instance data for a specific field and bundle.

Use the function to load up an array of instance data/settings, which you can then alter as necessary before passing back to:
* `field_instance_update()`

> Updates an instance of a field.

That will persist your changes to the database, and take care of clearing relevant caches.

A complete example might look like

```
$info = field_info_instance('node', 'body', 'article');
$info['description'] = t('New description');
field_instance_update($info);

```
> 3 votes

---
Tags: entities
---


# Question
Title: No administrative CSS for arabic language
I have a multilingual website with English, French, and Arabic; I updated from Drupal 7.22 to 7.23 and I found that I don't have the CSS for the homepage in Arabic, as the image below.

Why is it happening? How can I fix this?

### Notes

I'm aggregating and using Advanced CSS/JS Aggregation advagg. I'm using Boost module.

# Answer
> 0 votes
OK i find the solution: i emptied all the cache tables manually in the database and it's ok

# Answer
> 0 votes
By default, many themes have a separate RTL template or CSS. Depending on what theme you are using, you may have to create RTL CSS or change the behavior of which CSS files it's looking for. Try searching for a \*-rtl.css file (where * is some name that comes before the suffix.)

---
Tags: theming, i18n-l10n
---