# Question
Title: Can't login: user/login redirects to live site
I copied a live site built by a previous developer to my local MAMP environment, and discovered that trying to use /user/login redirected me to the live site. I discovered that .htaccess had numerous **dreaded** 301 redirects. So, I changed the .htaccess to a clean one, cleared cache, cleared history, rebooted MAMP, tried a clean browser. I think I've now cleared the 301 redirects to regular pages, but user/login still goes to the live site.

Created fresh local install with a clean .htaccess; clear cache, reboot MAMP, etc, still can't login to local.

Is there a backend way to login to drupal? Through drush?

Could that demon-spawn developer have set something else that prevents local login?

# Answer
If the live site uses HTTPS, implements SSL, try to check if is using modules like secure\_pages. This kind of modules sometimes causes that kind of redirections.

Another thing to check could be the settings.php to see if there are something related to this issue.
> 3 votes

# Answer
If you're using Domain or something like this, what I did (on Windows) was editing the "hosts" file to redirect the production site URL (http://www.production.com) to 127.0.0.1.

So all your requests to your production site will be redirected to localhost.

After that, edit your domain settings to set the domain to 127.0.0.1 (or the URL you access your development website).

Finally, delete the redirection in hosts file.

I would also suggest to check for custom modules and clear cache with drush.
> 2 votes

# Answer
Another module that can cause this problem is Ubercart SSL. I was being redirected when attempting to login and it took me a while to figure out which module was the culprit. `drush dis uc_ssl` did the trick.
> 0 votes

# Answer
If Secure page causing the issue then you can disable it with following ways

1) Drush command

**drush dis -y securepages**

2) Disable the status in DB

**UPDATE system SET STATUS =0 WHERE name = 'securepages'**
> 0 votes

---
Tags: users
---


title: First time user login, page redirect

text:
# Question
Title: First time user login, page redirect
I am having difficulty getting drupal to redirect a user to a specific page after completing the registration form.

In the user.module file there is this:

```
// No e-mail verification required; log in user immediately.
elseif (!$admin && !variable_get('user_email_verification', TRUE) && $account->status) {
    _user_mail_notify('register_no_approval_required', $account);
    $form_state['uid'] = $account->uid;
    user_login_submit(array(), $form_state);
    drupal_set_message(t('Registration successful. You are now logged in.'));
    $form_state['redirect'] = '';
}

```

I would have assumed that by entering the path you wish to redirect to, in the form redirect ,it would redirect. For example:

```
$form_state['redirect'] = '/page/I/Want/To/Redirect/To';

```

However this is not the case. When the user is logged in after completing the registration form they are taken to the homepage.

Once the user is logged in (from the registration form) I wish to send them to our services page. But for them to be sent to the homepage every subsequent time they login.

# Answer
> 3 votes
There is a very simple way to that using the Rules module.

# Answer
> 0 votes
You shouldn't modify core files like that. It doesn't break anything, but it's not considered good practice.

Instead you can implement `hook_form_alter` and modify the `#redirect` of the form, or add your own submit handler (`#submit`) to the `user_register_form`, then in that submit handler you can modify the `$form_state['redirect']`.

# Answer
> -1 votes
You can use multiple modules Rules, Login Destination and LoginToboggan.

Check Reference link from Drupal Document for more help.

---
Tags: users, redirection
---


# Question
Title: LDAP authentication module not working in xampp
When i enabled LDAP module for drupal 7 then always shows error No LDAP PHP Extension is loaded for PHP, so LDAP will not work properly. even after un comment extension=php\_ldap.dll from my php.ini, it is not working.i restart apache and php\_ldap.dll is also in php extensions.

# Answer
Yes i have sorted out this issue. In the \xampp\php folder you will find this file:libsasl.dll Copy it into the \xampp\apache\bin folder. Now try and start Apache again.It should now start.Now it is working.
> 2 votes

# Answer
Cross check following points.

1) Enable extension = php\_ldap.dll

2) Check do you have php\_ldap.dll file in your php extensions folder. If not, download the file and place it in php extension

3) Restart Apache Server.
> 0 votes

---
Tags: authentication-authorization
---


# Question
Title: How to add a new element in drupal 7 feed view
I have created a simple feed with drupal 7 views and i want to add some more elements. currently it supports title, description, link, creator and pubdate. I DON'T want to use any other module.

# Answer
> 0 votes
Views doesn't provide that functionality, so if you want to configure this via the UI you need to install Views RSS (or another module that provides similar functionality); you don't have another option, apart from writing it yourself.

If you just want to hack something together you can use just manually append your extra elements to the output string, e.g.

```
function MYMODULE_preprocess_views_view_row_rss(&$vars) {
  // Add an image.
  $node = node_load($vars['row']->nid);
  if ($node) {
    $wrapper = entity_metadata_wrapper('node', $node);
    try {
      $vars['item_elements'] .= '<image>' . $wrapper->field_images[0]->file->url->value() . '</image>';
    }
    catch (\Exception $e) {
      // No need to recover, just means there's no image.
    }
  }
}

```

But it's not exactly ideal, better to use the purpose-built module.

---
Tags: views, theming, feeds
---


# Question
Title: Get term value from user field and set that value to new field
How to get term from user field and set that to the field in node? When user is creating node I need to get term and set it to the node field.

I have field\_term\_reference in user fields and in node I have field\_book\_reference field. I need to get term from field\_term\_reference and set that term to the field\_book\_reference.

Both fields has autocomplete widget.

Here is my current non-working code:

```
function set_value_node_presave($node) {
global $user;
$user = user_load($user->uid);
$term = field_get_items($user, $account, 'field_term_reference');

$node->field_book_reference[$node->language][0]['value'] = $node->$term;

}

```

**SOLVED** Here is working code:

```
function set_value_node_presave($node) {
global $user;
$user = user_load($user->uid);
// Get field from user
$term = field_get_items('user', $user, 'field_term_reference');

$node->field_book_reference[$node->language][0]['tid'] = $term[0]['tid'];

}

```

# Answer
`$node->$term` definitely isn't what you want. Taxonomy references are stored by `tid`, so

```
$node->field_book_reference[$node->language][0]['tid'] = $term[0]['tid'];

```

should work
> 2 votes

---
Tags: 7, entities
---


title: if user is logged in only

text:
# Question
Title: if user is logged in only
I have a section of my drupal website that I only want displayed to users that are logged in. So if they click on "My Page" link and the user is not logged in it should redirect them to a login screen. I have attempted to complete this task by using the following code.

```
<?php
if (!user_is_logged_in()) drupal_goto('user/login'); ?>

```

This doesn't seem to throw any coding errors but none of my links such as register, login etc work. I get an error that I have a redirect loop that will never complete. I cannot seem to find a good solution for completing this.

# Answer
If you write down this piece of code outside any hook or function, it is normal that it loops because the user is always "not logged in".

However, if you've created your "page" through the admin menu system, as Parvind said, you can use Menu Access module or use that piece of code:

```
function hook_node_view($node, $view_mode) {
  if($node->nid == 'yournodeid" && $view_mode == 'full') {
    if (!user_is_logged_in())
      drupal_goto('user/login');
  }
}

```

If you've created the node programmatically (hook\_menu()), you can use access argument like this:

```
$items['testpage'] = array(
  'title' => 'Authenticated users',
  'page callback' => 'test_func',
  'description' => 'This page is accessible to authenticated users only',
  'access callback' => 'user_is_logged_in',
  'type' => MENU_CALLBACK,
);

```
> 1 votes

---
Tags: 7, theming
---


# Question
Title: On submission function is not being called in custom module
I have written a custom module for form submission the first time but submit button is not working.

Here is the code:

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

$node = array();
$pl_name=array();
$pl_name=getplaylist_to_edit(arg(1));

$node['text'] = array(
'#type' => 'textfield',
'#id'=>'edit-playlist-name',
'#value' => $pl_name[1],
);

$node['submit'] = array(
'#type' => 'submit',
'#value' => 'Update',
'#submit' => array('test'),
);

return $node;
}

function test()
{
echo '<script>alert("You have submitted the form.");</script>';
}

```

# Answer
> 0 votes
Could you try like this:

```
function my_form($form, &$form_state) {
  $pl_name=array();
  $pl_name=getplaylist_to_edit(arg(1));

  $form['text'] = array(
    '#type' => 'textfield',
    '#id'=>'edit-playlist-name',
    '#value' => $pl_name[1],
  );

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

  return $node;
}

function my_form_submit($form, &$form_state){
  echo '<script>alert("You have submitted the form.");</script>';
}

```

# Answer
> 0 votes
I just ran something similar to your callback function in my local test enviroment. For me the function was getting called, the echo/print wasn't doing anything. Try using a `drupal_set_message('you have submitted the form');` in stead of echoing out the java call to see if that gets fired.

I'm not 100% sure on this, but I THINK the reason this is happening is due to a redirect or page refresh that's happening after your submit function is called. That would wipe away anything you echo or print out from that function. As a general rule, it's probably best to stick with ether drupal\_set\_message to print messages out to the user, or download and install devel and use dsm() to print out test messages.

---
Tags: 7
---


# Question
Title: Creating custom form at registration process for unknown number of nodes
I have a project where I want to add one OR more "nodes" or content types at registration time. For example, I enter my name and email adress, and then I can add one or more trip (example) I made, and then, later, the content of the site itself will be modified by this information. For example, the main menu could display a tab for each trip (trip1, trip2, etc.).

Any idea where I should start?

# Answer
You can try with

`field_attach_form` to attach the 'trip' content type's fields to user form. (with an alter can become multivalue)

on submit you can use these values to populate the trip entity with `entity_metadata_wrapper` and create a new node

you can build N menu\_items than are the trip of the user by a custom menu
> 0 votes

---
Tags: forms
---


# Question
Title: Get field value in an entity form validation
In an entityform "form\_alter" function I have $form\_state with all the info inside I need. I could "hard-code" the language, but this is a multi language site... The information needed is at: `$form_state['values']['field_myone']['en'][0]['value']`

I'm aware of field\_get\_items or entity\_metadata\_wrapper, but I can't get either one to work.

This doesn't give me a wrapper back:

```
$wrap = entity_metadata_wrapper('entity_form', $form_state);

```

And this one doesn't work either:

```
$val = field_get_items('entityform', $form_state, 'field_myone');

```

Any help out there?

Thanks!

# Answer
I am also interested. Please post the answer if you solved.

This code:

```
$node = node_load($form_state['node']->nid;);
$node_wrapper = entity_metadata_wrapper('node', $node, array('bundle', $node->type));

```

solves in case you are editing a previously saved node (and the `nid` is then existing).
> 0 votes

---
Tags: forms
---


# Question
Title: Views contextual filters taxonomy name 2 fields using same vocabulary
I have a content where two fields using the same vocabulary. I want to show nodes related content filtered by the these fields.

I try with relation

**Relationships**

* content:field\_1
* (term from field\_field\_1) Taxonomy term: Content using field1 (Relationship term from field\_field\_1 ; Require this relationship )

**Contextual filters**

```
   (field_field_1) Content: field_2

   Provide default value : Taxonomy term id from url
   Load default filter from node page
   Limit terms by vocabulary ( country)

   Specify validation criteria ( taxonomy term )

    Vocabularies : Country
    Filter value type : Term name converted to Term ID
    Transform dashes in URL to spaces in term name filter values

```

This query returns nothing.

I don't want to use Views PHP code fields because of security concerns.

# Answer
If I understand your question correctly, out of the box the easiest way is to add a Contextual Filter Content: Has Taxonomy Term Id. This one does not care whether you have 1 field or 20 that reference taxonomy terms. Further details within are whether you want to match from URL on term id or term name, etc.

I came across your question whilst seeking an answer to mine How to filter on taxonomy term but only match one field on the node, where two fields (primary and secondary) both use the same vocabulary which I think is different.
> 0 votes

---
Tags: 7, views
---


title: Solr Search with 2 text fields

text:
# Question
Title: Solr Search with 2 text fields
I have a drupal 7 installation with apache solr search: But I need to use a custom search like this:

2 TextBox fields with:
What -\> Any word of the apache index.
AND
Where -\> A term reference in the content type.

# Answer
After looking for several forums and apache solr help, I made it like this...

Notes:

1 $form\_state\['values'\]\['keys'\] - The search text

2 $form\_state\['values'\]\['localidade'\] - The taxonomy term search value

function MYMODULE\_search\_block\_form\_submit($form, &$form\_state) {

```
// Check if localidade is empty
    if (empty($form_state['values']['localidade'])) {
    // localidade empty
        drupal_goto('pesquisa/' . $form_state['values']['keys']);
    } else {
    // with localidade
    // check what is the tid of my term localidade
        $t1 = $form_state['values']['localidade'];
        $t2 = taxonomy_get_term_by_name($t1, "localidade");
        $t3 = array_shift($t2);
    // term no found
        if (empty($t3->tid)) {
            drupal_set_message('Não reconheçemos a localidade ' . $form_state['values']['localidade'] . ', por favor coloque uma localidade sugerida.');
            drupal_goto('pesquisa/');
        } else {
    // build search parameter with the term tid
            $t11 = 'pesquisa/' . $form_state['values']['keys'];
            $options['query']['search_param'] = 'f[0]=bundle:empresa&f[1]=im_field_localidade:' . $t3->tid;
            drupal_goto($t11, $options);
        }

 }

```

}
> 0 votes

---
Tags: search
---


title: Log a user in manually, get session?

text:
# Question
Title: Log a user in manually, get session?
A service I have takes a username, and should find and log in a local Drupal user account with that username. After logging in, I need the session ID (from the sessions table) for that users new session.

I have some basic procedural code that I'd like to refactor for Drupal 8 practices:

```
$user = user_load_by_name($username);
if ($user) {
  user_login_finalize($user);
}

```

1) What's the OO way of loading a user entity? A service I found that may help loading a user is `entity.manager`, but is that the right way to do it?

2) Logging a user in? Should I just take the code from `user_login_finalize` and try and inject the services used and essentially "copy" what's done in that function?

3) After the user is logged in, how can I get their session information? Injecting the `current_user` service doesn't work, because the user data in there is stale after I log the user in.

**EDIT**: Looks like a user's session is not saved until `AuthenticationSubscriber` runs (listens for kernel response event), which is when the session data would be saved. Maybe I can manually save the session before then, and then obtain session? Not sure what that would impact.

# Answer
1. For general entity, yes you can use entity.manager service.

For user entity, you can use \Drupal\user\Entity\User. However in your case, you are going to load user by username, this can't be done by User Entity class, you have to use `entity.manager`.

`user_load_by_name` will call something like this:

```
$entity_manager = Drupal::service('entity.manager');
$user = $entity_manager->storage('user')->loadByProperties(array('name' => $nusername));

```
2. I will just use this function if there is no reason to replace it.
3. Use the session\_manager service.

```
$session_manager = Drupal::service('session_manager');
$session_id = $session_manager->getId();

```
> 1 votes

---
Tags: 8
---


# Question
Title: How to redirect to top level domain and not relative value
Under admin/config/system/site-information, the startpage is configured as /home. So when you go to www.domain.com, the content of /home is displayed. However, when a form is submitted, it automatically redirects to www.domain.com/home. Is there any way to prevent this?

# Answer
I resolved it as follows:

in the form submit handler, I simply added:

```
$form_state['redirect'] = '<front>';

```

Hope this helps someone...
> 3 votes

---
Tags: redirection
---


# Question
Title: How to print a view in node.tpl.php only if it's not empty
Views can be printed in tpl.php files with this code:

```
<?php print views_embed_view('myview','block_1'); ?>

```

However, if that view is empty, the view block code will be printed anyway:

```
<div class="view view-myview view-id-myview view-display-id-block_1 view-dom-id-abc123..."></div>

```

Is it possible to check if the view has any results first and then print it if it does? E. g.:

```
<?php if ($view_myview,block_1): ?>
<?php print views_embed_view('myview','block_1'); ?>
<?php endif; ?>

```

# Answer
You can check it using the below code

```
<?php
$viewName = 'myview';
$displayid = 'block_1';

$view = views_get_view($viewName,$displayid);
$view->execute();
$reviewCount = count($view->result); //It will return number of results
if($reviewCount>0){
print views_embed_view($viewName,$displayid);
}
?>

```

Hope it will help.
> 3 votes

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


# Question
Title: Global search/replace on special characters accidentally taken in on an import ( â€™ )
I have imported (through CSV using Feed Import) and large amount of information. I have a large amount character encoding issues such as

> Grimsbyâ€™s teaching focus is on...

Where `â€™` is in place of the apostrophe. Is there any way to search/replace myself out of this? Could I use an input filter?

# Answer
You can try the scanner module to do these sitewide text search and replace operations but it may be a little tricky because of the characters you're replacing (they look like MS smart quotes?)

Better solution might be to rollback your import, rexport your CSV with a UTF-8 character set and try your import again.
> 3 votes

# Answer
I ended up putting an input filter in place

```
function utf_fix_filter_info() {
    $filters['utf_fix_filter'] = array(
        'title' => t('UTF Fixer'),
        'description' => t('Fixes UTF oppsies'),
        'cache' => TRUE,
        'process callback' => 'utf_fix_substitute',
        'tips callback' => 'utf_fix_filter_tips',
        );

    return $filters;
}

function utf_fix_substitute($text, $filter, $format, $langcode, $cache, $cache_id) {

    $text = str_replace('â€™', "'", $text);

    return $text;
}

function utf_fix_filter_tips($filter, $format, $long) {

    return t('Replaces â€™ with an apostrophe');
}

```
> 1 votes

# Answer
I successfully used the Scanner module to replace smart/curly quotes with plain quotes.
> -1 votes

---
Tags: migrations
---


# Question
Title: Open Atrium 2: comment forms not appearing on pages
**Situation:**

* Recently created a fresh Open Atrium 2 installation to replace an old AO1.
* No content from the old OA1 database has been migrated, we're making a fresh start. Some content (a few pages) will be recreated by copy-pasting the content.
* No anonymous access allowed, only authenticated users have acces to any content. Only admins can create user accounts.
* As of yet, no groups and teams have been made -- there's only a handful of users. The actual userbase will be small enough that it can be managed simply by giving individuals access to certain spaces; groups and teams may be made later if the need arises. (I'm still partially in OA1 mode, really :) )

---

**Problem:** Comment forms do not appear anywhere in the site, for any user level (authenticated, editor, admin).

---

**I have:**

* checked whether the required comment modules are enabled (they are)
* checked permissions; authenticated users can view & post comments, skip approval & edit their own comments
* made sure commenting is enabled for that content type (it is by default, no settings changed there)
* made sure it's not simply a matter of permissions not being retroactive. Newly created content still has the same problem, though.
* checked individual nodes (in this case, calendar events) to make sure comments are open
* spent several hours googling, but found nothing beyond the things I've already tried.

---

Most likely I'm simply overlooking one little setting somewhere, but right now this has me stumped... Any pointers would be highly appreciated.

# Answer
I believe you need to add the comment box via panels. Admin \> Configuration \> Content Authoring \> Panelizer \> Content \[link to the right of Your Content Type\]
> 0 votes

---
Tags: nodes, comments, distributions
---


# Question
Title: Getting error rendering same node in different view mode
Unsupported operand types in /node/node.module on line 1419

On my site users have the ability to flag a content type (node) as being featured on the right rail. I then have a view that renders a view mode called card\_view of that specific node. This works great but if you attempt to render that card\_view view mode on the same page as the full content view mode you get an error above. Debugging the error occurs when rendering the full content and not the card\_view. This also occurs when attempting to render it programmatically:

```
// Error occurs here (snippet from node.module line 1419)
  $node->content += field_attach_view('node', $node, $view_mode, $langcode);

// Error occurs viewing full content and attempting to render same node in a different view mode
$node = node_load($nid);
$node_view = node_view($node, $view_mode = 'card_view', $langcode = NULL);
echo drupal_render($node_view);

```

If I remove the attempt to render this node in this view mode it works fine, and also if I attempt to render a separate node it works fine as well, it ONLY occurs when rendering the node view mode on that same node full content page.

# Answer
> 0 votes
I found the solution but do not know the actual cause. Apparently I have to clone the current node to avoid conflicts:

```
$node = clone menu_get_object();
$node_view = node_view($node, $view_mode = 'card_view', $langcode = NULL);
echo drupal_render($node_view);

```

If anyone has any detail feel free to edit or add a comment.

---
Tags: nodes, entities
---


# Question
Title: How to filter on taxonomy term but only match one field on the node, where two fields (primary and secondary) both use the same vocabulary
Using Drupal 7 Views \> Contextual Filter, how can I filter on taxonomy term but only match one field on the node, where two fields (primary and secondary) both use the same vocabulary? I have a vocabulary "Category" and I have organization nodes that can reference a category in either a Primary or Secondary field. The concept is that organizations can primarily serve one topic of interest but can secondarily serve others.

I thought I had great, early success, but on closer inspection, the term is matching against both fields (like taxonomy ought). I have had no luck in setting up only the primary field as the contextual filter for a term name, nor have I been able to first filter on taxonomy and then filter on the primary field.

What am I missing here?

Edit: Hmmm.. I wonder if it's because content fields in Views maybe match on "value" and category fields present themselves as "tid"?

Note: I don't think this is the same as Drupal 7 views contextual filters taxonomy name 2 fields using same vocabulary but I do love the way that one was titled!

# Answer
Ok - This is also out of the box Taxonomy Term behavior. My issue was I was selecting the wrong option for what I wanted. I wanted the behavior that converts term string to tid, and so the full solution is:

* Contextual filter on Content: Primary Category field
* Specify Validation \> Taxonomy Term, my vocabulary
* Select the option Term name converted to Term ID

Bam! Success! Now I get my list of nodes matching that vocabulary's terms as strings but only for the one of the multiple taxonomy fields of that vocabulary on the node. To further exemplify, my next step will be to create another View that is all the Secondary matching terms as "related" but not primary like this one is.
> 0 votes

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


title: Is there a process to run a task daily

text:
# Question
Title: Is there a process to run a task daily
I have business logic that interfaces with Drupal entities (in this case, users), and we need to generate reports off these records daily at a preset time. It would be easy for me to generate this data on-demand, but the requirements ask for a daily report.

I'm wondering if its possible in D7 to have the system schedule a specific cron task to run at a preset task over the time cron is expected to run (which right now, is every 3 hours). Another option I am considering is to have a Contrib Drush script that simply runs using the OS'es crontab/launchd. Which one makes the most sense?

# Answer
> 2 votes
I had to do something similar recently. The extremely simple answer I came up with was to simply keep track of the last time the function was run with a db variable.

So, in psudo code, I ended up doing something like this:

```
function hook_cron(){
  $now = new DateTime(date(DATE_ISO8601));
  $last_checked = new DateTime(variable_get('last_checkedvar', date(DATE_ISO8601, '0')));
  $diff = $now->diff( $last_checked );

  if ($diff->days >= 1){
    //do your stuff
  }
}

```

Works well for me. And it also doesn't interfere with any of the other cron tasks I have running on my site.

---
Tags: 7, cron
---


# Question
Title: Feeds Setup to Automatically Update and Delete Nodes
I have an RSS feed from which I use Feeds module to fetch data from this to create nodes of a particular content type, I then use Views to display this information.

**What settings do I use to setup Feeds module to automatically keep the nodes created in sync with an RSS feed?**

This seams like it should be quite easy but I am coming across some trouble with this. The RSS feed has new items added, items updated and items deleted, so the feeds module need to look for all of these and be in sync with these changes.

These are my Settings:

* Attached to: None
* Use Standalone form
* Periodic import: Often as possible
* HTTP Fetcher
* XPath XML Parser
* Replace existing nodes
* Skip has check
* Expire nodes: after 1 day (this I set to delete nodes to keep in sync with items being removed)
* Elysia Cron is set to run update at 2am.

# Answer
What version of Feeds are you using? Deletion of existing items is not currently in the latest stable release, but it is in the latest dev release of the Feeds module, 7.x-2.x-dev (2014-Sep-17).
> 2 votes

---
Tags: feeds
---


# Question
Title: Quantize/dither image using ImageMagick commands on image style actions
Is there a way to use custom imagemagick commands on a image style action. I'm trying to create a dither effect like the ones shown on the examples on the imagemagik site: http://www.imagemagick.org/Usage/quantize/#dither.

Here's another example: http://caca.zoy.org/study/out/lena5-2-1.png.

The command on the imagemagick website looks like this:

```
  convert colorwheel.png -dither Riemersma      -colors 16 dither_riemersma.gif

```

plus

```
  convert  logo.png  -remap pattern:gray50  mono_remap.gif
  convert -size 15x640 gradient: -rotate 90 \
                   -remap pattern:gray50     mono_remap_gradient.gif

```

but I don't know how or if it is possible to add this to an action.

Can someone shed some light on this? Is there an alternative method to accomplish this?

# Answer
> 0 votes
Solved it by using the Raw ImageMagick Effect module and adding a custom action with the following option:

```
-remap pattern:gray50

```

Final action should look like this after saving it:

```
Raw ImageMagick options -remap pattern:gray50

```

# Answer
> 0 votes
Imagecache actions has a 'custom' action which allows you to run your own actions. It may help you, though I used it years ago on a drupal 6 site with GD so can not say for certain if it will work for you.

---
Tags: media
---


title: Post a tweet on cron run

text:
# Question
Title: Post a tweet on cron run
I've got a piece of code below that takes a line from a book I wrote, hashtags some of the main words and posts it to twitter. I want it to automatically run on cron. However, usually the user is sent to twitter to authenticate and then redirected to the application. I'm not sure how to handle it. Apologies but any advice would be great. I'm thinking that I can use the Twitter module if it has an api?

```
<?php
session_start();
ini_set('display_startup_errors',1);
ini_set('display_errors',1);
error_reporting(-1);
include('eden.php');
eden()->setLoader();
//The client requests the server for a consumer key and a consumer secret out of band.
$auth = eden('twitter')->auth('***', '***');
//The client uses the consumer key to obtain a request token and a secret.

if(!isset($_SESSION['access_token'], $_SESSION['access_secret'])) {
    if(!isset($_SESSION['request_secret'])) {
        $token                      = $auth->getRequestToken();
        $_SESSION['request_secret'] = $token['oauth_token_secret'];
        $login                      = $auth->getLoginUrl($token['oauth_token'], 'http://localhost/weavetweet/');
        header('Location:' . $login);
        exit;
    }

   if (isset($_GET['oauth_token'], $_GET['oauth_verifier'])) {
        $token                      = $auth->getAccessToken($_GET['oauth_token'], $_SESSION['request_secret'], $_GET['oauth_verifier']);
        $_SESSION['access_token']   = $token['oauth_token'];
        $_SESSION['oauth_token']    = $token['oauth_token'];
        $_SESSION['oauth_verifier'] = $token['oauth_verifier'];
        $_SESSION['access_secret']  = $token['oauth_token_secret'];
        unset($_SESSION['request_secret']);
    }
}
//print_r($_SESSION);
//load in the book
$txt_file  = file_get_contents('***.txt');
//Explode into sentences
$sentences = explode('.', $txt_file);
shuffle($sentences);
//shorten to 100 chars
$tweet     = substr(array_pop($sentences), 0, 88);
$tweet = explode(' ', $tweet);
array_pop($tweet);
$tweet = implode(' ', $tweet);
$length_of_tweet = strlen($tweet);

$commonWords = array('A', 'He', 'me', 'however', 'the','I', 'i', 'a','able','about','above','abroad','according','accordingly','across','actually','adj','after','afterwards','again','against','ago','ahead','ain\'t','all','allow','allows','almost','alone','along','alongside','already','also','although','always','am','amid','amidst','among','amongst','an','and','another','any','anybody','anyhow','anyone','anything','anyway','anyways','anywhere','apart','appear','appreciate','appropriate','are','aren\'t','around','as','a\'s','aside','ask','asking','associated','at','available','away','awfully','b','back','backward','backwards','be','became','because','become','becomes','becoming','been','before','beforehand','begin','behind','being','believe','below','beside','besides','best','better','between','beyond','both','brief','but','by','c','came','can','cannot','cant','can\'t','caption','cause','causes','certain','certainly','changes','clearly','c\'mon','co','co.','com','come','comes','concerning','consequently','consider','considering','contain','containing','contains','corresponding','could','couldn\'t','course','c\'s','currently','d','dare','daren\'t','definitely','described','despite','did','didn\'t','different','directly','do','does','doesn\'t','doing','done','don\'t','down','downwards','during','e','each','edu','eg','eight','eighty','either','else','elsewhere','end','ending','enough','entirely','especially','et','etc','even','ever','evermore','every','everybody','everyone','everything','everywhere','ex','exactly','example','except','f','fairly','far','farther','few','fewer','fifth','first','five','followed','following','follows','for','forever','former','formerly','forth','forward','found','four','from','further','furthermore','g','get','gets','getting','given','gives','go','goes','going','gone','got','gotten','greetings','h','had','hadn\'t','half','happens','hardly','has','hasn\'t','have','haven\'t','having','he','he\'d','he\'ll','hello','help','hence','her','here','hereafter','hereby','herein','here\'s','hereupon','hers','herself','he\'s','hi','him','himself','his','hither','hopefully','how','howbeit','however','hundred','i','i\'d','ie','if','ignored','i\'ll','i\'m','immediate','in','inasmuch','inc','inc.','indeed','indicate','indicated','indicates','inner','inside','insofar','instead','into','inward','is','isn\'t','it','it\'d','it\'ll','its','it\'s','itself','i\'ve','j','just','k','keep','keeps','kept','know','known','knows','l','last','lately','later','latter','latterly','least','less','lest','let','let\'s','like','liked','likely','likewise','little','look','looking','looks','low','lower','ltd','m','made','mainly','make','makes','many','may','maybe','mayn\'t','me','mean','meantime','meanwhile','merely','might','mightn\'t','mine','minus','miss','more','moreover','most','mostly','mr','mrs','much','must','mustn\'t','my','myself','n','name','namely','nd','near','nearly','necessary','need','needn\'t','needs','neither','never','neverf','neverless','nevertheless','new','next','nine','ninety','no','nobody','non','none','nonetheless','noone','no-one','nor','normally','not','nothing','notwithstanding','novel','now','nowhere','o','obviously','of','off','often','oh','ok','okay','old','on','once','one','ones','one\'s','only','onto','opposite','or','other','others','otherwise','ought','oughtn\'t','our','ours','ourselves','out','outside','over','overall','own','p','particular','particularly','past','per','perhaps','placed','please','plus','possible','presumably','probably','provided','provides','q','que','quite','qv','r','rather','rd','re','really','reasonably','recent','recently','regarding','regardless','regards','relatively','respectively','right','round','s','said','same','saw','say','saying','says','second','secondly','see','seeing','seem','seemed','seeming','seems','seen','self','selves','sensible','sent','serious','seriously','seven','several','shall','shan\'t','she','she\'d','she\'ll','she\'s','should','shouldn\'t','since','six','so','some','somebody','someday','somehow','someone','something','sometime','sometimes','somewhat','somewhere','soon','sorry','specified','specify','specifying','still','sub','such','sup','sure','t','take','taken','taking','tell','tends','th','than','thank','thanks','thanx','that','that\'ll','thats','that\'s','that\'ve','the','their','theirs','them','themselves','then','thence','there','thereafter','thereby','there\'d','therefore','therein','there\'ll','there\'re','theres','there\'s','thereupon','there\'ve','these','they','they\'d','they\'ll','they\'re','they\'ve','thing','things','think','third','thirty','this','thorough','thoroughly','those','though','three','through','throughout','thru','thus','till','to','together','too','took','toward','towards','tried','tries','truly','try','trying','t\'s','twice','two','u','un','under','underneath','undoing','unfortunately','unless','unlike','unlikely','until','unto','up','upon','upwards','us','use','used','useful','uses','using','usually','v','value','various','versus','very','via','viz','vs','w','want','wants','was','wasn\'t','way','we','we\'d','welcome','well','we\'ll','went','were','we\'re','weren\'t','we\'ve','what','whatever','what\'ll','what\'s','what\'ve','when','whence','whenever','where','whereafter','whereas','whereby','wherein','where\'s','whereupon','wherever','whether','which','whichever','while','whilst','whither','who','who\'d','whoever','whole','who\'ll','whom','whomever','who\'s','whose','why','will','willing','wish','with','within','without','wonder','won\'t','would','wouldn\'t','x','y','yes','yet','you','you\'d','you\'ll','your','you\'re','yours','yourself','yourselves','you\'ve','z','zero');
//we want to take the words that are not in the common words array and add a hash to them
$new_tweets = array();
$tweetWords = explode(' ', $tweet);

foreach ($tweetWords as $key => $value) {
    if (!in_array(strtolower($value), array_map('strtolower', $commonWords)) == true)
     {
        $value = '#' . $value;
     }
     $new_tweets[] = $value;
  }
$new_tweets = implode(' ', $new_tweets);
$tweet = (substr($new_tweets, 2));
$tweet = $tweet . '...' . 'http://www.***.com #bicycletouring';
print_r($tweet);
print_r(strlen($tweet));

$tweets    = eden('twitter')->tweets('***', '***', $_SESSION['access_token'], $_SESSION['access_secret']);
if (strlen($tweet) < 140){
    $tweets->tweet($tweet);
}
print '<html><head><meta charset="utf-8"/></head><body>';
//print 'your tweet is' . '<br><br>' . $tweet;
print '<br><br>do you want to tweet it? if so click the button below.';
print '<form action="index.php" method="GET">
<input type="hidden" name="act" value="run">
<input type="submit" value="Run me now!">
</form>';
print '</body></html>';

```

# Answer
> 0 votes
I was able to go through the motions of registering my twitter account and app with the Twitter module and then this worked in hook\_cron.

```
  module_load_include('inc', 'twitter');
    $twitter_account = twitter_account_load('@accountname');
    drupal_set_message(t($twitter_account));
    $status = 'tnhis is the status';
    if (twitter_set_status($twitter_account, $status)) {
      drupal_set_message(t('Successfully posted to Twitter'));
    }

```

---
Tags: social-network
---


# Question
Title: Menu Block won't display when a page has a view block
I have the *Menu Block* module installed to provide some contextual menus for certain areas of a site. These generally work great. But I have a few pages where I'm adding a Views generated block to the bottom of the page, and on these pages the menu block seems to ignore the fact that these pages exist in the menu system and will not show anything.

If you have experienced this before and have a solution that's fantastic. Otherwise I'm hoping for some pointers as to where to look around for potential issues.

It seems to be related to the block using the row style instead of the fields style. If I change it to fields, the *Menu Block* module works as expected.

# Answer
> 0 votes
On Drupal 7, I used the Menu Position module, and set rules for the content types that were being displayed via a view. I set their parent menu item and that's it. This makes the Menu Block module treat any view page as a normal page, and the menu block finally appeared, correctly configured.

---
Tags: views, blocks, 6
---


# Question
Title: Using Backup and Migrate Module to download windows compatible backup
I have created a Drupal7 based web-site on my hosting server. I have made changes to the themes, created views and done other customizations. I would like to create a duplicate copy of the site on my local laptop, so that I can test my changes locally before making them live on the site. I installed the Backup and Migrate module on my host server and downloaded a backup of the entire site to my windows 7 laptop. I already have a WAMP installation and all required services running for creating drupal7 site.

The file I downloaded looks like a tar ball of the entire drupal folder and the DB and the size is 106 MB. Since, it is a tar ball I could not open the existing file in windows. My questions:

1. Is there a way to get around the tar ball? I tried specifying zip as the compression format, but that did not help. I do not see any option to specify no tar.
2. What is the correct way to create a copy of the site locally, considering I have made changes not only to DB, but other files too. I have seen other options such as exporting the DB and FTPing the sites folder. If I were to do this, how do I FTP the sites folder to my windows laptop?

Thanks

# Answer
> 1 votes
There's a couple steps you still need to do:

1. To "untar" the tar ball on Windows, you just need the right software for it. An easy to use and free software that supports TONS of compression types is 7-Zip -- http://www.filehippo.com/download\_7-zip\_64.
2. Once you have all the files available to you, you'll need to import the database into MySQL. Luckily WampServer comes with phpMyAdmin. You can find a link to it in the tray icon for WampServer. First create your database, then use the Import tab to load in the SQL file.
3. Modify the settings.php file to match the database database connection information for your local MySQL installation. The default installation of Drupal creates this file is at /sites/default/settings.php.
4. Then visit http:// my-local-host/ (or http:// my-local-host/\[my-drupal-subdirectory\]/) to see if it's working. (Replace "my-local-host" with "localhost" since StackExchange doesn't like "localhost" in a link).

# Answer
> 0 votes
I believe PHP supports output streams in gzip, tar, zip -- you simply need the correct PHP extension installed/enabled in your php environment. To my knowledge Backup and Migrate will make use of the available options in your configuration.

In the 2.x branch, zip is an allowed filter: http://cgit.drupalcode.org/backup\_migrate/tree/includes/filters.compression.inc#n77

You can see what your php configuration is easily on a system using `php_info()` on the command line or looking at `admin/status/reports` in the drupal administration area under the PHP report.

> What is the correct way to create a copy of the site locally, considering I have made changes not only to DB, but other files too. I have seen other options such as exporting the DB and FTPing the sites folder. If I were to do this, how do I FTP the sites folder to my windows laptop?

Backup and Migrate (BAM) is a fine way to backup a full drupal site. It has many contributed addon modules to backup to other destinations, such as Dropbox if needed. An additional option to BAM is `Drush` and the `archive-dump` command which gives you a `.tar.gz` (hehe) of an archive-manifest of your full site. You can the easily restore the site via commandline using `drush archive-restore /path/to/dump.tar.gz` .... see `drush help archive-restore` for full documentation examples.

I'm sorry I can't answer your question how to use FTP, this is a drupal only forum and general programming question should be resolved via Google or StackOverflow for instance.

---
Tags: backups
---


title: How to render only field label

text:
# Question
Title: How to render only field label
Is it possible to render only the field label from $view-\>result , like render the field value only

```
$display['label']='hidden';

```

print render(field\_view\_field('node',$node,'field\_date',$display));

# Answer
found it here $view-\>field\['field\_description'\]-\>options\['label'\];
> 0 votes

---
Tags: entities
---


# Question
Title: How to restrict access to page by URL depending on which page you came from
I have page which implements by hook\_menu and i want to permit access for this page if user come from certain form but not from just url string. How can i solve it? Thanks.

# Answer
> 0 votes
> depending on which page you came from

per se is impossible, because people can easily forge their `referer` header. What you need to do in your specific, form related situation is to:

* In form submit handler, set session variable, like `$_SESSION['acces_valid_to'] = time() + 3600` \- this will store time one hour into future for specific user.
* In access hook, for example `hook_node_access` if we are talking about nodes, test if this variable is set, and if it is still valid. If not, send `403 Forbidden`.
* If you want, you can unset it after any page view, that will make sure your user will view his page only once.

If you will have specific problems with any of these steps, ask next, more specific question.

---
Tags: forms, users, uri, 7, routes
---


# Question
Title: Remove components from a feature using Drush
Using Features UI to manage a big feature components is a tedious task.

Therefore in order to **add a new component** I use

```
drush fe myfeature views_view:myview1

```

Now how I **remove the uneeded component** myview2?

From the UI this operation is illustrated as below, I want to remove the conflicted community\_content with clone\_of\_community\_content:

The view:

# Answer
Remove the component by deleting the corresponding line in your feature's .info file. Then run:

`$ drush fu <feature_name>`

In your case:

1. Open the file `/sites/all/<features_folder>/myfeature/myfeature.info`.
2. Delete the following line.

`features[views_view][] = myview2`
3. Save the file.
4. Run `$ drush fu myfeature` in your site's folder.
> 8 votes

# Answer
There's **no direct drush command** (Drupal 7.31 & Drush version 6.3.0 and never heard such a thing for drush verson 7.x) to disable/remove an component. If you only want to remove the component, then you should do it with features UI.

But if you want to delete a field (for example), there how I do with drush :

1. First be sure that your field is not use in a custom module. (If necessary you will have to adjust your code)
2. Then let's ask drush to delete the field : `drush field-delete field_website`
3. Small check if field was really delete : `drush field-info fields | grep field_website`
4. And just recreate the features where you field was included : `drush fu myfeature`
5. If you are using git you can also check that your change make sense (I assume that you know how to use `cd` or relativ/absolut path) : `git diff myfeature`

Hope that help.
> 2 votes

---
Tags: drush, features
---


# Question
Title: Create View to display users with same select list value to each individual user
When a user registers on my site, he/she chooses the college he attended and the course he/she studied from select list fields i created using the profile 2 module

Is there a way to create a View that displays to each user the people who attended the same college & studied the same course.

Thank you.

# Answer
You can do it creating using Views with a contextual filter.

Profile2 has integration with views, and if you create a view's page display with a path like `yoursite.com/user/[username/id]/users-with-same-college` url. You get it!

Hope it helps.

Regards.
> 0 votes

---
Tags: views, users
---


# Question
Title: How do I control the number of cols in a textarea?
According to the Form API, you control the number of columns in a `textarea` with the `#cols` attribute. However, setting this seems to have no effect when I use it inside a `$form` array (the companion `#rows` attribute works as expected).

This may just be a bug (and I understand that bug-reports are off-topic on SE DrupalAnswers). But I have searched the issue queues and haven't found any bug reports about this, which makes me suspect that there is something rather basic that I've misunderstood.

So: What is the correct way to control the number of cols in a textarea?

Environment: Drupal 7 fresh install, Bartik theme with no customization.

# Answer
> 1 votes
Thanks David Thomas - CSS did it!

Since your comment is rather terse, I take the liberty of answering my own question where I describe how to use CSS in more detail.

To attach a CSS file, add the following to the form:

```
$form['#attached']['css'] = array(
  drupal_get_path('module', 'mymodule') . '/mymodule.css',
);

```

Then look at the HTML generated to find the class of the textarea:

```
<textarea id="edit-mymodule-data" name="mymodule_data" cols="40" rows="2"
  class="form-textarea">
Please fill in some data.
</textarea>

```

(Just for the record, notice that the values for `cols` and `rows` are picked up from the `$form` array, but unfortunately the value set for `cols` have no effect.)

The class of textarea is `form-textarea`, so placing the following in `mymodule.css` makes the textarea 100 pixels wide:

```
textarea.form-textarea { width: 100px; }

```

# Answer
> 0 votes
Yep, CSS did it. Just suggestion not to change width directly to text area but to most outer wrapper div since there may be that dragable line for resizing text area.

Also using *max-width* instead of *width* would be nice in the case that windows in not in full widh...

---
Tags: 7, forms
---


# Question
Title: Views query alter or condition not works
Want add some or conditions in view queries. I tried two solutions but it not working. What I do wrong?

```
function up_coaching_custom_views_query_alter(&$view, &$query) {
  $search_string = empty($_GET['filter']) ? '' : '%' . db_like($_GET['filter']) . '%';
  if ($view->name != 'users' || empty($search_string)) {
    return;
  }

  // First way
  $condition = db_or()
      ->condition('users.mail', $search_string, 'LIKE')
      ->condition('field_data_field_company.field_company_value', $search_string, 'LIKE')
      ->condition('field_data_field_user_name.field_user_name_value', $search_string, 'LIKE')
      ->condition('field_data_field_title.field_title_value', $search_string, 'LIKE');
  $query->add_where(2, $condition);

  // Second way
  $query->where[2] = array(
    'args' => array(),
    'type' => 'OR',
    'conditions' => array(
      array(
        'field' => 'users.mail',
        'value' => $search_string,
        'operator' => 'LIKE',
      ),
      array(
        'field' => 'field_data_field_company.field_company_value',
        'value' => $search_string,
        'operator' => 'LIKE',
      ),
      array(
        'field' => 'field_data_field_user_name.field_user_name_value',
        'value' => $search_string,
        'operator' => 'LIKE',
      ),
      array(
        'field' => 'field_data_field_title.field_title_value',
        'value' => $search_string,
        'operator' => 'LIKE',
      ),
    ),
  );
  $query->set_where_group('AND', 2);
  dpm($query);
}

```

# Answer
Ok, both solutions are work. The problem is in query fields that not exist because need add field tables. I didn't unserstand this because of this:

```
    catch (Exception $e) {
        $view->result = array();
        if (!empty($view->live_preview)) {
          drupal_set_message($e->getMessage(), 'error');
        }
        else {
          vpr('Exception in @human_name[@view_name]: @message', array('@human_name' => $view->human_name, '@view_name' => $view->name, '@message' => $e->getMessage()));
        }
      }

```

Views didn't show me error.
> 0 votes

---
Tags: views
---


# Question
Title: Why won't taxonomy list sort alphabetically?
Running Drupal 7.28, I've created a taxonomy vocab 'care centers' with a list of terms with care center names 'Atlanta''Boston''Cincinnati' 'Detroit' etc. Problem: Care centers were entered in random order 'Detroit' 'Boston' 'Atlanta' 'Cincinnati', when I click on 'Reset to Alphabetical' they reorder alphabetically, but when I save, they go back to order entered. People self-select their care center from a drop down list populated by the taxonomy, would help if it were displayed alphabetical.

How do I get the list to sort and display alphabetical?

# Answer
> 1 votes
Have you already tried with "Show row weights", it looks like a javascript problem; adding the weight manually will give you some hint about that problem.

---
Tags: taxonomy-terms
---


# Question
Title: Sanitizing User Input using Form API - Creating Nodes
I'm using D7 Form API to make some custom forms for users that create nodes on submit (using node\_submit & node\_save functions). This is an example form I'm using:

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

$form['node_title'] = array(
    '#type' => 'textfield',
    '#title' => t('Node Title'),
    '#size' => 20,
    '#required' => TRUE,
 );

$form['submit_button'] = array(
   '#type' => 'submit',
   '#value' => t('Create Node'),
 );

return $form;
}

```

This works great, but I'm just wondering about sanitization. From my research it seems like the check\_plain() function should be used for text fields for security. However, it also causes raw HTML entities to be saved.

For example, I am setting the node title in the submit function like this:

```
$node->title = check_plain($form_state['values']['node_title']);

```

This problem is, if the user enters something like this:

```
Mike's Tacos

```

it gets saved in the node title like this:

```
Mike's Tacos

```

So if I output that title anywhere (in a view, in a custom node--XX.tlp.php, etc, it shows in this way.

Can anyone help with how to still use check\_plain (or whatever function will provide the best security) but have the value saved with the human-readable format (Mike's Tacos)?

# Answer
> 5 votes
Filters are used for **output**, not input. It's the Drupal way; save the raw, un-sanitised data in storage, and filter (and cache) when it's being rendered.

You shouldn't run `check_plain()` on your node title before saving it, as it will be run through the same function by core/contrib when the node is being rendered, hence the double-encoding you're probably seeing.

If you're responsible for rendering the node title yourself at any point, you should always run it through `check_plain()` first:

```
echo check_plain($node->title);

```

But always on output, never on input.

---
Tags: 7, forms, nodes
---


# Question
Title: "Allow multiple values" vs "Allow multiple filter values to work together"
In Views, when adding an Argument for a vocabulary term id, I'm presented with the following 2 options:

**Allow multiple values** *If selected, users can enter multiple values in the form of 1+2+3 (for OR) or 1,2,3 (for AND).*

**Allow multiple filter values to work together** *If selected, multiple instances of this filter can work together, as though multiple values were supplied to the same filter. This setting is not compatible with the "Reduce duplicates" setting.*

The first option is perfectly clear to me. The second, however, I'm struggling with. What exactly does it do, and how does this differ from the "Allow multiple values" option?

Can the two of these options be used together? If so, what would be the expected outcome?

Thanks!

# Answer
Allow multiple filter values to work together is used when you want to pass multiple arguments to and match against one field. In other words allows for 'many to one' joins

In a sense it is similar to 1, 2, 3, however if you need to pass multiple sets like 123+345 and 889+678 there need to be 2 separate joins to the same table.

(assuming sometable has multiple results for your desired value like:

|nid|yourvalue|

|1 |123 |

|1 |345 |

|2 |678 |

|3 |222 |

|1 |789 |

|1 |823 |

|1 |845 |

|2 |678 |

|3 |222 |

|1 |889 |

select node.title from node node join sometable sometable\_1 on sometable.yourvalue in (123,345) join sometable sometable\_2 on sometable.yourvalue in (889,678)

Therefore 'Allow multiple filter values to work together' is the only way to get view to return nid 1

this is useful when you need to pass arguments that come from different sources (i.e. 1 could be taxonomy terms from 2 different vocabs).

I used this only when dealing with entityreference field that references terms from different vocabularies
> 1 votes

---
Tags: views
---


# Question
Title: Generate breadcrumb based on a given Path
How can I know the breadcrumb that will be generated in a page without visiting that page? Is this possible?

# Answer
It really depends on what module/configuration you are using to generate the breadcrumb, sometimes some basic configuration is set in the base theme you are using as well, you might wanna check that out in your `page.tpl.php` file. basically your question is so vague it's hard to answer.

but mostly in most of themes the breadcrumb is being generated like this:

```
Home > Node title

Home > Taxonomy Term > Node title

```
> 0 votes

# Answer
Not a direct answer, but if you want full control over your breadcrumbs (so that you can predict what the breadcrumb will be at a given path), take a look at Crumbs (https://www.drupal.org/project/crumbs) or Path Breadcrumbs (https://www.drupal.org/project/path\_breadcrumbs)

Both modules will allow you to define rules/criteria that are used to construct the breadcrumbs you want on your site.
> 0 votes

---
Tags: 7, breadcrumbs
---


title: Yearly Archive with month in drupal7

text:
# Question
Title: Yearly Archive with month in drupal7
I want to add news in my website . i want left sidebar and header as in image.

I dont know which module should i use for this.

Months are showing in tabs . I am using Bootstrap3 theme here

# Answer
> 1 votes
There is an `archive` view that comes bundled with Views (Check out `admin/build/views` page, views name Default Node view: archive (default)), just clone and modify it as per your need and it should work.

Also check this links containing discussion about the same requirement:

---
Tags: 7, views
---


# Question
Title: How to direct a dynamic url to a Drupal page
I created a little web app that allows people to keep content on a page. They can specify the url of the page. Instead of accessing their page like this: http://example.com/stuff?page=their\_url I want the url to be like this: http://example.com/stuff/their\_url

But I can't figure out how to direct a dynamic url to a Drupal page. I've even tried Apache redirects, but I can't get that working either. I keep getting 404's.

I'm willing to use Apache rewrites to get to the right page.

I'm willing to point to a regular PHP file on the server and bootstrap Drupal, but so far I haven't been able to get that working.

I'm willing to put PHP code into a Drupal page.

I really don't want to write my own Drupal module, so if you want to offer some Drupal code, please tell me where to use it.

I'm willing to use a Drupal 7 module if you know of any.

Thanks a lot!

-- Magmatic

# Answer
> 0 votes
So after a few hours I finally got something working. This is it:

In my .htaccess file I have a rewrite:

```
RewriteRule ^fz/(.*) fz.php?page=$1

```

Then in my fz.php file I have this:

```
<?

$_GET["q"] = "filezone";

define('DRUPAL_ROOT', getcwd());

require_once DRUPAL_ROOT . '/includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);

menu_execute_active_handler();

```

I have a Drupal page that I want to display. It's url is set to be "filezone". In fz.php, it displays this page. And on that page I can get the "page" value with $\_GET\["page"\].

# Answer
> 0 votes
i think that you can use the : function drupal\_goto

but not sure if that is for your case.

---
Tags: uri
---


title: Node Form Not submitting on ctool modal

text:
# Question
Title: Node Form Not submitting on ctool modal
I have a custom form, on submission of which I am calling ctools modal with a node form(content type: turn).

Code for Custom Form.

```
function _my_module_name_files_listing_form($form, &$form_state) {
  $form = array();
  $form_state['storage']['values'] = $files;
  $form['download_submit'] = array(
    '#type' => 'submit',
    '#value' => t('Download'),
    '#submit' => array('_my_module_name_files_download_submit'),
  );
  $form['create_segment'] = array(
    '#type' => 'submit',
    '#value' => t('Create Segment'),
    '#attributes' => array('class' => array('ctools-use-modal')),
    '#ajax' => array(
      'callback' => '_my_module_name_files_create_segment',
    ),
  );
  $form['upload_content'] = array(
    '#type' => 'submit',
    '#value' => t('Upload Content'),
    '#submit' => array('_my_module_name_files_upload_content'),
  );
  $form['delete_submit'] = array(
    '#type' => 'submit',
    '#value' => t('Delete'),
    '#submit' => array('_my_module_name_files_delete_submit'),
  );
  return $form;
}

```

Callback code for ajax submission rendering node form.

```
function _my_module_name_files_create_segment($form, &$form_state) {
  global $user;
  $form_id = 'turn_node_form';
  ctools_include('node.pages', 'node', '');
  ctools_include('ajax');
  ctools_include('modal');
  ctools_modal_add_js();
  ctools_add_js('ajax-responder');
  $destination = 'node/1';
  $form_state = array(
    'ajax' => TRUE,
    'title' => t('Form Title'),
  );
  $node = (object) array(
        'uid' => $user->uid,
        'name' => (isset($user->name) ? $user->name : ''),
        'type' => 'turn',
        'language' => LANGUAGE_NONE,
        'status' => TRUE,
  );

  $form_state['build_info']['args'] = array($node);
  $output = ctools_modal_form_wrapper($form_id, $form_state);
  if (!empty($form_state['ajax_commands'])) {
    $output = $form_state['ajax_commands'];
  }
  if (!empty($form_state['executed'])) {
    $output = array();
    // Redirect to destination.
    $output[] = ctools_ajax_command_redirect('node/8', 0);
  }
  print ajax_render($output);
  drupal_exit();
}

```

**Problem:** Node Form is coming fine on modal and hitting save button triggers ajax call but node form does not submit. Am I missing something here?

# Answer
Try replacing

```
ctools_include('node.pages', 'node', '');

```

with

```
ctools_form_include_file($form_state, drupal_get_path('module', 'node') . '/node.pages.inc');

```

It's possible that the node.pages.inc file isn't loaded if the form is found from cached data.
> 0 votes

---
Tags: 7, nodes, chaos-tool-suite
---


title: How to pass wildcard via drush exec?

text:
# Question
Title: How to pass wildcard via drush exec?
How to pass wildcard via drush exec on remote host (via ssh)?

I've tried already:

```
$ drush @foo exec 'ls -al *'
$ drush @foo exec "ls -al *"
sh: 1: ls -al *: not found
Command 'ls -al *' failed.
$ drush @foo exec "ls -al \*"
sh: 1: ls -al \*: not found
Command 'ls -al \*' failed.
$ drush @foo exec 'sh -c "ls -al *"'

```

Local shell is bash, remote shell is sh.

# Answer
`$ drush @foo ssh 'ls -al *'` works great, for any @foo alias that is remote.
> 1 votes

# Answer
Why are you passing `exec` a string?

```
✔ aw-dgurba ~ > drush help exec
Execute a shell command. Usually used with a site alias.

Examples:
 drush core-execute git pull origin  Retrieve latest code from git
 rebase

Arguments:
 command                                   The shell command to be executed.

Options:
 --escaped                                 Command string already escaped; do not add additional quoting.
 --ssh-options                             A string of extra options that will be passed to the ssh command (e.g. "-p 100")
 --tty                                     Create a tty (e.g. to run an interactive program).

Aliases: exec, execute
aw-dgurba ~ > drush exec "ls ~/*"
sh: 1: ls ~/*: not found
Command 'ls ~/*' failed.

```

Yet,

```
aw-dgurba ~ > drush exec ls ~/*.txt
/home/dgurba/catch22_excerpt.txt

```

Note the `help description` does not pass a quoted string. If you escaped options already than use `--escaped` option. If you need special handling via ssh then supply the necessary `--ssh-options`.
> 0 votes

---
Tags: drush, ssh
---


# Question
Title: Pagers of two different contents are conflicting
There are two contents in my website, say `CA` and `CB`, I created a view for each one and it displays 10 items and for the rest of the items pager is used. `CA` is in the `sidebar first` region and `CB` is the main content which lists some thing. the `Use AJAX:Yes` configuration is used for `CA` and `Use AJAX:No` for `CB` is used. the problem is when the `next` link in `CB` pager is clicked and the page goes to `www.example.com/content?pager=2` both `CA` and `CB` are going to the second page of the 10 contents. why they are conflicting and how do I can solve this problem?

thanks

# Answer
> 1 votes
You can assign a different PagerID to the pager when editing the View. This should compensate for the conflict. By default, all pagers have an ID of 0, but if you need 2 views on the same page, then you need to manually select a different ID for one of them.

---
Tags: views, nodes, paging, chaos-tool-suite
---


# Question
Title: How to fix millions of Alt Text are missing on body content?
This question is very similar to my other question. I have a website missing millions of **Alt Text** in **body content**(not image field). My solution is to set the default Alt Text as the file name without extension. Is it even possible, if so, how?

-- -- added additional info on Oct 2nd 12:40pm for tenken : below is a screenshot of setting

**PS: there is no replace setting on Setting section**

Here is the screenshot on setting section

# Answer
> 2 votes
Try using the Search and Replace Scanner module to search through the text of your `body field`. You could use a regular expression to search for image tags without alt attributes.

Some excerpts from the module page:

> Features
>
> * Can search and replace text in CCK text fields, in addition to standard node title and body fields
> * Plain text search and replace regular expression search and replace
> * Case sensitive search option

This module is designed to work on MySQL and dedicated servers, be sure to review the module page and accompanying documentation.

# Answer
> 1 votes
I'm a big fan of offloading this type of regressive work to the client, meaning I would just write a Javascript function to do the work for me and let the user's browser do the work. With jQuery, it is basically a one-liner. Is there some part of your implementation that would not work with this solution? The upside is that you wouldn't have to worry about tinkering with the database at all.

---
Tags: nodes, media
---


# Question
Title: Drupal module development - How to build admin items list?
I'm creating a Drupal module and I would like to know how to build the admin panel table with the list of each items that I've been created with the module.

What is the hook to use ? and/or the API function... ? I did not found it.

All the tutorials that I read on the web explain how to create a form for submitting content but no one explain how to create the list of the content that have been submitted with the form.

You can see in the joined picture two examples of that I want to do.

# Answer
> 3 votes
I think you have at least two possibilities to proceed.

First, you can use "Views" module to display a list of whatever you want (you can easily configure it to display all contents of a certain content-type that the user currently seeing the page created, etc, etc). You can inspire yourselft with this article about creating an administration page with Views 2 (http://zugec.com/2010/08/create-administration-pages-views-2). It is not very different.

If you want to do it programmatically, you can always create a "page" that displays whatever you want using `hook_menu()`. Just set the path under "admin/" and permissions the way you want. Use the page callback function to make the appropriate query (select the nodes you want, created by the current user, order them, sort them, etc...) and to display the results.

If you want more explanations about one of the two solutions provided up there, just ask and I'll develop deeper :-)

---
Tags: 7, hooks
---


# Question
Title: Problem drupal with domain and redirection
I have problem with drupal site when migrate it from dev to production. My website works fine until I tried to login as admin. After enter username,password ,and click login I got error page not found. Because I were redirected to a wrong path. For example. I were redirected to www.domain.com/cgp/user but the correct path should be www.domain.com/user. Bellow is actual screenshot. Does anyone have the same problem and know to to fix it? Thank you.

Bellow is virtual host config `<VirtualHost *:80>
 ServerName www.domain.com
 ServerAlias domain.com
 DocumentRoot "/root_directory"
 ProxyPass / http://webserver_id/cgp/
 ProxyPassReverse / http://webserver_id/cgp/
 ErrorLog "logs/cgp-error_log"
 CustomLog "logs/cgp-access_log" common
 # redirect non www to www
 RewriteEngine On
 RewriteCond %{HTTP_HOST} !^www\. [NC]
 RewriteRule ^ http://www.%{HTTP_HOST}%{REQUEST_URI} [R=301,L]
</VirtualHost>`

# Answer
The problem could be in several areas, depending on your deployment method.

First of all, have you cleared your caches? This fixes most issues, especially after importing a database.

It could be a server configuration issue, did you set it up or did someone else? There could be version differences between the installed software on the dev and prod servers.

Lastly, have you tried setting the `$base_url` in your settings.php?
> 0 votes

# Answer
I still don't know what cause the problem. I use another trick I saw someone suggest. I create a cgp symlink in cgp drirectory point to cgp directory itself. And it's work. I will need to test abit more but seem like this work fine.
> 0 votes

---
Tags: redirection, .htaccess, domain-access, subsites
---


# Question
Title: How to remove the 'Reply' link in comments?
I'm currently using the following line of code in my `comment.tpl.php` file:

```
<?php print render($content['links']) ?>

```

This also prints the 'Reply' link, but I'd like to remove that one. How can I do that?

---

**Note:** I'm able to hide the 'Reply' link with CSS, but that's not a very nice solution.

# Answer
> 4 votes
If you wanted to remove all links, you could do it in a template file like this:

```
hide($content['links']);
print render($content);

```

But I don't know how to hide just the comment reply link this way. Based on a short article here, it looks like you can unset the reply link with a preprocess function in template.php like this:

```
function themename_preprocess_comment(&$variables) {
  unset($variables['content']['links']['comment']['#links']['comment-reply']);
}

```

# Answer
> 2 votes
I think you should be able to change this behavior by modifying the `comment settings` for each content-type. This could be done by going into `admin/structure/types/manage/<your-content-type>`, scroll down and click on `comment settings` in the left menu. In the settings form you then uncheck the box next to `Show reply form on the same page as comments`.

The above doesn't seems to work, but you could easily make a small module and implement `hook_comment_view()`:

```
function <YOURMODULE>_comment_view($comment, $view_mode, $langcode) {
  unset($comment->content['links']['comment']['#links']['comment-reply']);
}

```

---
Tags: 7, theming, comments
---


# Question
Title: Menu callback error : Undefined offset: 4 in _menu_translate()
I have created a menu item with form. Everything is working fine, but I am getting the following error message on the menu page.

> Notice: Undefined offset: 4 in \_menu\_translate() (line 777 of /home/sysop/old-server/heisenberg/includes/menu.inc).

The code I am using is the following.

```
/*
 *implements hook_menu
 */
function planet_extension_menu() {
 $items['admin/structure/feeds_admin'] = array(
'title' => 'Planet Extension',
'page callback' => 'main_table',
'access arguments' => array('access administration pages'),
'file' => 'planet_extension.admin.inc',
'type' => MENU_CALLBACK,
);

    $items['admin/structure/feeds_admin/manage/%/delete'] = array(
    'title' => 'Delete',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('delete_feed',4),
    'access arguments' => array('access administration pages'),
    'type' => MENU_LOCAL_TASK,
    'file' => 'planet_extension.admin.inc',
    );

    $items['admin/structure/feeds_admin/manage/%/submit'] = array(
    'title' => 'Approve',
    'page callback' => 'submit_feed',
    'page arguments' => array(4),
    'access arguments' => array('access administration pages'),
    'type' => MENU_LOCAL_TASK,
    'file' => 'planet_extension.admin.inc',
    );
    return $items;
}

```

file : planet\_extension.admin.inc

```
/**
 * Function main_table().
 */

function main_table() {

  $header = array(

    array('data' => t('ID'), 'field' => 'id', 'sort' => 'asc'),

    array('data' => t('Title of Feed'), 'field' => 'title'),

    array('data' => t('Feed URL'), 'field' => 'url'),

    array('data' => t('TYPE'), 'field' => 'category'),

    array('data' => t('Submitted By'), 'field' => 'email'),

    array('data' => t('Operations'), 'colspan' => 2),

  );

  $query = db_select('planet_extension', 'p');

  $query->fields('p', array('id','title','url','category','email'));

  $table_sort = $query->extend('TableSort') // Add table sort extender.

                      ->orderByHeader($header); // Add order by headers.

  $pager = $table_sort->extend('PagerDefault')

                      ->limit(20);

  $result = $pager->execute();

  $rows = array();

  foreach($result as $res){

    $rows[] = array($res->id, $res-> title, $res->url, $res->category, $res->email,(l(t('Approve'), 'admin/structure/feeds_admin/manage/' . $res->id . '/submit')),(l(t('Decline'), 'admin/structure/feeds_admin/manage/' . $res->id . '/delete')));
}
  // If rows are not empty theme and display the rows.

  $output = '';

  if (!empty($rows)) {

    $output = theme('table', array('header' => $header, 'rows' => $rows, 'attributes' => array('id' => 'sort-table')));

    $output .= theme('pager');

  }

  else {

    $output .= t("No results found.");

  }

  return $output;

}

/*
 *Delete function
 */
function delete_feed($form,&$form_state,$variable) {
      $form['feed_id'] = array(
      '#type' => 'value',
      '#value' => $variable,
      );
    return confirm_form($form, t('Are you sure you want to delete this feed %variable ?',
    array('%variable' => $variable)), '/admin/structure/feeds_admin', 'Warning!! Would you like to continue with delete?', t('Delete'));
  }

/**
 * Delete given field
 */
function delete_feed_submit($form,&$form_state) {
    $id = $form_state['values']['feed_id'];
    $num_deleted = db_delete('planet_extension')
      ->condition('id', $id)
      ->execute();
    drupal_set_message(t('Feed %id successfully removed.', array('%id' => $id)));
    drupal_goto('/admin/structure/feeds_admin');
  }

/**
 *submit handler
 */
function submit_feed($variable) {
}

```

# Answer
What is the `%` parameter in the url used for - a feed item maybe?

For that type of UI, you may need to add a load function and use a named parameter instead for the `%`

e.g:

```
/**
 * Implements hook_menu
 */
function planet_extension_menu() {
 // ...
 // ...
    $items['admin/structure/feeds_admin/manage/%pe_feed_item/delete'] = array(
    'title' => 'Delete',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('delete_feed',4),
    'access arguments' => array('access administration pages'),
    'type' => MENU_LOCAL_TASK,
    'file' => 'planet_extension.admin.inc',
    );
 // ...
 // ...
}

/**
 * Menu callback load function for pe_feed_item argument
 * This function loads the feed item
 * which is then passed as a page argument to the menu callback function
 */
function pe_feed_item_load($fid) {
  // Load feed item somehow from feed id and return it, e.g:
  return db_query("SELECT * FROM {pe_feed_item} WHERE fid = :fid", array(':fid' => $fid))->fetchObject();
}

```
> 2 votes

# Answer
I was experiencing a similar problem, where the pages which were created with the panels module were working fine and arguments were being passed around fine but I would get this error for certain paths.

I used a `subque_to_arg` stub function:

```
function my_custom_url_part_to_arg($arg) {
  return $arg;
}

```

where `my_custom_url_part` is used in a url like `admin/custom_folder/%my_custom_url_part`
> 0 votes

---
Tags: forms, routes
---


title: How do I add a form to the block?

text:
# Question
Title: How do I add a form to the block?
I want to add a configuration form for a block. The form's style is the following:

```
    one year (label)    input text box value    eg:$10
    two years           input text box value
    three years         input text box
    500 accounts        input text box
    1500 accounts       input text box
    2500 accounts       input text box
    image:              can upload an image

```

How do I do it? I should write a module to get that.

How do I design the table, which is used to store the input box value and image value.
How do I design the fields? Which hook should I use?

# Answer
You can use a combination of the Webform module and Views. Create a node with the form you want using the webform module and you can then create a block with Views for that particular node.
> 2 votes

# Answer
The Webform module is a really easy way to design the form you need. Rather than use Views (although it is a dependency of Webform) there is an option within Webform to allow you to use it as a block and easily place it on any page.

Once you have installed Webform module you can create a new content item of type Webform. Save that and then edit it. Go to the advanced settings by choosing the Webform Tab, Form Settings button, Advanced Options (at the bottom).

Select the Available As Block check box.

Now you can add the form to any page(s) as a block by going to Structure - Blocks and adding the new content you've just created.
> 0 votes

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


title: override node.tpl.php in a module

text:
# Question
Title: override node.tpl.php in a module
I created a module that should be able to display the content of a certain content type. The displaying is kinda complex and to be able to turn it off and to group everything together i created a module for this.

But in the end it should just override the normal node.tpl.php with a custom .tpl.php file. When i put the file in my template folder it gets picked up and the pages shows as intended, but i can't get it to work when the file is in module folder.

I read a lot of things about regsiter the .tpl file and preprocess but nothing that combines the pieces i need.

This is what i have so far

```
function apps_theme($existing, $type, $theme, $path) {
    $items = array(
        'node--app' => array(
            'template' =>  drupal_get_path('module', 'app') . '/node--app',
            'variables' => array('node' => (object)array())
        )
    );
    return $items;
}

function apps_preprocess_node(&$vars) {
    $variables['theme_hook_suggestions'][] = 'node__app';
}

```

# Answer
It is not clear in your question if you are placing your template in `sites/all/custom/modules`, or in `sites/all/custom/modules/the_name_of_mymodule`. It needs to be the later.

However, if you:

* Have your template in the proper place.
* Visited the `admin/appearance` path to force a theme registry refresh.
* Cleared all the caches aftewards.

...but still no dice, you can always specify in your hook\_theme() implementation the `theme_path` key:

```
<?php
function apps_theme($existing, $type, $theme, $path) {
    $items = array(
        'node_app' => array(
            // Don't specify the path in the template name.
            // Unless you have your template inside a directory within this module.
            'template' =>  'node--app',
            'variables' => array('node' => (object)array()),
            // If you want to put the tpl in another location, you can use this key.
            'theme path' => drupal_get_path('module', 'another_module'),
        ),
    );
    return $items;
}

```
> 3 votes

# Answer
Thought I would post the solution that I found:

```
function MYMODULE_theme($existing, $type, $theme, $path) {
  return array(
    'node__NODETYPE' => array(
      'render element' => 'content',
      'base hook' => 'node',
      'template' => 'node--NODETYPE',
      'path' => drupal_get_path('module', 'MYMODULE') . '/templates',
    ),
  );
}

```
> 3 votes

# Answer
I got it working by following this:

http://www.metachunk.com/blog/adding-module-path-drupal-7-theme-registry
> 2 votes

---
Tags: 7, theming
---


# Question
Title: How to redirect all unpublished nodes of a certain type
**Problem**

I'm running a job site where content appears and disappears quickly. This means I end up with a lot of 404s from Google indexing pages only for them to disappear.

I want to redirect all unpublished nodes of a certain type to a particular page, depending on a value on the node and display a drupal message depending on what just happened.

I'm trying to come with a solution which is easy to maintain and will scale, should the site grow to have thousands of nodes.

Has anyone solved this sort of problem? What kind of solution did you use?

**My current ideas**

1. Use the redirect module.

I've created a module which will redirect all my nodes when they're unpublished via either a cron action or a form action using the redirect API.

The problem is this creates a lot of redirects. While it might take a while to become unmanageable, several other questions mention the module scales quite well into the thousands I would like it to be future proof is possible.

One option to solve this was to delete unused redirects however because I run Varnish in front as a cache, it is unable to tell which redirects have been active.

2. Do it server side

I'm running Nginx, I presumably could set up a location block which would redirect all 404s.

If I put the node information I needed in the URL I could just grab it from there and then redirect each set of nodes.

This is an ok solution, but the pages are redirecting to country so there would have to be 330 location blocks in my nginx config, which isn't particularly slick.

It also makes it impossible to set a message on page load.

3. Use the rules module

You can setup content viewed redirects using the rules modules but unfortunately Varnish caching breaks this.

# Answer
> 1 votes
I ended up going with the first option and using the following solution to make sure the redirects never got out of hand:

Basically when a job advert goes down it will get given a 301 redirect. Then I remove every redirect for a job advert older than 3 months.

Hopefully this will remove the worst of the 404 problem because: If Google crawls the link in the three months then it will be redirected and change its index.

If a person comes across it in the three months they'll be correctly redirected and if no-one has bothered to try it for three months then I've probably avoided the 404 problem.

The code just involved calling an extra cron job and then altering a version of the `redirect_purge_inactive_redirects();` function.

```
function redirect_purge_job_redirects(array $types = array('redirect'), $interval = NULL) {
  //set interval in code to 3 months in seconds
  $interval = 7776000;
  $query = db_select('redirect');
  $query->addField('redirect', 'rid');
  if (!empty($types)) {
    $query->condition('type', $types);
  }
  //add in condition here to select all redirects
  //for the job adverts.
  //the path for all the job adverts begins with job
  //so I look for that.
  $query->condition('redirect', 'job'.'%', 'LIKE');
  $query->condition('access', REQUEST_TIME - $interval, '<');
  $query->addTag('redirect_purge');
  $rids = $query->execute()->fetchCol();

  if (count($rids)) {
    redirect_delete_multiple($rids);
    watchdog('redirect', format_plural(count($rids), 'Removed 1 inactive redirect from the database.', 'Removed @count inactive redirects from the database.'));
    return $rids;
  }
}

```

# Answer
> 1 votes
Another option may be to write your own simple module to do the redirect when an unpublished node is loaded/viewed by a user who does not have permission.

You could implement one of the node API hooks to call `drupal_goto()` if the node is an unpublished one (`$node->status == NODE_NOT_PUBLISHED`) and the user doesn't have permission. (Use `user_access()` to check permission)

The one problem may be with the order in which permissions are checked versus those hooks, which at this moment in time I can't quite remember the order things fire with regards hooks for node load/view and user permissions. But hopefully it gives you some ideas.

---
Tags: 7, redirection
---


title: link to profile in menu

text:
# Question
Title: link to profile in menu
I am using the default profile as a "user dashboard" I have a main navigation link that needs to link to the users profile so is there a way to insert a dynamic link based on the current user? I need to add something like

```
user/{$GLOBALS['user']->uid}

```

If there anyway of accomplishing something like this?

# Answer
You can use the link directly as `/user`. It also goes to the profile page which is similar to the `/user/{$GLOBALS['user']->uid}`

Now if you want user id also with it, e.g profile in `edit mode (user/10/edit)` then you need to add Menu Link module. It provides you option to use Token to make the link dynamic for every user profile instead of static path.

Hope it will help.
> 0 votes

# Answer
You can use tokens to create a menu link with this path: `user/[current-user:uid]/edit`.
> 0 votes

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


# Question
Title: How to link 'no result behaviour' to node?
When editing a view, i'm faced with a difficulty.
There's an image field, in the field settings i set the images (submitted when creating the node) to be linking to the node.
The problem is that in set up a default image in the no result behaviour setting.

```
<img alt="No Image" class="no-img" src="/sites/default/files/img-custom/no-image.gif" height="190px" />

```

I'd like this 'default image' to be linking to the node as well.

Any ideas on how to do this ?

# Answer
An easy way would be to set up a default image for the field. This setting is on the field settings page for the field on the node.

OR

You could to use tokens in the view. Add the path field to the view (set it to not visible), make sure it is higher than the image field. Then you should be able to add an anchor tag around your image tag and use the token value. eg.

```
<a href="[path]"><img alt="No Image" class="no-img" src="/sites/default/files/img-custom/no-image.gif" height="190px" /></a>

```

OR

You could to use tokens in the view like this. Add the path field to the view (set it to not visible), make sure it is higher than the image field. Under the 'rewrite results' section, check 'Output this field as a link' and add the link path token there.
> 2 votes

---
Tags: 7, views
---


# Question
Title: What methods are available to assign a TPL to a specific url for Drupal 7 theming?
Currently I have a custom javascript libary that is being loaded on all pages of the site as i hardcoded it into the **html.tpl.php** file. I konw you can target specific nodes or node types via the tpl filename format, but what if I wanted more control of where this tpl is activated? Is there some type of regex formating that I can use for html.tpl.php?

What I want to be able to do is load my custom js library on all pages **except** for a specific content type and a few views urls. How can this be done the most efficient way?

# Answer
Unset the JS or CSS assets on page build with either hook page build or hook page process and drupal add js.

Alternatively you can use hook theme to define custom tpl files on custom business logic (such as url paths).

Im on my phone, unable to gives more info or examples until at pc.
> 1 votes

---
Tags: 7, theming
---


title: How to pull parent taxonomy from nodes

text:
# Question
Title: How to pull parent taxonomy from nodes
I have a taxonomy list like so...

Parent One Subitem One SubItem Two SubItem Three Parent Two Subitem Four Parent Three SubItem Five SubItem Six

I also have a content type that uses subitems in a field, along with other fields.

I need to have a view that will show the parent taxonomy terms in addition to the other fields in the CCK. Something like

Parent Fields Title Book Subotem 1 Parent Two - SubItemsTwo Title Book Subotem 3

Please advise

# Answer
> 0 votes
You should look into Relationships for this.

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


title: menu inside views page

text:
# Question
Title: menu inside views page
I was wondering if this is possible. I have a views which is displayed as a page and I want to have menu inside that page. Is there a module available to achieve this?

Here's a picture of what I want to copy:

Thanks for the suggestions. I'm a newbie

# Answer
> 0 votes
You can use menu block module, install it then create a block of your menu you want, then with attachment feature of views,add it(your block) to your views(as attachment) and enjoy :).

# Answer
> 0 votes
If you simply want to place a menu in side bar use Menu Block Module.When user clicks on a menu item, it will load the page linked to that menu item.

But If you want to provide filter criteria in side bar, like if user clicks on "Koryo", It will filter the results and display results of "Koryo" only, than you should consider Facet API.

---
Tags: views, routes
---


title: Taxonomy term duplicates result

text:
# Question
Title: Taxonomy term duplicates result
I have created nodes and added taxononmy

Under views i want taxonomy seperarte. it is showing

A, B, C, A , B

A, B , C are my taxnomy terms

i want A , B, C are in tabs as a taxonomy

Any idea

# Answer
> 1 votes
I believe you can use Views to display your node and aggregate your Taxonomy terms to prevent duplicates.

# Answer
> 1 votes
I was wrong about aggregation, you don't need it.

In your case, you might want to use the "Multiple field option" of your taxonomy field. Leave the "Display all values" box checked, and choose to display only one value.

And don't forget to group results by taxonomy in your format options.

This works fine for me.

---
Tags: views, 7
---


title: Webform Component with multiple fields

text:
# Question
Title: Webform Component with multiple fields
I would like to make a custom module that integrates with webform (7.4).

I need to have a combo field which could be added to a form as one field but consists of 4 text areas.

I have found a discussion on this topic here -\> http://drupal.org/node/965068 but first its confusing how he does it at the end he just says he figured it out, but also this is a solution for 6.3 and i need for the 7.4

Any help would be greatly appreciated.

# Answer
> 2 votes
You could use https://www.drupal.org/project/webform\_addmore.

A more flexible solution would be to use the Entityform module in combination with https://www.drupal.org/project/field\_collection.

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


# Question
Title: Replace Views prev/next pagination with image arrows
Is there a template that would allow me to replace Views' prev/next text pagination with image arrows instead? I could do it with CSS but I don't feel that is ultimately an optimal solution.

# Answer
You can use the theme\_pager\_link function to override the core pager link. Or you can have a look at this article that may be helpful: https://www.drupal.org/node/318565
> 1 votes

# Answer
In general use CSS for this - not bad solution. But if you want use a changes in the output - You need use special function in your template.php your theme. For example for "mini\_pager" - You need implementation the theme\_views\_mini\_pager() function. For another pagers use the same method.
> 0 votes

---
Tags: 7, views, theming, media, paging
---


# Question
Title: Make label translatable in Global: Custom Text field
I'm using Drupal 7 and I have a Global: Custom Text in my view

```
<div class="myclass">
  <h3>Label</h3>
  <div class="title">[title]</div>
  <div class="category">[category]</div>
</div>

```

When I try to translate the 'Label' from

```
`Configuration » Regional and language » Translate interface`

```

I get an error 'The submitted string contains disallowed HTML'. That is because the label is wrapped in a div. I could add the div in include/locale.inc in the function

```
`locale_string_is_safe($string)`

```

but I don't think is a good idea to edit the Drupal core.

Do you have any better solution?

# Answer
Use `hook_views_pre_view` and set your global header programmatically. E.g.

```
$view->set_item_option($view->current_display, 'header', 'area_text_custom', 'content', $header);

```
> 0 votes

# Answer
You can create a template for the field, i.e.

**views-view-field--your-view-name--nothing.tpl.php**

in which, instead of the default code:

```
print $output;

```

you add the following code:

```
$yourstr = t('Your Cool Label');
$out = str_replace('Your Cool Label', $yourstr, $output);
print $out;

```

In this way you'll find "Your Cool Label" under the translatable strings interface (admin/config/regional/translate/translate).

Just remember to "Rescan template files" under Theme -\> Information of your view, then save.
> 0 votes

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


# Question
Title: Webform: send uploaded files as attachments
I have a webform where a user can upload a file; I want this file to be attached to the email sent to the site manager.

What is the best practice doing so? I tried finding a helper module, but I didn't find one.

# Answer
> 5 votes
Or you can use Mail System and Mime Mail modules. A "Include files as attachments" checkbox will appear in Webform E-Mails configuration.

# Answer
> 2 votes
You can use Mimemail module to send a file as attachment in webform, and also you can choose file types.

**Mimemail:**

* It permits users to receive HTML email and can be used by other modules. The mail functionality accepts an HTML message body, mime-endcodes it and sends it.
* If the HTML has embedded graphics, these graphics are MIME-encoded and included as a message attachment.
* Adopts your site's style by automatically including your theme's stylesheet files in a themeable HTML message format
* If the recipient's preference is available and they prefer plaintext, the HTML will be converted to plain text and sent as-is. Otherwise, the email will be sent in themeable HTML with a plaintext alternative.
* Allows you to theme messages with a specific mailkey.
* Converts CSS styles into inline style attributes.
* Provides simple system actions and Rules actions to send HTML email with embedded images and attachments.

> Note that there are some serious limitations you need to take into consideration when creating email layouts, see the Email Standard Project for more information.

# Answer
> 0 votes
First Paste this code in your current theme Template.php file

```
function yourthemename_webform_mail_headers($node, $submission, $email) {
  $attach_bool = false;
  foreach ($node->webform['components'] as $item) {
    if ($item['type'] = 'file') {
      $attach_bool = true;  // found a file component!
      break;
    }
  }
  $headers = array(
    'X-Mailer' => 'Drupal Webform (PHP/' . phpversion() . ')',
  );
  if ($attach_bool) {
    $hash = md5('randomstring');  // remember you can change randomstring to anything you want, just make sure it's consistent w/ part 2
    $headers['Content-Type'] = "multipart/mixed; boundary=\"".$hash."\"";
  }
  return $headers;
}

```

Don't forget change youthemename with your theme name

2) Now Create webform-mail.tpl.php in your current theme directory and paste this code.

```
<?php
// $Id: webform-mail.tpl.php,v 1.3.2.2 2010/03/25 02:07:29 quicksketch Exp $

/**
* @file
* Customize the e-mails sent by Webform after successful submission.
*
* This file may be renamed "webform-mail-[nid].tpl.php" to target a
* specific webform e-mail on your site. Or you can leave it
* "webform-mail.tpl.php" to affect all webform e-mails on your site.
*
* Available variables:
* - $node: The node object for this webform.
* - $submission: The webform submission.
* - $email: The entire e-mail configuration settings.
* - $user: The current user submitting the form.
* - $ip_address: The IP address of the user submitting the form.
*
* The $email['email'] variable can be used to send different e-mails to different users
* when using the "default" e-mail template.
*/
?>
<?php
$hash = md5('randomstring');  // refer to part 1
$attachments = '';
foreach ($node->webform['components'] as $item) {  // loop through each webform component
  if ($item['type'] == 'file') {  // is it a file?
    if ($submission->data[$item['cid']]) {  // did the user attach a file?
      $result = db_query_range('SELECT f.filename, f.filepath, f.filemime FROM {files} f WHERE f.fid = ' . $submission->data[$item['cid']]['value'][0], 0, 1);
      // query the database for the file information
      $file = db_fetch_array($result);
      $attachments[] = array(
        'mime' => $file['filemime'],
        'path' => $file['filepath'],
        'name' => $file['filename'],
        'data' => chunk_split(base64_encode(file_get_contents($file['filepath']))));
    }
    ob_start();
  }
}

if (is_array($attachments)) {
  print "--".$hash."\n"
    ."Content-Type: text/plain; charset=ISO-8859-1\n";
}
?>
<?php print t('Submitted on %date'); ?>

<?php if ($user->uid): ?>
<?php print t('Submitted by user: %username'); ?>
<?php else: ?>
<?php print t('Submitted by anonymous user: [%ip_address]'); ?>
<?php endif; ?>

<?php print t('Submitted values are') ?>:

%email_values

<?php print t('The results of this submission may be viewed at:') ?>

%submission_url

<?php
if (is_array($attachments)) { // let's attach the files now
  foreach ($attachments as $attachment) {
    print "--".$hash."\n"
      ."Content-Type: ".$attachments['mime']."; name=".$attachment['name']."\n"
      ."Content-Disposition: attachment; filename=".$attachment['name']."\n"
      ."Content-Transfer-Encoding: base64\n\n"
      .$attachment['data']."\n";
  }
  print "--".$hash."--";
}
print(ob_get_clean());
?>

```

Now clear cache and done and taken from this source and I never used this before.

# Answer
> 0 votes
I think webform\_multifile module useful for what u want.

---
Tags: webforms, files
---