# Question
Title: Is this SQL query even possible in Drupal 7?
I'm trying to find a way to run this query in a custom drush command to dump chunks of data from the DB into CVS files.

The query works fine directly in the terminal but I was wondering how would you do it in code for Drupal 7? I guess I can transform a PHP array to a CVS file but wanted to know if Drupal has a way to write more complex queries like this :)

Big thanks in advance!

Query:

```
SELECT uid, name, mail INTO OUTFILE '/path/sqldumps/result.csv'
FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"'
ESCAPED BY '\\'
LINES TERMINATED BY '\n'
FROM users
WHERE uid != 0

```

# Answer
> 0 votes
Drupal has it's own abstraction layer to work with database , this method helps Drupal to work with different kind of databases like PgSQL or even oracle (just a database driver will handle everything).

You can get familiar with this api in : Drupal Database API

A more exclusive reference could be : Drupal Dynamic Queries

---
Tags: database
---


title: Entity Reference Image not rendered

text:
# Question
Title: Entity Reference Image not rendered
I have a content type with an Entity Reference field. The field references multiple images.

Using Display Suite, I can set the display format to "entity id" and when I view the content, I get a list of IDs as expected. But when I change it to "Rendered Entity", I'd expect the rendered images, but nothing is actually rendered. This is not a CSS-issue, the rendered field has no actual HTML in it. Any ideas?

# Answer
> 0 votes
You need to check the "manage display" section of the entity you're rendering and make sure the images are set as visible items in the selected "entity view mode". By default it takes "default".

---
Tags: media, entities
---


# Question
Title: Switch site language after IP to locale redirect
I have a Multilingual Drupal 7 website. using i18. I redirect my visitors based on IP address with IP to locale module. Now e.g. visitors from Holland (Dutch IP) are redirected to http://landberg.at/nl

But now I am not able to select another language, with my language switcher? E.g an English person who lives in Holland must be able to switch to the English version. http://landberg.at/en

How do I have to achieve this? Is this anyway possible with language redirect based on IP?

(currently on my site I switched IP 2 locale OFF)

# Answer
You have tried Language Switcher module but you are not getting any result. Once try to use Language Switcher Dropdown module.

> Language Switcher Dropdown is a very simple module that exposes a new block, similar to the default Language Switcher block provided by Locale module. The new block allows site visitors to switch languages using a drop-down select list instead of using hyperlinks.
> 0 votes

# Answer
# Consider a special patch

Your issue seems fairly similar to what is described in Patch for language switcher to override ip2locale. It is for D6 though (not sure what this question is for D6 or D7 ... I think D7). Not sure if you want to consider exprimenting with the patch attached to it (attention: status of the issue is "needs review").

# Check language detection

It seems to me that you should check your configuration at Configuration -\> Languages -\> detection and selection: the order specified there could be what explains the current behaviour in your site.

You'd have to experiment a bit with what the exact order in your case should be. In my experience, I often get these kind of issues to work by using an order like 'URL, Default, User', and not something like 'Default, URL, User'. It could well be that that is all that's needed here ... So try to experiment a bit with the various combinations in this order to see if it helps.

Curious to hear what the result of checking this will be ...
> 0 votes

---
Tags: i18n-l10n, redirection
---


title: How to customize the <title> tag

text:
# Question
Title: How to customize the <title> tag
I have downloaded nexus free theme and I want to change the title in all pages of my site.

Is there a way to do it editing the template.php?

thanks...

# Answer
If you using D7 and not D8, take a look at page\_title module. I just googled it for you.

> The word "title" is a bit overloaded. Every piece of content in Drupal has a title, and so does every page. The page title is the one found in the HTML head inside the tag. It is also used on SERPs (Search Engine Result Pages) and can greatly enhance your websites SEO (Search Engine Optimization).
>
> This module gives you granular control over the page title. You can specify patterns for how the title should be structured and, on content creation pages, specify the page title separately to the content's title.
> 3 votes

---
Tags: theming
---


# Question
Title: Filter out nodes with the same title in views
I have an event system which uses the date repeat entity to clone repeating events and another section which uses the similar by terms module to create a view of events related to the article.

However I want to filter out the repeating events, is there a way of adding a condition that if the titles match then ignore them?

# Answer
Consider looking at the Views Distinct module to do this ... Here are some details about this module (from its project page):

> Relationships or other joins in Views often create "duplicate" results. For example, a node with a field that has multiple values may show up in the View once per value in the multi-value field. It's frustrating, and the "DISTINCT" SQL query option in the Views UI does not actually solve the problem because the result row is technically distinct. This module aims to give a simple GUI method to remove or aggregate these "duplicate" rows.
>
> For any given field, including "Global: Text" fields, you can optionally mark the field as filtered ("Filter Repeats") or aggregated ("Aggregate Repeats"). All rows with the same value in that field will either be removed as duplicates (filtered), or aggregated in-line.
>
> The "value" of the field as used for filtering or aggregation can be taken pre-render (fastest and totally cacheable), or post-render (after any rewrite rules or other transformations have occurred). Post-render actions are a bit slower (the View must be re-rendered, though the query is not re-run), but also work with Global fields, like Global: Text w/rewrite rules.

If this doesn't work for you, or for some reason you cannot / do not want to use this module, then consider any of the alteratives suggested by Sumit Madan ... (+1 !).
> 1 votes

# Answer
There are three ways I can think of to do this :

1. By using hook\_views\_query\_alter, which I can say would be the best option.
2. Write custom code in template/module wherever it suits you, just views\_embed\_view and pass arguments programmatically.
3. **The Bad but Quick Way :** Use php filter in view's contextual filter. I would suggest not to go this way.

Use one of these ways only if answer by **Pierre.Vriens** doesn't work for you. :)
> 1 votes

---
Tags: views
---


# Question
Title: Webform: request submitted values in all page breaks
I have multiple page breaks in a webform. Can I get all the values submitted in all previous page break? Actually I can get only the values for one previous page break(the last one submitted).

For example if i'm in the page break 4 only can request the values submitted in page break 3 not in all the previous (2 and 1). The other values are not present.

I'm using the hook\_form\_alter.

Getting the info from $form\_state\["input"\]\["submitted"\]

```
    function custom_module_form_alter(&$form, &$form_state, $form_id) {
      if(substr($form_id,0,20 ) == 'webform_client_form_') {
        dsm($form_state["input"]["submitted"]);
        //Only info from one page break(previous)
      }
    }

```

# Answer
You can retrieve submitted values across all pages from `$form_state['storage']['submitted']`.

Note that this represents values from *past* pages and not the current page. Here is the code I use to get them all (past & current) page values into a single array:

```
$values = _webform_client_form_submit_flatten($node, $form_state['values']['submitted']);
$values += $form_state['storage']['submitted'];

```
> 0 votes

---
Tags: webforms
---


# Question
Title: "Illegal choice full_html in Text format element" when submitting form programatically
Im trying to create a block programatically. I have created a function, which does the work for me.

```
function _create_footer_contact() {

  form_load_include($form_state, 'inc', 'block', 'block.admin');

  $form_state = array();
  $form_state['values'] = array(
    'machine_name' => 'footer_contact',
    'title' => 'TITLE',
    'info' => 'INFO',
    'body' => array(
      'value' => 'BODY TEXT',
      'format' => 'full_html',
    ),
    'regions' => array(
      'mytheme' => 'footer',
      'myadmintheme' => '-1',
    ),
    'visibility' => '0',
    'pages' => NULL,
    'custom' => '0'
  );

  drupal_form_submit('block_add_block_form', $form_state);
}

```

The problem is the 'format' value, which throws an error if it is set to anything but 'plain\_text' (if format is set to 'plain\_text' the form submits nicely and a block is created).

```
WD form: Illegal choice full_html in Text format element.
An illegal choice has been detected. Please contact the site administrator.

```

To debug I have tried to examine the $form\_state of 'block\_add\_block\_form' using hook\_form\_alter and dpm(). When I manually submit a block the 'format' is set to 'full\_html'.

So... how do I submit a form programatically with full\_html set as format?

# Answer
You can try this.It works i think so

```
$form['formItem'] = array(
     '#type'=>'text_format',
     '#title' => t('Field Label'),
     '#value' => 'This is my value',
     '#format'=>'full_html',
);

```
> 0 votes

---
Tags: forms
---


title: Updating user fields in Drupal 7

text:
# Question
Title: Updating user fields in Drupal 7
I have created several custom fields for my Drupal 7 users, which I imported from an external users table.

I am now trying to automate the population of these custom fields using a custom module, however my code is not working. The following code is what I have been working with:

```
<?php

function get_sage_fields($username) {

  // Get the extra fields for Sage users
  $sage_fields = db_query('SELECT OFFICE_ID, TRADE_STATUS, DESIGNATION,
    FIRST_NAME, LAST_NAME, PHONE_NUMBER, MAILING_ADDRESS, ACCOUNT_PREFIX,
    ALLOW_TO_TRADE FROM USER WHERE USER_ID = $username');
  return $sage_fields;
}

function sage_fields_user() {

  // Grab all usernames from the users table
  $usernames = db_query('SELECT name FROM users')->fetchCol();

  // Load the users
  $users = user_load_multiple($usernames);

  // Loop through and edit each user
  foreach($users as $user) {

    // Load the extra data
    $extra_data = get_sage_fields($user->name);

    // Update user fields
    $user->field_office_id[$user->language][0]['value'] = $extra_data['office_id'];
    $user->field_trade_status[$user->language][0]['value'] = $extra_data['trade_status'];
    $user->field_designation[$user->language][0]['value'] = $extra_data['designation'];
    $user->field_first_name[$user->language][0]['value'] = $extra_data['first_name'];
    $user->field_last_name[$user->language][0]['value'] = $extra_data['last_name'];
    $user->field_phone_number[$user->language][0]['value'] = $extra_data['phone_number'];
    $user->field_mailing_address[$user->language][0]['value'] = $extra_data['mailing_address'];
    $user->field_allow_to_trade[$user->language][0]['value'] = $extra_data['allow_to_trade'];

    // Save the user object
    user_save($user);
  }
}

```

I enabled my custom module under admin/modules and included it in my .info file with:

`files[] = sage_fields.module`

However, if I go to `field_revision_[FIELD_NAME]` in my D7 database, I do not see these fields populated.

Could someone please point out where I have gone wrong?

# Answer
So Simple. just paste it

```
$user_fields = user_load($user->uid);
$user_fields->field_points['und'][0]['value'] = $points;
user_save($user_fields);

```
> 5 votes

# Answer
There's a couple of things...

Firstly the argument you're passing to `db_query()` (`$username`) is a string so needs to be wrapped in quotes in the query. The database layer actually allows you to pass in parameters, which is safer (as it protects against SQL injection), and means you don't need to worry about this:

```
$args = array(':username' => $username);
$query = db_query('SELECT OFFICE_ID, TRADE_STATUS, DESIGNATION,
          FIRST_NAME, LAST_NAME, PHONE_NUMBER, MAILING_ADDRESS, ACCOUNT_PREFIX,
          ALLOW_TO_TRADE FROM USER WHERE USER_ID = :username', $args);

```

The second thing is that you need to actually convert the result from `db_query()` to something useable in the calling function. In your case you want a single object from the query, so you would user the `fetchObject()` method:

```
return $query->fetchObject();

```

If you change your `get_sage_fields()` function to look more like the above code you'll probably have a bit better luck :)

**EDIT**

Just to clarify, the finished code would look something like this:

```
function sage_fields_menu() {
  $items['user-data-import'] = array(
    'title' => 'User Data Import',
    'access arguments' => array('access administration pages'), // Or whatever permission you want to use
    'page callback' => 'sage_fields_import_user_data',
    'type' => MENU_CALLBACK
  );

  return $items;
}

function get_sage_fields($username) {
  // Get the extra fields for Sage users
  $args = array(':username' => $username);
  $sage_fields = db_query('SELECT OFFICE_ID, TRADE_STATUS, DESIGNATION,
    FIRST_NAME, LAST_NAME, PHONE_NUMBER, MAILING_ADDRESS, ACCOUNT_PREFIX,
    ALLOW_TO_TRADE FROM USER WHERE USER_ID = :username', $args);
  return $sage_fields->fetchObject();
}

// Don't call this function sage_fields_user as that will be an implementation
// of hook_user() and will cause you problems.
function sage_fields_import_user_data() {
  // Set

  // Grab all user ids from the users table
  // You need the ids to load the user objects in user_load_multiple
  $uids = db_query('SELECT uid FROM users')->fetchCol();

  // Load the users
  $users = user_load_multiple($uids);

  // Loop through and edit each user
  foreach($users as $user) {

    // Load the extra data
    $extra_data = get_sage_fields($user->name);

    // Update user fields
    $user->field_office_id[$user->language][0]['value'] = $extra_data['office_id'];
    $user->field_trade_status[$user->language][0]['value'] = $extra_data['trade_status'];
    $user->field_designation[$user->language][0]['value'] = $extra_data['designation'];
    $user->field_first_name[$user->language][0]['value'] = $extra_data['first_name'];
    $user->field_last_name[$user->language][0]['value'] = $extra_data['last_name'];
    $user->field_phone_number[$user->language][0]['value'] = $extra_data['phone_number'];
    $user->field_mailing_address[$user->language][0]['value'] = $extra_data['mailing_address'];
    $user->field_allow_to_trade[$user->language][0]['value'] = $extra_data['allow_to_trade'];

    // Save the user object
    user_save($user);
  }

  return 'Done';
}

```

I've added a menu hook after you've cleared Drupal's cache you just need to go to http://mysite.com/user-data-import and it will start the process. The above code is based on your module being called `sage_fields`, you'll need to change that in the `hook_menu()` function if it's called something else.

As I mentioned in your other question running this for 8500+ users in one go will probably time out the server; you'll probably want to run this import in batches.
> 1 votes

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


title: entity_load based on language selection

text:
# Question
Title: entity_load based on language selection
I have a node for different language, but I would like to load node for "en" language only using `entity_load` after firing entity query.

How can I achieve it using this function in Drupal 7

# Answer
> 0 votes
Try to install i18n module then you should be able to create a new content type for this node and set the language to EN under the "Multilingual Settings" tab.

---
Tags: 7, nodes, database
---


# Question
Title: How to programatically update existing user profile field in drupal 7
We are using Drupal 7 and the Profile2 module.

We create and add a value to a field in the profile using this code:

```
$profile = profile_create(array('type' => 'main', 'uid' => $account->uid));
$lang = LANGUAGE_NONE;
$profile->field_headline[$lang][0]['value'] = 'Software Engg';
profile2_save($profile);

```

How can we programtically update the user profile field 'field\_headline'?

Please advice us.

# Answer
You just need to load the user using drupal function

```
profile2_load_by_user($account->uid, $type_name = NULL)

```

`$account->uid` =\> user id

`$type_name` =\> one of the profile types of profile 2 if any otherwise NULL

```
   $profile =  profile2_load_by_user($account, $type_name = NULL)
   $profile->field_headline[$lang][0]['value'] = 'update Software Engg';
   profile2_save($profile);

```

For more information Click Here

Hope it will work for you!
> 6 votes

# Answer
Update specific value of user

```
$user_fields = user_load($user->uid);
$user_fields->field_points['und'][0]['value'] = $points;

user_save($user_fields);

```
> 0 votes

---
Tags: 7, users, updating
---


# Question
Title: Field collection 'add more' and 'remove' hooks?
I am currently working on a project where i have a content type that has 2 field collections. (with cardinality 1) Each field collection has one other field collection (with unlimited cardinality).

To summarize:

Content type X

* Field collection 1
    + Some fields
    + Field collection A (unlimited cardinality)
* Field collection 2
    + Some fields
    + Field collection B (unlimited cardinality)

Now,

I want field collection A and B to respond to each others "add item" and "remove" actions. So that when you add an item to field collection A, automatically an item to field collection B is added as well and vice versa.

Are there any hooks available for this?

I have been doing some research but there is very little documentation about this that i can find.

Thanks so much in advance!

# Answer
I managed to solve this with some jQuery.

Not sure if this is the "cleanest" way to do this, but it works. I hook into the mousedown() event of the "add another item" button,and trigger the other button's mousedown manually.

I also added a delay of 800ms, because of some conflicting events if the 2 mousedowns are too quickly after eachother.

Hope this helps anyone in the future.

```
$('#edit-field-pressure-calculation-und-0-field-pressure-calculation-line .clearfix .field-add-more-submit').mousedown(function() {
    setTimeout(function() {
      $('#edit-field-heat-calculation-und-0-field-heating-calculation-line .clearfix .field-add-more-submit').mousedown();
    }, 800)

  });

```
> 0 votes

---
Tags: hooks, nodes, entities
---


# Question
Title: How to use 'session' to check path history of user
I want to keep a track of the pages user visited, I got to know i can do this with the help of session and hook\_node\_view. Being a beginner, i couldn't find any particular help on using session API, can anyone help?

# Answer
> 0 votes
if you just want to track user visiting there are some modules ready for that like user visits .

or if you want to do something and need to write a module for that then hook\_node\_view will fire when user is viewing a node . you can implement it like below :

```
function YOURMODULENAME_node_view($node, $view_mode, $langcode)
{
   global $user; //user data is here
}

```

now you can do what you want with user.

---
Tags: sessions
---


title: Node Teaser template in custom module

text:
# Question
Title: Node Teaser template in custom module
I have used given below code for node--\[content\_type\].tpl.php (default) template file

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

```

but I don't know how to call my node--\[content\_type\]--\[view\_mode\].tpl.php

Please suggest.

# Answer
> 1 votes
You can use node--\[content\_type\].tpl.php for changing the output for view mode.

```
if ($teaser) {
  // node is being displayed as a teaser

} else {
  //all other cases
}

```

# Answer
> 0 votes
in your theme template.php on function THEME\_NAME\_preprocess\_node(&$variables) put the

```
$variables['theme_hook_suggestions'][] = 'node__' . $variables['type'] . '__' . $variables['view_mode'];

```

then on the theme copy node.tpl.php to node--article--full.tpl.php (for example) and edit as you want.

Now, you can have template for each content type and for each view mode.

---
Tags: nodes, theming
---


# Question
Title: Entity reference field with custom class
I created two content type Writer & Book. Writer has entity reference field that link to Book nodes. When display Writer node, I like the book nodes that attached to it display as list and the first list item has CSS class of "first".

Output the list is simple but I couldn't figure out how to add that CSS class.

If possible, I prefer do it with template.php or node--content\_type.tpl.php flies, not using JQuery, Views or another modules.

Appreciate any suggestions, Thanks!

# Answer
Inside your tempalate.php file, add the following for that field. This is the standard implementation of theme\_field. I added the line if `($delta == 1) $classes .= ' first';` to add the class.

```
function yourthemename_field__yourfieldname ($variables) {
  $output = '';

  // Render the label, if it's not hidden.
  if (!$variables ['label_hidden']) {
    $output .= '<div class="field-label"' . $variables ['title_attributes'] . '>' . $variables ['label'] . ': </div>';
  }

  // Render the items.
  $output .= '<div class="field-items"' . $variables ['content_attributes'] . '>';
  foreach ($variables ['items'] as $delta => $item) {
    $classes = 'field-item ' . ($delta % 2 ? 'odd' : 'even');
    //add your class here
    if ($delta == 1) $classes .= ' first';
    $output .= '<div class="' . $classes . '"' . $variables ['item_attributes'][$delta] . '>' . drupal_render($item) . '</div>';
  }
  $output .= '</div>';

  // Render the top-level DIV.
  $output = '<div class="' . $variables ['classes'] . '"' . $variables ['attributes'] . '>' . $output . '</div>';

  return $output;
}

```

Furthermore, you can change this for different view modes and different bundles. The rest is in documentation.
> 0 votes

---
Tags: entities
---


# Question
Title: How do I suggest broken link fixes to a Drupal module project page description?
I noticed that a Drupal module's project page description has a broken link.

How do I suggest/contribute the change? Is this done through GIT?

# Answer
> 1 votes
Basically, you want to report documentation bug, because project page is maintained by module maintainers, and it's entry point to all other documentation.

1. You need to log in
2. Go to the module page
3. In the right sidebar, you will have section "Issues for \[module name\]"
4. Enter issue queue by clicking any link in this section, for example open bugs.
5. On the page "Issues for \[module name\]", click "Create a new issue"
6. Set the Component field to "Documentation" (unless maintainers defined better fitting component option for your purpose)
7. Fill all the rest as needed

# Answer
> 0 votes
This question seems like a variation of something I recently ran into when I was looking for the "official" documentation of the Raty module, which you can find via the "Read documentation" link on its project page. Here is some more info about this module:

> ... Raty is designed to be an immediate, zero-config option to either display stars from any numeric field or use them as field input widgets.

Trying to get started with this docu is not obvious. That's why I went for a plan-b ... I decided to try to contribute some brand new Community documentation about the Raty module. It's still a kind of "work in progress", but I'd hope it'll be considered as a "best possible alternative available today". Anybody interested in contributing to it also: be my guest and go ahead to also contribute to it.

I also created an issue for Raty, i.e. Complete community docu for the Raty module. So now it's a matter of waiting for the (co-) maintainers to yes/no consider the issue I created (though the Community documentation page is already there, be it that it isn't obvious yet to make people aware of that).

---
Tags: community-official-site
---


# Question
Title: How do I programatically generate multiple "add to cart" forms on product display?
I've got a matrix of 12 products, which can be added to the cart by users after selecting different term reference fields, which then select the appropriate product. This is shown on a product display.

However, I'd like to have multiple add-to-cart forms, each with a different line item selected on the product display field.

Basically, I've got a field collection, and I'd like to iterate through each of the field collection entities and display an add to cart form, with my full 12-product matrix of options, for each of these field collection items.

It would seem that I could get the add to cart field, all formatted, using

```
field_default_view($entity_type, $entity, $field, $instance, $langcode, $items, $display)

```

But I am currently on the node.tpl.php file, and I can't quite work out which entity objects are which to pass to this function. Nothing really resembles what I'm seeing passed to `commerce_cart_field_formatter_view`.

Am I thinking about this wrong? Is there a better way to accomplish this?

# Answer
I implemented this through patching Commerce Add to Cart Extras. My patch can be found here: https://www.drupal.org/node/1836200

In brief, the line item type contains a reference to an entity, a field collection item, actually.

I used views to generate a list of products with an add to cart form using Commerce Add to Cart Extras, joining (by a views relationship) on my field tables that provide the reference which must be attached to the line item.

Next, I had to alter Commerce Add to Cart extras so that the views result containing my entity id which must be added to the line item will copy that id over to the line item when the line item is created.

In the end, I have a list of multiple instances of the same product with a quantity field and a single add to cart button. Each product has the entity which must be added to the line item. When one of those products is added to the cart, the entity id gets copied over to the line item.
> 0 votes

---
Tags: theming, commerce
---


# Question
Title: Are spam registrations a threat to a Drupal 7 site
Yesterday, as I was explaining to a client that someone would need to remove spam registrations, the client asked me what difference it made if they are in the system because we can just turn off all privileges that anonymous users don't have.

I was not able to give her a compelling argument of why this clean up is important. The fact that I like to keep everything on a website nice and clean was not a compelling argument for her. What are the security or other risks in not cleaning up the spam users?

# Answer
Will there be a number of authenticated users on this site who are not spammers, or does your project only require a few users to create content? If it's the latter, the best bet is to simply turn off user registration, and have the owner create accounts as needed. If the former, programs like Mollom should help with cutting down spam and the basic package doesn't cost.

As far as performance goes... if spammers can post content, the obvious issue is comment/content spam. You can use the Disqus module to mitigate this, i.e. offloading the work to Disqus. If not, then if you need to send emails to all users through a service, then you will necessarily have email list bloat. If the volume gets very high, then you could potentially have availability issues, though I don't see that very often.
> 0 votes

---
Tags: users, security, advertising
---


# Question
Title: Drupal Multilanguage domain specific with PORT not working
I have setting up drupal 7 with 2 languages:

1. English Default
2. Spanish

Also, Point 2 domains for each language from language configuration settings

* www.drupal-experiment.local:90 (English)
* es.drupal-experiment.local:90 (Spanish)

**Setting.php** Base URL set in /sites/default/settings.php file.

> $base\_url = "http://www.drupal-experiment.local:90";

Can anyone look at my configuration, where I have missed something so, Other/inner links are not getting PORT with given URL.

e.g. If I try to login it will submit data to URL without PORT number.

> http://www.drupal-experiment.local/

See attached screen-shots for configuration set for domain with PORT 90.

> **Languages list**

> **English Language Configuration**

> **Spanish Language Configuration**

# Answer
> 1 votes
I'm pretty confident that the reason for your issue / problem, is because Language detection by domain only works on port 80. That issue has 'some patches' attached to it', and status = Needs review.

Not sure if you want to try/consider experimenting with any of the patches in this issue though.

Something else you may want to check is your configuration at `Configuration -> Languages -> detection and selection`: the order specified there could be what explains the current behaviour in your site.

You'd have to experiment a bit with what the exact order in your case should be. In my experience, I often get these kind of issues to work by using an order like 'URL, Default, User', and not something like 'Default, URL, User'. So try to experiment a bit with the various combinations in this order to see if it helps.

Curious to hear if either of those options will somehow help ...

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


# Question
Title: How to inspected the file system to investigate if the image was uploaded
After I upload an image, I see blank image. How can I inspect the file system to investigate if the image was uploaded or not?

Thanks, M

# Answer
If your file is not appearing after an upload via the field api then you might want to check if your files directory is writable by apache. Typically this would be sites/default/files.

NOTE: sites/default/files should ONLY be writable by apache and nothing else.
> 0 votes

---
Tags: files
---


# Question
Title: Commerce Kickstart: facets are disabled when using back button
Commerce Kickstart facets get temporarily disabled (showing reduced opacity) after selecting one of them until the new search downloads. This is a cool feature. However, if the user clicks the browser's back button after that, then the previous page is displayed without reloading and the facets are still disabled, therefore making a new search impossible unless the user manually reloads the page.

In order to reproduce this problem, just visit KickStart Demo (http://demo.commerceguys.com/products), select a facet term, wait until the search is loaded and then go back.

What's the easiest way to solve this? I've been thinking of forcing a page reload in search pages or to use jQuery to make sure that all facets are enabled. Neither of them sound very natural.

Thanks for you answers! David

# Answer
This is an issue with how FireFox serves cached pages when you use the Back button.

There appears to be two ways of solving this:

1) Per the first answer here, set `autocomplete="off"` for all form elements that can be disabled. As that form likely isn't one you have direct control over (without hacking a module), you'll have to do this with a hook\_form\_alter().

2) The second answer in the question linked above provides some JavaScript that you can use to stop this from happening:

```
window.addEventListener('pageshow', PageShowHandler, false);
window.addEventListener('unload', UnloadHandler, false);

function PageShowHandler() {
    window.addEventListener('unload', UnloadHandler, false);
}

function UnloadHandler() {
    //enable button here
    window.removeEventListener('unload', UnloadHandler, false);
}

```
> 0 votes

---
Tags: commerce, search
---


# Question
Title: Can't visit site after switching on Language Detection 'Session' in combination with Ip to locale
My siteis in a kind of a loop? I can't login anymore and visit the site? http://landberg.at/nl/nl/nl/nl/nl/nl/nl/nl/nl/nl/nl/nl/nl/nl/nl/nl/nl/nl/nl/nl/nl/en/user

What do i have to do. Its a combination with IP to local and Language Detection 'Session'

* How do i disable Language Detection 'Session' from mySql database manually?
* i already disabled IP to local module from database...

I really need my site back as soon as possible.

Thanks!

**Update:**

I solved it by entering ?language=en behind my URL. After this i was able to login again.

# Answer
I solved it by entering ?language=en behind my URL. After this i was able to login and visit my site again.
> 1 votes

---
Tags: i18n-l10n, sessions
---


# Question
Title: How to create a default value for an entity base field in Drupal 8
Both the Examples module and the Drupal Console `generate:entity:content` both have code like this:

```
$fields['first_name'] = BaseFieldDefinition::create('string')
  ->setLabel(t('First Name'))
  ->setDescription(t('The first name of the Contact entity.'))
  ->setSettings(array(
    'default_value' => '',
    'max_length' => 255,
    'text_processing' => 0,
  ))

```

I was thinking that if I provided `'default_value' => 'Fred'` in place of `'default_value' => ''` that I might affect the default value of the field. I would expect to have seen Fred when creating an entity of this type, and I might have expected to see Fred as the default value in the entity's table definition, but it's not there.

I'm learning D8 and so have two parts to this question really, the first is just how to provide a default value, the second is if this `default_value` key isn't it, what *is* it for?

# Answer
The code is outdated, you should create a patch to fix it.

There is a new separate method for the default value, `setDefaultValue()`.
> 3 votes

---
Tags: entities, 8
---


# Question
Title: Hide specific sections on admin configuration page
I wondering how I may hide some sections on the administration configuration page? I would like to hide some sections entirely for instance the `media` section and then only remove certain items for others, under the `system` section I only like to remove the `cron` item.

I tried to alter the `admin/config` page using `hook_admin_paths_alter()` and `hook_preprocess_page()` but without any luck. Would be nice if some one could point me in the right direction on how to achive this.

```
function MODULE_admin_paths_alter(&$paths) {
   // hide some paths
   $paths['admin/config/system/cron'] = FALSE;
}

function MODULE_preprocess_page(&$variables) {
  if(path_is_admin(current_path())) {
    // I don't know how to modify the markup of the page
    // tried to add a template called page--admin--config.tpl.php but
    // without any luck
  }
}

```

In the end I used @Captain Pants solution:

```
function pe_admin_permission() {
  return array(
    'access extended config' => array(
        'title' => t('Access Extended Configurations'),
        'description' => t('Gives a user access to extended configuration pages.'),
        'restrict access' => TRUE,
    ),
  );
}

function pe_admin_menu_alter(&$items) {
  // add all items you would like to hide here
  // if you hide all items in a specific section the entire block
  // will be removed
  $sections = array(
    'admin/config/system/cron',
    'admin/config/system/actions',
    'admin/config/system/mimemail',
    'admin/config/system/mailsystem',
    'admin/config/date/date_popup',
  );

  // loop through each item you would like to hide
  foreach($sections as $section) {
    $items[$section]['access callback'] = 'user_access';
    $items[$section]['access arguments'] = array('access extended config');
  }
}

```

# Answer
> 4 votes
You have stated that it would be "nice" to have these paths inaccessible. If a user is not supposed to have access to this paths then you should go above and beyond just "hiding links so nobody can see". Here is the solution to both remove those links from the config page AND having those links inaccessible if one were to type in the url in their address bar.

You will need to make a module with the following code. Note: I'm only doing this for the cron config page.

```
/**
 * Implements hook_permission().
 */
function my_module_permission() {

  return array(
    'access cron config' => array(
      'title' => t('Access Cron Config'),
      'description' => t('Gives a user access to the cron configuration page.'),
      'restrict access' => TRUE,
    ),
  );
}

/**
 * Implements hook_menu_alter().
 */
function my_module_menu_alter(&$items) {

  $items['admin/config/system/cron']['access callback'] = 'user_access';
  $items['admin/config/system/cron']['access arguments'] = array('access cron config');
}

```

This will give you the "Access Cron Config" permission on the permissions page and there you can choose which role has the cron page appear for them.

Please research more on hook\_permission and hook\_menu\_alter for clarification on how to do this for the media pages.

# Answer
> 3 votes
Content for every section on this page is built in theme\_admin\_block\_content function. As a solution you may copy this function into your theme template.php file and unset sections which you want to hide.

```
function myadminthemename_admin_block_content($variables) {
  $content = $variables['content'];
  $output = '';

  if (!empty($content)) {
    $class = 'admin-list';
    if ($compact = system_admin_compact_mode()) {
      $class .= ' compact';
    }
    $output .= '<dl class="' . $class . '">';
    $hide_links = array(
      'admin/config/system/cron',
      'admin/config/system/mimemail',
      'admin/config/date/date_popup'
    );
    foreach ($content as $item) {
      if (!in_array($item['href'], $hide_links)) {
        $output .= '<dt>' . l($item['title'], $item['href'],  $item['localized_options']) . '</dt>';
        if (!$compact && isset($item['description'])) {
          $output .= '<dd>' . filter_xss_admin($item['description']) . '</dd>';
        }
      }
    }
    $output .= '</dl>';
  }
  return $output;
}

```

# Answer
> 0 votes
You could define a new **Role** (say you call it `sub-admin`). And then you perform these extra steps:

1. Start by granting ALL permissions to that role, so that it looks like a copy of the predefined Administrator role.
2. For each of the sections within the administration configuration for which you want something to be removed: locate the required permission related to it, and remove that permission again for the sub-admin role.
3. For cron within the system section, use a similar approach as in step '2.'.
4. For users for which you want to restrict access to these admin sections, grant them the role of `sub-admin`, but not `administrator`.

With this approach you use standard Drupal techniques, based on the permission system. With probably no unexpected issues whenb upgrading to future releases (like D8?) of Drupal.

Makes sense?

# Answer
> -1 votes
you could use some css to hide the sections for UX, and then use Rules or a redirect module on the paths themselves to keep people from directly entering the url.

> The Rules module allows site administrators to define conditionally executed actions based on occurring events (known as reactive or ECA rules). It's a replacement with more features for the trigger module in core and the successor of the Drupal 5 workflow-ng module

You could use hook\_menu\_alter() instead of Rules in a custom module to keep it simple.

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


# Question
Title: Create a checkboxes-field with a radiobutton for all items
Usercase: Have a list with services for shops. Those services can be done with an appointment, or without. So the services are checkboxes, and the radio needs to show if it can be done with or without an appointment.

I am scratching my head over this, tried some modules like double\_field and composed\_field, but they do not fit this case it seems. End-users must be able to choose the services they sell, and also verify if they sell this with or without an appointment.

Example-sketch:

# Answer
You can also achieve that using the Double Field module.

Go to your content type and add field **Type** as Dobule field and **Wideget** as *checkbox and checkbox*

You can add *Prefix* or *suffix* for each field to display them as label for them.

Additionally you can use the Field Group module to make them under a roof.

Here is the screenshot:
> 3 votes

# Answer
# Conditional Fields

Another approach to consider, is to use the Conditional Fields module ... Here is an excerpt from its project page:

> ... allows you to manage sets of dependencies between fields. When a field is “dependent”, it will only be available for editing and displayed if the state of the “dependee” field matches the right condition.
>
> When editing a node (or any other entity type that supports fields, like users and categories), the dependent fields are dynamically modified with the States API.

Refer to the Community Documentation for this module for a lot more information about this module.

**Note**: this module still has an Alfa status (only), but over 38K sites using it already. Therefor I believe "alfa" is not the right label (anymore)à for this release. It should be at least an RC-version ... if not just an official release ...

# Field Group

Maybe you want to consider the Field Group also, to create 3 'groups' (1 for each of the 3 services). Excerpt from its project page:

> Fieldgroup will group fields together. All fieldable entities will have the possibility to add groups to wrap their fields together. Fieldgroup comes with default HTML wrappers like vertical tabs, horizontal tabs, accordions, fieldsets or div wrappers.

# DataTables

To actually **query** these combined fields, you can create an appropriate view in a **tabular** display format that uses the DataTables **module**, which uses the datatables **plugin**.

Here are a few online samples to see that module at work (a rather basic views display, using the **dataTables views style**):

* AbitMORE-scm.com: experiment with the search box in the upper right, eg first type "without" in it, see what happens, and then continue typing so that it becomes "without packages". Doing so you'll only get the rows displayed that contain both keywords somewhere in any of the columns (= 'and' operation), in this sample "without" in 1st column and "packages" in 2nd column.
* Dr.Chgman.com: similar suggestion for the search box, like "zmf z- 1.2" (pause a few secs before typing the spaces in between).
> 2 votes

# Answer
I would suggest you to use the Field Collection module in this scenario. You have to add a field\_collection type field in your entity(node) and make its cardinality "unlimited". Now follow these steps:

1. Go to manage field section of the field\_collection item you've just added.
2. Add services field and make it checkboxes/drop-down whichever you like, you can add options for the checkboxes there. But I would suggest to make services a taxonomy vocabulary and attach them through term\_reference field type here.
3. Add a boolean checkbox field for appointment.

That should work.
> 1 votes

# Answer
Writing your own module can solve your problem too .

for that you need to create your own field which contains 2 values. first you have to introduce your field to drupal , use hook\_field\_info() for that .

```
function ModuleName_field_info() {
   return array(
      'ModuleName_services' => array( //your sub-Field machine readable name.
          'lable' => t('Services'), //Human readable name
          'description' => 'some description', //optional
          'default_widget' => 'widget_name', //optional (text_textfield works here)
          'default_formatter' => 'formatter_name', //(text_default is fine)
      ),
      'ModuleName_appointment' => array(
         'lable' => t('Appointment Status'),
         'description' => 'some description',
         'default_widget' => 'widget_name',
         'default_formatter' => 'formatter_name',
      ),
   );

```

then Implement hook\_field\_schema($fields) to specify a place in database . other options could find here and here

```
function ModuleName_field_schema($fields) {
 columns = array (
  'service' => array(
    'type' => 'varchar',
    //other options could find [here][2] and [here][3]
    'not null' => true,
   ),
   'appointment' => array(
     'type' => 'int',
     'size' => 'tiny',
     //More options if you wish
   ),
  );
  $indexes => array('services');
 return array($columns , $indexes);
}

```

if you want more customization you can define your own field\_widget and your own field\_formatter too . more on that you can also assign some field settings which can be modified in future using Field UI.
> 1 votes

---
Tags: 7, entities
---


# Question
Title: How to make JS Async and eliminate unnecessary JS?
I've been told this could be done with the Magic module but I couldn't find documentation\videos\readme anywhere for it so I ask how to do these specific things with it in my Drupal 7 site:

1. How to make JS Async?
2. How to eliminate unnecessary JS?

I need this for trying to take care the known Page spped insights advice "Eliminate render blocking JS above the fold content". Thanks.

Update: This could be done with AdvAgg module easily, see the following answer by Mikeytown2:

# Answer
AdvAgg can move the JS to the footer and also defer it with minimal issues. It can also async load the JS but this results in bad things from happening as drupal/jQuery is not async safe. Setting `async => TRUE` via hook\_js\_alter works, just be careful as the script needs to be async safe. You can also set the async attribute in the options array when using drupal\_add\_js.

It can also async load CSS but that results in a flash of unstyled content. Issue to fix this: Inline critical css

See Reorder Javascript loading in theme? for an example of AdvAgg doing this. The AdvAgg readme is slightly outdated but points you in the right direction on how to get a higher pagespeed score.

Will also suggest http://www.webpagetest.org/
> 1 votes

# Answer
you can use async\_js for loading asynchronly.

and in hook\_js\_alter you can remove js files you don't want to have on the page.

you can also place the JS at the bottom of the page in your theme's html.tpl.php, by printing

`<?php print $scripts; ?>`

just before the `</body>` tag.
> 2 votes

---
Tags: performance
---


title: Add user edit fields to pane

text:
# Question
Title: Add user edit fields to pane
I have a pane on a Dashboard page that's supposed to be an accordion.

It's supposed to update user information. I still haven't figured out how can I add user fields inside this pane, for example:

Update your information:

Name \_______

Password \_______

E-mail \_______

etc.

Is that possible? Do I have to use a preprocess function to add that?

Thanks in advance.

# Answer
> 0 votes
There is a module in drupal called Form Block . This module will allow you to present many forms through blocks . Advanced Form Block is another module with same goal .

if these modules couldn't help you can do it by yourself . create a module , create your own form , your form callback can be User save , export your form as a block .

---
Tags: users, panels
---


# Question
Title: No response from Services Entity API when added '.json' to the end of alias
While configuring Services module, when I add '.json' to the end of the resource alias I get an emtpy page. Other resources that are not provided via Services Entity API output json the same way. The Services Entity API module have no documentation in this direction. Any ideas?

Edit: Also adding '.xml' gives empty response which points to that I am doing something wrong:)

# Answer
Okey,

You shouldn't add the suffixes like .json or .xml to the end of the alias name like you do with some other resources if the resources are provided by services\_entity module. Adding the suffix directly to end of the whole url solved it.

`example.com/endpoint/resource_alias/resource_id.json` ie: `example.com/api/entity_node/5.json`
> 1 votes

---
Tags: 7, entities, services
---


# Question
Title: Why can't I add another allowed file extension to a Drupal 7 image field?
I've added the SVG file extension for image uploads via `admin/structure/types/manage/image/fields/gallery_image`, as you see below:

>

But when I go to upload an image, I'm still not allowed to upload SVG.

>

I definitely pressed "Save" in the admin page, and I cleared the cache, and I even see the settings as I wanted them in the database, when I inspect the `field_config_instance` table. There must be some other table or cache that's not updating. Any idea?

# Answer
> 7 votes
The Image widget internally allows (and silently enforces post Drupal 6) the use of only the `png`, `gif`, `jpg` and/or `jpeg` extensions. So, while you can remove an extension from a field, eg, I have removed `gif` from most of my implementations to avoid anything animated, you can't add any to this list. I would imagine this is because it in itself displays the image after being uploaded and didn't want to break any displays in older IE browsers in the actual form (plus, who knows how image styles would work on them as well :)

# Answer
> 2 votes
As noted, there's no easy way to simply allow Drupal's core Image module to accept SVG. Instead you can use the contributed module SVG Embed (grudgingly chosen over a filefield for SVG in this discussion) or this sandbox (not officially released) SVG module.

UPDATE: I now recommend svgimg also in Sandbox but likely being released soon. Using it in production, and very happy.

# Answer
> 2 votes
You can simply use a file field and implement `hook_field_formatter_info_alter` in your custom module to enable the "Image" formatter also for file fields. Then you can easily ouput for uploaded SVG as embedded image.

```
/**
 * Implements hook_field_formatter_info_alter().
 */
function MODULNAME_field_formatter_info_alter(&$info) {
  $info['image']['field types'][] = 'file';
}

```

# Answer
> 2 votes
There is also another way around it--using the Media module. Once this is installed, the SVG format can be added at admin/structure/file-types, under image.

If I'm not mistaken, Drupal still doesn't allow SVGs by default due to backwards compatibility concerns (primarily IE8 and below). I've been placing SVGs for some time on projects, though, and have yet to hear a complaint.

---
Tags: entities, media, caching, files, users
---


# Question
Title: What are Entity tags (Etags) and how do you configure them in relation to your Drupal site's files?
The GTmetrix Page speed & optimization test notified me that 13 components in my site (all are files) have "misconfigured Etags", so I ran a search query like " Drupal Entity tags " in Google and found almost nothing that was instructive for me (for my knowledge and understanding) on how to solve it via the Drupal UI. Therefore my question is first of all what are these Etags (or Entity tags) and how can I add them (or just configure them right, if they exist), For the relevant files?

Much thanks,

# Answer
https://en.wikipedia.org/wiki/HTTP\_ETag

Inside your .htaccess file add this to the bottom `FileETag MTime Size`
> 1 votes

---
Tags: performance
---


title: How to change the price ? (add_to_cart)

text:
# Question
Title: How to change the price ? (add_to_cart)
Here is my code

```

function addToCart($product_id, $quantite){
    global $user;
    $product = commerce_product_load($product_id);
  $line_item = commerce_product_line_item_new($product, $quantite);
  $line_item->data['context']['product_ids'] = array($product_id);
  $line_item->commerce_unit_price->amount  = '900';
  commerce_cart_product_add($user->uid, $line_item);
}

```

The above code add the product to the cart with the correct quantity but the price isn't changed ... Any idea ?

**Update (resolved thanks to scott's answer)**

```

//Panier
function addToCartCallback()
{
    addToCart($_POST['product_id'], $_POST['quantite']);
}

function addToCart($product_id, $quantite){
  global $user;
  $product = commerce_product_load($product_id);
  $line_item = commerce_product_line_item_new($product, $quantite);
  $line_item->data['context']['product_ids'] = array($product_id);
  commerce_cart_product_add($user->uid, $line_item);
  $order = commerce_cart_order_load($user->uid);
  commerce_cart_order_refresh($order);
}

function groupes_views_commerce_cart_line_item_refresh($line_item, $order_wrapper) {
  global $user;
  $idProduit = $line_item->commerce_product['und'][0]['product_id'];
  $prix = getPrixClient(getIdClient($user->uid), $idProduit) * 100;
  $line_item->commerce_unit_price[LANGUAGE_NONE]['0']['amount'] = $prix;
  $line_item->commerce_unit_price[LANGUAGE_NONE]['0']['data']['components']['0']['price']['amount'] = $prix;
}

```

# Answer
I thought of another way to do it.

Start with code that just adds the product to the cart without modifying.

```
function addToCart($product_id, $quantite) {
    commerce_cart_product_add_by_id($product_id, $quantite);
}

```

Then you can use a hook to modify the line item amount

```
//alter the price in cart & order
function my_module_commerce_cart_line_item_refresh($line_item, $order_wrapper) {

    $price = 100; //1 dollar
    $line_item->commerce_unit_price[LANGUAGE_NONE]['0']['amount']=$price;
    //alter the base_price component
    $line_item->commerce_unit_price[LANGUAGE_NONE]['0']['data']['components']['0']['price']['amount']=$price;

}

```

If this doesn't work try forcing the cart refresh e.g.

```
function addToCart($product_id, $quantite) {
    global $user;
    commerce_cart_product_add_by_id($product_id, $quantite);
    $order = commerce_cart_order_load($user->uid);
    commerce_cart_order_refresh($order);
}

```
> 1 votes

# Answer
Programmatically adding or modifying the price of a line item is quite tricky.

Here is an example of updating a line item amount

```
// Create a line item with quantity 1 and this product.
$line_item = commerce_product_line_item_new($product, 1, $order->order_id);

// set up price data
$line_item_price = commerce_price_field_data_auto_creation();
$line_item_price['amount'] = 900.0 * 100; // DC stores in cents
$line_item_wrapper = entity_metadata_wrapper('commerce_line_item', $line_item);
$line_item_wrapper->commerce_unit_price = $line_item_price;

// fix price data components
commerce_line_item_rebase_unit_price($line_item_wrapper->value());

// Save the line item to get its ID.
commerce_line_item_save($line_item);

```

Take a look at this article for a full example of adding a line item programmatically.

http://divingintodrupal8.com/#drupal-commerce-adding-line-items-programmatically

Edit:

Here is your code with a couple of changes. Note when we create the order now we set the status to 'cart'.

```
function addToCartTest($product_id , $quantite){
  global $user;

  // first create a new order
  $order = commerce_order_new ($user-uid, 'cart');
  // Save the order so its ID is assigned.
  commerce_order_save($order);
  $order_wrapper = entity_metadata_wrapper('commerce_order', $order);
  //Now we can add a line item - assuming $price is the amount without sales tax
  // get product by sku
  $product = commerce_product_load($product_id);
  // Create a line item with quantity 1 and this product.
  $line_item = commerce_product_line_item_new($product, $quantite, $order->order_id);
  // set up price data
  $line_item_price = commerce_price_field_data_auto_creation();
  $line_item_price['amount'] = 100 * 100; // DC stores in cents
  $line_item_wrapper = entity_metadata_wrapper('commerce_line_item', $line_item);
  $line_item_wrapper->commerce_unit_price = $line_item_price;
  // fix price data components
  commerce_line_item_rebase_unit_price($line_item_wrapper->value());
  // apply sales tax
  //commerce_tax_rate_apply(my_module_tax_rate(), $line_item);
  // Save the line item to get its ID.
  commerce_line_item_save($line_item);
  // Add the line item to the order using the wrapper.
  $order_wrapper->commerce_line_items[] = $line_item;
  commerce_order_save($order);
}

```

Also note the code above sets the amount to $100.
> 0 votes

---
Tags: 7, commerce
---


# Question
Title: How can I make the list of exposed filters hide options with no existing nodes?
I'm using Drupal commerce, and I have a "Product Type" select field in the "Accessories" content type. There are 20+ options. In the views page I'm exposing that field, but I want only the options to display that have 1 or more nodes with that option selected. Is that possible?

# Answer
I came across this module when I was doing some search regarding your question.

Views Selective Filters seems to do just the same. As the module page mentions

> This module allows to have an exposed filter only show options that belong to result set. The options are calculated real-time with the current View's configuration, including the filters selected by the user so you get dynamic dependent filters.

I haven't used this module personally. But this module is worth checking out.
> 1 votes

# Answer
I am not sure if that can be done with views. Even if it can be done, I am sure it will take a considerable amount of coding and I am not sure if it will be performant enough(might reduce the performance).

This can be done easily with Apache Solr module.

> Faceted search is supported if you use the facet API module. Facets will be available for you ranging from content author to taxonomy to arbitrary fields.

When you enable facet API with apache solr module, you should get the facets(similar to filters). Facets will be displayed only if there are some results which have the value of the facet in their node.

**Note :** You will need to set up a Java server to have the Apache Solr running.
> 1 votes

---
Tags: 7, views
---


title: Embed a form inside a modal

text:
# Question
Title: Embed a form inside a modal
I have a modal in my form.

```
$form['myid_print_preview_modal'] = array(
  '#type' => 'item',
  '#markup' =>
    '<div id="myid_print_preview_modal" title="ID Preview">
    </div>',
);

```

I want to embed a set of form controls in my modal like textfield, buttons and etc. Is it possible? A simple example would be good for my comprehension. I don't want to use any existing module. I want to go hard code.

# Answer
Download and install webform module. This module supports different kinds of fields that might be needed in your form. This module also supports Ajax submission.

After installing this module and building the form, use Modal Forms module.

> Modal forms make use of the modal feature in the ctools module to open some common forms in a modal window. Supported forms

* Log in (modal\_forms/nojs/login)
* Request new password (modal\_forms/nojs/password)
* Create new account (modal\_forms/nojs/register)
* Contact (modal\_forms/nojs/contact)
* Comment (modal\_forms/nojs/comment/reply/%node)
* Webform (modal\_forms/nojs/webform/%node)

So in this way no coding is needed.
> 0 votes

---
Tags: forms, javascript, nodes
---


# Question
Title: What is the best way to add my custom PHP functionality to a Drupal homepage?
I have a custom PHP application I've written that accesses an API via SOAP, processes some data from the web service, and outputs an HTML table with the results. I'm an experienced WordPress developer and have been able to add my application's functionality into WP sites by creating A custom theme and adding the PHP/HTML code directly into the homepage template.

I now have someone asking me to add this to a Drupal site (v 7.34) - the end goal is to have the HTML table that the application outputs display on the Drupal site's homepage. The site is running the Porto 2.0.3 theme if that makes a difference.

I am pretty new to Drupal and I'd like to know what the best way to accomplish this is. I looked into adding PHP directly into a block, but my application consists of 2 files (an API class and the actual code that produces the output) so I'm not sure that's a good option.

My searching leads me to believe that creating a custom module is the best path (especially since I don't want future updates to the Porto theme to break the functionality) but I'd like to confirm that before I wander down that path. Or is is better/easier to override the homepage template to add my code?

I'd really appreciate some advice from experienced devs - not looking to be spoon fed and perfectly willing to do my own research, but a helping hand from people familiar with this system would be a huge help.

# Answer
> 4 votes
The best way forward is to go ahead and create a new module. You can find the steps from this link .It also shows you how to create a block from code.

You can add your files in the module and then make a function call which returns the table and add it as your block content. You can then include your block in the home page from admin interface in any region that you want it to be.

Hope it helps.

# Answer
> 2 votes
you could include it in one of the template files page--front.tpl.php, html--front.tpl.php, node--front.tpl.php depending on its scope, and so long it was a sub-theme, upgrading would not break that, but a custom module is probably the best route - most would argue that that type of processing should be kept out of the theme layer.

---
Tags: 7, theming
---


# Question
Title: Is there a Drupal rating module that lets you rate from 1 - 10?
I'm looking for a Drupal module that will let me rate something on a scale of 1 - 10.

It doesn't look like the Fivestar or Rate module would allow that.

Any suggestions?

# Answer
The VotingAPI module (D6 and D7) offers a framework to developers of Drupal modules about voting and/or rating. It uses a standardized API and schema for storing, retrieving, and tabulating votes for Drupal content.

VotingAPI offers these key features:

* Create/Retrieve/Update/Delete operations for voting data.
* Whenever a vote is casted, it calculates the results and caches them. These calculations can either be the default calculations (average, total, etc), or they can be implemented via custom tallying functions.
* Via its integration with the **Actions** module, it can trigger workflow steps whenever votes are casted and results are tallied, such as promoting a node to the front page, hiding a comment flagged as spam, or sending some eMail.
* It integrates with the **Views** module, which allows for slice and dice of the content of a site based on user consensus. And tt provides functions to format vote data to display them to users.

**Rating related modules with a stable release for D7**:

**Other rating related modules**:

**Rating related modules with maintenance/development status 'unknown'**:
> 2 votes

---
Tags: 7, rating
---


# Question
Title: Restrict delete operation on a node referenced by another node
I am using References module to make a node reference in my course content type that reference to school content type (a course belong to one school and a school have many courses).

Now what I want is if I'm going to delete a school, the delete operation will not be completed if the school referenced by any courses.

I've read `hook_node_delete()` and `hook_delete()`, written them in my custom module, tried to `dpm($node)` but no use!

```
function mymodule_delete($node) {
    dpm($node);
}
function mymodule_node_delete($node) {
    dpm($node);
}

```

The school node still be deleted!

According to hook\_node\_info() , I create:

```
function mymodule_node_info() {
  return array(
     'school' => array(
      'name' => t('School'),
      'base' => 'school',
      'description' => t('A short description'),
    )
  );
}

```

> base: (required) The base name for implementations of node-type-specific hooks that respond to this node type. Base is usually the name of the module or 'node\_content', but not always

And then in my mymodule.module:

```
function school_delete($node) {
    dpm($node);
}

```

The code still not working!

# Answer
I believe you are invoking the hook incorrectly - according to the API page for hook\_delete():

> This is a node-type-specific hook, which is invoked only for the node type being affected

Further disccussed on the Node API Hooks Page:

> Node-type-specific hooks: When defining a node type, hook\_node\_info() returns a 'base' component. Node-type-specific hooks are named base\_hookname() instead of mymodule\_hookname() (in a module called 'mymodule' for example). Only the node type's corresponding implementation is invoked. For example, poll\_node\_info() in poll.module defines the base for the 'poll' node type as 'poll'. So when a poll node is created, hook\_insert() is invoked on poll\_insert() only. Hooks that are node-type-specific are noted below.
> 0 votes

# Answer
If you are familiar with Rules (if you are not check here) you can use this selection :

add an integer field to school content type (this field is going to count courses which are referenced to a school)

on node creation event , check if it is a course type , if it is before saving that read the school reference value , then go and increase the school course count .

on node deletion , check if it is a course , then before deletion read the field school and decrease its course count value ,

and finally we are going to use some code :

```
//Implement hook_delete
function ModuleName_delete($node) {
   if($node->type == "school") //if your type machine readable name is school
   {
       if($node->course_count[LANGUAGE_NONE][0]['value'] < 0) //check field name ...
       {
           node_delete($node->nid);
       }
   }
}

```
> 0 votes

---
Tags: 7, nodes
---


# Question
Title: How to programatically change file user owner
I'm using the Services module. I can upload files through web services, but the problem is that all the created files have the same owner, the user account used for the web services. I would like to change this user, but I don't know how to do it.

I have been looking for the functions defined in the file.inc file, but I haven't found a function to change this. How could I change the file's owner?

# Answer
> 0 votes
I don't know of a module built to handle this, but you could build something easily enough to do it:

* the DB table file\_managed handles files, and includes a uid field which is the user ID of the file 'owner'

This could be modified in a custom module, but a **MAJOR WARNING** that I don't know what potential damage this could cause to other elements of the site, perhaps someone with more experience with the DB could add some advice in this regard

---
Tags: 7, files, services
---


title: How do I add og:image script in meta?

text:
# Question
Title: How do I add og:image script in meta?
My facebook is grabbing the wrong image.

I try to adding this open graph image in my head.

```
<meta property="og:image" content="<?= $_GET['image'] ?>" />

```

and

```
<meta property="og:image" content="<?php echo $image; ?>"/>

```

but the content image path is not shown. It became this

```
<meta property="og:image" content="" />

```

I want it to be like this. If the article A have image a\_name.jpg, the meta will be `<meta property="og:image" content="/images/a_name.jpg"/>`

If the article B have image b\_name.jpg, the meta will be `<meta property="og:image" content="/images/b_name.jpg"/>`

# Answer
> 0 votes
You need to supply the tag the full URL to the image. If you install the Metatag module not only can you have full control over keyword, description, etc. but also all the og tags too per node.

---
Tags: meta-tags
---


title: SMTP configuration issue in drupal 7

text:
# Question
Title: SMTP configuration issue in drupal 7
In SMTP module configuration I have set the following fields:

```
SMTP Server: smtp.live.com
SMTP port:25
Use encrypted protocol: NO

```

In `E-MAIL OPTIONS`,

```
E-mail from address: myadress@hotmail.com
SEND TEST E-MAIL: myadress@hotmail.com.

```

but it gives me the long detail of errors with the last line `SMTP Error: Could not authenticate.` Same error when I try to use below configuration:

```
 SMTP Server: smtp.gmail.com
 SMTP port:25
 Use encrypted protocol: SSL

```

In `E-MAIL OPTIONS`,

```
E-mail from address: my_gmail_address
SEND TEST E-MAIL: my_another_address.

```

But when I used port 80 instead of 25 then it gives me the following error for `SMTP.live.com`

```
SMTP -> ERROR: Failed to connect to server: Connection timed out (110) drupal 7

```

**UPDATED:**

Below is the screen shot for gmail configuration.

# Answer
> 2 votes
Change Port number to 465 or 587 in case of `SMTP Server: smtp.gmail.com` and 587 in case of `SMTP Server: smtp.live.com`.

As per : https://www.arclab.com/en/kb/email/list-of-smtp-and-pop3-servers-mailserver-list.html.

---
Tags: 7, emails
---


# Question
Title: How to resolve fatal error 'Cannot redeclare commerce_kickstart_preprocess_html'?
I have installed an ecommerce website with Commerce Kickstart, **not** in demo mode. Everything was OK and I began to add products and then my problem started; when I click on 'products category' I receive this error message:

> Fatal error: Cannot redeclare commerce\_kickstart\_preprocess\_html() (previously declared in /homepages/44/d576739206/htdocs/profiles/commerce\_kickstart/themes/commerce\_kickstart\_theme/template.php:41) in /homepages/44/d576739206/htdocs/profiles/commerce\_kickstart/themes/commerce\_kickstart\_theme/template.php on line 41

This is what that line 41 (as in the error message) looks like.

```
function commerce_kickstart_preprocess_html(&$variables) {
  drupal_add_css('http://fonts.googleapis.com/css?family=Lobster+Two:400,700', array('type' => 'external'));
}

```

What could the problem be? How can I solve it?

**Update** (as in one of the comments): I tried to change as you said it and I have this message:

`Fatal error: Cannot redeclare commerce_kickstart_theme_preprocess_html() (previously declared in /homepages/..../htdocs/profiles/commerce_kickstart/themes/commerce_kickstart_theme/template.php:9) in /homepages/..../htdocs/profiles/commerce_kickstart/themes/commerce_kickstart_theme/template.php on line 41 code`

**Update 2** : So if I use another theme, the problem is solved. And there are 2 (minor) differences in the new error message : Now it is in that line "9" (no longer "41") :

`function commerce_kickstart_theme_preprocess_html(&$variables) { // Add conditional stylesheets for IE drupal_add_css(path_to_theme() . '/css/commerce-kickstart-theme-ie-lte-8.css', array('group' => CSS_THEME, 'weight' => 23, 'browsers' => array('IE' => 'lte IE 8', '!IE' => FALSE), 'preprocess' => FALSE)); drupal_add_css(path_to_theme() . '/css/commerce-kickstart-theme-ie-lte-7.css', array('group' => CSS_THEME, 'weight' => 24, 'browsers' => array('IE' => 'lte IE 7', '!IE' => FALSE), 'preprocess' => FALSE));`

**Update 3** : Here is template.php :

```
<?php
/**
 * Preprocess variables for html.tpl.php
 *
 * @see system_elements()
 * @see html.tpl.php
 */
function commerce_kickstart_theme_preprocess_html(&$variables) {
  // Add conditional stylesheets for IE
  drupal_add_css(path_to_theme() . '/css/commerce-kickstart-theme-ie-lte-8.css', array('group' => CSS_THEME, 'weight' => 23, 'browsers' => array('IE' => 'lte IE 8', '!IE' => FALSE), 'preprocess' => FALSE));
  drupal_add_css(path_to_theme() . '/css/commerce-kickstart-theme-ie-lte-7.css', array('group' => CSS_THEME, 'weight' => 24, 'browsers' => array('IE' => 'lte IE 7', '!IE' => FALSE), 'preprocess' => FALSE));

  // Add external libraries.
  drupal_add_library('commerce_kickstart_theme', 'selectnav');
}

/**
 * Implements hook_library().
 */
function commerce_kickstart_theme_library() {
  $libraries['selectnav'] = array(
    'title' => 'Selectnav',
    'version' => '',
    'js' => array(
      libraries_get_path('selectnav.js') . '/selectnav.min.js' => array(),
    ),
  );
  return $libraries;
}

/**
 * Override the submitted variable.
 */
function commerce_kickstart_theme_preprocess_node(&$variables) {
  $variables['submitted'] = $variables['date'] . ' - ' . $variables['name'];
  if ($variables['type'] == 'blog_post') {
    $variables['submitted'] = t('By') . ' ' . $variables['name'] . ', ' . $variables['date'];
  }

function commerce_kickstart_theme_preprocess_html(&$variables) {
drupal_add_css('http://fonts.googleapis.com/css?family=Lobster+Two:400,700', array('type' => 'external'));
 }
}

```

# Answer
Because the two file paths are the same file, it suggests a possible problem with your op-code caching.

Check if you have any PHP op-code cache enabled; you should only have one op-code cache utility and may need to disable one.

You may also need to tweak your APC settings (if enabled).

```
apc.include_once_override = 0

```

Check also https://stackoverflow.com/questions/4575341/php-with-apc-fatal-errors-cannot-redeclare-class.
> 1 votes

# Answer
This problem might be a variation of what is described in Fatal error: Cannot redeclare bartik\_preprocess\_html().

Here is something that may help you resolve your problem (inspired by some of the things I read in that link): edit the "template.php" in the theme you're using, within line 41 replace the `function commerce_kickstart_preprocess_html` with something like `function mytheme_preprocess_html`. Make sure that the '`mytheme`' in it is identical to the folder name of your theme. Make sure to refresh the cache (!!!) and then try again to see what happens. If it solves your problem, then it's probably because sub-theme functions should start with the name of the sub-theme (not the parent theme).

So consider reviewing the content of that link, it might give you some ideas to either find a work around, or to refine your question (by editing it), and add some more details like:

* What is the theme you're using (and what is the folder name of it)?
* What happens if you (temporary) change to another theme?

While trying to better document your question (add detials), you might even find the actual reason for your problem, and maybe even a solution (which we would then want to learn about also!).

Note: a completely different approach is to review the content of Fatal error: Cannot redeclare MYTHEME\_preprocess\_page() ...
> 0 votes

---
Tags: commerce
---


# Question
Title: translate menu item using entity translation
I am kind of confused and really need some guidance Is there a way to translate menu items using entity translation?(One item for all languages) Thanks

# Answer
With Drupal core alone, user-defined menu items are not translatable. The Menu translation module, part of the i18n package, allows users to select a translation mode for each menu. **LINK**
> 1 votes

# Answer
Use the `entity_translation_i18n_menu` submodule of Entity translation.

> Allows menu items to be translated on the entity form.

It has good integration with the `i18n_menu` module.
> 1 votes

---
Tags: routes, i18n-l10n
---


title: Not show node count view in drupal 7

text:
# Question
Title: Not show node count view in drupal 7
I have installed node count view module and configured it.

But it's not showing me anything anywhere in my site. And I am not getting the setting of node count view.

Any suggestions about where I can see the 'node counts'?

# Answer
Visit `admin/config/system/statistics` and enable the following settings.

These are the standard options I use for showing the node count. They some to work well in my case.
> 0 votes

# Answer
I'm assuming you are using the Node view count module (there doesn't seem to be a 'Node count view' module ...). And also that you used `admin/config/content/count-views` to configure the module, i.e. to select the node types and user roles for which to count node view.

There doesn't seem to be lot (any?) of documentation about this module available. Not a readme.txt, no "Read documentation" link on the project pages, etc. The best 'documentation' that I have been able to find so far is what is written in issue 2123609. Here is a summary of it:

* The module integrates with the Views module.
* A few views are included/shipped with the module (enable them as apprpriate).
* A admin user can see statistics by visiting `/admin/config/content/node-views-count-statistics`.

Potentially something that you might want to review/check also, is what is written in issue 2317873 ... Therefor consider editing your question related to the theme you're using, and/or if you're using the Display Suite module ... (that would explain why you don't see anything ...).
> 0 votes

---
Tags: 7, nodes
---


# Question
Title: Is it possible to combine a Bootstrap theme with an existing custom Drupal 6 theme?
Is it possible to combine a Bootstrap theme with an existing custom Drupal 6 theme?

I want to use Grayscale in my Drupal 6 website. But I already have an existing custom theme and I am not sure if I can simply use it. Or whether the styling will interfere with other stylesheets in Drupal.

# Answer
There is the Bootstrap base theme for D7 (and even an upcoming D8 version), which bridges the gap between Drupal and the Bootstrap Framework, with also quite a few (contributed) sub-themes available for it already.

So if your question was about D7, then it seems such combination that you're looking for should be possible. As you may know already, the Bootstrap base is not available for D6. But maybe you can use the D7-version of it as inspiration to somehow make such combination also work for D6. Ultimately even come up with a backport of the Bootstrap base theme for D6?

**Note**: as mentioned by Molot's in the comment to this answer, there is "some" D6 backport of it available on github ... Via Drupal.org there doesn't seem to be any D6 versions, however there "is" some D5 version of it also ... Maybe upgrading the D5 version to D6 is another approach to consider? Using Browse code repository only results in D7/D8 versions though ...
> 3 votes

---
Tags: 6, theming
---


title: JS and CSS in hook_preprocess_hook()

text:
# Question
Title: JS and CSS in hook_preprocess_hook()
In the project I am working on I have created a theme hook that renders a .tpl.php file:

```
/**
 * Implements hook_theme().
 */
function my_module_theme() {

  $theme['my_module_list'] = array(
    'variables' => array(
      '#markup' => array(),
    ),
    'path' => drupal_get_path('module', 'my_module'),
    'template' => 'templates/my_module_list',
  );

  return $theme;
}

```

Then I want some JS and CSS to be added only when this theme hook is used in the current page. Thus I implemented of theme\_preprocess\_hook() as such:

```
/**
 * Implements template_preprocess().
 */
function my_theme_preprocess_my_module_list(&$vars) {
  drupal_add_js(drupal_get_path('module', 'my_module') . '/js/my_module.js');
  drupal_add_css(drupal_get_path('module', 'my_module') . '/css/my_module.css');
}

```

However it appears that the preprocess function is not called every time the hook is used resulting in CSS and JS not being added. What am I missing? Is it bad practice to add it there? And if yes where should I add it in order for it to be loaded only when necessary? I couldn't find any documentation that clarifies it and I've also seen it done other places.

Thanks a lot in advance :-)

# Answer
> 1 votes
I would add JS/CSS files inside the preprocess\_page() function. If I don't want the CSS/JS files loading on some pages I will use an IF statement and check for a setting or if something exists etc, this will depend on the project.

# Answer
> 1 votes
Why don't you just use info files to add JS and CSS? My experience says it is the best way - it's stable, clean, easy to fint and tune. Also, it helps with aggregation and caching if you always have one set on all pages.

For conditionals - just use CSS and JS rules to find out if the page is one they need to be applied on. For example, test for specific class on `<body>` element, or script / style elements by their specific class or id.

---
Tags: theming
---


# Question
Title: Cannot Find property after adding it with hook_entity_property_info_alter (callback not firing)
I'm very new to drupal, so forgive me if this is a simple question, but I have been working on this for a few days and have not yet found a solution.

I have an entity, to which I've added the property "hour\_created" via the `hook_entity_property_info_alter()` function. The property has a getter\_callback function that simply returns an integer for now. I can see that this property has been added by calling `watchdog("normal", print_r($info, true))` after adding the property in the same `hook_entity_property_info_alter()` function.

The problem is that it does not appear this property is ever actual added to the entity when I try to look at it through Drupal. I added a `watchdog("normal", print_r($item, true));` call in the callback, but the watchdog is never called, and never appears in the logs. To try and get the callback to fire, I have tried the following:

1. node-load through drush
2. loading the node through the site directly
3. directly attempting to access the property with php

Unfortunately, I have had no success with any of my above attempts. I suppose what we can boil this question down to is 'How can I make my entity property getter\_callback fire, and why isn't it fired when I load the node?' I apologize if any of this is a little muddled, please let me know if any of this is unclear or if you need more information.

Thanks!

**EDIT:** Here's the code for my callback:

```
function mymodule_test_property_getter_callback($item) {
  watchdog("normal", print_r($item, true));
  return 10;
}

```

And here's my `hook_entity_property_info_alter()` function:

```
function mymodule_entity_property_info_alter(&$info) {
  $info['node']['bundles']['mynode']['properties']['test_property'] = array(
    'label' => t('Just a test!'),
    'type' => 'integer',
    'computed' => TRUE,
    'required' => TRUE,
    'getter callback' => 'mymodule_test_property_getter_callback'
  );
  watchdog("normal", print_r($info, true));
}

```

# Answer
I think this is what's going on...

With your current code you've described the property to the entity API module; if you want to access it via that you already can:

```
$node = node_load($nid);
$wrapper = entity_metadata_wrapper('node', $node);
print $wrapper->test_property->value(); // Prints '10'

```

But the core entity system has no knowledge of `test_property`, so it doesn't show up on a node object from `node_load()`. To get it there, you'll need to implement `hook_node_load()`:

```
function mymodule_node_load($nodes, $types) {
  foreach ($nodes as $node) {
    if ($type == 'mynode') {
      $node->test_property = mymodule_test_property_getter_callback($node);
    }
  }
}

```

There's also the outside chance that your getter callback will rely on something having been added to the node object already, by another module's implementation of `hook_node_load()`. You can get past that by moving your implementation to last in the queue, with `hook_module_implements_alter()`.

If you want Views support, I think you'll also need to implement `hook_views_data_alter()` to add the property to the `node` table. But maybe the entity module will magic that up for you, it's a good'un.
> 4 votes

# Answer
Answer suggested by Clive works perfect. For views integration 'entity views field' =\> TRUE, has to added, for example

```
    function mymodule_entity_property_info_alter(&$info) {
      $info['node']['bundles']['mynode']['properties']['test_property'] = array(
        'label' => t('Just a test!'),
        'type' => 'integer',
        'computed' => TRUE,
        'required' => TRUE,
        'getter callback' => 'mymodule_test_property_getter_callback',
         'entity views field' => TRUE,
    );
    watchdog("normal", print_r($info, true));
    }

```
> 0 votes

---
Tags: nodes, entities
---


# Question
Title: Where can I configure user and admin email message in Ubercart cart module?
Where can I configure user and admin email message in Ubercart cart module in Drupal 7?

I want to change the email body of user notification email and admin.

# Answer
Go to

> sites/all/module/ubercart/uc\_order/templates/

than select *file user* or *admin*
> 0 votes

---
Tags: 7, ubercart
---


# Question
Title: Drupal 7: use Form API to make a button that doesn't submit the whole page
I want a button that runs a callback function using the AJAX method included in Form API. The button I have still submits the whole node edit form. I don't want it to do that - just pass a couple variables to the callback function and display the results. How can I do that?

This is my FAPI code for that button:

```
    $form['rid_import']['rid_get'] = array(
                '#type' => 'button',
                '#value' => t('Import'),
                '#attributes' => array(
                    'id' => array('fetch_rid'),
                    'class' => array('col-sm-3', 'col-xs-4')
                ),
                '#parents' => array('rid_import'),
                '#limit_validation_errors' => array(),
                '#executes_submit_callback' => false,
                "#submit" => array('sql_no_submit'),
                '#ajax' => array(
                    "callback" => 'sql_fetch_restid',
                    "wrapper" => 'rid_sql_query',
                    "event" => 'click'
                )
          );

```

**EDIT**

You're right, I was being unclear. Basically what I wanted is something that works like your "Add More" or "Remove" buttons when you have multiple-value fields, but just to run my function without reloading the page – grab some data from the DB and show it there on the node edit form. I have a multivalue field collection that should be populated with those values and then saved together with the rest of the node. That's why I don't want it to go ahead and save the node. However, if it isn't possible I guess I will have to find another way to do what I need.

And tried to add a submit function, still reloads the whole page.

# Answer
Just try to use "submit" as the type and specify a custom "#submit". From the ajax\_example module:

```
$form['add_name'] = array(
  '#type' => 'submit',
  '#value' => t('Add one more'),
  '#submit' => array('ajax_example_add_more_add_one'),
  '#ajax' => array(
    'callback' => 'ajax_example_add_more_callback',
    'wrapper' => 'names-fieldset-wrapper',
  ),
);

```

This does not submit the form with the default submit handler but with your own. In this case it is "ajax\_example\_add\_more\_add\_one".

Hope it helps, j
> 1 votes

# Answer
Well, I happened to find this entry: Ajax Callback Function in Submit Button Doesnt Work

The answer was to remove the ID of the submit button. Which I did. Now at least I'm not getting a page reload.

I will mark this as solved. Thanks to Mołot and schlicki for their time.
> 1 votes

---
Tags: 7, forms
---


# Question
Title: Can't access custom field through entity_metadata_wrapper
I've created a custom field and widget with the Field API. I've added this custom field to one of my node entities by using the Field UI and named it field\_pec\_uuid. However, when i try to access the values of this field by using entity\_metadata\_wrapper like so:

```
$node_wrapper = entity_metadata_wrapper('node', $nid);
print $node_wrapper->field_pec_uuid->value();

```

It will give me the following error:

```
EntityMetadataWrapperException: Unknown data property field_pec_uuid. in EntityStructureWrapper->getPropertyInfo() (regel 335 van /webroot/d7_root/sites/all/modules/contrib/entity/includes/entity.wrapper.inc).

```

When I print the values of $node\_wrapper-\>value() I can clearly see the field exists and even has the value I've been giving it. However, when I print the values of $node\_wrapper-\>getPropertyInfo() I can see the field name is not listed. What am I missing here? Anyone has any indications?

I can't for the life of me figure out how to get my field listed by $node\_wrapper-\>getPropertyInfo(). Below is my code.

```
/**
 * Field & Widget section
 */

/**
 * Implementation of hook_field_info()
 *
 * @return [type] [description]
 */
function poh_eduref_field_info() {
  return array(
    'eduref_uuid' => array(
      'label' => t('Eduref UUID Field'),
      'description' => t('This field stores UUID values.'),
      'settings' => array('allowed_values' => array(), 'allowed_values_function' => ''),
      'default_widget' => 'poh_eduref_eduref_widget',
      'default_formatter' => 'poh_eduref_field_formatter_view',
    ),
  );
}

/**
 * Implements hook_field_widget_info
 *
 * @return [type] [description]
 */
function poh_eduref_field_widget_info() {
  return array(
    'poh_eduref_eduref_widget' => array(
      'label' => t('Education Reference Field'),
      'field types' => array('eduref_uuid'),
      'settings' => array(
        'autocomplete_path' => 'eduref/autocomplete',
      ),
    ),
  );
}

/**
 * Implements hook_field_widget_form()
 *
 * @param  [type] &$form       [description]
 * @param  [type] &$form_state [description]
 * @param  [type] $field       [description]
 * @param  [type] $instance    [description]
 * @param  [type] $langcode    [description]
 * @param  [type] $items       [description]
 * @param  [type] $delta       [description]
 * @param  [type] $element     [description]
 * @return [type]              [description]
 */
function poh_eduref_field_widget_form(&$form, &$form_state, $field, $instance, $langcode, $items, $delta, $element) {
  $item =& $items[$delta];

  $element['uuid'] = array(
    '#type' => 'fieldset',
    '#title' => $element['#title'],
    '#description' => t('This is the description.'),
  );

  $element['uuid']['value'] = array(
    '#type' => 'textfield',
    '#title' => 'Education Reference',
    '#autocomplete_path' => $instance['widget']['settings']['autocomplete_path'],
    '#default_value' => isset($item['value']) ? $item['value'] : '',
  );

  return $element;
}

function poh_eduref_field_presave($entity_type, $entity, $field, $instance, $langcode, &$items) {
  if($field['type'] == 'eduref_uuid') {
    foreach ($items as $delta => $item) {
      if (isset($item['uuid']['value'])) {
        $items[$delta]['value'] = $item['uuid']['value'];
      }
    }
  }
}

/**
 * [poh_eduref_autocomplete_callback description]
 * @param  [type] $string [description]
 * @return [type]         [description]
 */
function poh_eduref_autocomplete_callback($string) {

  $query = new EntityFieldQuery();
  $result = $query->entityCondition('entity_type', 'node')
  ->entityCondition('bundle', 'poheduref')
  ->fieldCondition('field_eduref_display_name', 'value', $string.'%', 'LIKE')
  ->execute();

  if($result['node']) {
    foreach(array_keys($result['node']) as $nid) {
      $node = entity_metadata_wrapper('node', $nid);
      if($node->field_eduref_uuid && $node->field_eduref_display_name) {
        $json_array[$node->field_eduref_uuid->value()] = $node->field_eduref_disorder->value().'/'.$node->field_eduref_type->value().'/'.$node->field_eduref_display_name->value();
      }
    }
  }

  return drupal_json_output($json_array);
}

/**
 * Implementation of hook_field_is_empty()
 *
 * @param  [type] $item  [description]
 * @param  [type] $field [description]
 * @return [type]        [description]
 */
function poh_eduref_field_is_empty($item, $field) {
  $temp = array_keys($field['columns']);
  $key = array_shift($temp);
  return empty($item['uuid'][$key]);
}

function poh_eduref_field_formatter_info() {
  return array(
    'eduref_uuid' => array(
      'label' => t('UUID'),
      'field types' => array('eduref_uuid'),
    ),
  );
}

function poh_eduref_field_formatter_view($entity_type, $entity, $field, $instance, $langcode, $items, $display) {
  $element = array();
  switch ($display['type']) {
    case 'eduref_uuid' :
      foreach ($items as $delta => $item) {
        if (isset($item['value'])) {
          $element[$delta]['#markup'] = $item['value'];
        }
      }
      break;
  }
  return $element;
}

/**
 * [poh_eduref_field_validate description]
 * @param  [type] $entity_type [description]
 * @param  [type] $entity      [description]
 * @param  [type] $field       [description]
 * @param  [type] $instance    [description]
 * @param  [type] $langcode    [description]
 * @param  [type] $items       [description]
 * @param  [type] $errors      [description]
 * @return [type]              [description]
 */
function poh_eduref_field_validate($entity_type, $entity, $field, $instance, $langcode, $items, &$errors) {
  foreach ($items as $delta => $item) {
    if(empty($item['field_pec_uuid'])) {
      //$errors[$field['field_name']][$langcode][$delta][] = array('error' => 'uuid_empty_error', 'message' => t('Field empty.'));
    }
  }
}

```

EDIT: For anyone who stumbles into the same issue; the solution as provided by Clive was to add a property\_type key to the hook\_field\_info implementation, like so:

```
function poh_eduref_field_info() {
  return array(
    'eduref_uuid' => array(
      'label' => t('Eduref UUID Field'),
      'description' => t('This field stores UUID values.'),
      'settings' => array('allowed_values' => array(), 'allowed_values_function' => ''),
      'default_widget' => 'poh_eduref_eduref_widget',
      'default_formatter' => 'poh_eduref_field_formatter_view',
      'property_type' => 'text',
    ),
  );
}

```

In my case 'text' as value will suffice, as its a simple textfield. If you need more advanced examples I recommend reading the links Clive provided.

# Answer
`EntityMetadataWrapper` comes from the Entity API module; by default it only knows about core field types, you have to explicitly tell it how to handle custom fields.

That involves adding `property_type` and possibly `property_callbacks` keys to your field info array.

See What does the 'property\_type' key do in hook\_field\_info()? for a bit more information, and here for a code sample.
> 3 votes

---
Tags: entities
---


# Question
Title: htaccess multisite config crashed after sites move to other host
I am on my long way to move my D6 site to other hosting company. It was hard but finally seems it's almost done but I am stacked on multisites configuration. Situation is like this:

**Drupal folder (from ftp/apache access point of view)**

* /webs/drupal/site (main )
* /webs/drupal/site/sites (multisites)

**domains:**

* www.a.com
* www.b.a.com

point to:

* /webs/drupal/

**/webs/drupal/.htaccess file**

```
#redirect to */site
RewriteEngine On
RewriteCond %{HTTP_HOST} ^(www.)?b.a.com$
RewriteRule ^(/)?$ site [L]
RewriteCond %{HTTP_HOST} ^(www.)?a.com$
RewriteRule ^(/)?$ site [L]

```

**/webs/drupal/site/.htaccess**

* it's standard D6 .htaccess with "always add 'www' prefix" rule on

**The problem is that I can:**

* access default site using all combinations like www.a.com, a.com, a.com/site
* access subsite like www.b.a.com/site

**but all calls like:**

* www.b.a.com
* b.a.com

**redirects to the main site www.a.com/site ...**

Any ideas?

# Answer
> 1 votes
It was a matter of the firefox cached data. After cleaning the cache it works.

---
Tags: multi-sites, .htaccess
---


# Question
Title: How to change order_number on hook_commerce_payment_order_paid_in_full or hook_commerce_checkout_complete
I'm trying to change the order\_number after the order has been created. Specifically, I need to do this in the `hook_commerce_checkout_complete` or `hook_commerce_payment_order_paid_in_full` functions.

I'm sending orders out for 3rd party fulfillment and want to store the 3rd party's unique order\_number (which is different than Drupal Commerce's order\_number) into DC's order\_number column.

I **do not** need to change the order\_number in `hook_commerce_order_presave` because this happens before I make the call to 3rd party fulfillment when the new order\_number gets generated in their system.

You can see in the code below that this is being executed as the order is paid in full, during checkout completion. In this example the order\_number 00001890 is trying to be changed to 9999999 and saved, but the new order\_number is not actually saving.

```
function custom_module_commerce_payment_order_paid_in_full($transaction) {
  print "<pre>";
  print "paid in full\n";
  print_r($transaction);

  $orderid = $transaction->order_id;
  $order = commerce_order_load($orderid);

  print "BEFORE CHANGING ORDER NUMBER \n";
  //order number is 00001890
  print_r($order);

  $order->order_number = 9999999;

  print "AFTER CHANGING ORDER NUMBER \n";
  //order number is 9999999
  print_r($order);

  $result = commerce_order_save($order);

  print "Order save result\n";
  //SAVED_UPDATED = 2
  print_r($result);

  print "DID ORDER NUMBER CHANGE??? \n";
  //no, it did not change, it's still 00001890
  print_r($order);

  $order = commerce_order_load($orderid);
  //confirm order number did not change, it's still 00001890
  print_r($order);

  print "</pre>";
  die();
}

```

Any help or advice would be much appreciated!

# Answer
I don't think it's a good idea to change the order id.

I would rather goto `admin/commerce/config/order/fields` and a new number field which will be used to store the 3rd party's order id in the field.

That way you are not changing the default workflow of Drupal commerce and it will also be easier for you to compare your order id against the third party order id if something goes wrong.
> 0 votes

---
Tags: commerce
---


title: Change pager href attribute

text:
# Question
Title: Change pager href attribute
I'm new to Drupal and I've a 'pager' link that shows the second page of a block. It's `href` attribute is set to something like this `'?page=0%2C1'` I want it to be simply `'#'`. It worked by setting `$attributes['href']` to `'#`' in pager.inc but I'm not sure if I'm supposed to modify this file or not.

# Answer
> 0 votes
I think we've covered why this might not be a good idea in comments, but to change the output of the pager you just need to override `theme_pager_link()` in your site's theme.

You'll need to reproduce the original function almost exactly, except you'll probably want to ditch the use of `pager_get_query_parameters()`, and alter the `url()` on the penultimate line to use a fragment.

---
Tags: paging
---