# Question
Title: I have a field which looks corrupted. How should I remove all traces of it?
**Problem**

I have a taxonomy field that I was forced to re-create with different values after a number of errors. (I deleted the field and taxonomy and re-created them.)

It's used as an exposed filter in views and unfortunately appears to have become corrupted. Whenever I use it as a filter, in the drop down it only shows the previous values of the field (before it was re-created).

Clearing the cache, re-creating the field, clearing the search indexes, creating new views have all had no effect. Other identical field names with different machine names work fine so I'm presuming it's corrupted.

How should I go about cleaning this field from my database?

I'm considering just re-making it under a different name but I'm worried about the consequences of leaving some corruption in my database.

# Answer
This is totally off the top of my head so use with much caution, and after taking lots of backups!

```
// Remove taxonomy index records. Do this BEFORE removing field data tables.
$indexed_tids = db_query("SELECT field_foo_tid FROM field_data_field_foo WHERE entity_type = 'node' AND bundle = 'bundle_field_is_attached_to'")->fetchCol();
db_delete('taxonomy_index')->condition('tid', $indexed_tids)->execute();

// Remove the field data tables completely
db_drop_table('field_data_field_foo');
db_drop_table('field_revision_field_foo');

// Remove the field config
db_delete('field_config')->condition('field_name', 'field_foo')->execute();
db_delete('field_config_instance')->condition('field_name', 'field_foo')->execute();

// Clear up
drupal_flush_all_caches();

```

That should get tid of a taxonomy field called field\_foo, and all associated index data.

Note this is for a core install - if you have other modules installed that rely on that field or taxonomy data in some way, things might not be so easy.
> 1 votes

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


title: Access node only from manual URL

text:
# Question
Title: Access node only from manual URL
Looking for a module or hint to allow a node only be accessed from the manually set URL.

Ex. having node 42 with `URL path setting = myStory` can only be accesed with `http://host/myStory`, while `http://host/node/42` will return a `NOT FOUND`.

# Answer
With respect to all of the commentary given to the question, if you really want to do this, you can look at `$_SERVER['REQUEST_URI']` in any number of places and based upon its content, do things differently.

For example, if you go to:

```
www.example.com/path/to/hidden/content

$_SERVER['REQUEST_URI'] will be /path/to/hidden/content

```

yet if you go to

```
www.example.com/node/###

$_SERVER['REQUEST_URI'] will be /node/###

```

but the same content will be displayed while the url in the browser will be different.

So, if you want to obfuscate your nodes based up that, you could delete their content in a preprocess hook, or cobble together something in hook\_init to do a 404 but just also be very wary of the caching of pages for anonymous users as well, so hook\_boot would be needed instead, and do you want to do this for logged in users and any of numerous other what ifs.........

Plus, if you have global redirect or another similar module installed, the above won't work as it will have already redirected you to the alias.
> 1 votes

# Answer
I believe your looking for the Rabbit Hole module.

> Rabbit Hole can prevent this node from being accessible on its own page, through node/xxx

And from options:

> Deliver a page not found page.
> 0 votes

---
Tags: 7, users
---


# Question
Title: Custom content type and custom list view
Hi totally new to Drupal and I've managed to set everything up I needed to. Custom content types, taxonomies etc.

Firstly I'd like to know how to link to a page which will display all the posts in my custom content type.

# Answer
> 0 votes
If you're wanting to build "lists" of things then I would check out the Views module. You will create a new content view and filter by the new content type. If you're struggling building a View just google for 'drupal views tutorials' and there will be a ton to show you how to build things with views.

---
Tags: theming, nodes
---


# Question
Title: How to setup multisite to multisite rsync with drush?
I try to rsync between a multisite setup (local) and a multisite setup (stage). If I run a sync it will copy all sites from dev to stage but I just want the current site to be synced.

```
$drush rsync @dev @stage

```

My drush alias file is located in ~/.drush/example.aliases.drushrc.php

```
$aliases['local'] = array(
  'root'           => '/Users/admin/Sites/drupal',
  'uri'            => 'example.local',
  'shell-aliases'  => array(
    'dump' => '!drush sql-dump --gzip --ordered-dump'
  ),
  'path-aliases' => array(
    '%dump'          => '/Users/admin/dev-' . date('Ymdhis') . '.sql',
    '%drush'         => '/Users/admin/drush',
    '%site'          => 'sites/example/',
  ),
);

// REMOTE: STAGING
$aliases['stage']  = array(
  'remote-user'      => 'xyz',
  'remote-host'      => 'stage.example.com',
  'root'             => '/home/xyz/www/stage.example.com',
  'uri'              => 'stage.example.com',
  'path-aliases' => array(
    '%drush'         => '/home/xyz/drush',
    '%drush-script'  => '/home/xyz/drush/drush',
    '%dump-dir'      => '/Users/admin/.drush-backups/example.stage',
    '%site'          => 'sites/example/',
  ),
  'command-specific' => array(
    'sql-sync'       => array(
      'no-cache'     => TRUE,
    )
  ),
  'shell-aliases'    => array(
    'dump' => '!drush sql-dump --gzip --ordered-dump'
  ),

  // DB
  'databases' =>
  array(
    'default' =>
    array(
      'default' =>
      array(
        'database'   => 'xyz',
        'username'   => 'xyz',
        'password'   => 'xyz',
        'host'       => 'xyz',
        'port'       => 'xyz',
        'driver'     => 'mysql',
        'prefix'     => '',
      ),
    ),
  ),
);

```

Questions:

1. %site: My project folder in sites/ is called example on the local side and has the same name on the staging side. Do they need to be different?
2. Do i need to put **all** domains in site.php on my staging server? At the moment I am using just the actual setup ($sites\['stage.example.com'\] = 'stage.example.com';) on my staging server. My local sites.php file:

```
$sites['example.local'] = 'example.local';
$sites['stage.example.com'] = 'stage.example.com';
$sites['example.com'] = 'live.example.com';

```
3. Are the directories *all/* and *default/* always needed?

My local Setup:

* Drush 7.x dev
* PHP 5.5.x
* MAMP

My Server Setup:

* Drush 7.x dev
* PHP 5.5.x

***Edit:** Removed opinion based questions ;)*

# Answer
1. On Drupal 6, your sites folders must be the **same**. Since you are using Drupal 7, they can be different, but it is more convenient if they are the same.
2. You do not need to copy all of your multisites to your dev server. The drush rsync option you are looking for is `--exclude-other-sites`. This will cause rsync to skip everything in the sites folder except for sites/all, and the site you are syncing from.
3. sites/all is where sites/all/modules and sites/all/themes go, so you typically need these. With some effort it might be possible to move your contrib modules elsewhere (if everything was in a profile, or if you hand-modified your registry), but this would be an unusual setup. sites/default is not needed.
> 3 votes

---
Tags: drush, multi-sites
---


title: Generic orders URL

text:
# Question
Title: Generic orders URL
Is there a way to create a page that requires the user to log in and then shows them all their orders, but only the orders of the logged in user. I need it to the same URL for all users as an external source, that knows noting about the user accounts, will be directing them to it. Currently I see urls like this

```
http://127.0.0.1:8080/drupal/user/142/orders

```

but I want a url like this

```
http://127.0.0.1:8080/drupal/orders

```

And since I've already customised the view of the Orders screen I'd really like to re-use that view, just place it on a generic url. If a non-logged in user tries to go to `http://127.0.0.1:8080/drupal/user/142/orders` they get told the page doesn't exist rather than told to log in.

# Answer
If you have appropriate access control on your custom View, then use something like the Redirect 403 to User Login module so customers are returned to your /orders URL after logging in.
> 0 votes

---
Tags: 7, commerce
---


# Question
Title: commerce_display_path is relative and doesn't work from Order page
I'm trying to create a link from the Order view back to the product page so a customer can order it again. I've added a field to the view to load commerce\_display\_path (and set it as hidden) then another field that is some metadata about the original purchase (the line item is customised and I'll get the product page to read that url and repeat the customisation). That field uses rewrite rules for display like so

`<a href="[commerce_display_path]?bundleId=[econecom_bundle_id-value]">Reorder</a>`

However the commerce\_display\_path is relative so I end up with a URL like `node/6?bundleId=71398558` and when used from the orders page the browser sees `http://127.0.0.1:8080/drupal/user/142/orders/node/6?bundleId=71398558`, which is useless.

If I manually put a `/` at the beginning of the `a` tag it will get the wrong url because in my test environment drupal is running as /drupal. I could put `/drupal` in but I think there should be a better way to get the sites base url into the rewrite rules.

# Answer
I'm not sure where your second token is coming from, but assuming that's part of the View as well, why are you rewriting the link directly with HTML instead of using the "Output this field as a link" code that's designed to accept Drupal paths and generate appropriate absolute URLs from them? That's what I'd do or else I'd look into rewriting the commerce\_display\_path field as well to make it work.
> 0 votes

---
Tags: 7, views, commerce
---


title: How to render fields in form?

text:
# Question
Title: How to render fields in form?
I passed the `$uid` as a `hook_menu()`-wildcard to a form and loaded the user of that uid with `$account = user_load($uid)`. Admin then is able to fill some textfields and save. I want some other non editable fields from $account simply to be displayed as markup or anything like that in the form. Tried to pass these fields to #markup like so: `'#markup' => $account->field`.

But this doesn't work. Should this normally work? What am I doing wrong?

Or would it be better to display an aditional block which fetches the $uid from the URL and prints me my fields?

# Answer
> 2 votes
I don't see anything wrong with your approach. `'#markup' => $account->field` should work. Do you have it nested under a key?

```
$form['static_field'] = array(
    '#markup' => $account->field
);

```

---
Tags: 7, forms
---


title: Hand generate views relationship

text:
# Question
Title: Hand generate views relationship
Here's the setup: the previous site builder linked a large quantity of assets to particular nodes. Now that I'm on board, we want to expand those nodes into larger sections, but we need the linked assets to show up on all the pages.

Right now we have a view that uses a contextual filter to look at the NID. Then, it refers to a relationship to see what assets are related to that NID. Then, the view is filtered and displayed.

I need to come up with a way to display that same view on different pages that obviously don't share the same NID. I've tagged all the pages within a section with the same taxonomy term. I'd like to create a custom relationship that runs an equation that converts tid to nid.

> tid 62 = nid 15
> tid 63 = nid 47
> tid 64 = nid 153

I think you get the picture. Any help? If you have a better idea please let me know, thanks! -JB

# Answer
Here are a couple of ideas for you:

1) If there aren't too many nodes with assets - you could remove the contextual filter and create an "Or" Filter Group in the regular filter section of the view (based on NID). Then just list all of the NID's you want to filter by (NID 15 **Or** NID 47 **Or** NID153). That should pull in all of the assets from each of the Nodes without having to change the view much.

2) If you tagged the nodes containing the assets with taxonomy terms - you should also be able to use a regular taxonomy term filter instead of the contextual filter. I think in that case you would just need to add a **Content: Taxonomy terms on node relationship** to the view. That should open up a bunch of new taxonomy filter options in the regular filter section of views. You could then filter by term id or name.

You would just have to make sure you apply the **Content: Taxonomy terms on node relationship** to the term id filter when you set it up.
> 0 votes

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


# Question
Title: How do I move a Drupal site from WAMP server to a live server?
I'm a newbie with this so am having quite a bit of trouble. I've created a Drupal site in WAMP Server and am raedy to move the site to my hosting with Heart Internet.

I've copied C:/Wamp/www/mywebsite into a zip folder and uploaded/unzipped into my hosting space so the files are uploaded successfully.

I then went into phpMyAdmin on my computer and exported my database. I then created a blank database on my web hosting on the live server. this database username is c150-drupal and i generated a random password. I then clicked 'restore' on my new blank database and selected the database that I exported from WAMP. however I keep getting the error message below:

ERROR 1044 (420000) at line 22: access denied for user 'c150-drupal'@'%' to 'postcodedatabase'

I'm so confused how I should be exporting mysql databases in order to upload them to my webserver. Also is it acceptable to export a database from WAMP in order to use as a backup incase anything goes wrong so I could import the database back into WAMP?

Thank you,.

# Answer
> 0 votes
You should check your user privilege on your production server because you can't do this action.

This thread deals with your problem : https://stackoverflow.com/questions/8838777/error-1044-42000-access-denied-for-user-localhost-to-database-db

# Answer
> 0 votes
I take it you're using phpMyAdmin on the hosting server as well? make sure the DB names are the same for the new/empty one and the one you exported from - and if you manually changed the .sql file, make sure you changed the name in all places (CREATE and USE queries);

also check that the user has appropriate permissions for the new/empty DB - the hosting services often have it not in phpMyAdmin, but at the came place where you create DBs and users - look for something like "Add User To Database", and do exactly that - add the user to the DB with enough permissions to create/write

hope this helps

---
Tags: database
---


# Question
Title: Display different menu links based on page/theme
I have a custom main theme for my website along with a Blog theme using themeswitcher. All content in my /blog directory uses the Blog theme.

Question: I would like to display different links in the main menu when users are on my blog theme vs. main website theme. If I choose to display the Primary Menu in my blog theme all of my main website links show up. Are there any menu Modules that allow enable/disable links based on directory and/or pages?

I there an easy way to do this?

# Answer
You will need to mange the links in 2 different menus. for example Main Menu for all website links and Blog Menu to have the links related to Blog pages.

Disable the Main Menu and the Secondary Menus from your theme settings.

Now goto blocks pages and configure the main menu block scroll down to bottom

under Show block on specific pages

select All pages except those listed and type blog/\*

now save this block configuration and goto configure Blog Menu scroll down to bottom and select Only the listed pages and type the same in texarea ( blog/\* ) and save the block configuration.

Now depending on your URL pattern it will display your required menu.
> 1 votes

---
Tags: routes, navigation
---


# Question
Title: How to display tabbed menu, created via hook_menu?
I am fairly new to Drupal and still figuring out its inner workings. Currently, I am playing around with creating own modules. I want to create a tabbed menu via hook\_menu and display it. Unfortunately, I seem to fail here. I lack the understanding how to activate the coded menu in the hook on one of my pages. Since I do not define a block (and with such have no hook block\_info or block\_view in my module), I am not able to place my module via the structure menu anywhere. And by itself, the tabbed menu does not show up anywhere. My module is available in the modules' list and I can activate and deactivate it. I also cleared all caches, but I can't seem to find it anywhere. Hence, my question is: how do I activate and place the menu on my site?

My module has the two files dummy\_module.module and dummy\_module.info.

dummy\_module.module:

```
/**
 * Implements hook_menu().
 */
function dummy_module_menu() {
  $items = array();
  $items['dummy'] = array(
    'title' => 'dummy_module',
    'page callback' => 'temp_output',
    'access callback' => TRUE,
    'weight' => 1
  );
  $items['dummy/new_tab1'] = array(
    'title' => 'Current 1',
    'type' => MENU_DEFAULT_LOCAL_TASK,
    'page callback' => 'temp_output1',
    'weight' => 2
  );
  $items['dummy/new_tab2'] = array(
    'title' => 'Current 2',
    'type' => MENU_LOCAL_TASK,
    'page callback' => 'temp_output2',
    'weight' => 3
  );

  return $items;
}

function temp_output() {
  return 'Hello world!';
}

function temp_output1() {
  return 'Hello world 1!';
}

function temp_output2() {
  return 'Hello world 2!';
}

```

dummy\_module.info:

```
name = Dummy Module
description = This is a dummy module and hence the basis for all further module development.
core = 7.x
files[] = dummy_module.module

```

# Answer
Alright, I found the problem: my tabs definitions were lacking the extra line

```
'access callback' => TRUE,

```

With this line in each tab definition, the tabs show up as extected. Here is my final code for dummy\_module.module:

```
<?php

/**
 * Implements hook_menu().
 */
function dummy_module_menu() {
  $items = array();
  $items['dummy_module'] = array(
    'title' => 'dummy_module',
    'page callback' => 'temp_output',
    'access callback' => TRUE,
    'weight' => 30
  );
  $items['dummy_module/new_tab1'] = array(
    'title' => 'Current 1',
    'type' => MENU_DEFAULT_LOCAL_TASK,
    'page callback' => 'temp_output1',
    'access callback' => TRUE,
    'weight' => 1
  );
  $items['dummy_module/new_tab2'] = array(
    'title' => 'Current 2',
    'type' => MENU_LOCAL_TASK,
    'page callback' => 'temp_output2',
    'access callback' => TRUE,
    'weight' => 2
  );

  return $items;
}

function temp_output() {
  return 'Hello world!';
}

function temp_output1() {
  return 'Hello world 1!';
}

function temp_output2() {
  return 'Hello world 2!';
}

```
> 1 votes

---
Tags: routes
---


# Question
Title: Changing a form value or input field value during the submit handler
I am trying to change the value of a text area field at the end of my submit handler. I have tried using `form_set_value` and `$form['form_id']['#value'] = 'something';` to accomplish this but after clicking the submit button the field never changes. Also the submit button that I am trying to change the field with comes from the file managed form. I also included `$form_state['rebuild'] = true;` after I set the field's value. Here is my code

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

//do something with then file code
...

```

then

```
$form_set_value($form['value_to_change'], 'update the value, $form_state);

```

//I also tried

```
$form['value_to_change']['#value'] = 'update the value';

$form_state['rebuild'] =TRUE
}

```

In the form my code is

```
$form['value_to_change'] = array(
'#type' = 'text area',
'#value' => 'this will change',
);

```

# Answer
> 3 votes
Just stumbled upon this and it's pretty dead so here's the answer in case OP still cares... turns out @Mołot is right.

The correct way to programatically change a form's submitted value is actually during validation and not during submission.

If you go back and re-read the documentation for form\_set\_value(), you'll notice that it explicitly says:

> Changes submitted form values during form validation.

---
Tags: ajax, forms
---


title: Module not found during installation

text:
# Question
Title: Module not found during installation
I am creating an install profile that requires, among other things, a slew of Features. Because of the intricacies of the project, which is a multi-site, I have in sites/mysite.com/modules/custom\_features 3 different categories of features, each in its own folder: my\_install\_profile/, my\_other\_install\_profile/, and common/.

Drupal seems to be finding all of the modules that my install profile requires just fine, except one. It's expecting to find it in sites/mysite.com/modules/custom\_features/my\_install\_profile/ but the module actually lives in sites/mysite.com/modules/custom\_features/common/.

I've triple-checked the install profile, and any dependent modules. I can't find anything path-specific, or specific to this module, that might be causing the confusion.

It doesn't report that the module is missing at the beginning of installation, but partway through I get this:

`Warning: include_once(umn_import_content_type.features.inc) [function.include-once]:
 failed to open stream: No such file or directory in include_once()
 (line 7 of /www/sites/mysite.com/modules/custom_features/my_install_profile/my_feature/my_feature.module).`

`Warning: include_once() [function.include]:
 Failed opening 'my_feature.features.inc' for inclusion
 (include_path='.:/Applications/MAMP/bin/php/php5.3.14/lib/php') in include_once()
 (line 7 of /www/sites/mysite.com/modules/custom_features/my_install_profile/my_feature/my_feature.module).`

Why is Drupal looking for this in the wrong folder?

# Answer
It appears that the issue was at the infrastructure level. The error resolved when I restarted Apache.
> 1 votes

---
Tags: installation, installation-profiles
---


title: PHP Fatal Error

text:
# Question
Title: PHP Fatal Error
I'm getting a PHP fatal error whenever I try to use taxonomy\_term\_save(). I am using it in an install script which may be pertinent information.

```
PHP Fatal error:  Class name must be a valid object or a string in /var/www/proface.com/includes/common.inc on line 7779, referer: http://domain/install.php?profile=company_install_profile&locale=en&op=start&id=1

```

Why would this happen? The terms look correct to me:

```
  $terms = array();

  drupal_load('module', 'taxonomy');
  $vocabulary = taxonomy_vocabulary_machine_name_load('distributor_types');

  $term = new stdClass();
  $term->name = "Platinum Distributors";
  $term->description = '';
  $term->vid = $vocabulary->vid;
  $term->weight = 0;
  $term->vocabulary_machine_name = 'distributor_types';
  $term->format = 'plain_text';
  $term->uuid = 'ee4e4f18-ad5e-46df-a2e7-145876efd907';
  $terms[] = $term;

```

Pulled out each of the terms from a foreach loop and...

```
  taxonomy_term_save($term);

```

And when I print out the entity name that is causing problems, it spits out, "taxonomy\_vocabulary".

This is the function throwing the error, the line with "new $class($entity\_type)" is line 7779.

```
function entity_get_controller($entity_type) {
  $controllers = &drupal_static(__FUNCTION__, array());
  if (!isset($controllers[$entity_type])) {
    $type_info = entity_get_info($entity_type);
    $class = $type_info['controller class'];
    $controllers[$entity_type] = new $class($entity_type);
  }
  return $controllers[$entity_type];
}

```

I believe the version for this is 7.22.

# Answer
It's actually my coworker that should get credit for this, not me, but here's the solution:

```
drupal_load('module', 'taxonomy');

module_enable(array('taxonomy'), FALSE);

$vocabulary = taxonomy_vocabulary_machine_name_load('distributor_types');

```

The taxonomy module wasn't enabled.
> 1 votes

# Answer
My working theory right now is that as of that point in your code Drupal isn't aware of the `taxonomy_vocabulary` controller. You could try running `entity_get_info('taxonomy_vocabulary')` first to inform Drupal of the `taxonomy_vocabulary` controller.
> 0 votes

---
Tags: taxonomy-terms, installation
---


# Question
Title: Is the use of the $GLOBALS array in Drupal in anyway 'less secure' or 'bad practice'?
Is the use of the $GLOBALS array in Drupal in anyway 'less secure' or 'bad practice'. Like using:

```
$GLOBALS['user']->uid

```

instead of

```
$account->uid

```

if it were avialable?

Thanks.

# Answer
> 2 votes
Short answer is no it is not bad practice or insecure, it is fine to use the $user global. Drupal core and a huge amount of modules use the $user global.

If you want to be really picky though:

However, it is possible for you to install bad code into your site somewhere that puts bad things into the $user global.

That is just a risk in general though with putting any code on your site, it doesn't just relate to the $user global.

Also, for all I know the $account variable you talk about could be bad because I have no idea where that variable is coming from as your question doesn't detail it.

# Answer
> 3 votes
Directing using

```
global $user
$user->uid

```

adds a new variable to your current scope, which adds potential for misuse and other accidents.

Using

```
$GLOBALS['user']->uid

```

can be seen as a safety precaution. You can still mess things up, but it is somewhat harder, and you don't introduce a new variable.

However, directly poking around in the `$user` object is bad in a lot of cases, especially explicitly using `$user->uid`.

Whenever possible, you should leverage the API. For example, use

```
if (user_is_logged_in()) { ... }

```

instead of

```
global $user;
if ($user->uid) { ... }

```

and use `user_access()` instead of using `$user->roles`.

One place where explicit `$user->uid` use may be needed is with database queries, though that can be lessened somewhat with `EntityFieldQuery->addAccount` and `db_select->addtag('node_access')`.

---
Tags: users
---


# Question
Title: Error message getting displayed but not getting highlighted fields in Drupal 7
Drupal 7 is not displaying highlighted fields on using `form_set_error` but error message is getting displayed. I have rendered my form hook\_form in template. Could that be the cause for this issue?

Here is my code:

```
if(($form_state['values']['field1']=='' ){
 form_set_error('', t('one field is required'));

 }

```

# Answer
First argument of `form_set_error` tells Drupal what element should get highlighted. Obviously empty string means "none", so your code works exactly as designed.

To make field required, you can go a simpler way: Use `#required` attribute and let Drupal take care for details.

To round it off, as Clive said, your code would be:

```
form_set_error('field1', t('one field is required'));

```

But if you're just checking for an empty field, use `#required`.
> 5 votes

# Answer
It's not working for me using the below code:

```
  $form['field1'] = array(
        '#title' => t('Field1'),
        '#size' => 24,
        '#type' => 'textfield',
    '#default_value' =>$field ,
    '#required' => TRUE,
  '#element_validate' => array('function_name'),

  );

if(($form_state['values']['field1']=='' ){
 form_set_error('field1', t('one field is required'));

 }

```

getting the error message in red at the top but my text box is not getting highlighted with red border. I have used this text box in hook\_form in a module, but i have called this form in theme using

```
print render(drupal_get_form('hook_form'));

```

I guess the error message is not getting highlighted since am calling this in a theme.

This is getting worked when i call my form in a module but i want the form to be called from a template. In this case my error message is not getting highlighted with red border over the text box.
> 0 votes

---
Tags: forms, theming
---


# Question
Title: Content status, view different fields, different roles
I want to know if there are any modules for the following situation:

User X of role A creates a case (special node type). If user Y logs on (of role B). He sees a case has been submit. He then can add pictures to the case (user X can't do this, he doesn't have the rights). Once that is done User X will see a the new node and can check out the pictures (but can't change them, or delete). And so on untill the case has the status closed.

I've looked at some modules for this and the Workflow module seems to lack what I want to do here.

I'm pretty sure people must have done something similar to this so that's why I'm asking.

Modules I know i'll have to know:

Views (to get my lists of a content type with a certain status)

Is this possible at all in Drupal? Worst case scenario is that I'll extend a node with my own entity and keep the node id, and programatically change the state of the node and let users add pictures.

Thanks for reading!

# Answer
> 1 votes
If pictures should be part (field) of a case node type, use Field Permissions module to set separate permissions for different roles.

If pictures should be separate node type, use Entity reference module to reference parent case from picture node. On the case page you can add a Views block with pictures referencing this case with a button to add new picture.

In both cases you would need some custom code to support your particular workflow.

---
Tags: views, rules, entities, workflows
---


# Question
Title: How to translate menus that are made in views?
I'm having hard time translating my menu to other languages, when I try to translate menus that I made with views I confront with "You are not authorized to access this page." Is there any easy way to translate such kind of menus?

# Answer
> 0 votes
I would recommend you to not generate menu items with views. Just give it a path and create menu items manually which point to the appropriate path. If you need to have a speaking URL, create URL-Aliases for it in each language. This does the trick, usually.

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


# Question
Title: The login doesn't show a username anymore
I can't login into my Drupal anymore and I'm not sure why. I've got the BOTCHA Spam Prevention module and commerce (enabled with anonymous checkout). Now my login looks like this: I can't create a new user: "the field username is required" and I can't request my password (there is no username/email field).

I repaired the session table already. Tried several browsers and computers and the admin account has the User ID 1.

Don't know how I can get back into my Drupal :-S Any ideas?

Thanks, Chris

# Answer
You could try to disable the module that causing the problem. There are multiple ways of doing that.

### Using Drush

> `drush dis modulename`

### Database hack

In the system table find the module and set its status to 0

> `UPDATE {system} SET status=0 WHERE name='modulename'`
> 1 votes

---
Tags: users
---


# Question
Title: How to display the profile page in Modal window
By using ctools, i am able to display a form in modal window. Now i wish to display a page(the profile page) in modal window.

Below is the sample code (call by menu page callback) to display a html content in modal window, but how to display a page (user/1/profile) , i know i almost there..

any ideas?

```
function mymodule_profile_modal(  $user,$js)
{
  $output = t('<p>Lorem ipsum dolor sit amet...</p>');
  $title = t('Modal example');
  if ($js) {
     ctools_include('ajax');
     ctools_include('modal');
     ctools_modal_render($title, $output);
     // above command will exit().
   }

 }

```

# Answer
This tutorial might help you: http://drupion.com/blog/10-steps-creating-ctools-modal-window-drupal-7
> 0 votes

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


# Question
Title: User menu page visible to the author user (uid)
The view module has a great function when set a menu tab with contextual filter user:uid, so the user that is author of that node will be able to see the content. Lets say for an example the flag module has a view bookmarks, so when a user choose some node to follow/flag it will be available in his user/%/bookmarks.

How can I do this with custom code? I have my code here as a test:

```
<?php
function mymodule_menu() {

    $items = array();

    $items['user/%/add-news'] = array(
        'title' => 'Hello World',
        'page callback' => 'mymodule_user_news',
        'page arguments' => array(1),
        'access arguments' => array('access content'),
    );

    return $items;
}

function mymodule_user_news() {
        return 'Hello world';
}

```

This "Hello World" everybody can see it. Of course, because I'm using `'access arguments' => array('access content'),`

How can I set this page to be visible only for user author?

I'm planning to add here a form, so the user can fill the form and send it to the administrator of the website.

Oh, by the way when I set a link only visible to the author user I use this echo l(t("Profile edit"), 'user/' . $GLOBALS\['user'\]-\>uid . '/edit');

How can I use the $GLOBALS\['user'\]-\>uid in a module?

# Answer
> 1 votes
Access arguments

> Understanding access arguments in Drupal's menu system can be a little confusing, but they are really quite simple. Let's take this example and work through the arguments.
>
> ```
> <?php
>   $items['foo/bar/user'] = array(
>     'title' => 'Foobar',
>     'description' => 'List, add, and edit Foobars.',
>     'page callback' => 'foo_bar_function',
>     'access callback' => 'user_access',
>     'access arguments' => array('administer users'),
>   );
> ?>
>
> ```
>
> Permissions Arguments, array('this\_permission') Here access arguments is the key for an array that contains one item administer users. This means that the current user must have permission to administer users in order to access the page. Which page? Notice the first line gives the path to $item. The path is 'foo/bar/user'.
>
> In this example, 'administer users' is the string that drupal uses to reference permissions. If you go to the permissions page (Administer
>
> > > User Management \>\> Permissions), you can see a list of strings you might use for access arguments. Each permission can be used by your module.

---
Tags: hooks
---


# Question
Title: How to configure wysiwyg_tools_plus module?
Has anyone used this module (wysiwyg\_tools\_plus)? It give ckeditor the ability to create tabs & accordion effects via a wysiwyg (sample video). The docs on usage look good, but I'm having a hell of a time figuring out how to actually get the icons to show up in ckeditor.

I've done this:

* installed ckeditor module & verified usage
* installed/enabled wysiwyg\_tools\_plus
* set ckeditor as the editor for my text formats
* tried to edit profiles (/admin/config/content/wysiwyg/profile/full\_html/edit), but haven't found a way to add the Tab or Accordion buttons

Any idea what I need to configure?

# Answer
There's two ways of running CKEditor in Drupal, as a straight module install, and as a component of the WYSIWYG Tools module. It's the latter that you need.

So, install the normal WYSIWYG Tools module and then follow the instructions to install an editor (CKEditor) within. I've found only \< v4 seems to work for this unfortunately, but there is an update to v3 from 2013 which seems to work ok.

Once you've got that working you will get a WYSIWYG editor that has no buttons, it's not broken, it just doesn't tell you that you have to configure it for each view (full HTML / filtered HTML etc) and select the buttons you want to appear.

When choosing the buttons, near the bottom there's a few for accordion & tabs, so just make sure these are selected for the content types you want to use.

It's not exactly intuitive, but it's actually fairly easy when you know how!

Hope that helps.
> 2 votes

---
Tags: 7, wysiwyg
---


# Question
Title: Two login forms on a same page (user/login)
I've used hook\_form\_FORM\_ID\_alter() to alter the user/login form. Now I have to create another form that will have different submit handler because will be connecting with web service.

The hook\_form\_FORM\_ID\_alter() is altering the existing default login form and cannot create another form. We have sellers and customers users.

The reason for creating 2 forms is: On the first form the submit handler is connecting with the web service for the customers method and the submit handler of the second one it should connect with the method web service for the sellers. Is it possible to do this?

# Answer
Here are some quick thoughts that should help you thinking.

I'm not sure yet if it's the best option (have to think about it for a while and I don't know all your details) but:

1. Create a new page via custom module, say `/login`.
2. Implement `hook_page_alter()` in the custom module and redirect all requests from `/user/login` to `/login`. Simply by:

```
if (arg(0) == 'user' && arg(1) == 'login') {
  drupal_goto('login');
}

```
3. Create an alternate login form through your custom module with different submit handlers etc.
4. On `/login` page, create any markup you need and pass the two forms. First form will be the regular drupal login form (you can get it by `drupal_get_form('user_login')`) and the second one will be the one you created manually. This way you have 2 login forms on the same screen with different submit handlers.

Check out `user_login()` function in the `user.module` file. That is the function that creates the login form.

**Important**: I didn't test this. Check it in and out to make sure there are no conflicts with other modules or workflows.

Hope this makes sense!
> 1 votes

---
Tags: forms, hooks
---


# Question
Title: Does drupal_get_path_alias only work if you are requesting a page, or can it also work if you are requesting a form?
Does `drupal_get_path_alias` only work if you are requesting a page, or can it also work if you are requesting a form? For example:

```
drupal_get_path_alias(node/1);

```

works fine, but the below doesn't

```
drupal_get_path_alias(node/1/edit);

```

so the user sees a mixture of aliased and normal paths. Could I have:

```
content/todays-news

```

and

```
content/todays-news/edit

```

Thanks

# Answer
The Sub-pathauto module can help with that

> The Drupal Path module matches only full URLs when creating SEO-friendly aliases. This module extends that behavior by also matching known sub-paths and replacing them with their respective alias.
>
> For example, if user/1 is aliased to users/admin, this module rewrites the link to the user contact page user/1/contact to use the aliased URL users/admin/contact instead.
> 1 votes

# Answer
For Drupal 6 there was a Sub-path URL Alias module.

> The Drupal Path module matches only full URLs when creating SEO-friendly aliases. This module extends that behavior by also matching known sub-paths and replacing them with their respective alias. For example, if node/1 is aliased to content/alias, this module rewrites the link to the node edit page node/1/edit to use the aliased URL content/alias/edit instead. This also includes Views URLs taking a node as argument (node/%/yourview), in short, every URL that is based on, or extends, an existing alias. In combination with the Pathauto module it is possible to get rid of all remaining exposed internal URLs.

I'm not sure if there is any for D7. If not porting it would be the option to go for.
> 1 votes

---
Tags: path-aliases
---


# Question
Title: how to get the values of a view in _preprocess_views_view_fields drupal7
I have a view of multiple content types. I only select the name and an image from those content types so I'm sure what the format of output is going to be. how can I get the field values of view in MYTHEME\_preprocess\_views\_view\_fields?

`kpr()` function doesn't work here because for every content type there is a specific name for fields, say for content type A and B it is `field_A_name` and `field_B_name`.

thanks

# Answer
hope this will help,

```
     function yourtheme_preprocess_views_view_fields(&$vars) {
    if ($vars[view] -> name == 'yourviewname') {
         foreach ($vars[view]->result as $key => $value) {
            kpr($value -> field_field_name['0']);//here you will get the name field RAW value and  RENDERED value in array.
        }
    }
}

```
> 1 votes

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


# Question
Title: Book navigation - how to customize outline to show progress and enforce serial navigation
I have a task to customize Book outline to:

* force the pages of the book to be read from start to finish. Once a page has been read it can be revisited.
* show the progress through the book.

I was thinking of using the outline links to do this. For pages that have not been read the outline item would not be a link. Once the page has been read it becomes a link.

I am fairly new to Drupal and have some experience creating and modifying modules. It would seem that this could be accomplished by extending the Book module but I have not looked at the code yet.

Does this seem like the best way to go or is there an existing module that would help?

# Answer
> 1 votes
The Course module has the facilities needed to implement these features. With a few code and css tweaks and otherwise standard Drupal content and block configurations I was able to satisfy these requirements to a large degree.

I should have explained in the original post that my site is actually a series of training modules. I had originally planned to make this a book with the pages being the training modules. With the Course module I instead created a book for the top level container and then added the courses (using the course content type) to this book. Inside each course was another book that held the actual content pages. I forced the user to navigate the pages of the course using the navigation links at the bottom of each page by hiding the outline until they had finished each course. They could also see their progress by navigating through the courses to see which ones they had completed (with a large green check mark). This is not a perfect solution but it works.

---
Tags: nodes
---


title: Render videos in CKEditor (WYSIWYG)

text:
# Question
Title: Render videos in CKEditor (WYSIWYG)
I am using Media Module 2.x.alpha2 + File Entity Alpha2

Using WYSIWYG (CKEditor)'s Add Media button I can upload videos but there is no proper file formatter to display it in the page, all I see is:

```
<source type="video/mp4" src="http://path/sites/default/files/myfile.mp4"></source>
<source type="video/ogg" src="http://path/sites/default/files/SSA50002.ogv"></source>

```

How can I properly rewrite the code to have a proper formatter etc:

```
<div id="video_lightbox_myvideo" class="lightbox" style="display: none;">
<embed name="player_1" id="player"
          type="application/x-shockwave-flash"
          pluginspage="http://www.macromedia.com/go/getflashplayer"
          width="800" height="600"
          src="http://path/wel/players/jwflvplayer/player.swf"
          allowfullscreen="true"
          allowscriptaccess="always"
          flashvars="file=' . $video_path . '&fullscreen=true&image=' . $video_preview . '&skin=http://path/wel/players/jwflvplayer/skins/mainley.swf">
          </embed>
 </div>

```

# Answer
> 1 votes
Instead you can use Wysiwyg Media Embed module to embed videos.

> This is an integration of the CKEditor MediaEmbed plugin for the Wysiwyg module.

---
Tags: media, files
---


# Question
Title: How can i create a view of all drupal commerce products with the orders they appear in?
I try to create an administrative view which lists all products in my drupal commerce installation, where some cols should contain data from the orders in which they appear:

```
PROD | PRICE | ORDERED
----------------------
one  | 12.-  | -
----------------------
two  | 10.-  | Pete P.
     |       | Anna D.
-----------------------
three ...

```

But as far as i can see, if i start a view of products, i have no relation to referencing line-items.

If i would start with line-items, i could not have products in my list, which appear in no orders...

# Answer
> 0 votes
Drupal Commerce does support some reverse reference relationships, but currently there is only a reverse relationship from products to nodes that reference them, not from products to line items that reference them. If I were you, I'd instead make the base table orders, because you can more easily establish relationships from orders to line items to products and get at the same fields that way. We use commerce\_order as the base table for shopping cart Views, for example.

---
Tags: views, commerce
---


# Question
Title: Can drupal_http_request be secure (https)?
I'm using drupal\_http\_request to parse some user details between servers.

Is it possible to secure drupal\_http\_request using https or should I fall back to cURL?

If there's a better way, do tell.

# Answer
Yes, it can.

```
case 'https':
  // ***************
  // Note: Only works when PHP is compiled with OpenSSL support.
  // ***************
  $port = isset($uri['port']) ? $uri['port'] : 443;
  $socket = 'ssl://' . $uri['host'] . ':' . $port;
  $options['headers']['Host'] = $uri['host'] . ($port != 443 ? ':' . $port : '');
  break;

```
> 5 votes

# Answer
Not sure if I am understanding you properly, but `drupal_http_request()` does handle `https://` URLs. If you want to send a request to https://example.com, you can do it.
> 4 votes

# Answer
No,

drupal\_http\_request doesn't correctly verify certificates, which makes it impossible to tell if you connected to the right server.

See https://drupal.org/node/1081192 for details and a path forward. This also includes a workaround you can deploy with some work.
> 3 votes

---
Tags: 7, database
---


# Question
Title: D7: filter fields in content type based on selected taxonomy terms
I am wondering if it is possible to display certain fields to users when they fill in a content type, based upon which taxonomy term they have selected prior in that same content type.

So for example, I have one generic NEWS content type, but it included several sub news categories. Say, I have made a NEWS vocabulary with 3 taxonomies, named: press, book, lecture. All three demand different information, thus different fields. Now I don't want to expose all these fields, but only those fields that are related to the taxonomy term one selected when filling in the content type.

Any pointers if this can be done?

# Answer
> 1 votes
You could make use of Conditional Fields module

> Conditional Fields allows you to manage sets of dependencies between fields. When a field is “dependent”, it will only be available for editing and displayed if the state of the “dependee” field matches the right condition.

---
Tags: taxonomy-terms, nodes, entities
---


# Question
Title: "fwrite(): supplied argument is not a valid stream resource"
drush throws an error

> "**Notice**: Use of undefined constant STDERR - assumed 'STDERR' in **/kunden/192766\_10587/bin/drush/includes/drush.inc** on line **1668**
> **Warning**: fwrite(): supplied argument is not a valid stream resource in **/kunden/192766\_10587/bin/drush/includes/output.inc** on line **34**

What I did is the following. (I followed the instruction from the README.)

1. Cloned drush

```
git clone --branch 7.x-5.x http://git.drupal.org/project/drush.git

```
2. Wrote into the ~/.bashrc

```
export PATH="$PATH:~/bin/drush:/usr/local/bin"
alias drush=~/bin/drush/drush.php

```
3. Refreshed the bashrc

```
source ~/.bashrc

```
4. Set the 'drush' command executable:

```
 chmod u+x /path/to/drush/drush

```

Drush is working but it shows errors every time.

What did I do wrong?

# Answer
You should not run drush.php directly. It is preferable to define DRUSH\_PHP, like this: `export DRUSH_PHP='/usr/local/bin/php'` Then you may continue to use the drush script as usual. This is documented in the README.
> 1 votes

---
Tags: drush
---


# Question
Title: A user field's text format defaults to "- Select -", how do I force it to an allowed option?
I have added a field, "Bio" to the user profile. All user roles have permissions for "Filtered Text", and the field text format settings are limited to "Filtered Text" only, with override default order on. I've set it to default to "Filtered Text" in the Default Value field as well.

When I edit my profile as an authenticated user (who only has permissions for "Filtered Text"), the selector refuses to default to "Filtered Text", as demonstrated in the screenshot:

How can I force this to default to Filtered Text, or moreover why is it not defaulting?

I have tried altering the field's text format in `hook_form_alter`, with the line:

`$form['field_bio']['und'][0]['format'] = 'filtered_html';`

but it still defaults to "- Select -"!

Is there another way to force, on the form, a default value in a hook?

# Answer
The text format is added in an after build function somewhere. This is off the top of my head so might need some tweaking, but the idea will be very similar:

```
function MYMODULE_form_some_form_alter($form, &$form_state) {
  $form['field_bio']['#after_build'][] = '_MYMODULE_some_form_alter_textformat_options';
}

function _MYMODULE_some_form_alter_textformat_options(&$element) {
  $element[LANGUAGE_NONE][0]['format']['#default_value'] = 'filtered_html';
}

```
> 1 votes

---
Tags: 7, forms, input-formats
---


# Question
Title: Update existing content using migrate module
I'm using migrate module in Drupal 7 to update existing content of a Drupal site. My source and destination tables are the same. I got some documentation from http://drupal.org/node/1117454. Here's my code:

```
<?php
class MTestMigration extends Migration {

  public function __construct() {
    parent::__construct();
    $this->systemOfRecord = Migration::DESTINATION;
    $this->team = array(
      new MigrateTeamMember('foo', 'foo@bar.com', t('Site builder')),
    );

    $this->description = t('Migrate basic slides');

    $source_fields = array(
      'nid' => t('The node ID of the slide'),
      'title' => t('The node title of the slide'),
      'uri' => t('the slide image'),
    );

    $q = db_select('node', 'n');
    $q->leftjoin('field_data_field_image', 'i', 'i.entity_id=n.nid');
    $q->leftjoin('file_managed', 'f', 'i.field_image_fid=f.fid');
    $q->fields('n', array('nid', 'vid', 'type', 'language', 'title', 'uid', 'status', 'created', 'changed', 'comment', 'promote', 'sticky', 'tnid', 'translate'))
      ->fields('f', array('uri'))
      ->condition('n.type', 'slide', '=');
    $this->source = new MigrateSourceSQL($q, $source_fields);

    $node_options = MigrateDestinationNode::options(LANGUAGE_NONE, 'filtered_html');
    $this->destination = new MigrateDestinationNode('slide', $node_options);

    $this->map = new MigrateSQLMap($this->machineName,
        array(
          'nid' => array(
            'type' => 'int',
            'unsigned' => TRUE,
            'not null' => TRUE,
            'description' => 'Unique Node ID',
            'alias' => 'n',
          )
        ),
        MigrateDestinationNode::getKeySchema()
    );

    $this->addFieldMapping('is_new')
      ->defaultValue(TRUE);

    $this->addFieldMapping('nid', 'nid');
    $this->addFieldMapping('title', 'title');
    $this->addFieldMapping('is_new')->defaultValue(TRUE);
    $this->addFieldMapping('uid', 'uid');
    $this->addFieldMapping('revision')->defaultValue(TRUE);
    $this->addFieldMapping('revision_uid', 'uid');
    $this->addFieldMapping('created', 'created');
    $this->addFieldMapping('changed', 'changed');
    $this->addFieldMapping('status', 'status');
    $this->addFieldMapping('promote', 'promote');
    $this->addFieldMapping('sticky', 'sticky');
    $this->addFieldMapping('comment', 'comment');
    $this->addFieldMapping('language')->defaultValue('und');

    $this->addFieldMapping('path')->issueGroup(t('DNM'));
    $this->addFieldMapping('pathauto_perform_alias')->defaultValue('1');

    $this->addFieldMapping(NULL, 'name');
    $this->addFieldMapping(NULL, 'vid');
    $this->addFieldMapping(NULL, 'type');
    $this->addFieldMapping(NULL, 'language');
    $this->addFieldMapping(NULL, 'tnid');
    $this->addFieldMapping(NULL, 'translate');

    $this->addFieldMapping('field_image', 'uri')
      ->arguments(FILE_EXISTS_RENAME);
  }
}

```

I end up with this error:

> Column not found: 1054 Unknown column 'map.destid1' in 'field list': SELECT n.nid AS nid, n.vid AS vid, n.type AS type, n.language AS language, n.title AS title, n.uid AS uid, n.status AS status, n.created AS created, n.changed AS changed, n.comment AS comment, n.promote AS promote, n.sticky AS sticky, n.tnid AS tnid, n.translate AS translate, f.uri AS uri, map.destid1 AS migrate\_map\_destid1, map.needs\_update AS needs\_update FROM {node} n LEFT OUTER JOIN {field\_data\_field\_image} i ON i.entity\_id=n.nid LEFT OUTER JOIN {file\_managed} f ON i.field\_image\_fid=f.fid LEFT OUTER JOIN {migrate\_map\_mtest} map ON n.nid = map.sourceid1 WHERE (n.type = :db\_condition\_placeholder\_0) AND (map.sourceid1 IS NULL OR map.needs\_update = 1) ; Array ( \[:db\_condition\_placeholder\_0\] =\> slide ) in MigrateSourceSQL-\>rewind()

# Answer
This post about Unknown column 'destid1' in 'field list' helped me when I had the same problem.

In particular, drop the `migrate_map_*` and `migrate_message_*` tables since they may have been created incorrectly beforehand.
> 3 votes

---
Tags: migrations
---


title: Get site_name without html

text:
# Question
Title: Get site_name without html
I've got a custom module that is sending some emails and I want to put the `site name` in the subject line, but whenever I look up the `site_name` in code, it is wrapped in html.

This is the code I use to generate the subject line:

```
$variables = array(
    '%site_name' => variable_get('site_name'),
    '%tags' => $params['tags'],
);

$subject = t('%site_name: Verify your Subscription', $variables);
error_log("subject=$subject");

```

In the email I received and in the error log, this is what $subject is:

```
<em class="placeholder">liberalgeek.com</em>: Verify your Subscription

```

Why is the `site_name` wrapped in html?

How can I either strip the html or lookup the `site_name` in a different way so that it doesn't have the html to start?

# Answer
The problem is that you are using bad modifier for the `t()` function.

```
$variables = array(
    '@site_name' => variable_get('site_name'),
    '@tags' => $params['tags'],
);

$subject = t('@site_name: Verify your Subscription', $variables);
error_log("subject=$subject");

```

Note the @site\_name change. If you use

* `@site_name` -- it will be run through check\_plain and returns without any theming.
* `%site_name` -- check\_plain with theme\_placeholder.
* `!site_name` -- Allows all HTML.

Also note that this is not limited to site name. Whenever you use `t()` function, you should use above placeholder pattern to ensure CSRF-safe variable display. Do not use `t()` function for use-entered variables. For an example, `t($form_state['values']['name']);` is bad!. Real use of `t()` function is when you use it with your own text and optionally user-entered data.

Good luck!
> 6 votes

# Answer
It is in the variable table. You can read it directly from the database. In Drupal 7 this value is of type blob (in Drupal 6 it was longtext). It is serialized so you cannot simply read it with a select query.

I have some PHP code here that shows how to write to it and read from it. http://www.siteconsortium.com/h/p1.php?id=drpl001

Also, if you are using Drupal 7 the link above it shows how read it in the UI (Configuration -\> System -\> Site Information). Modifying it here works.

Don't forgot to dump the cache though if cache is enabled if you change it in the database.
> 0 votes

---
Tags: 7
---


# Question
Title: Why would single-use (harcoded) tokens not validate in the Message module, when the dynamic version does?
In the Message module, why does the following dynamic token validate nicely `[message:field-message-content:body]` but the single-use (harcdoded) token does not `@{message:field-message-content:body}`

Basically changing `[token]` to `@{token}` doesn't work.

Note: I know I have to create a new message and just can't change the template on the fly to back-propagate existing messages.

For reference from the module's readme.txt:

> # Tokens
>
> * "Dynamic" tokens When defining a message type, it is possible to use Drupal tokens in any of the message fields, in order to inject certain content into the field on the fly. E.g. Entering the string "\[current-date:short\]" to the message text will display the current request time instead of the token. E.g. \[message:user:mail\] will be replaced with the message author's username (When displaying the message). If the message has fields (e.g field\_node\_ref), its contents will accessible by the token system as well under \[message:field\_node\_ref\]. (For instance: \[message:field\_node\_ref:title\]). This relies on "Entity token" module that ships with Entity API. Enabling "Token" module is also recommened, as it provides more tokens and shows a token browser in the message type creation page.
> * "Single use" tokens The single-use tokens are similiar to the dynamic tokens, excepet they're being replaced by their content as the message is created; Meaning this content will not get updated if it's reference gets changed. E.g. "@{message:user:name}" - Will be replaced by the message author's name (When creating the message).
> You can use this for example when you know the user's name is not going to change, so there is no reason for re-checking all the time the user name -- hardcoding it makes more sense.

**Note**: There is nothing in the error logs. Essentially when I use the dynamic token, it works and if I change it to a hardcoded token, then it doesn't. Basically changing `[token]` to `@{token}` it no longer works. I know I have to create a new message and just can't change the template too.

# Answer
Provided you're using Rules to send the message, i'll suggest you to manually save the message entity after having set all required fields but right before sending the message.

Single Use token are evaluated at save time.
> 0 votes

# Answer
"Single use" tokens may saved to database one time and not be changed when update relate entity,while "Dynamic" tokens was replace when theme the message.
> -3 votes

---
Tags: 7, message-subscribe
---


# Question
Title: Select Panel Node Layout on Node edit form
I have multiple different layout variations all for the same node type, is it possible to select which one will be used from the node edit form?

For example I have a node type of product which has the following layout variations:

* 2 Column
* 3 Column
* 2 Column Hybrid

On the node edit for I would have then have a drop down (or something else) which allows me to select one of the variations listed above. Is this possible?

# Answer
> 1 votes
It sounds like you are using Panels (presumption based on the column names), so this is very easy to achieve.

In Page Manager, enable and edit node\_view. Create a new panel variant. Enable Selection Rules for the variant. Add the selection rules `"node_type = product"` and `"field_layout = 2 column"`.

Then carry on through the rest of the config, ie choose 2 column layout and put in your fields/blocks/etc. You will then have to create 2 more variants (or clone and edit the current variant), changing the selections rules and layout to suit.

# Answer
> 1 votes
You can use Panelizer for this purpose http://www.drupal.org/project/panelizer. Check this article for details http://drupalwatchdog.com/2/1/panelizer-layouts

# Answer
> 1 votes
I have done this using a combination of taxonomy and selection rules in Panels:

* Create multiple layouts (variants)
* Create matching terms in a "Layout" vocabulary.
* Use the term as a selection rule for each layout.
* Assign the vocabulary to each content type that should allow that layout choice. You can make it a dropdown or radio buttons (not checkboxes, obviously!).

Authors can then choose which layout to use when creating/editing a node.

---
Tags: 7, panels
---


# Question
Title: Send email on changing line item field value
I have a custom list field on the product line item type, which is for the ability to set seperate shipping statuses for each product in one order.

When the store admin updates this list field on a line item, the site will need to send out an email to the customer.

Is there a nice way to make this happen?

# Answer
> 0 votes
There are three approaches I can think of.

1. Use a hook to alter the update function to send an email out based on your conditions.
2. Add JS to handle the change via a custom AJAX call.
3. Create a cron job that monitors changes in the database and emails out messages when changes are picked up.

The first two options are your best and from those, depending on skill level, I would choose one.

---
Tags: commerce
---


title: Add link to my module output

text:
# Question
Title: Add link to my module output
I have many field for my custom module.

And output:

```
    if($slides->rowCount() > 0 ){
        $output .= '<ul id="head_slider" class="clearfix">';
        foreach($slides as $sld):
            $nd = node_load($sld->nid);
            if(count($nd->field_simage) >  0){
                $img_url = image_style_url('img_960x378',$nd->field_simage['und'][0]['uri']);
            }
            $output .= '<li><img src="'.$img_url.'" alt="'.$sld->title.'" /></li>';
        endforeach;
        $output .= '</ul>';
    }

    return $output;
}

```

Content type has url field. It's name `field_surl` When users insert a link to this field, must wrap this link to my output.

I tried this but not working:

```
$output .= '<li><a href="'.$field_surl.'"><img src="'.$img_url.'" alt="'.$sld->title.'" /></a></li>';

```

Result of this output:

```
<a href='field_surl'>...</a>

```

How can I fix it?

# Answer
With the few things I know about your field field\_surl and about the way you tried to solve it, I might purpose this simple answer, sorry if it sounds obvious :

You wrote :

```
$output .= '<li><a href="'.$field_surl.'"><img src="'.$img_url.'" alt="'.$sld->title.'" /></a></li>';

```

Where did you initialize your $field\_surl variable ? At least, assuming $field\_surl is loaded within the same node, try :

```
$output .= '<li><a href="'.$nd->field_surl.'"><img src="'.$img_url.'" alt="'.$sld->title.'" /></a></li>';

```

Or even better, as suggested in @Brandon comment, use url() function :

```
$options = array('absolute'=>TRUE); //i.e, or set whatever options you need for your url
$my_url = url($nd->field_surl, $options);
$output .= '<li><a href="'.$my_url.'"><img src="'.$img_url.'" alt="'.$sld->title.'" /></a></li>';

```
> 0 votes

---
Tags: 7
---


# Question
Title: How to render a node with different DS View modes depending on taxonomy term?
I have a Content type containing a term reference field and some other fields. I have created 3 Display suite view modes for this content type. I want each node of this content type to be displayed in one of the defined DS view modes depending on the value of the term reference field of that node.

# Answer
> 1 votes
You can switch view modes using hook\_entity\_view\_mode\_alter. In pseudo code, something like:

```
function your_module_entity_view_mode_alter(&$view_mode, $context) {

    //check that this is a node of typex, and check current view mode
    if ($context['entity_type'] == 'node' && $context['entity']->type == 'typex' && $view_mode == 'full') {

      //check current taxonomy terms
      [code]

      //code to set view mode
      if (condition based on taxonomy terms) {
        $view_mode = 'new_view_mode';
      }
    }
}

```

---
Tags: display-suite, entities
---


title: Field Collection Views and Blocks

text:
# Question
Title: Field Collection Views and Blocks
I've assembled a content type with a Field Collection (image, text and link). I installed the Field Collection Views module and duplicated the view it came with. I added a block display to the view and in the Content Display set the name to the view machinename and the id to the block machine name.

It works fine on my node page but the block won't show up when I place it on the page. How do I go about getting it to render?

# Answer
Turns out I was going about this the wrong way. I didn't need the "Field Collection Views" module. In views I chose relationships and added "content: the\_name\_of\_my\_collection\_field" then I could just add the fields to the view like normal.
> 1 votes

# Answer
I believe it only works when you have a Node on the page that has field\_collection(s).

> (1)After install this module,then you could goto host entity's fields display settings page,such as admin/structure/profiles/manage/resume/display.

It's just enabling Edit / Delete buttons for Views of nodes with collections. It's not **only** showing collections of things in a block (its needs the parent node).
> 0 votes

---
Tags: views, blocks, entities
---


title: Extra fields in Search page

text:
# Question
Title: Extra fields in Search page
Is a module available that can add a particular field on the search page? I'd like for user's to see an image-field if applicable.

# Answer
> 0 votes
You can use Display Suite module to create custom view mode for search results.

---
Tags: media, search
---


title: Views Formatter Problem

text:
# Question
Title: Views Formatter Problem
How do I control what gets displayed for Views Formatting? I mean, Something is wrong here. I have a View set up to show Fields of a Content Type, when I click on the `Content: Body` Field it shows Formatting Options, Default, Plain Text, Trimmed, Summary or Trimmed. I just want to output the Body field of a content type AS HTML. What the hell is wrong this. I select "Default" View, but I get absolute NOTHING returned. When I select Plain Text, I just get the text returned, no HTML.

What do I need to do so that the default option in Views actually outputs something? Preferrably outputs it in the default format, which is HTML.

# Answer
> 1 votes
I have the Display Suite Module installed in Drupal 7.25. I went to `Admin -> Configuration -> Content Authoring -> Text Formats` and Disabled the Display Suite Text format, Cleared the Cache, and now all of my Body: Content is showing as HTML in my Views as it should!

Hope this helps someone! There is a problem with the Display Suite Code Text Format that is causing the Default formatter and any other displays (even Content) to NOT Show anything!

---
Tags: views, entities
---


# Question
Title: Create AJAX multi step form which changes based on user input
I am trying to create a form where initially, the user is presented with just one field, which is their email address. When they click submit, I would like it to be an AJAX submit where I then lookup their email in a custom table in the database and then present them with additional form fields that will either be blank if we do not have their email address in the sytem, or will be pre-populated and ready for them to edit, if we already have them in the system. I was thinking a multi step AJAX form might do the trick, but I don't know if it even needs to be "multi step". Can I accomplish this with just a standard AJAX submit? I just can't figure out how to show/populate those additional fields after they submit the form. This is what I have so far, I just can't figure out how to only show the additional fields AFTER the submit and verification process:

```
/**
 * Implements hook_form().
 */
function _vista_form($form, &$form_state) {

  $form = array();

  $form['email'] = array(
    '#type' => 'textfield',
    '#title' => 'Email',
    '#required' => TRUE,
  );

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

  // all of the fields below this are the ones that I would like to show ONLY after I look them up and then I can prefill them in or not
  $form['id'] = array(
    '#type' => 'hidden',
    '#value' => 0,
  );

  $specialties = db_query("SELECT specialty_code, specialty_name FROM {specialties_vista}")->fetchAll();
  $default_specialties = explode('^', '');

  $specialty_options = array();
  foreach ($specialties as $specialty) {
    $specialty_options[$specialty->specialty_code] = $specialty->specialty_name;
  }

  $form['specialty'] = array(
    '#type' => 'select',
    '#multiple' => TRUE,
    '#size' => 10,
    '#title' => 'Specialty',
    '#description' => 'Hold Control or Shift while clicking to select multiple specialties',
    '#options' => $specialty_options,
    '#empty_option' => '-All-',
    '#empty_value' => 'all',
    '#default_value' => $default_specialties,
  );

  $type_options = array(
    'VISTA-HealthCare-Partners-Government' => 'Vista Healthcare Partners',
    'International' => 'International Locum Tenens',
    'Permanent' => 'Permanent Physician',
    'US-Locum-Tenens' => 'US Locum Tenens',
  );

  $form['job_type'] = array(
    '#type' => 'checkboxes',
    '#multiple' => TRUE,
    '#title' => 'Type of Job',
    '#options' => $type_options,
    '#empty_option' => 'Choose a placement type',
    '#empty_value' => 'all',
    //'#default_value' => $type_selected,
  );

  $form['active'] = array(
    '#type' => 'checkbox',
    '#title' => 'Subscribe/Unsubscribe',
    '#default_value' => 1,
  );

  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Submit'),
    '#attributes' => array('class' => array('submit')),
    '#ajax' => array(
      'callback' => '_display_form',
      'wrapper' => 'ajax_wrapper',
      'effect' => 'fade',
    ),
  );

  return $form;
}

function _display_form($form, $form_state) {
  //do database lookup here and set some variables? Not sure.
  return $form['wrapper'];
}

```

# Answer
> 0 votes
You need to keep track of the step you're in. The first time a user hit's the form you would initialize a variable, say `$step`and give it the value `1`. On submit you augment that value to be in step `2` on the form rebuild. In the form builder itself (`_vista_form()`) you add form items depending on the current step. The same goes for validation and submit handlers. Usually you would use switch statements.

Have a look at this very complete tutorial: http://www.jaypan.com/tutorial/drupal-7-ajax-driven-multi-step-forms-non-javascript-fallback

---
Tags: ajax, forms
---


# Question
Title: How can I grant permissions to anonymous users per session to download a file?
Anon users can fill out and submit a form (webform). As soon as submitted, the user will be offered to download a pdf file with his entered form data. How can I manage this? With sessions?

# Answer
> 1 votes
Take a look at Webform protected downloads. It's a module I wrote a while ago to tackle this kind of situation.

Edit: Ah, sorry, just read your question again. The part with the modified pdf content depending on user input is not addressed by my module. Though, as the system uses the private file system you could maybe hook into there. This is not trivial though.

I see another easier option. You create a custom menu callback and use webform hooks or the redirect configuration of the webform to send the user to this url that contains the submission id of the webform (say, `special-pdf-access/SUBMISSION_ID)`. With this information you can load the submission, thus accessing all the data entered by the user, then create a pdf file with this info and display a link to that file.

You have to pay attention to security though, so as not to allow arbitrary users to load pdf files they shouldn't have access to. For this you can use the global $\_SESSION variable, to store the submission id after webform has processed the submission, and then check in the custom menu callback if the submission id in the session equals the requested submission as given in the url.

# Answer
> 0 votes
If you want to continue using the webform module, you will have a difficult time because you will need to write an interface module to the webform module. I have done this and it is not straight forward by any stretch of the imagination.

If you were to instead create your own very simple module with the form you could accomplish this easily on submit. You would just take the form data, store it where you like in a database table and then generate the PDF offering the user a link to download the PDF once generated. You could then delete the temporary PDF from your system so prying people could not access it. Name the file something simple and append a unique id associated generated from the session id so that it cannot be easily guessed.

---
Tags: webforms, sessions
---


# Question
Title: How would I hide a form and display thank you content in the same area - drupal 6
I've been trying to get to grips with the form api, I'm currently trying to hide a form after it has been submitted and to display a thank you template in the same area as the form was in.

Hoping someone might have an answer.

Thanks

# Answer
> 0 votes
Or use $form\_state\['rebuild'\] in the submit handler and check for submitted values in the form builder. That way you can display the form the first time the user hit's the page, and after submission you display your message. This is something like a multistep form, so you could take any of the numerous tutorials for multistep forms in drupal. Also have look at the official example in form\_example\_tutorial.inc

---
Tags: 6, forms
---


title: Set Views exposed filter to ignore case

text:
# Question
Title: Set Views exposed filter to ignore case
I have a view which uses an exposed filter to let the user filter the results via keyword (in other words it behaves like a text search). The actual field is implemented using views\_fields\_combine module, but I assume this issues applies to any field which contains text. The problem I have is that the filter only works correctly if the case of the "search" text matches the content in the field.

For example if the field contains "Cool Capacitors" and the user types "Cool" in the exposed filter then there will be a resulting match. But it the user types "cool" then the filter will not find any matching results.

I would like to know if there is a method of making the exposed filter ignore the case when making matches. Strangely enough I have not been able to find any information on this on the internet. I am wondering if I am try to do something that exposed filters was not designed to do? Perhaps there is some alternative method I could consider?

# Answer
This should help you directly or get you started in the right direction - Combine fields filter case-sensitive search
> 1 votes

---
Tags: views
---


# Question
Title: Uncaught exception thrown after moving my website to localhost
My website works right on server, I took a backup from database and public\_html in order to have a copy of my webstie in localhost.

I imported the database but it reported an error, some thing was wrong with content of `cache_views` table, so I emptied this table and database successfully imported. I replaced public\_html with the old one and configured `settings.php`. but it doesn't work, it reports this error :

**Additional uncaught exception thrown while handling exception.**

Original

```
PDOException: SQLSTATE[HY000]: General error: 2006 MySQL server has gone away: SELECT s.lid, t.translation, s.version FROM {locales_source} s LEFT JOIN {locales_target} t ON s.lid = t.lid AND t.language = :language WHERE s.source = :source AND s.context = :context AND s.textgroup = 'default'; Array ( [:language] => fa [:source] => Makes the view results available as a context for use in Panels and other applications. [:context] => ) in locale() (line 684 of C:\xampp\htdocs\test\modules\locale\locale.module).

```

Additional:

```
PDOException: SQLSTATE[HY000]: General error: 2006 MySQL server has gone away: INSERT INTO {watchdog} (uid, type, message, variables, severity, link, location, referer, hostname, timestamp) VALUES (:db_insert_placeholder_0, :db_insert_placeholder_1, :db_insert_placeholder_2, :db_insert_placeholder_3, :db_insert_placeholder_4, :db_insert_placeholder_5, :db_insert_placeholder_6, :db_insert_placeholder_7, :db_insert_placeholder_8, :db_insert_placeholder_9); Array ( [:db_insert_placeholder_0] => 0 [:db_insert_placeholder_1] => php [:db_insert_placeholder_2] => %type: !message in %function (line %line of %file). [:db_insert_placeholder_3] => a:6:{s:5:"%type";s:12:"PDOException";s:8:"!message";s:455:"SQLSTATE[HY000]: General error: 2006 MySQL server has gone away: SELECT s.lid, t.translation, s.version FROM {locales_source} s LEFT JOIN {locales_target} t ON s.lid = t.lid AND t.language = :language WHERE s.source = :source AND s.context = :context AND s.textgroup = &#039;default&#039;; Array ( [:language] =&gt; fa [:source] =&gt; Makes the view results available as a context for use in Panels and other applications. [:context] =&gt; ) ";s:9:"%function";s:8:"locale()";s:5:"%file";s:52:"C:\xampp\htdocs\test\modules\locale\locale.module";s:5:"%line";i:684;s:14:"severity_level";i:3;} [:db_insert_placeholder_4] => 3 [:db_insert_placeholder_5] => [:db_insert_placeholder_6] => h t t p://localhost:81/test/ [:db_insert_placeholder_7] => [:db_insert_placeholder_8] => 127.0.0.1 [:db_insert_placeholder_9] => 1389935326 ) in dblog_watchdog() (line 154 of C:\xampp\htdocs\test\modules\dblog\dblog.module).

```

# Answer
I solved the problem this way: set max\_allowed\_packet = 4M to the file php.ini
> 5 votes

---
Tags: 7, database, importing-exporting
---


# Question
Title: Views simply won't output HTML at all for me in any content types, what to do?
I have Installed Drupal 7.26 (Default Installation), and on a Fresh Installation, I have Views Module (CTools All Sub Modules Installed) and PathAuto Module installed ONLY. OK, So I create a Content Type and delete the Body Field that is created by default, and create another Field called Section and have it set to LONG TEXT, than make it filterable in the settings so that the user can select the text format, and have it set to an UNLIMITED amount of areas, with required UNCHECKED.

I than create 1 node using this content type with FULL HTML selected as the text format for each section and save it.

I now go to the Views Module and attempt to use an Unordered List, of Fields and select `Content: Section` as the field, The formatter is set to `Default`, I set a filter on it for `Content Type` and select `Is One of` That content types name. I see nothing in the preview at the bottom and so I go ahead and save it anyways as it should show something. I have the page path set to `node` so that it shows up on the front page. However, there is nothing being returned for the output of this view on the Front Page.

No matter what theme I choose, I can not get HTML to output in this view whatsoever.

Is there some sort of settings I have not performed somewhere? I go to Reports -\> Status and everything checks out fine. All Green sections there. I go to run Cron, again, no problems whatsoever so it seems. How to debug this? Or is this an actual confirmed bug in Views? Or Drupal? Or something else?

If I change the type from Fields to Content, it still shows no body content, but now only shows the Title of the Content and links to the Page where it is located at, but on that page, it shows nothing but the title. How can this be fixed? OMG, this is a nightmare. I've been trying to hunt down the problem for days with no luck at all!

# Answer
> 0 votes
* "node" is registered menu path by node module
* You should not set a page path "node" which already exists.
* Create a block view using views instead of page view
* Enable the block on home page

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


# Question
Title: How to create dynamic query for inner join on same table?
I want a dynamic query to do inner join on same table.

My query is:

```
SELECT t1.table1 FROM table1 t1 INNER JOIN table2 t2 ON t1.id = t2.id AND t1.name = t2.name"

```

I want to join table1 and table2 based on id and name present in table2.

What is the equivalent dynamic query in Drupal for this? How this can be achieved?

# Answer
> 1 votes
```
$query = db_select('table1','t1');
$query->join('table2','t2','t1.id1=t2.id2');
$query->fields('t1', array('some fields'))
      ->fields('t2', array('some fields'));
$result = $query->execute()->fetchAll();

```

Then you can do print\_r stuff into $result like

```
echo "<pre>";print_r($result);echo "</pre>";

```

If you have devel module installed and enabled, then you can also use:-

```
dsm($result);

```

This will give the whole result in form of array. If you need in form of object, then you need to modify few lines of code like this:-

```
$data = $result->execute();
while($result = $data->fetchObject()){
  //Do your related stuff
}

```

I think it will help a lot. Thanks.

---
Tags: database
---


# Question
Title: programmatically getting custom node belonging to a term
have searched google but cannot find anything specific . Intention is to get all Custom Node types that have been assigned a specific term of vocabulary . for example the follwoing is a db query to get custom node type.

`$query->condition('type', "news_article")->fields('n',array('nid'))->orderBy('created', 'DESC')->range(0,90);`

can the same query be modified to also add the filter for term id .

One other related question is that how can (in PHP) we get the term id from the url of the pattern e.g `<drupal site>/taxonomy/term/2` .

any help appreciated

# Answer
> 0 votes
Thank you for the comments. Instead of using entity field query , have used the solution mentioned in the following question:

https://drupal.stackexchange.com/questions/52334/know-the-term-id-get-all-the-node-id-belong-to-it?rq=1

# Answer
> 1 votes
This might be helpful

How to use EntityFieldQuery

It works great for me. As far as the other question is concern, there are many ways of doing this. the simplest would be below, provided that you are accessing link in your question:

```
<?php
    $arg0 = arg(0);
    $arg1 = arg(1);
    $arg2 = arg(2);

    echo $arg0; //this will echo 'taxonomy'
    echo $arg1; //this will echo 'term'
    echo $arg2; //this will echo 2 (term ID)
?>

```

Info about `arg()` can be found here: arg()

# Answer
> 1 votes
You can use arg() function for getting tid, if you are panels then you can find it in $context. Anyways I am assuming you are not using panels. So, the code goes this way:-

```
$arg = arg();
$query = db_select('node','n');
$query->join('taxonomy_index','ti','n.nid=ti.nid');
$query->fields('n', array('nid', 'title'))
  ->condition('n.type', 'your_content_type_machine_name')
  ->condition('ti.tid', $arg['2']);
$result = $query->execute()->fetchAll();
//do dsm($result); if you have devel module enabled.
or you can use our traditional way. echo "<pre>";print_r($result);echo "</pre>";

```

I think this query help you in getting associated nids of particular tid.

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


# Question
Title: Taxonomy terms follow/unfollow module (even for anonymous users)
I want a subscriptions/notifications like module which works for anonymous users too.

Users should be able to subscribe to a taxonomy term, and then be alerted if content is created for that term.

Subscriptions work great but the lack of support for an anonymous user is quite disappointing. I don't get why we can't send a verification mail for any anonyomous user based subscription.

Any Drupal Module which does that?

# Answer
> 2 votes
You can use my sandbox module Total Subscription

This module is in the Drupal project applications' issue queue.

It will provide the functionality as per your requirement.

---
Tags: 7, taxonomy-terms, notifications, emails
---


# Question
Title: How can I allow users to receive e-mails whenever I update my blog in Drupal 7?
I have a blog in English and Japanese in Drupal 7. I created this blog using a custom content type and Views, not the built-in blog module.

I have an RSS feed (made in Views) for each language. I would like to allow users to subscribe to receive all English-language updates to content type "blog" or all Japanese-language updates to content type "blog." (I anticipate most users will only want one language or the other. If a user really wants both languages, I don't mind making them subscribe twice.)

I looked into using Feedburner on the RSS feeds, but the Feedburner module has not been updated for D7 and I would rather not rely on an external service. (When I tried setting up Feedburner without the module, it told me my RSS feed didn't exist even though the support link allowed me to validate it.)

I also looked at the Simplenews module, but that module apparently requires creating each newsletter post separately. What I want to do is automatically e-mail subscribed users when I post an update to the blog.

I'm sure there are a lot of ways to do this, but there are so many "mail helper"-type modules that I'm at a loss as to where to get started.

To summarize my requirements, I want to:

* Automatically e-mail subscribers when a new blog post in the appropriate language is added.
* Both authenticated and anonymous users should be able to subscribe.
* Subscriptions must require confirmation (legal requirement).
* Compatibility with the MIME Mail module would be a nice bonus.

# Answer
> 1 votes
Another alternative option is using Google Feedburner to send the email on your behalf.

See the documentation online for more information.

Once Google feedburner has 'burned' your feeds, you can get an embed code for the sign-up form so users can receive email alerts. The reason why this suits your needs so well, is that it all revolves around having a quality RSS feed source, and Views is capable of producing this. The only real question is whether you want to have full content or a teaser only in the RSS (and therefore email).

Another advantage this has over the above newsletter/trigger options is that it only sends a daily digest, so at max 1 email is sent per day for each RSS feed burned. This will prevent you from spamming your loyal subscribers when you have active days.

Google feedburner features include (straight from the above documentation):

**Subscription management**

* View and sort the list
* Activate, deactivate, and delete individual email addresses
* Export your list in Excel or CSV format
* Receive an optional email when people unsubscribe

**Communication preferences**

* Customize the subject line and body text of the email that is sent to subscribers after they opt in to receive your feed by email. This can come in handy if you want to localize the email.
* IMPORTANT NOTE: Emails are text only and the original ${confirmlink} reference must be included in your confirmation email in order to activate the subscription.

**Email Branding**

* Customize the subject line and title of the email that is sent to your subscribers
* Add a custom logo that appears at the top of HTML email messages
* Change body and headline text fonts, sizes, and color as well as the color of the links

**Delivery Options**

* Choose your time zone
* Select a two-hour delivery window within which your daily digest will be sent

Example tutorial on how to set this up can be found here.

# Answer
> 5 votes
This can be acquired easily. I can give you some steps to follow.

There are actually at least 2 ways to achieve that

A. Using Triggers (core module)

1. First activate the core module Triggers. This will provide you basic triggers (in your case UPDATE trigger) and actions to run when condition is met.
2. Go to Admin \> Configuration \> Actions then CREATE AN ADVANCED ACTION, then select: Send e-mail. In the recipient field you need to select a proper token provided by simplenews module to match all the registered users. (make sure you also have Token module installed)
3. Go to Admin \> Structure \> Triggers, then Node tab. Choose the third: TRIGGER: AFTER SAVING UPDATED CONTENT.

If you need more control then implement the hook

function YOURMODULE\_trigger\_info\_alter(&$triggers) { //Here dpm($triggers) to see where is your update trigger and do the changes. } ?\>

B. Using Rules (contrib module) Basic the same thing. If you get stuck follow these steps on a similar issue on this blog: http://adellefrank.com/blog/how-to-email-notifications-comments-drupal7

# Answer
> 5 votes
Simplenews module does everything what you need. It can be configured that each your blog post automatically became an newsletter and are sent to subscribers. Just in Simplenews configuration select content type Blog to be a newsletter source.

To make this:

1. Open configuration form of Blog content type (/admin/structure/types/manage/blog)
2. In "Publishing options" tab check "Use as simplenews newsletter"

# Answer
> 1 votes
If you want to do it programmatically, see drupal\_mail($module, $key, $to, $language, $params = array(), $from = NULL, $send = TRUE),

When node is updated the hook hook\_node\_update($node) will be fired. If you want to create own composed mail format use hook\_mail($key, &$message, $params). So you have to write 2 hooks first hook\_node\_update and hook\_mail. Inside hook\_node\_update you have to write drupal\_mail function that will call your hook\_mail.

# Answer
> 0 votes
You can use my sandbox module Total Subscription

This module is in drupal project queue. Here is the link for it:- LINK

I think it will give functionality which you require.

---
Tags: 7, feeds, emails
---


# Question
Title: How does entity_metadata_wrapper work with array?
This is my code to return value of fields in a content type called `library`

```
$wrapper = entity_metadata_wrapper('node',$variables['node']);
$variables['name']= $wrapper->field_library_book_name->value();
$variables['writer']= $wrapper->field_library_book_writer->value();
$variables['detail']= $wrapper->field_library_book_detail->value();
$variables['photo']= $wrapper->field_library_photo->value();

```

it works right for name, writer and detail but for image it only prints **Array()**. this is the `var_dump()` output of this array:

```
array(13) {
  ["fid"] => string(3) "382"
  ["alt"]=> string(0) ""
  ["title"]=> string(0) ""
  ["width"]=> string(3) "145"
  ["height"]=> string(3) "194"
  ["uid"]=> string(2) "23"
  ["filename"]=> string(15) "n_471_1_img.png"
  ["uri"]=> string(43) "public://library_book_photo/n_471_1_img.png"
  ["filemime"]=> string(9) "image/png"
  ["filesize"]=> string(5) "40854"
  ["status"]=> string(1) "1"
  ["timestamp"]=> string(10) "1389166558"
  ["rdf_mapping"]=> array(0) { }
}

```

this is my question: how to output the image itself ?

# Answer
The function theme\_image will output the value as an img-tag. Is that what you are looking for?

```
$photo_field = $wrapper->field_library_photo->value();
$image = theme('image_style',
  array(
    'style_name' => 'large',
    'path' => $photo_field['uri'],
  )
);

```
> 2 votes

---
Tags: nodes, theming, entities
---


title: Extending user reference

text:
# Question
Title: Extending user reference
I have built a content type named "Project" which will showcase some projects by the members of a group. I have used a user reference field in that content type, so that the contributors of a project can be enlisted.

Now I am trying to put in the user's profile page the links to the projects he contributed to. How can I achieve that?

# Answer
> 0 votes
I finally figured out my own ... I created a page view with url 'user/%/project' and added a contextual filter so that when no filter value is present, it gets filter value by getting user ID from url. Then added it to the navigation menu, and I was done.

# Answer
> 0 votes
You will need to use views and panels. You will create a new user home page using panels. Within that panel you will want to create a view that lists all the content types `Project` filtering on the user.

Otherwise, you will need to create your own module.

---
Tags: users
---


# Question
Title: Find the custom module responsible for a URL
On a site I did not originally develop, I'm stuck having to fix display issues on an arbitrary page.

Is there a way to locate the custom built module responsible or the source of a given URL path?

# Answer
You can use "hook\_menu\_alter" to list all routes and you can see the module via the module key.

```
function HOOK_menu_alter(&$items) {
    if(isset($items['yoururlpattern'])){
        drupal_set_message($items['yoururlpattern']['module']);
    }
}

```
> 1 votes

---
Tags: uri
---


# Question
Title: What is the difference between havingCondition and having?
Drupal dynamic queries have 2 conditional clauses called having and havingCondition.

The documentation states "The Having clause behaves identically to the WHERE clause, except that it uses methods havingCondition() and having() instead of condition() and where()."

Other than this I can't find any mention of either clauses anywhere (including in the examples module), or any examples of their use.

What is the difference between the 2 functions?

# Answer
I figured it out though trail and error.

Example of a having clause:

```
$query->having('user_count > 0');

```

Example of a havingCondition clause:

```
$query->havingCondition('user_count', 0, '>');

```

Essentially you can pass the alias, value and operator as separate arguments into havingCondition, but have to pass them all as one string into having.
> 1 votes

---
Tags: database
---


title: entity_metadata_wrapper file load

text:
# Question
Title: entity_metadata_wrapper file load
I'm trying to load and get the file using entity\_metadata\_wrapper. this is my code

```
$wrapper = entity_metadata_wrapper('node',$variables['node']);
$file_field= $wrapper->field_library_file->value();
$variables['file'] = theme('file_link', array('file' => file_load($file_field['fid'])));

```

and `<?php print $file;?>` outputs nothing. I've found this in this address . how can I get set of files that belongs to a node.

thanks.

---

**UPDATE:**

this is the code I use for theme hook suggestion, this code is on top of the the above code.

```
$suggest = "page__node__library";
$variables['theme_hook_suggestions'][] = $suggest;

```

I created a page and renamed it to `page--node--library.tpl.php` and `<?php print $file;?>` is in this page.

# Answer
> 0 votes
Some corrections after, can you put the context of the execution? Like the function where you call this code and where you output $file variable?

```
$wrapper = entity_metadata_wrapper('node',$variables['node']);
// raw() should give you file object in your case
$file_field= $wrapper->field_library_file->raw();
// theme_file_link 'file' parameters have to be a file object
$variables['file'] = theme('file_link', array('file' => $file_field ));

```

Docs :

Note :

@clive comment : no need to value() because he have already used that function below, if we follow the source code given... In that case, value() and raw() methods should return the same file object.

```
theme('file_link', array('file' => $file_field))

```

Edit : Can you dump your $file\_field variable? You can do it via this snippet

```
drupal_set_message('<pre>'.print_r($file_field, true).'</pre>');

```

---
Tags: theming, nodes, files, entities
---


# Question
Title: how to add "create node form" in a block?
I just wanted to know how to add "create node form" in a block

when i copy the source code and make a block out of that code, **only public** could post from that. when i am posting **as a user** it says timeout and tells us to refresh the page. plz someone give me solution.

SO i tried to add the following code in page.tpl.php

```
$form = node_add('nodetype');
print drupal_render($form);

```

# Answer
> 3 votes
there are two modules which can give option to create node from block Formblock module , Advanced Form Block

# Answer
> 1 votes
> function mymodulename\_block\_info() {
>
> ```
> $blocks['mymodulename_node_form'] = array(
>     'info' => t('Post a Node'),
>     'cache' => DRUPAL_NO_CACHE,
> );
> return $blocks;
>
> ```
>
> }

/\** Implements hook\_block\_view() \*/

> function mymodulename\_block\_view($delta = ''){
>
> ```
>  switch ($delta) {
>     case 'mymodulename_node_form':
>         $block['content'] = drupal_get_form('mymodulename_node_form');
>         //$block['content'] = block_contents($delta);
>         break;
> }
> return $block;
>
> ```
>
> }

# Answer
> 0 votes
You should use below code in your template file.

```
if (!function_exists('node_add')) {
  module_load_include('inc', 'node', 'node.pages');
}

```

# Answer
> 0 votes
I just posted this in response to another question. This is what you would place into a custom module. Alternately, you could try Advanced Form Block module as mentioned (I haven't yet), which as of today is still supported.

For people still having trouble with their code when using anything AJAX-related (e.g. 500 errors) or simply trying to open up the 'blocks' tab in Panels without some error (e.g. some Entity Translation functions) you might want to try the following module code instead in Drupal 7 (but some parameters may still need to be added for your purposes).

```
function custom_example_block_info() {

    $blocks['example_node_form'] = array(
       'info' => t('What an example'),
    );
    return $blocks;

}

function custom_example_block_view($delta = ''){

    $block = array();

    switch ($delta) {
        case 'example_node_form':
            global $user;
            //Note: 'type' is your node content type and 'language' must be included
            $node = (object) array('uid' => $user->uid, 'name' => (isset($user->name) ? $user->name : ''), 'type' => 'example', 'language' => LANGUAGE_NONE);

            $form_state['build_info']['args'] = array($node);

            form_load_include($form_state, 'inc', 'node', 'node.pages');
            $block['content'] = drupal_build_form('example_node_form', $form_state);

            break;
    }
return $block;

}

```

The important difference is that drupal\_get\_form cannot load the $form\_state so we use function form\_load\_include(&$form\_state, $type, $module, $name = NULL) to ensure the include file is loaded whenever the form is processed and function drupal\_build\_form($form\_id, &$form\_state) instead of drupal\_get\_form to pass $form\_state. The lines above create the $form\_state.

---
Tags: forms, blocks, nodes
---