# Question
Title: How to deal with SalesforceException: HTTP Method 'PATCH' not allowed
I've the the Salesforce module mapping in place integrated with Commerce module and I've the following SalesforceException when purchasing the order:

```
SalesforceException: HTTP Method 'PATCH' not allowed. Allowed are HEAD,GET,POST

```

What's happening and how to deal with or debug this problem?

# Answer
> 0 votes
The format of the HTTP SFDC API callback for inserting/upserting records is:

```
/services/data/v20.0/sobjects/ObjectName/customExtIdField__c/Id

```

The ObjectName is the Name of an Salesforce table i.e. 'Contact' or 'Account'. And Id is the Id of a specific record you want to update in the table.

The possible cause of the error for that would be that you're calling SFDC API with the invalid data.

Please check if your REST URL is correct, probably your objectId is not passed through. E.g. If you have dependencies between the other objects, check if these were created in the first place, before creating your main object.

Related:

---
Tags: 8, crm
---


# Question
Title: multiple entity type in entity field query
how to add mutilple entity\_type and bundles in EntityFieldQuery?

`$query->entityCondition('entity_type', 'profile2')
 ->entityCondition('bundle', 'user_profile');`

Is there any way to do like this

`$query->entityCondition('entity_type', array('profile2','user'))
 ->entityCondition('bundle', array('user_profile','property'));`

# Answer
This should work:

```
$query->entityCondition('entity_type', array('profile2','user'))
      ->entityCondition('bundle', array('user_profile','property'), 'IN');

```
> 6 votes

---
Tags: entities, database
---


# Question
Title: How to add two fieldConditons in Entity field Query?
Is this the correct way to add field Conditions

```
$query->entityCondition('entity_type', 'profile2')
   ->entityCondition('bundle', 'user_profile')
   ->fieldCondition('field_town_city', 'value', "%".$search_title."%", 'LIKE')
   ->fieldCondition('field_land_state', 'value', "%".$search_title."%", 'LIKE');

```

# Answer
You can chain multiple field conditions, however I'd probably try something like this (haven't tested it):

```
->fieldCondition('field_town_city', 'value', $search_title, 'CONTAINS')

```

The EntityFieldQuery::fieldCondition() invokes the addFieldCondition() method, see the possible $op values on api.drupal.org:

https://api.drupal.org/api/drupal/includes!entity.inc/function/EntityFieldQuery%3A%3AaddFieldCondition/7
> 3 votes

---
Tags: database
---


title: How do I theme a form element?

text:
# Question
Title: How do I theme a form element?
I was able to theme the form. Now I want to put a submission button into a `<div>`, but I can't theme the submission button.

This code worked for the form.

```
print "text text text";
print drupal_render_children($variables["form"]);

```

Here is the code I used to theme the submission button.

```
$form['submit'] = array(
  '#type' => 'submit',
  '#value' => t('Submit'),
  '#attributes' => array('style' => "padding: 0 10px;"),
  '#theme' => "submit",
);

function scores_theme($existing, $type, $theme, $path) {
  $path = drupal_get_path('module', 'scores');
  return array(
    'submit' => array(
      'render element' => 'submit',
      'template' => 'submit',
      'path' => $path,
    ),
  );
}

```

What should I put into submit.tpl.php? Any of these doesn't work.

```
print drupal_render_children($submit);

print drupal_render($variables['submit']);

print drupal_render($submit);

```

# Answer
> 2 votes
You should be able to wrap form elements with #prefix and #suffix:

```
$form['submit'] = array(
  '#type' => 'submit',
  '#value' => t('Submit'),
  '#attributes' => array('style' => "padding: 0 10px;"),
  '#theme' => "submit",
  '#prefix' => "<div class='submit-button-custom'>",
  '#suffix' => "</div>",
);

```

# Answer
> 2 votes
And, if you're using a horizontal form it REALLY gets outta whack if you don't include one more key field in the prefix/suffix...

So, do this... for horiz. type forms (typically ones that are floated left, with a submit at the end.. ):

instead of just this...

```
...
'#prefix' => "<div class='submit-button-custom'>",
'#suffix' => "</div>",
...

```

Do this...

```
...
'#prefix' => "<div class='submit-button-custom'>
              <label for=op> <label>",
'#suffix' => "</div>",
...

```

Where 'op' is the 'name' attribute (in this case) of your supposed submit button.

Hope this helps.

# Answer
> 2 votes
```
function YOUR_THEME_form_FORM_ID_alter(&$form, &$form_state) {
      $form['submit']['#prefix'] = '<div class="scores-submit-btn">';
      $form['submit']['#sufix'] = '</div>';
}

```

# Answer
> 0 votes
As each Drupal form has a submit button, if you want to style the submit button you can achieve it in 2 way by using #prefix and #suffix form properties. #prefix and #suffix will wrap the form element into a given HTML tag.

In a custom form, use the following.

```
$form['submit'] = array(
  '#type' => 'submit',
  '#value' => t('Submit'),
  '#prefix' => "<div class='scores-submit-btn'>",
  '#suffix' => "</div>",
);

```

In a form created by another module, you can use `hook_form_alte()` to add the form elements.

```
function hook_form_alter(&$form, &$form_state, $form_id) {
  switch ($form_id) {
    case 'FORM_ID':
      $form['submit']['#prefix'] = "<div class='scores-submit-btn'>";
      $form['submit']['#sufix'] = "</div>";
      break;
  }
}

```

In a CSS file, just give the style you want.

```
.scores-submit-btn {
  padding: 0 10px;
}

```

# Answer
> 0 votes
As you want to add span on below form mentioned on https://drupal.stackexchange.com/questions/100442/how-to-change-or-alter-the-html-code-generated-by-drupal-7-form-element\].

You can use this

```
$form['item_name'] = array(
      '#title' => '<span>Pin Number</span>',
          '#type' => 'password',
      '#size' => 35,
          '#maxlength' => 40,
          '#required' => TRUE,
    );

```

---
Tags: theming, forms
---


# Question
Title: How to add markup inside a form radio button div
Currently I have a form displaying radio buttons and I added some markup to it by attaching #suffix to the form element. However, I found that this didn't do exactly what I needed. This created the following code structure:

```
<div class='field-wrapper'>
  <div class='radio-button-group-wrapper>
     ...
      <div class='radio-button-group-inner-wrapper'>
          <div class='radio-button'>
            <input type='radio'></input>
            <label></label>
          </div>
          <div class='radio-button'>
            <input type='radio'></input>
            <label></label>
          </div>
      </div>
 </div>
 <div>Markup goes here</div>
</div>

```

I'm trying to figure out how to add markup inside the 'radio-button' div, right after the label tag. How can I do this? If there is no Drupal way of doing it, I can add it with javascript, but that's not ideal.

EDIT: I have chosen to try using a custom template for this form element, but its not working. Here is my code:

```
'my_module_is_member_radios' => array(
  'variables' => array(
    'description' => array(),
  ),
   'template' => 'templates/my_module_is_member_radios',
),

```

# Answer
> 0 votes
I was able to follow @Alfred's advice above and used the #theme element to make this work. I added this to my module theme hook:

```
'my_module_is_member_radios' => array(
  'render element' => 'form',
  'template' => 'templates/my_module_is_member_radios',
),

```

and in the template used this:

```
$armedForcedInfo = "some markup";
$civilianInfo = "some more markup"

$variables['form'][0]['#suffix'] = $armedForcedInfo;
$variables['form'][1]['#suffix'] = $civilianInfo;
print drupal_render($variables['form'][0]);
print drupal_render($variables['form'][1]);

```

---
Tags: forms, theming
---


# Question
Title: RSS feed is not including <content:encoded>
I have an RSS feed going into mailchimp for my website (www.abercynonprimary.org.uk), feeding off the News page which is a View of teasers. The feed address is the website address with "/news.xml" on the end.

The problem I have is that mailchimp needs the tag :

```
<content:encoded>

```

somewhere in the feed, in order for me to properly use the mailchimp rss tag of full\_content. At the moment, as mailchimp cant see the content:encoded html tag in my feed, it treats it as summary content, and generates a Read More in my Newsletter which doesnt work (links to nothing).

I'm just using the Views setting of Content (not fields) in my News View for the feed (see screen shot attached). I have also attached the note back from Mailchimp Support.

Mailchimp Support - \*"I checked the feed for the your account and it appears that there's "content:encoded" within the feed, but it is not explicitly spelled out in the tags as

```
<content:encoded>

```

In order for MailChimp to read this as expected, this tag needs to display exactly as stated in the Merge Tags article on the feed. Once these tags are added, things should work as expected and you would only need the default "read more" link that comes with the Merge tag. "\*

can anyone help me get my feed to show full content instead of defaulting to summary, and therefore causing Mailchimp to generate a Read More which doesnt work.

thanks

# Answer
You can use Views RSS: Content Elements module, I'm using it and works well...
> 1 votes

---
Tags: views, feeds, emails
---


# Question
Title: DB and modules in folder that doesn't exist
Ok, so I ran into an issue today that completely baffles me...

I have a staging server that I have about 30 sites on. Most are WordPress and about 5 are Drupal. Yesterday I worked on a Drupal site that stores modules in `contrib` and `custom` directories. The other Drupal installs use the default setup for modules (no `contrib` or `custom` folders). Everything worked for all sites yesterday with no issues.

I came into my office today and noticed that 2 of the Drupal sites are all messed up. When I visit Site1 I get an error page stating:

```
Notice: Undefined index: olympusat in _drupal_maintenance_theme() (line 74 of /var/www/vhosts/parables.stage/public_html/includes/theme.maintenance.inc).
Notice: Trying to get property of non-object in _drupal_theme_initialize() (line 145 of /var/www/vhosts/parables.stage/public_html/includes/theme.inc).
PDOException: SQLSTATE[42S02]: Base table or view not found: 1146 Table 'd_parables.languages' doesn't exist: SELECT * FROM {languages} ORDER BY weight ASC, name ASC; Array ( ) in language_list() (line 2651 of /var/www/vhosts/parables.stage/public_html/includes/bootstrap.inc).
Notice: Trying to get property of non-object in _theme_build_registry() (line 710 of /var/www/vhosts/parables.stage/public_html/includes/theme.inc).
Notice: Trying to get property of non-object in _theme_build_registry() (line 710 of /var/www/vhosts/parables.stage/public_html/includes/theme.inc).
Notice: Trying to get property of non-object in _theme_build_registry() (line 710 of /var/www/vhosts/parables.stage/public_html/includes/theme.inc).
Notice: Undefined index: olympusat in theme_get_setting() (line 1414 of /var/www/vhosts/parables.stage/public_html/includes/theme.inc).
Notice: Trying to get property of non-object in theme_get_setting() (line 1451 of /var/www/vhosts/parables.stage/public_html/includes/theme.inc).
Notice: Trying to get property of non-object in theme_get_setting() (line 1461 of /var/www/vhosts/parables.stage/public_html/includes/theme.inc).
Notice: Undefined index: olympusat in template_preprocess_maintenance_page() (line 2702 of /var/www/vhosts/parables.stage/public_html/includes/theme.inc).
Notice: Trying to get property of non-object in template_preprocess_maintenance_page() (line 2702 of /var/www/vhosts/parables.stage/public_html/includes/theme.inc).
Warning: array_keys() expects parameter 1 to be array, null given in template_preprocess_maintenance_page() (line 2705 of /var/www/vhosts/parables.stage/public_html/includes/theme.inc).
Warning: Invalid argument supplied for foreach() in template_preprocess_maintenance_page() (line 2705 of /var/www/vhosts/parables.stage/public_html/includes/theme.inc).

```

So first thing I did was try to flush the cache... output is below.

```
[root@StagingServer public_html]# drush cc all
Drush command terminated abnormally due to an unrecoverable error.   [error]
PDOException: SQLSTATE[42S02]: Base table or view not found: 1146 Table 'd_parables.languages' doesn't exist: SELECT * FROM {languages} ORDER BY weight ASC, name ASC; Array
(
)
 in language_list() (line 2651 of /var/www/vhosts/parables.stage/public_html/includes/bootstrap.inc).

```

So I decided the DB was somehow corrupted. I dumped a fresh version of the DB from PRODuction and tried to visit the page. Same error as above... So I ran drush cc all again and I got the exact same error...

Confirmed I was in the correct folder and still the same issues.

Ok, I'll just try to fix Site2 first then...

Site2 just has a blank page. Checking the error log shows:

```
PHP Fatal error:  require_once(): Failed opening required '/var/www/vhosts/olympusat.stage/public_html/sites/all/modules/contrib/entity/includes/entity.inc' (include_path='.:/usr/share/pear:/usr/share/php') in /var/www/vhosts/olympusat.stage/public_html/includes/bootstrap.inc on line 3146

```

The problem with this error is that there is no `contrib`folder for modules. This is setup on Site1 only. SO next I wanted to confirm that each site was pointing to the correct DB. I verified both settings.php files were correct... they are.

I am lost on what to do next... Site2 is using a default setup and all modules are in the `sites/all/modules` directory. I cannot understand why it's looking in the contrib folder for a module. The module does exist in the modules directory... Not really sure how to fix this issue.

So I decided to check permissions and ownership for the sites in question. Everything seems correct...

Any suggestions or insight on this is appreciated.

Thanks

**More Info**

So this is what is happening after I use `registry_rebuild` (`drush rr`)

**Site1:** Command Line:

```
cd /var/www/vhosts/parables.stage/public_html
cd sites/all/modules/contrib/registry_rebuild
php registry_rebuild.php

```

ouput:

```
DRUPAL_ROOT is /var/www/vhosts/parables.stage/public_html.<br/>
Bootstrapping to DRUPAL_BOOTSTRAP_SESSION<br/>
Bootstrap caches have been cleared in DRUPAL_BOOTSTRAP_SESSION<br/>
Doing registry_rebuild() in DRUPAL_BOOTSTRAP_SESSION<br/>
Bootstrapping to DRUPAL_BOOTSTRAP_FULL<br/>
Rebuilding registry via registry_rebuild_cc_all in DRUPAL_BOOTSTRAP_FULL<br/>
All caches have been cleared with registry_rebuild_cc_all.<br/>
There were 711 files in the registry before and 711 files now.<br/>
All caches have been cleared with registry_rebuild_cc_all.<br/>
If you don't see any crazy fatal errors, your registry has been rebuilt.<br/>

```

Site works as expected.

**Site2** Command Line:

```
cd /var/www/vhosts/olympusat.stage/public_html
cd sites/all/modules/registry_rebuild
php registry_rebuild.php

```

ouput:

```
DRUPAL_ROOT is /var/www/vhosts/olympusat.stage/public_html.<br/>
Bootstrapping to DRUPAL_BOOTSTRAP_SESSION<br/>
Bootstrap caches have been cleared in DRUPAL_BOOTSTRAP_SESSION<br/>
Doing registry_rebuild() in DRUPAL_BOOTSTRAP_SESSION<br/>
Bootstrapping to DRUPAL_BOOTSTRAP_FULL<br/>
Rebuilding registry via registry_rebuild_cc_all in DRUPAL_BOOTSTRAP_FULL<br/>
All caches have been cleared with registry_rebuild_cc_all.<br/>
There were 734 files in the registry before and 734 files now.<br/>
All caches have been cleared with registry_rebuild_cc_all.<br/>
If you don't see any crazy fatal errors, your registry has been rebuilt.<br/>

```

Site works as expected.

Now when I check Site2 (parables.stage)

I see the error:

```
Fatal error: require_once(): Failed opening required '/var/www/vhosts/parables.stage/public_html/sites/all/modules/entity/includes/entity.inc' (include_path='.:/usr/share/pear:/usr/share/php') in /var/www/vhosts/parables.stage/public_html/includes/bootstrap.inc on line 3062

```

Notice there is no `contirb` folder in the path as this site is setup to use...

So I clear the cache:

```
cd /var/www/vhosts/olympusat.stage/public_html
drush cc all

```

Now I get the error:

```
Notice: Undefined index: olympusat in _drupal_maintenance_theme() (line 74 of /var/www/vhosts/parables.stage/public_html/includes/theme.maintenance.inc).
Notice: Trying to get property of non-object in _drupal_theme_initialize() (line 145 of /var/www/vhosts/parables.stage/public_html/includes/theme.inc).
PDOException: SQLSTATE[42S02]: Base table or view not found: 1146 Table 'd_parables.languages' doesn't exist: SELECT * FROM {languages} ORDER BY weight ASC, name ASC; Array ( ) in language_list() (line 2651 of /var/www/vhosts/parables.stage/public_html/includes/bootstrap.inc).
Notice: Trying to get property of non-object in _theme_build_registry() (line 710 of /var/www/vhosts/parables.stage/public_html/includes/theme.inc).
Notice: Trying to get property of non-object in _theme_build_registry() (line 710 of /var/www/vhosts/parables.stage/public_html/includes/theme.inc).
Notice: Trying to get property of non-object in _theme_build_registry() (line 710 of /var/www/vhosts/parables.stage/public_html/includes/theme.inc).
Notice: Undefined index: olympusat in theme_get_setting() (line 1414 of /var/www/vhosts/parables.stage/public_html/includes/theme.inc).
Notice: Trying to get property of non-object in theme_get_setting() (line 1451 of /var/www/vhosts/parables.stage/public_html/includes/theme.inc).
Notice: Trying to get property of non-object in theme_get_setting() (line 1461 of /var/www/vhosts/parables.stage/public_html/includes/theme.inc).
Notice: Undefined index: olympusat in template_preprocess_maintenance_page() (line 2702 of /var/www/vhosts/parables.stage/public_html/includes/theme.inc).
Notice: Trying to get property of non-object in template_preprocess_maintenance_page() (line 2702 of /var/www/vhosts/parables.stage/public_html/includes/theme.inc).
Warning: array_keys() expects parameter 1 to be array, null given in template_preprocess_maintenance_page() (line 2705 of /var/www/vhosts/parables.stage/public_html/includes/theme.inc).
Warning: Invalid argument supplied for foreach() in template_preprocess_maintenance_page() (line 2705 of /var/www/vhosts/parables.stage/public_html/includes/theme.inc).

```

Also, the title says Olympusat Media... not parables... So I start this loop over...

I'm deciding to delete these sites and set them back up... Hopefully this will cause this to go away.

# Answer
It sounds like a module might have been removed from the /modules directory without being properly uninstalled.

A registry rebuild *usually* fixes this type of issue. If you're using Drush, make sure you have the registry rebuild extension downloaded:

```
drush dl registry_rebuild -y

```

Once this is done, go ahead and run the following command from the Drupal webroot:

```
drush rr

```

As I said, that should hopefully do the trick.
> 1 votes

---
Tags: drush, debugging
---


title: Making a fan site

text:
# Question
Title: Making a fan site
I'm trying to create an artist/fan base site. I have created content type(artist) and would want to add a "be a fan" tag to it. Where owner of content(artist) can see who fanned him and fan can see list of artists he's following.

I have tried drupal.org/projects/flag and changed bookmark to be a fan but its not working the way i want it to. Assistance needed.

# Answer
You are mixing your flags types. Flags are defined for a specific entity. The bookmarks flag is defined for node. Once you have created a flag you cannot change its entity type to which it is attached. You want a users flag, which is displayed on user pages, and as you want it on a node page (content type artist) you will have to go the extra mile.

Look at this post which explains how to get the users flag in node.tpl.php

Placing a flag link on a page
> 0 votes

---
Tags: flags
---


title: node_save not responding inside module

text:
# Question
Title: node_save not responding inside module
Drupal: 7.31 Php: 5.5.9-1ubuntu4.3

I am trying to create node type 'recibo\_promocion\_type', after create nodes of type 'offer\_type' (**diferent type)**. I am using hook\_node\_presave. I run the code in the development environment 'run php code', successfully, but the same code within in my personal module **does not respond**, getting a blank page. I did debug and the line of code that fails is '**node\_save ($node)**'.

function nuevo\_Recibo\_Promocion($nid, $uid, $ruta){

```
define('DRUPAL_ROOT', getcwd());
require_once DRUPAL_ROOT . '/includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);
global $user;
$nodeConfigura=node_load($nid);
$node = new stdClass();
$node->nid=0;
$node->type = 'recibo_promocion_type';
$node->uid = $user->uid;
$node->name = $user->name;
$node->title = $nodeConfigura->title;
$node->language = 'es';
$node->field_organizacion = $nodeConfigura->field_organizacion;
$node->field_enlace['und'][0]['url']=$ruta;
$node->field_enlace['und'][0]['title']=$nodeConfigura->title;
$node->field_enlace['und'][0]['attributes']['target']=0;
$node->field_fecha_promocion = $nodeConfigura->field_fecha_promocion;
$node->field_cliente_envio['und'][0]['target_id'] = $uid;
node_object_prepare($node);
$node = node_submit($node);
node_save($node);

```

}

This is the test code with moc parameters from 'ejecute code php' of dev module, and save node successfully. The moc parameters was extrated from dpm($node) replace save\_node($node) in a module.

```
//moc paraeters
$ruta='http://...';
$uid=184;
$nid =81;

$nodeConfigura=node_load($nid);
$node = new stdClass();
$node->type = 'recibo_promocion_type';
$node->uid = 1;
$node->title = $nodeConfigura->title;
$node->language = 'es';
$node->field_organizacion = $nodeConfigura->field_organizacion;
$node->field_enlace['und'][0]['url']=$ruta;
$node->field_enlace['und'][0]['title']=$nodeConfigura->title;
$node->field_enlace['und'][0]['attributes']['target']=0;
$node->field_fecha_promocion = $nodeConfigura->field_fecha_promocion;
$node->field_cliente_envio['und'][0]['target_id'] = $uid;

node_object_prepare($node);
$node = node_submit($node);
node_save($node);

```

the node save successfully.

This is the result to repace 'node\_save($node)' for 'dpm($node)' in function 'nuevo\_Recibo\_Promocion' inside my module:

I tried also:

1)Use drupal\_register\_shutdown\_function but the bug is the same.

2)I have created a xmlrpc service, and replace instead the nuevo\_Recibo\_Promocion call function. The xmlrpc creates successfully the node, but if it's invoked from 'execute php code' (dev module). if xmlrpc it's invoked from from my module, it doesn't created the new node.

$methods = xmlrpc('http://...', array('reciboPromocion.new' =\> array($nid,$ruta,$uid)));

3) I have disabled all my modules to avoid confict with othes modules (loops Infinite)

4) use try{} catch(exception $e){}... to get the bug.

5) use hock\_cron(), but not save the new node.

6) I've tried the user custom permissions, the function node\_access($node) before node\_save ($node) in two cases: my personal module and dev console 'Run PHP code'. The result is true in all cases.

The question for is, why the process do not shoot any exception, alert, or notify, The result is a don't response and '**blank page**' in my web browser.

any suggestion?

# Answer
> 0 votes
When you are doing node\_save() inside hook\_node\_presave, it will trigger hook\_node\_presave where you have node\_save()...

You could move the node\_save else where. Perhaps if your using form in creating the original node just add submit handler in case the node type matches? Or some other way to by pass the infinite loop.

# Answer
> 0 votes
Solved: The problem was the following:

1) I had not closed the hook\_presave function, missing the last '}'. 2) The first sentence of my \_presave function is:

if ($ node-\> type == 'configuracion\_promocion\_type') { .... }

3) In the last function of my code had a '}' more.

The result was this strange behavior, because in my opinion, should not work with drupal not closed my code.

In the console dev 'execute php code' only proved the insertion node, so it was not in the infinite loop.

Thank you all.

---
Tags: nodes
---


# Question
Title: How to restrict user posting a node in certain circumstances
I've created a new user role (country\_admin) and I have created a field for these users called user\_country. This can be set when registering a user to UK or USA.

I have created a taxonomy 'Countries' and have added UK and USA as terms. I have also created a term reference on my articles so that articles can be assigned to a country.

The functionality I require is that only the user who has UK in the user\_country field can post an article with the term set to UK.

I am looking at hook\_node\_access\_records() and hook\_node\_grants() and have got the functionality working so UK users can only VIEW or UPDATE UK articles using this, however, in hook\_node\_grants() there doesn't seem to be an "ADD" operation.

How would I do this?

Current hook\_node\_grants() below

```
/**
* Implements hook_node_grants().
*/
function curator_scraper_node_grants($account, $op) {
    if ($op == 'view') {
        if (array_key_exists(DRUPAL_AUTHENTICATED_RID, $account->roles)) {

            //Let's get the country id the user is linked with
            $uid = $account->uid;
            $user = user_load($uid);
            $country = $user->field_user_country['und'][0];

            $grants[MYMODULE_REALM] = array(
                MYMODULE_GRANT_ID_PUBLIC, // Allow public data
                $country, // this should be users' country link
            );
        }
        else {
            // this is an anonymous user, give them the 'public' grant ID
            // that allows them access to public nodes
            $grants[MYMODULE_REALM] = array(
                MYMODULE_GRANT_ID_PUBLIC,
            );
        }
    }
    if ($op == 'update'){
        //We can grant update permissions here similar to the above
        // but where is $op == "add"???
    }
    return $grants;

}

```

# Answer
> -1 votes
You can use the Node access user reference module:

> Gives content access permissions to users for content that references the users with User reference or Entity reference.
>
> This is great if you want your content authors to be able to choose additional authors, or choose who can view their content, as well as being able to display the list of authors or viewers within your content, or in views displays.

---
Tags: users, nodes
---


# Question
Title: How does one check if user has created a node of a content type in rules?
I would like to check if a user already authored a node from a content type before creating one for the user in rules. How do I create a condition for this? Thanks!

# Answer
My solution was to create a user flag (global flag type) then create a rule that flags the author of the node after creation. The rules condition also checks for the node's taxonomy term.

In my original rule, I added a new condition to check if user has NOT been flagged, then create the node for them.

On my website users won't be creating Group nodes themselves so this works for me.
> 1 votes

# Answer
After seeing these big answers for Rules, I think you can try to do the same via code. Its much smaller and extremely faster than Rules!

```
/**
 * Implements hook_node_prepare()
 * @param type $node
 */
function mymodule_node_prepare($node) {
  if ($node->type == "my_type") {
    if (!isset($node->nid)) {
      $existing_nid = db_query("SELECT nid FROM {node} WHERE (type = :type1) AND uid = :uid", array("type1" => "my_type, "uid" => $node->uid))->fetchField();
      if ($existing_nid != FALSE) {
        drupal_goto("node/$existing_nid/edit");
      }
    }
  }
}

```

This code checks if the user already have created a node, if yes, instead of allowing him to create a new one, we redirect him to the edit form of the existing node.

If you want this feature without Rules or code, you can try the Profile module. It has this magical feature to configure any content-type as 'profile'. And when a content-type is configure as 'profile', users are not allowed to have more than one node of that particular type.

Thanks!
> 2 votes

# Answer
NOTE: This will still let them reach the actual create a node etc. So this is more of a "reactive" solution than proactive solution. To stop them before they even start creating the node, I dont think rules is the tool for the job. You will most likely need to create a simple custom module with form alter and a query. If the query returns \> 1 show the form, if not show a message.

A very quick and easy way to do the checking part is using VBO.

* You create a VBO view with the UID (Author) as contextual filter and the content type as normal hidden filter. This will basically return any nids for the UID you give to the view.
* Set the pager to display a specified number = 1.
* Now, in rules you can use this VBO view as a condition "Check number of results returned by a VBO view"
* Choose the VBO view you created from the dropdown
* Use the data selector and the UID of the created/about to be created node for the arguments.
* Put 1 as the number of results and use negate checkbox.

This will basically return TRUE if the user HAS NOT already created a node of that content type (because of the negate checkbox). So what you will want to do is then in the actions delete the node (delete entity) and show a message using "Show a message" action.

Done.
> 1 votes

# Answer
took me some time..

## First things first

I cant tell what action you want to trigger in rules, preventing the node from being saved is not possible at this point anymore (ran into this as I was testing my rule).

however, if you want to do something else, like editing the content, flag it for moderation or whatever I have a solution for you.

## Create a custom module with the new condition

This will create 2 new conditions, one for checking if a user created a post of a given node before, and one for simple text checking the content type and user entity. Both rules also check for the status of the post and return true only if published. This could easily be extended to check string content type and int uid.

module functions:

```
/*
 * Implementation of hook_rules_condition_info()
 */
function mymodule_rules_condition_info() {
  return array(
    'mymodule_condition_has_other_post' => array(
      'label' => t('User has other post of same content type for given node.'),
      'parameter' => array(
        'node' => array('type' => 'node', 'label' => t('node')),
        'user' => array('type' => 'user', 'label' => t('user')),
      ),
      'group' => t('User'),
    ),
    'mymodule_condition_has_post' => array(
      'label' => t('User has post of content type.'),
      'parameter' => array(
        'contentType' => array('label' => t('content type'), 'type' => 'text'),
        'user' => array('type' => 'user', 'label' => t('user')),
      ),
      'group' => t('User'),
    ),
  );
}

function mymodule_condition_has_post($contentType, $user) {
  $query = new EntityFieldQuery();
  $query->entityCondition('entity_type', 'node')
    ->entityCondition('bundle', $contentType)
    ->propertyCondition('status', 1)
    ->propertyCondition('uid', $user->uid);
  $result = $query->execute();

  if (isset($result['node'])) {
    return true;
  } else {
    return false;
  }
}

function mymodule_condition_has_other_post($node, $user) {
  return mymodule_condition_has_post($node->type, $user);
}

```

## Create a rule with your events, conditions and actions

I created one to send an email to all users with administrator role.

```
{ "rules_has_post" : {
    "LABEL" : "has_post",
    "PLUGIN" : "reaction rule",
    "REQUIRES" : [ "mymodule", "rules" ],
    "ON" : [ "node_presave" ],
    "IF" : [
      { "mymodule_condition_has_other_post" : { "node" : [ "node" ], "user" : [ "node:author" ] } }
    ],
    "DO" : [
      { "mail_to_users_of_role" : {
          "roles" : { "value" : { "3" : "3" } },
          "subject" : "new node on [site:name]",
          "message" : "user [node:author] created a new node: [node:url]",
          "from" : "system@example.tld"
        }
      }
    ]
  }
}

```

The documentation pages are pretty outdated, it has a completly different syntax for d7 than to d6. I looked the correct one up in the `rules.api.php`.
> 1 votes

# Answer
i found this piece of code on drupal.org that works pretty well

https://www.drupal.org/node/2052241

```
global $user;

$result = db_query("SELECT COUNT(nid) FROM node JOIN users ON node.uid = users.uid

WHERE node.status = :status AND users.uid = :uid AND node.type = :type",

array(":status"=> 1,":uid" => $user->uid, ":type" => 'configuration_1'))

->fetchField();

if ($result >= 1){
    return FALSE;
    }

 else{

return TRUE;

}

```

What i would love is checking if the user has any node created by a specific date eg tuesday
> 0 votes

---
Tags: 7, nodes, rules
---


# Question
Title: AJAX error when ctools_modal_command_dismiss() is called
So I'm having a problem with dismissing a Ctools modal within a form submit's callback function. Once I have processed any submit data, I'd like to dismiss the modal without redirecting the page (easy enough), but each time I click the submit button with ctools\_modal\_command\_dismiss() included in the callback function, I'm presented with an AJAX error such as below:

**An AJAX HTTP error occurred. HTTP Result Code: 200 Debugging information follows.**

I'm stumped as to why this is happening. The modal works perfectly without the dismiss function.

```
function pay_rise_menu() {
  $items = array();
  $items['pay_rise/%ctools_js'] = array(
    'page callback' => 'pay_rise_modal_email_share',
    'page arguments' => array(1),
    'access arguments' => array('access content'),
  );

  return $items;
}

function pay_rise_modal_email_share($ajax) {
  if ($ajax) {
    ctools_include('ajax');
    ctools_include('modal');

    $form_state = array(
      'ajax' => TRUE,
      'title' => t('Share by email'),
    );

    $output = ctools_modal_form_wrapper('pay_rise_modal_email_share_form', $form_state);

    if (!empty($form_state['ajax_commands'])) {
      $output = $form_state['ajax_commands'];
    }

    print ajax_render($output);
    drupal_exit();
  }
  else {
    return drupal_get_form('pay_rise_modal_email_share_form');
  }
}

function pay_rise_modal_email_share_form($form, &$form_state) {
  $form = array();

  $form['recipient'] = array(
    '#type' => 'textfield',
    '#title' => t('Recipient'),
    '#attributes' => array(
      'placeholder' => 'Recipient email...',
    ),
  );

  $form['body'] = array(
    '#type' => 'textfield',
    '#title' => t('Message'),
    '#attributes' => array(
      'placeholder' => 'Message...',
    ),
  );

  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Submit'),
    '#ajax' => array(
      'callback' => 'pay_rise_modal_email_share_form_callback',
    ),
  );

  return $form;
}

function pay_rise_modal_email_share_form_callback($form, &$form_state) {
  $values['message'] = $form_state['values']['body'];
  drupal_mail('pay_rise', 'share', $form_state['values']['recipient'], 'en', array('values' => $values));
  $form_state['ajax_commands'] = ctools_modal_command_dismiss('Thanks. Your message has been sent.');
}

```

The above is invoked once the following link is clicked:

```
l('email', 'pay_rise/nojs', array('attributes' => array('class' => 'ctools-use-modal icon-mail')))

```

# Answer
Managed to solve this myself with the following:

By default, the php.ini file on a precise64 vagrant box sets execution\_limit to 30 (for some reason). Increasing this incrementally seems to have fixed the issue for me at least.
> 0 votes

# Answer
You are doing it wrong, ctools modal works a little bit different. Better do it like this:

remove `#ajax` property from form submit button, let it work as usual:

```
...
$form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Submit'),
  );
...

```

define submit callback as usual:

```
function pay_rise_modal_email_share_form_submit($form, &$form_state) {
  $values['message'] = $form_state['values']['body'];
  drupal_mail('pay_rise', 'share', $form_state['values']['recipient'], 'en', array('values' => $values));
}

```

build modal callback:

```
function myCallback($js = NULL) {
  if (!$js) {
    drupal_access_denied();
    drupal_exit();
  }

  ctools_include('modal');
  ctools_include('ajax');

  $form_state = array(
    'title' => t('My modal title'),
    'ajax' => TRUE,
    'build_info' => array(
      'args' => array(),
    ),
  );

  $commands = ctools_modal_form_wrapper('pay_rise_modal_email_share_form', $form_state);

  if (!empty($form_state['executed'])) {
    $commands = array();
    $commands[] = ctools_modal_command_dismiss();
  }

  print ajax_render($commands);
  drupal_exit();
}

```

ctools itself handles ajax submission.. That's it.
> 0 votes

---
Tags: forms, chaos-tool-suite
---


# Question
Title: How to change upload destination from private to public?
On a Drupal 7 installation I have an image gallery (set up with the media gallery module). I set the upload destination to private to protect those images for anonymous users. Unfortunately it turned out, that the performance of private images is that poor, that the gallery became quit unusable.

So I decided to switch the destination to public for the node type. But as there already exist nodes of the mentioned type (I assume that my be the reason), the options of the node type's filed, where to set the destination is greyed out:

Is there any way to change the destination for existing nodes?

# Answer
You could accomplish this by moving the files out of the private directory and into the public directory (make sure the paths stay the same!). Then you would need to update the 'file\_managed' table. The 'uri' table will list the files as either private or public. The mySQL would be similar to:

```
UPDATE file_managed SET uri = REPLACE(uri, 'private://', 'public://') where instr(uri, 'private') > 0;

```

***NOTE*** Please make sure to test this on a dev site before doing in production.
> 2 votes

---
Tags: 7, media
---


# Question
Title: Unable to login into admin after theme change
I am new to Drupal and to understand the basics I created a new theme in Drupal and enabled it as default. It works fine, however, I am not being able to log in into admin. I reinstalled Drupal and the admin login works fine. When the default theme is enabled it works, but it doesn't work when my custom theme is enabled.

My *.info* file is -

```
name = My First Custom Theme
description = A custom them to understand how Drupal works
core = 7.x

stylesheets[all][] = css/style.css

regions[header] = Header
regions[content] = Content
regions[menu] = Menu
regions[left_sidebar] = Left Side Bar
regions[main_content] = Main Content
regions[footer] = Footer

```

And my *tpl.php* file is -

```
<div id="header">
    <?php print render($page['header']); ?>
</div>

<div id="menu">
    <?php print render($page['menu']); ?>
</div>

<div id="wrapper">
    <div id="content">
        <div id="left_sidebar">
            <?php print render($page['left_sidebar']); ?>
        </div>

        <div id="main_content">
            <?php print render($page['main_content']); ?>
        </div>
    </div>
</div>

<div id="footer">
    <?php print render($page['footer']); ?>
</div>

```

I tried accessing admin page using following ways but without success -

> http://www.mysite.com/user
>
> http://www.mysite.com/?q=user

Any idea where I am going wrong ?

# Answer
> 1 votes
To quote you, it sounds like the answer to your question is you needed to:

> ...include `<?php print render($page['content']); ?>` in my tpl.php file. ...the drupal login form wasn't appearing on my site since no default region was specified.

# Answer
> 0 votes
My whole site crashed due to an error similar to the one above. It’s deadly, because I couldn’t even log into my Admin control panel. Warning: require\_once(/public\_html/site/wp-content/themes/flexfit-child/framework/functions/meta-box/meta-box.php): failed to open stream: No such file or directory in /home2/skegley/public\_html/site/wp-content/themes/flexfit/functions.php on line 239 Fatal error: require\_once(): Failed opening required ‘public\_html/site/wp-content/themes/flexfit-child/framework/functions/meta-box/meta-box.php’ (include\_path=’.:/opt/php54/lib/php’) in /home2/skegley/public\_html/site/wp-content/themes/flexfit/functions.php on line 239

To fix, go into WordPress installation database.

The SQL is:

INSERT INTO `wp_options` (`option_id`, `option_name`, `option_value`, `autoload`) VALUES

\[a bunch of irrelevant lines\]

(47, ‘template’, ‘flexfit’, ‘yes’), (48, ‘stylesheet’, ‘flexfit-child’, ‘yes’), Change the last line displayed there to (48, ‘stylesheet’, ‘flexfit’, ‘yes’),

In other words, to fix the broken site, go to wp\_options table. installing the child theme as normal only changes stylesheet to the child theme. you have to change the stylesheet back to the original theme’s stylesheet.

---
Tags: theming, users
---


# Question
Title: Date Range filtering using Google Search Appliance crashing
I'm working with the Google Search Appliance and corresponding drupal module. I've followed the user guide linked on the project page (also here) on creating filters. I was hoping to create a date range filter, however, I'm a bit stumped on how to filter on content types that have date ranges themselves.

For example, if I had a content type of person who had a year range of 1900 - 1970 (IE, years they lived). I figured I would create a metadata field that would have each date listed, so that google would know each year the content type covers. The filter part is the part where I'm having trouble.

In my custom module, i'm trying to set my $query\['gsa\_query\_params'\]\['requiredfields'\] to be a range of dates in the form of "1900|1901|1902". That does work, but if the range is too big (around 30 years), the search fails. I'm lost.

# Answer
So the drupal module uses curl to query the google search appliance, which means if your url is too long, you may run into issues.

It would be better to send a range to the Google search appliance by altering the `$query['gsa_query_params']`, ether by using the required-fields or partial-fields.

However, google doesn't currently support ranges to be sent via these options. Hopefully they'll add that functionality, but if you can't wait indefinitely for them to add the functionality, you can get a bit hacky and get it to work.

So, the Google Search Appliance has a flag, "**inmeta**" which does allow you to create a integer range. The catch here is it can only be used in a query field. IE a search for

> "John Doe AND inmeta:1901-1940"

What you could do though is use the GSA Drupal module.

`hook_google_appliance_query_alter` (where your altering your queries to create your other filters) to add to your q string "`AND inmeta:[range]`". The issue here is that when you use this, drupal will display the full q string, with the inmeta field showing. Which might look strange for your users. You could save a copy of the q string before adding the range to your $query variable. Then, before displaying the page, but after the query has been executed, switch the query string back out.
> 0 votes

---
Tags: 7, search
---


title: Theming Views Display

text:
# Question
Title: Theming Views Display
Can I use Views templates to theme the row style output of a specific display in my view so it doesn't affect the other displays I created? If so, how?

# Answer
> 2 votes
Try this:

1. on the view edit screen click on the display you want to theme
2. click on the "Advanced" tab so that it slides down
3. in the "Others" section click on the "Theme: Information" link
4. in the "Row style output:" section you'll see the template file names you can use, you are currently using the one that is bold, the last name is the most specific, i.e. something like views-view-fields--VIEWNAME--DISPLAYNAME.tpl.php

simply copy views-view-fields.tpl.php from the "theme" directory of the Views module to the directory of your theme, rename the file and modify as you wish (and clear the cache)

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


# Question
Title: How can I change the Available Menus to all, programmatically, for a specific content type?
Hello I'm trying to alter a content-type's menu options by code, since there will be new menus that keep being created on the site and I can't keep going back to the content type to keep adding every single menu to the Available Menus. I should be able to set the default available menus to all, or all custom... but I can't figure this out. I'm looking at the function menu\_form\_node\_type\_form\_alter and created a module to override, however nothing changes, and the Main Menu is always the default available menu. I'm actually trying to prepopulate the parent menu through the URL, which only works if the parent menu is checked as available, but it's not working for all the new menus because the parent menu is not set as available ... How do I override the default menu option for a certain content type so that the available menu checkboxes gets set automatically to all of the custom menus that were created?

Thanks in advance!

update: still not figured out yet, but, I went straight into the core menu module and modified this piece of the function above:

```
  $form['menu']['menu_options'] = array(
    '#type' => 'checkboxes',
    '#title' => t('Available menus'),
    '#default_value' => variable_get('menu_options_' . $type->type, array('main-menu')),
    '#options' => $menu_options,
    '#description' => t('The menus available to place links in for this content type.'),

```

changing the 'main-menu' to a different name actually works straight from core but doesn't work when trying to override with my own module.

# Answer
> 1 votes
If I understand you correctly you want to change the available menus for node types when new menus are created.

You can implement hook\_menu\_insert to respond to new menu creation and you can use variable\_set to add the new menu to the available menus for the selected node types.

E.g. this will add all new menus to the page and article node types:

```
function mymodule_menu_insert($menu) {
  $types = array('page', 'article');
  foreach ($types as $type) {
    $menus = variable_get('menu_options_' . $type, array());
    $menus[] = $menu['menu_name'];
    variable_set('menu_options_' . $type, $menus);
  }
}

```

If you already have created a bunch of custom menus, you'll basically need to call variable\_set as in the example above.

---
Tags: routes, nodes
---


# Question
Title: How to style an "all day event" to have it styled like any other event?
I am on Drupal 7. Everything works fine in Calendar module, except when I add the **all day event** then the styling is changed, I wanted the same styling for all the events.

> "All day events" are created by "date\_all\_day" module which comes with "date" module.

# Answer
> 1 votes
As far as I understand it this is a CSS question. All you need to do is add styles to overwrite the color change. It is actually two different styles that need to be changed. The following code will set them back to the yellow and light grey color that is the default for the calendar module.

```
.calendar-calendar .month-view .full td.multi-day div.monthview,
.calendar-calendar .week-view .full td.multi-day div.weekview,
.calendar-calendar .day-view .full td.multi-day div.dayview {
  background: #ffc;
  color: #777;
}

.calendar-calendar .month-view .full td.multi-day .inner .monthview .continues,
.calendar-calendar .month-view .full td.multi-day .inner .monthview .cutoff,
.calendar-calendar .week-view .full td.multi-day .inner .weekview .continues,
.calendar-calendar .week-view .full td.multi-day .inner .weekview .cutoff {
  background: #ffc;
  color: #777;
}

```

---
Tags: views, theming, datetime
---


title: Change node field with a comment

text:
# Question
Title: Change node field with a comment
I'm creating an issue tracking system with Drupal 7.

I have a content type called "Issue". in it there is a field "Assign To" that is a user reference field.

When a client create the issue he can specify the user that should handle it.

But when a client ads a comment to an issue, he sometimes want to change the assigned user. Currently the only way to do it is by adding the comment, saving and the editing the issue, changing the "Assign To" field and saving.

I would like to make the "Assign To" (and the "Status") field available in the comment or as a separate component in the page.

Where should I start?

# Answer
I found the following module that does a great job: Comment Node Edit.

> Gives Site Administrators ability to mark field instances as "editable by comment." When a field is editable by comment, the field will show up in the "add comment" form.
> 1 votes

# Answer
On Drupal 7, use this module: https://www.drupal.org/project/comment\_alter

That's exactly what you need in this situation.
> 0 votes

---
Tags: entities
---


# Question
Title: hook_form_node_type_form_alter does not work
The sort comments module has a function in sort\_comments.module as below:

```
  /* drupal@ganovelli.it - blackice78 */
  define('SORT_COMMENTS_OLDER_FIRST', 1); // default
  define('SORT_COMMENTS_NEWER_FIRST', 2);
   /* Alter node type form: allow user to decide comments sorting */
 function sort_comments_form_node_type_form_alter(&$form, $form_state) {
  $form['comment']['comment_default_sorting'] = array(
 '#title' => t('Sort'),
 '#type' => 'select',
 '#options' => array(1 => t('Older first'),
                     2 => t('Newer first')),
 '#default_value' => variable_get('comment_default_sorting_' . $form['#node_type']-  >type, SORT_COMMENTS_OLDER_FIRST),
  );
 }

```

so that if you go to structure\>content types, and for example for Article choose edit, then in comment setting, it will give you a drop down menu, so that you can select the order for showing comments, older first or newer first.

I am trying to do something similar, so in order to see how does it work, I have this in my annotations.module file:

```
define('Annotations_OLDER_FIRST', 1); // default
define('Annotations_NEWER_FIRST', 2);
/* Alter node type form: allow user to decide comments sorting */
function Annotations_form_node_type_form_alter(&$form, $form_state) {
  $form['comment']['annotations'] = array(
    '#title' => t('Sort'),
     '#type' => 'select',
    '#options' => array(1 => t('Older first'),
                     2 => t('Paragraph number')),

  #default_value' => variable_get('annotations_' . $form['#node_type']-  >type, Annotatiios_OLDER_FIRST),
  );
  }

```

But I can not see the drop down menu, at the same place that I see the drop down menu for sort comments module. Does anybody know what is the reason?

# Answer
You have a syntax error on the last line, it should start with an apostrophe, and your constant is mispelled. So it probably isn't compiling properly. If drupal was picking up the hook you would probably get a white screen of death.

So this means:

You need to make sure the beginning of the function name is exactly the same as your module name - did you use a capital A when naming the module? PHP is case sensitive.

Lastly, make sure you clear the cache so that Drupal picks up the new hook. Install drush if you haven't already, go to the /install\_directory/sites/mysite directory and run

```
drush cc all

```

(assuming you're on linux with command line access)
> 2 votes

---
Tags: nodes
---


# Question
Title: Custom Drupal field widget causing check_plain() error
I'm working on a custom field widget for Drupal 7. Everything appears to be working correct, but now I'm getting this error:

> Warning: htmlspecialchars() expects parameter 1 to be string, array given in check\_plain() (line 1565 includes\bootstrap.inc)

My .module hooks:

```
<?php
/**
 * Implements hook_field_widget_info().
 */
function MYMODULE_field_hook_info() {
  return array(
    'CUSTOM_field' => array(
      'label' => t('Custom Text Area'),
      'field_types' => array('text_long'),
      'behaviors' => array(
        'multiple values' => FIELD_BEHAVIOR_DEFAULT,
        'default value' => FIELD_BEHAVIOR_DEFAULT,
      ),
    ),
  );
}

/**
 * Implements hook_field_widget_form().
 */
function MYMODULE_field_widget_form(&$form, &$form_state, $field, $instance, $langcode, $items, $delta, $element) {
  switch($instance['widget']['type']) {
    case 'CUSTOM_field':
      $element['text_long'] = array(
        '#type' => 'textarea',
        '#attributes' => array('id' => 'MYFIELD', 'rows' => '5', 'cols' => '3'),
        '#default_value' => isset($items[$delta]['value']) ? $items[$delta]['value'] : '',
      );
      break;
  }
  return array('value' => $element);
}

```

My guess is that it's something in the way Drupal is attempting to validate my value with check\_plain(), but I can't figure out what's wrong.

# Answer
> 0 votes
According to the hook description, $items is an "**Array** of default values for this field." You are trying to look in an **array of arrays** in your default value.

You need to change this line:

```
    '#default_value' => isset($items[$delta]['value']) ? $items[$delta]['value'] : '',

```

to look in the $items array, rather than the $items\[$delta\] array (which doesn't exist) by removing \['value'\], like this:

```
    '#default_value' => isset($items[$delta]) ? $items[$delta] : '',

```

---
Tags: entities
---


# Question
Title: How do I load an external class into the Controller?
I'm playing with module building in Drupal 8, but can't really figure out how to include a custom class which does not extend any other. The class' only purpose is to reduce the amount of code I have in a controller.

However, I get the error:

> Fatal error: Class 'Drupal\first\FirstClass' not found in /var/www/drupal/modules/first/src/Controller/DefaultController.php on line 30

*How do I let `DefaultController.php` know where to find `FirstClass.php`?* Should I just do an include\_once()?

Routing file:

```
first.default_controller_hello:
  path: 'first/hello/{name}'
  defaults:
    _content: '\Drupal\first\Controller\DefaultController::hello'
    _title: 'first Title'
  requirements:
    _permission: 'access content'

```

Controller function:

```
namespace Drupal\first\Controller;

use Drupal\Core\Controller\ControllerBase;
use Drupal\first\FirstClass;

class DefaultController extends ControllerBase {

  /**
   * hello
   * @return string
   */
  public function hello($name)
  {
    $a = new \Drupal\first\FirstClass();
    dsm($a);
    return "Hello ".$name." !" . $a->getV();
  }
}

```

Outside Class:

```
<?php
namespace Drupal\first;

class FirstClass {

    public static function getV() {
        return 'well it works?';
    }
}

```

# Answer
> 5 votes
Drupal 8 uses a autoloader standard called PSR-4: http://www.php-fig.org/psr/psr-4/

Practically means your namespaces should result in the following directory structure

```
first
  - src
  --- FirstClass.php
  --- Controller
  ----- DefaultController.php
  - first.info.yml

```

---
Tags: 8
---


# Question
Title: Modify how Drupal builds fields on a per form basis
I want to change the way Drupal builds specific fields on a specific node edit/add form on my site. For example, when I use print drupal\_render($form\['textarea'\]); in my node--CONTENTTYPE--form.tpl.php file, I get the default Drupal render of the field widget. I want to modify the HTML markup of the field widget.

There are three ways I can think of that might solve this problem:

1. Using a forms equivalent of the theme\_field() hook. This seems ideal, but after searching for the last few hours, I haven't found anything on this.
2. Building custom field widgets for every field type I'm using on that node. This is definitely not ideal and I have to believe there's an easy way to do this in Drupal from a theme point of view.
3. Manually build the HTML markup for the form and field in node--CONTENTTYPE--form.tpl.php with print $form\['textarea'\]\['und'\]\[0\]\['title'\]; and the like.

Is there a hook in Drupal to do this, or must the code for every field I want to modify be manually generated?

# Answer
I think your third option is the most direct solution since you are only looking to change one form and that file will only be called when you use that form.

The only alternative I can think of is to use hook\_form\_FORM\_ID\_alter and iterate through the form items, putting html into the `#prefix` and `#suffix` values; or creating `#attribute['class']` or `#attribute['style']` values depending on what you are trying to achieve.
> 0 votes

---
Tags: theming, forms
---


# Question
Title: Scan Remote FTP server (Akamai) for files, use filename to create content
I'm wondering if there is an existing workflow to achieve what I'm looking for before I'm forced to go and build my own. This is, preferably, in drupal 7.

I have media files stored on an akamai server that need to be scanned either via a cron or manual start and after they're scanned, their filenames need to be put into separate content. I do not need the files individually parsed, I just need the filenames added to title and add the filename to a textbox within the created content.

I have found a few methods that sound similar to what I'm looking for such as: \- Storage API: Does connect, but cannot find files that were not uploaded via their service. \- File Field Sources: No remote FTP, but does scan local and such. \- Bulk Media Upload: Does scan and create a new node for each, does not do remote.

Any ideas?

# Answer
> 0 votes
How about feeds?

<sub>(Sorry this would/should be a comment but I don't have enough rep yet)</sub>

---
Tags: media, files
---


# Question
Title: Expose filter with collabsible div on click in a Calendar
I have created a calendar showing Events in different cities.The City names are taken as Taxonomy and are displayed as a filter.On selecting a Particular city the Calendar shows all the events of that particular city in that month.I want the number of events in that particular city in the filter next to the city name.On clicking the City name in filter it should display the event details under it. Eg.If Atlanta have 4 events and Chicago have 1 event London doesnt have any event in July it should be displayed as

* Atlanta(4)
* Chicago(1)
* London(0)

for that particular month. On clicking the City the display is like-

Atlanta

* Event1
* Event2
* Event3

Chicago(2)

London(0)

ALong with calendar filtering and showing only Events related to Atlanta.

How to get this Functionality please help.

# Answer
I'm going to assume that each event is a node in Drupal, yes?

The filters you are describing are called 'facets', and there are a number of ways you can get them, but probably the most robust is to:

* Install Apache Solr on your server if you haven't already
* Install the Solr Search module in Drupal and configure it to search your events
* Install the Facets API module and enable facets for your Country attribute

All of these things are well documented.

The one I had the most trouble with was the initial install of Apache Solr, but the instructions are specific to your O/S so unless you're using RedHat or a derivative, the blog post that helped me won't be very useful.
> 0 votes

---
Tags: datetime
---


title: Related Profiles block

text:
# Question
Title: Related Profiles block
I have two profile types teacher and students. They both have a taxonomy field “State”.

Below each teacher’s profile I want to show students from his State.

I have added two relationships:

1) User: Profile 2) Field: State (which is a taxonomy term field).

Then added a contextual filter Taxonomy term: Term ID. Under "When the filter value is NOT available" have selected default value "Taxonomy term id from url".

But it doesn't displays any matching profiles. I have done similar functionality for content entity type and it works. I guess the problem is due to profile entity type or am I missing something?

Can you please tell where I am going wrong? Thanks!

# Answer
I think the problem lies in your contextual filter. Presumably the teacher's profile page does not contain the taxonomy term ID in the URL, it usually doesn't unless you've done something tricky to put it there.

So: the view is looking at yoursite/user/\[uid\] and it thinks that the \[uid\] is the taxonomy term id (because you told it so), so doesn't find any matches and returns a nil result.

I'm not sure how to fix that, but hopefully this will help you troubleshoot.
> 0 votes

---
Tags: views, users
---


title: form submission in Drupal

text:
# Question
Title: form submission in Drupal
i have made a custom module for form in drupal using dupal API,and made a table in my database...now What i want is to save the value of drop down box instead of it's index into database...my .module file is:

```
<?php
function form_test_menu() {
$items['formtest'] = array(
'title' => 'Form Test',
'page callback' => 'drupal_get_form',
'page arguments' => array('form_test_form'),
'access callback' => TRUE,
);
return $items;
}
function form_test_form($form,&$form_submit) {
$form['name'] = array(
'#title' => t('Name'),
'#type' => 'textfield',
'#required' => TRUE,
);
$form['college'] = array(
'#title' => t('College/University'),
'#type' => 'textfield',
'#required' => TRUE,
);
$form['education'] = array(
'#title' => t('Education'),
'#type' => 'select',
'#description' => 'Select your higher education .',
'#options' => array(t('--- SELECT ---'), t('B.tech'), t('MCA'), t('MBA'),t('Graduate')),
'#required' => TRUE,
);
$form['percentage'] = array(
'#title' => t('Percentage/CGPA'),
'#type' => 'textfield',
'#required' => TRUE,
);
$form['application'] = array(
'#title' => t('Job Applied'),
'#type' => 'select',
'#options' => array(t('---select---'),t('Web Developer'),t('Web Designer'),t('SEO'),t('Marketing')),
'#required' => TRUE,
);
$form['submit'] = array(
'#value' => 'Submit',
'#type' => 'submit',
);
return $form;
}
function form_test_form_submit($form, $form_state) {
global $user;
db_insert('drupal')
->fields(array(
'name' => $form_state['values']['name'],
    'college' => $form_state['values']['college'],
    'education' => $form_state['values']['education'],
    'percentage' => $form_state['values']['percentage'],
    'application' => $form_state['values']['application'],

))->execute();
drupal_set_message("successfully saved data");
} ?>

```

any help will be appreciated. Thank you.

# Answer
I think the easiest way to do this would be to make the key the same as the value. For instance:

```
$form['education'] = array(
  '#title' => t('Education'),
  '#type' => 'select',
  '#description' => 'Select your higher education.',
  '#options' => array(
    '_none' => t('-- SELECT --'),
    'B.tech' => t('B.tech'),
    'MCA' => t('MCA'),
    'MBA' => t('MBA'),
    'Graduate' => t('Graduate')
  ),
  '#required' => TRUE,
);

```

You need to pass values in associative array
> 2 votes

# Answer
You just build associative array for options.

```
'#options' => array('select'=>'select','Web Developer'=>'Web Developer','Web Designer'=>'Web Designer','SEO'=>'SEO','Marketing'=>'Marketing'),

```
> 1 votes

# Answer
As you haven't accepted the answer yet, i want to suggest another approach.. I don't know why but I don't like to declare select option keys as its values(may be the reason is keys are used for systems, values are for users, may be its fine to set them the same..).

Form submit function accepts to arguments - `$form, $form_state`, you know what `form_state` is for.. And `form` argument holds the full state of the form with its fields and their configs and so on.. My suggestion is to get form select option values by `$form` arguemnt (by this way you don't need to worry how keys will be declared..):

Here is an example:

```
...
$form['education'] = array(
'#title' => t('Education'),
'#type' => 'select',
'#description' => 'Select your higher education .',
'#options' => array(t('--- SELECT ---'), t('B.tech'), t('MCA'), t('MBA'),t('Graduate')),
'#required' => TRUE,
);
...

```

form submit function:

```
function form_test_form_submit($form, &$form_state) {
// we're getting the education select key
$educationKey = $form_state['values']['education'];

// here is the education select value
$educationValue = $form['education']['#options'][$educationKey];
...
}

```
> 1 votes

# Answer
A shorter way to create the associative array is with `drupal_map_assoc`

```
drupal_map_assoc(array(t('Value 1'), t('Value 2'), t('Value 3')))

```

e.g:

```
$form['education'] = array(
  '#title' => t('Education'),
  '#type' => 'select',
  '#description' => 'Select your higher education .',
  '#options' => drupal_map_assoc(array(t('--- SELECT ---'), t('B.tech'), t('MCA'), t('MBA'),t('Graduate'))),
  '#required' => TRUE,
);

```

The array keys will then match the values.

Watch the use of t() in the array keys though, as if translations exist the stored value will be the translated string. You may prefer to hard code a single language/string for the array keys instead.

e.g:

```
array('value_1' => t('Value 1'), 'value_2' => t('Value 2'), 'value_3' => t('Value 3'))

```
> 1 votes

---
Tags: 7, hooks
---


# Question
Title: javascript does not work after form load through ajax
I am using field collection module for showing some fields with add more option using ajax built in functionality of field collections. in my field collection I have added some javascript on some of the fields. As soon as I click add more button form loads well with ajax but javascript does not work please help.

# Answer
Make sure you're using `Drupal.behaviors` to add your javascript. The JS will be "re-attached" after the AJAX event as compared to say `$(document).ready` that will only run once on page load.

More info https://www.drupal.org/node/756722
> 2 votes

# Answer
Behavior handling has changed again in Drupal 7, with modules now required to explicitly define their attach handler, and optionally specify a detach handler.

```
(function ($) {
  Drupal.behaviors.exampleModule = {
    attach: function (context, settings) {
      $('.example', context).click(function () {
        $(this).next('ul').toggle('show');
      });
    }
  };
})(jQuery);

```
> 2 votes

---
Tags: ajax, javascript
---


# Question
Title: Cannot get JQuery plugin working on Drupal 7
I am trying to run a Jquery plugin QTip. The problem is that it is not running even though all the files are in the corect folders (plugin is both in info file and attched as a script below) and I took the code below from the plugin's website and pasted in the html section of WYSYWIG editor. Can anyone tell me why this is the case?

```
<script type="text/javascript" src="/sites/all/themes/bf/js/jquery.qtip.min.js"></script>
<script type="text/javascript">// <![CDATA[

// Create the tooltips only on document load
$(document).ready(function()
 {
// By suppling no content attribute, the library uses each elements title attribute by default
 $('#content a[href]').qtip({
  // Simply use an HTML img tag within the HTML string
  content: 'dfdfdfdfdf'
   });
});
// ]]></script>
<div id="content">
<a href="dddf.html">Why this not working</a>
</div>

```

# Answer
> 2 votes
From the Drupal 7 upgrade guide:

> Javascript should be made compatible with other libraries than jQuery by adding a small wrapper around your existing code:

```
(function ($) {
      // Original JavaScript code.
})(jQuery);

```

> The $ global will no longer refer to the jquery object. However, with this construction, the local variable $ will refer to jquery, allowing your code to access jQuery through $ anyway, while the code will not conflict with other libraries that use the $ global.

```
(function ($) {
  // Create the tooltips only on document load
  $(document).ready(function() {
    // By suppling no content attribute, the library uses each elements title attribute by default
    $('#content a[href]').qtip({
      // Simply use an HTML img tag within the HTML string
      content: 'dfdfdfdfdf'
    });
  });
})(jQuery);

```

# Answer
> 0 votes
By default Drupal 7 uses jQuery 1.4.4. the Qtip2 ( I assume you are using the latest Qtip) has a requirement of jQuery 1.6 and up. http://qtip2.com/guides

Install the jquery-update module https://www.drupal.org/project/jquery\_update and set the front-end to the required version level for Qtip and you should be ok.

---
Tags: 7, javascript
---


# Question
Title: What is the purpose of Master Display in Views module of Drupal 7? Why is it not present in every Drupal 7 installation?
I have been using Views on Drupal 7 a lot and I enjoy it every time. Great module. I have always noticed the existence of "Master" display while creating views but, never bothered about its existence until today when I noticed that there is no "Master" display in my another server running the same instance of Drupal 7 (same version of Views and Views UI modules)? The two servers differ only in OS, Apache, MySQ and PHP versions, shown as follow:

```
Core      : 7.31
Views     : 7.x-3.8
Views UI  : 7.x-3.8
PHP       : 5.3.3 and 5.4.16
Apache    : Apache/2.2.15 and Apache/2.4.6 (CentOS)
Database  : 5.1.73 (MySQL) and 5.5.37-MariaDB
Centos    : 6.5 & 7.0

```

I am a bit confused why "Master" display is not present in recent server but, is available in my other server even though both run same instance/version of Drupal 7? I would greatly appreciate if you could share your knowledge/understanding of "Master" display and its existence/use/purpose (in theory or practical examples if you got any).

# Answer
> 14 votes
To always see the Master Display you need to set the 'Always show the master display' setting at

```
admin/structure/views/settings

```

The Master Display is a convenience and time saver when you have a set of related displays (block, page, feed etc.). You create the master view and then all of the other displays are 'clones' of the master that you then customize individually. Also, when you revert a setting in an overridden display it will revert to that of the master. I also think that the master display is fully saved in the database, and for all the other displays on the same view only the overridden parts are saved, hence less storage.

The Master Display has no associated menu and is therefore good when you need a view but do not want to unnecessarily create a menu entry (ie page) or block or other views resource. It is typically used in this fashion when embedding a view in code, or by other modules that take a view as a parameter, ie Answers, and Views Field View.

---
Tags: views, 7
---


title: Rate module Thumbs Counter

text:
# Question
Title: Rate module Thumbs Counter
I've installed the Rate Module in order to add a simple thumbs up/down rating system on nodes. By default it displays the average percentage (see below) but all I want is to display a simple counter of up/down votes.

Any ideas?

# Answer
Copy the file:

```
rate-template-thumbs-up-down.tpl.php

```

that you find in the module rate/templates/thums-up-down to your theme's template folder.

Then change these two lines that print out the percentage:

```
<div class="percent"><?php print $results['up_percent'] . '%'; ?></div>
...
<div class="percent"><?php print $results['down_percent'] . '%'; ?></div>

```

to this:

```
<div class="percent"><?php print $results['up']; ?></div>
...
<div class="percent"><?php print $results['down']; ?></div>

```
> 3 votes

---
Tags: theming, rating
---


title: Overlay in Views not Working

text:
# Question
Title: Overlay in Views not Working
I am using Views 7.3.8 with Drupal 7.30. I use this combination for a total of 5 individual sites.

On 1 of my sites when I go into any view\>\>\> edit page and try to click on field/title or any link on the edit page, the overlay pops up with a blank screen and just sits there empty.

I have tried disabling along with several other things short of uninstall/reinstall.

Any ideas?

# Answer
> 2 votes
This error usually causes due to **Jquery version incompatibility**, try installing jquery\_update module and navigate to

`example.com/admin/config/development/jquery_update`

and choose jQuery version for administrative pages as **1.5 or 1.7**

---
Tags: views
---


# Question
Title: Why does entity_metadata_wrapper does not preserve node's custom URL while updating other fields?
I am programmatically loading a node of custom content type (i.e. staff) using entity\_metadata\_wrapper and add a reference to a collection of other nodes and then save the node.

The custom nodes (i.e. of type staff) has a custom a URL, set when the node was created (they are all created manually but, subject to being updated programmatically on regular basis). I also have pathauto module enabled but, I don't need it for this specific scenario.

entity\_metadata\_wrapper does load the node, assign the references and magically resets the node's custom URL to automatic. Any idea about this behaviour? Is there any way to preserve the custom URL?

Here is the code that loads the node, establish reference and saves the node :

```
      $node = node_load($staff_drupal_id);
      $wrapper = entity_metadata_wrapper('node', $node);
      $wrapper->field_staff_selected_publication->set($publication_ids);
      $wrapper->save();

```

# Answer
> 0 votes
In case someone else face the same issue, I come across the following

> Pathauto uses the following logic (listed by priority) to determine if the Pathauto checkbox should be checked when editing a node:
>
> If the node is a new node, it defaults to having an automatic alias. If the node is not a new node: If the node does not currently have an alias, it assumes that the node was manually un-aliased, so it will default to not have an automatic alias. If the node's current alias matches the alias that Pathauto would generate based on the pattern, then it will default to checked. Otherwise, the checkbox will default to be unchecked. If you are using the Pathauto persistent state module, then once you save a node, the checkbox will remain checked or unchecked regardless of the logic above until you check or uncheck it later.
>
> If you have content you've created before installing Pathauto that you would like to ensure that the checkbox is checked whenever you edit them, then you should use the 'Update URL alias' bulk action on your content listing admin page (admin/content/node).
>
> If you are saving changes to nodes automatically using node\_save, you need to specify $node-\>path\['pathauto'\] = FALSE; in Drupal 7 or $node-\>pathauto\_perform\_alias = FALSE; in Drupal 6 (see http://drupal.org/node/1179988) in order to stop pathauto overwriting any custom paths you might already have for the node.

In Drupal 6

```
$node->path['pathauto'] = FALSE;

```

in Drupal 7

```
$node->pathauto_perform_alias = FALSE;

```

---
Tags: nodes, entities
---


# Question
Title: How to get the commerce subscription status for current user on particular product page?
How can I get the product subscription status for current logged in user on particular product page. Suppose user can subscribe for a video tutorial and we have video as a product then how can we know that current user had already subscribed to this product or not.

# Answer
I'm actually in thought of adding comment to your question, but my reputation count made me convert my comment to answer. (Yes, I'm a beginner!)

**For your question:** You have multiple products in your page and there exists a distinct 'commerce sp time' per product. So, the process flow would be,

When an end user subscribes to a particular product:

1. Disable the subscribe button of that product (may be a video tutorial) and change its value to 'subscribed'.
2. Set a schedule for the user with respect to 'commerce sp time' of that product, to trigger a custom PHP code (probably, enabling the susbcription button of that product).

*All my concern is, Is this useful?* *I had already achieved this feat technically, so would you..*
> 0 votes

---
Tags: notifications, commerce
---


# Question
Title: To suppress this error, add the option --strict=0 Drush
My custom Drush commands use options(--ver,--env,etc). Whenever the option is used, I get message:

```
Unknown option: --ver.  See `drush help build-asset` for available options. To suppress this error, add the option --strict=0.

```

By adding --strict=0, it will suppress the message, however. how to make the custom Drush commands run with --strict=0 automatically or what needs to be done to avoid this all together. Thank you for helping

# Answer
> 3 votes
The fact that Drush is telling you that the options you are using on the commandline are not supported by your command is a feature. This protects you from having the wrong thing happen if you mistype an option name; it is not a good idea to subvert this feature, because that leaves you open to confusion when you do make a typo.

To declare which options your command uses, define the 'options' element, and list all of the options that are applicable for your command. For instructions, see drush topic docs-examplecommand.

For your command, your options should look something like this:

```
'options' => array(
  'ver' => array(
    'description' => 'Specify a version number.',
  ),
  'env' => array(
    'description' => 'Describe your environment.',
  ),
),

```

You might find the drushify command to be useful in starting you off when creating a Drush commandfile. It will make a nice template for your command that you can edit to suit; the command options is one thing that is roughed in for you. Just delete the parts of the generated code that you don't need, fill in your implementation and command help, and you're good to go.

# Answer
> 3 votes
There's enough situations where I need to do that that I have just defined an alias in my startup file.

`alias drush='drush --strict=0'`

This is in my .zshrc file (or put in your .bashrc file if using bash).

---
Tags: drush
---


title: Add additional values to a view result

text:
# Question
Title: Add additional values to a view result
I try to accomplish following task:
I have a view with all products that were ordered during certain period of time (based on invoice creation time). (view is of type of order) I am using sql agregation and table display.
I have 3 products: apple, orange, banana

Problem: If orange was not ordered, it is not shown in results like this (and I understand that is because I work with ubercart order which contains only ordered products)

```
apple 3
banana 2

```

What I need, is to show 0 value for products that were not ordered as well:

```
apple 3
banana 2
orange 0

```

How is this possible to solve? Maybe add values to view result? Thank you for help.

EDIT: it is not possible to create the view using relationships other way around (create view type of node and use relationship to order) as suggested by @ J. Reynolds, because I use invoice date for filtering ordered products and it is not possible to get to invoice data (probably because invoice data are in different table)
I also tried combining 2 results together using solution here https://www.drupal.org/node/1013774#comment-4547362 but it seems that it is working only if both views are same of same type. (I just simply can not create a view of type ubercart order product or ubercart order and display products that were not ordered.)

EDIT: After reviewing 2 answers (by @routh and @viktor.likin) I think both are wrong. The problem is that the table I use to get ordered products amounts (uc\_order\_products) simply does NOT contain products that were not ordered. It contains ONLY orders that were ordered. Logically I am not able to show all products in my table.

Generated queryfollowed by exported view

```
SELECT uc_orders.order_id AS order_id,
   uc_order_products.model AS uc_order_products_model,
   uc_orders.uid AS uc_orders_uid,
   uc_order_products.title AS uc_order_products_title,
   SUM(uc_order_products.qty) AS uc_order_products_qty
 FROM uc_orders uc_orders
 LEFT JOIN uc_invoice uc_invoice ON uc_orders.order_id = uc_invoice.order_id
 LEFT JOIN uc_order_products uc_order_products ON uc_orders.order_id = uc_order_products.order_id
 WHERE (uc_invoice.created >= 1396303200) AND (uc_invoice.created <= 1398895199) AND (uc_orders.order_status not in ('canceled', 'canceled1'))
 GROUP BY uc_order_products_title
  ORDER BY uc_order_products_model ASC

```

Exported view:

```
$view = new view;
$view->name = 'testsumuuu';
$view->description = '';
$view->tag = '';
$view->base_table = 'uc_orders';
$view->core = 6;
$view->api_version = '2';
$view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */
$handler = $view->new_display('default', 'Defaults', 'default');
$handler->override_option('fields', array(
  'model' => array(
    'label' => 'SKU',
    'alter' => array(
      'alter_text' => 0,
      'text' => '',
      'make_link' => 0,
      'path' => '',
      'absolute' => 0,
      'link_class' => '',
      'alt' => '',
      'rel' => '',
      'prefix' => '',
      'suffix' => '',
      'target' => '',
      'help' => '',
      'trim' => 0,
      'max_length' => '',
      'word_boundary' => 1,
      'ellipsis' => 1,
      'html' => 0,
      'strip_tags' => 0,
    ),
    'empty' => '',
    'hide_empty' => 0,
    'empty_zero' => 0,
    'hide_alter_empty' => 1,
    'exclude' => 0,
    'id' => 'model',
    'table' => 'uc_order_products',
    'field' => 'model',
    'relationship' => 'none',
  ),
  'order_id' => array(
    'label' => 'Order ID',
    'alter' => array(
      'alter_text' => 0,
      'text' => '',
      'make_link' => 0,
      'path' => '',
      'absolute' => 0,
      'link_class' => '',
      'alt' => '',
      'rel' => '',
      'prefix' => '',
      'suffix' => '',
      'target' => '',
      'help' => '',
      'trim' => 0,
      'max_length' => '',
      'word_boundary' => 1,
      'ellipsis' => 1,
      'html' => 0,
      'strip_tags' => 0,
    ),
    'empty' => '',
    'hide_empty' => 0,
    'empty_zero' => 0,
    'hide_alter_empty' => 1,
    'link_to_order' => 0,
    'exclude' => 1,
    'id' => 'order_id',
    'table' => 'uc_orders',
    'field' => 'order_id',
    'relationship' => 'none',
  ),
  'title' => array(
    'label' => 'Title',
    'alter' => array(
      'alter_text' => 0,
      'text' => '',
      'make_link' => 0,
      'path' => '',
      'absolute' => 0,
      'link_class' => '',
      'alt' => '',
      'rel' => '',
      'prefix' => '',
      'suffix' => '',
      'target' => '',
      'help' => '',
      'trim' => 0,
      'max_length' => '',
      'word_boundary' => 1,
      'ellipsis' => 1,
      'html' => 0,
      'strip_tags' => 0,
    ),
    'empty' => '',
    'hide_empty' => 0,
    'empty_zero' => 0,
    'hide_alter_empty' => 1,
    'exclude' => 0,
    'id' => 'title',
    'table' => 'uc_order_products',
    'field' => 'title',
    'relationship' => 'none',
  ),
  'qty' => array(
    'label' => '',
    'alter' => array(
      'alter_text' => 0,
      'text' => '',
      'make_link' => 0,
      'path' => '',
      'absolute' => 0,
      'link_class' => '',
      'alt' => '',
      'rel' => '',
      'prefix' => '',
      'suffix' => '',
      'target' => '',
      'help' => '',
      'trim' => 0,
      'max_length' => '',
      'word_boundary' => 1,
      'ellipsis' => 1,
      'html' => 0,
      'strip_tags' => 0,
    ),
    'empty' => '',
    'hide_empty' => 0,
    'empty_zero' => 0,
    'hide_alter_empty' => 1,
    'exclude' => 0,
    'id' => 'qty',
    'table' => 'uc_order_products',
    'field' => 'qty',
    'relationship' => 'none',
  ),
  'views_sql_groupedfields' => array(
    'label' => 'Group By Fields',
    'alter' => array(
      'alter_text' => FALSE,
      'text' => '',
      'make_link' => FALSE,
      'path' => '',
      'absolute' => '',
      'alt' => '',
      'rel' => '',
      'link_class' => '',
      'prefix' => '',
      'suffix' => '',
      'target' => '',
      'trim' => FALSE,
      'max_length' => '',
      'word_boundary' => TRUE,
      'ellipsis' => TRUE,
      'strip_tags' => FALSE,
      'html' => FALSE,
    ),
    'empty' => '',
    'hide_empty' => 0,
    'empty_zero' => 0,
    'hide_alter_empty' => 1,
    'exclude' => '1',
    'id' => 'views_sql_groupedfields',
    'table' => 'views_groupby',
    'field' => 'views_sql_groupedfields',
    'relationship' => 'none',
    'views_groupby_fields_to_group' => array(
      'title' => 'title',
    ),
    'views_groupby_sql_function' => 'sum',
    'views_groupby_fields_to_aggregate' => array(
      'qty' => 'qty',
    ),
    'views_groupby_field_sortby' => 'model',
    'views_groupby_sortby_direction' => 'asc',
  ),
));
$handler->override_option('filters', array(
  'created' => array(
    'operator' => 'between',
    'value' => array(
      'type' => 'date',
      'value' => '',
      'min' => '2014-04-01 00:00:00',
      'max' => '2014-04-30 23:59:59',
    ),
    'group' => '0',
    'exposed' => TRUE,
    'expose' => array(
      'use_operator' => 0,
      'operator' => 'created_op',
      'identifier' => 'created',
      'label' => 'Ubercart invoice number: Invoice date',
      'optional' => 1,
      'remember' => 0,
    ),
    'id' => 'created',
    'table' => 'uc_invoice',
    'field' => 'created',
    'relationship' => 'none',
    'override' => array(
      'button' => 'Override',
    ),
  ),
  'order_status' => array(
    'operator' => 'not in',
    'value' => array(
      'canceled' => 'canceled',
      'canceled1' => 'canceled1',
    ),
    'group' => '0',
    'exposed' => FALSE,
    'expose' => array(
      'operator' => FALSE,
      'label' => '',
    ),
    'id' => 'order_status',
    'table' => 'uc_orders',
    'field' => 'order_status',
    'relationship' => 'none',
  ),
));
$handler->override_option('access', array(
  'type' => 'none',
));
$handler->override_option('cache', array(
  'type' => 'none',
));
$handler->override_option('use_ajax', TRUE);
$handler->override_option('items_per_page', 0);
$handler->override_option('style_plugin', 'sheet');
$handler->override_option('style_options', array(
  'grouping' => '',
  'expansion' => '0',
  'template' => 0,
  'sheetsave' => 'socialcalc:version:1.0
MIME-Version: 1.0
Content-Type: multipart/mixed; boundary=SocialCalcSpreadsheetControlSave
--SocialCalcSpreadsheetControlSave
Content-type: text/plain; charset=UTF-8

# SocialCalc Spreadsheet Control Save
version:1.0
part:sheet
part:edit
part:audit
--SocialCalcSpreadsheetControlSave
Content-type: text/plain; charset=UTF-8

version:1.5
sheet:c:1:r:1
--SocialCalcSpreadsheetControlSave
Content-type: text/plain; charset=UTF-8

version:1.0
rowpane:0:1:36
colpane:0:1:8
ecell:A1
sort::-1:up::::
--SocialCalcSpreadsheetControlSave
Content-type: text/plain; charset=UTF-8

--SocialCalcSpreadsheetControlSave--
',
));
$handler->override_option('exposed_block', TRUE);
$handler = $view->new_display('block', 'Block', 'block_1');
$handler->override_option('block_description', '');
$handler->override_option('block_caching', -1);

```

# Answer
You can handle this with a custom view installed with a custom site module under `/sites/default/modules`

After reviewing the Ubercart code, it seems that the views have a hard coded exclusion in them to remove items with NULL value orders. The views use the Drupal filter views\_handler\_filter\_numeric to remove items with less than 1 order.

From uc\_views.views.inc:

```
$data['uc_order_products']['order_product_id'] = array(
'title' => t('Order product ID'),
'help' => $order_products['fields']['order_product_id']['description'],
'field' => array(
  'handler' => 'views_handler_field',
  'click sortable' => TRUE,
),
'sort' => array(
  'handler' => 'views_handler_sort',
),
'filter' => array(
  'handler' => 'views_handler_filter_numeric',
),
'argument' => array(
  'handler' => 'views_handler_argument_numeric',
  'name field' => 'title',
  'numeric' => TRUE,
  'validate type' => 'order_product_id',
),
);

```

From the Drupal docs:

```
Simple filter to handle greater than/less than filters

```

https://api.drupal.org/api/views/handlers!views\_handler\_filter\_numeric.inc/class/views\_handler\_filter\_numeric/7

My approach would be to copy the existing view into a custom module, and alter this behavior programatically. Addtionally exporting your views to a custom module as .inc files is recommended, as it speeds up loading of views by PHP. It's a win/win.

To get you started, here's a tutorial on how to export your existing view to a .inc file:

http://websmiths.co/blog/drupal-views-tutorials-exporting-views-code

Once you've done that, just edit the code to make your changes.
> 0 votes

# Answer
It seems that while an aggregation process **INNER JOIN** is used so it misses if a order does not exist. The query should user **OUTER JOIN** left or right to not miss products if an order does not exist. I looked over settings I did not find. I guess it should use OUTER JOIN by default. I ask you to show us what query the views generates. Show us the aggregation settings.
> 0 votes

# Answer
IF what you want is only to show results you can solve it rewriting the view's template at some level.

My approach will be to read the IDs of the ordered products (from template), then launch at the end of the report a sub-view with the IDs of the ordered products excluded as argument.

Match elements theming and you are done.

Not elegant but effective.
> 0 votes

---
Tags: views, 6, ubercart
---


# Question
Title: Commerce - Require login only for specific products
I'm building a commerce site using drupal commerce. I know how to have anonymous users checkout, I know how to require login before checkout, but I can't figure out how to specify for each product if it requires a login or not...

# Answer
> 1 votes
You could use Rules to enforce login when the product is added to the cart.

e.g

* Event: Before/After adding product to cart
* Conditions: if user is not logged in (i.e. uid=0) and product match (e.g SKU matches)
* Action: Redirect to user/login?destination=cart

Something like that could suffice.

# Answer
> 0 votes
You could add some special field to flag this. After you can use rules to force some users to log in.

---
Tags: 7, commerce
---


# Question
Title: Creating Drupal nodes from Javascript (Drupal 7)
We have a page inside our Drupal site that contains two canvases (one webGL). When the user presses the save button, we create a dataURL (about 300kb) and would like to send this png to drupal (from Javascript) to create a Drupal node. What would be the best way to accomplish this?

# Answer
> 3 votes
Here's a few things you can try. Your scenario may require customizations or other workarounds.

First, make a content type with an image field.
Second, in hook\_menu, register a path and callback and post the image with ajax. You will have to post your image data on this url.

```
function MODULE_menu(){
   $item['path/to/post/node/data'] = array(
       'page callback' => 'your_callback',
       'access arguments' => array('create <type> content'),
   );
}

```

Then, setup you callback as

```
function your_callback(){
    // Storing image data to file
    $success = file_put_contents($file_path,  base64_decode($_POST['image_data']));
    // Creating node
    if($success){
      $node = new stdClass();
      $node->type = '<type>';
      node_object_prepare($node);
      $node->title    = 'Node Created Programmatically on ' . date('c');
      $node->language = LANGUAGE_NONE;

      $file_realpath = drupal_realpath($file_path);
      $file = (object) array(
        'uid' => 1,
        'uri' => $file_realpath,
        'filemime' => file_get_mimetype($file_realpath),
        'status' => 1,
      );
      $file = file_copy($file, 'public://');
      // field_image is assumed as the machinename of your image field.
      $node->field_image[$node->language][0] = (array)$file;

      node_save($node);

      drupal_json_output(array('status' => 'OK', 'message' => 'New image node content is created'));
    }else{
      drupal_json_output(array('status' => 'FAILURE', 'message' => 'There is some issue in order to create new image node.'));
    }

}

```

# Answer
> 0 votes
Instead of snippets, use a more complete Drupal javascript framework such as

---
Tags: 7, javascript
---


# Question
Title: View with multiple value fields: suppress display of repeated column values
My content type has two fields: field\_title and field\_related. The field\_related is of type Entity Reference and its cardinality is set to unlimited.

The view should display the title, updated date and all related titles, in tabular form, like this:

```
Title          Updated      Related
=====================================
Chapter 1      2014-01-01   Note A
                            Note B
                            Note C
Chapter 2      2014-02-02   Note A
                            Note B

```

Currently, it is displaying this:

```
Title          Updated      Related
=====================================
Chapter 1      2014-01-01   Note A
Chapter 1      2014-01-01   Note B
Chapter 1      2014-01-01   Note C
Chapter 2      2014-02-02   Note A
Chapter 2      2014-01-01   Note B

```

I tried grouping, but it divided the whole table into separate tables.

I see no point here in using aggregation here (maybe I am wrong..)

What is the solution to this?

# Answer
> 0 votes
The answer was obvious. For the Entity Reference type of field, don't use fields from the referenced entity (like e.g. "Title") from a relationship. Instead, use the field from the main entity (without relationship). As a result, it displays a title of the referenced entity anyway and not an ID or something.

But in this case, the field gets "Multiple Field Settings" config group, which should be set to "Display all values in the same row". I saw that solution before, but in my view there wasn't this config group at all. That's because I used a field from relationship, which apparently doesn't have a setting for multiple value, because in that entity it's single value, it's a title.

---
Tags: 7, views
---


# Question
Title: allowed values for node/entity/user reference field
Can you get allowed values for reference field?

i tried with:

```
$all_fields_info = field_info_fields();
$allowed_values= list_allowed_values($all_fields_info["field_user_ref"]);

```

but it is not working ..

# Answer
> 1 votes
For an entityreference fields use:

```
$allowed_values = entityreference_get_selection_handler("field_user_ref")->getReferencableEntities();

```

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


# Question
Title: how to associate multiple nodes with one node
I have a content type "events" and all the node created under this content type will have further node.

The red boxes in the above pictures are node links which are associated to the "event node".

Every node created under "Event Content Type" will have relative information nodes as shown in boxes below.

How i should be doing this association? Should i create content types for all red boxes and then make entity/node references ?

any clue? thanks

# Answer
> 1 votes
I recommend that you model this from an object oriented perspective. I would create the following content types:

1. Event content type (composed of event, overview, agenda, live broadcast maybe)
2. Speakers
3. Resources
4. Venue
5. Sponsorship
6. Registration

The reason for embedding overview, agenda and live broadcast to the event is because they are closely related to to specific event and creating separate content type for them would be expensive (because there is a very less probability that two event have the same agenda or overview).

Whereas other content types such as Speakers, Resources, Venue, Sponsorship, Registration can be regarded as separate content types, because:

1. To allow referencing the same content type by multiple event nodes i.e. for example, you will have a speaker who would speak in several events, or a resource that would be useful in several events hence, you will be avoid loads of duplication/inconsistency etc.
2. The other reason to create separate content type is to achieve low coupling and high cohesion. Speakers are different than events, the best way would be to reference than to embed a a list of speaker into event content type. Fields of a Speaker content type, does not directly relate to an Event (i.e. Database normalization perspective)

This would give you a clean set of content types that are linked with each other using references and can be queries very easily using views, contextual filters and relationship.

Good luck.

# Answer
> 0 votes
You could create separate content types and use a custom module to handle the node/entity reference links, but for a smoother more self-contained approach, I might suggest:

* use a single content type that contains all of the information for all of the sub-nodes
* use a bit of jquery to handle showing/hiding certain elements on the screen

One drawback to this approach is the amount of work required when add/removing fields since the javascript would also need to be changed, but it would allow for a single page load instead of multiple page loads for a single "event", and keeps all the data in one place.

---
Tags: nodes
---