# Question
Title: Does Commerce Override Username Or Is Username Linked To A Node?
Commerce Kickstart 2.

I used the included Feed to import users. I applied this patch: https://www.drupal.org/node/1570544 so I could keep the existing UIDs. Seemed to work OK.

I then wrote a script to import sales orders from an external db. That too seemed to go OK, except that the Username displayed on all reports, views, in fact -anywhere- that the field User:Name is displayed, it shows the First Name/Last Name of the billing profile of the last linked order. eg.

The username is 'MEGACORP'. But 'Frank Smith' is displayed as the User Name because that was the First/Last name of the imported order. -And- the link to the user account profile is users/frank\_smith

The weird thing is that when people log in, they log in with the -correct- Username, ie. megacorp, -not- Frank\_Smith

I looked at the SQL table Users and the Username is correct. (ie. megacorp)

AND I stumbled on creating a view of users, but as a wild-ass-guess set a relation to node entity reference and the Title field is 'Megacorp'.

Here are my field mappings in my customer profile import:

```
// Full Name(Required)
$profile_billing->commerce_customer_address[LANGUAGE_NONE][0]['name_line'] = $name;
// Country(Required)
$profile_billing->commerce_customer_address[LANGUAGE_NONE][0]['country'] = $row->country_iso_code_2;
// Address 1(Required)
$profile_billing->commerce_customer_address[LANGUAGE_NONE][0]['thoroughfare'] = $row->billing_street1;
// Address 2
$profile_billing->commerce_customer_address[LANGUAGE_NONE][0]['premise'] = $row->billing_street2;
// City(Required)
$profile_billing->commerce_customer_address[LANGUAGE_NONE][0]['locality'] = $row->billing_city;
// State(Required)
$profile_billing->commerce_customer_address[LANGUAGE_NONE][0]['administrative_area'] = $row->zone_code;
// Postal Code(Required)
$profile_billing->commerce_customer_address[LANGUAGE_NONE][0]['postal_code'] = $row->billing_postal_code;
//Business name(Required)
$profile_billing->field_business_name[LANGUAGE_NONE][0]['value'] = $row->billing_company;
 // Phone(Required)
$profile_billing->field_phone_number[LANGUAGE_NONE][0]['value'] = $row->billing_phone;`

```

So... 1. why is Username not pulling from the Users SQL table?

2. Is the above behaviour something Commerce does? If so, can I turn it -off-?
3. Is there -always- a related node for each user?
4. The field billing\_company doesn't seem to display on any view, even though it is available to import. How do I access -that-? I guess -that- is what I expected to appear on various forms/reports (eg. the invoice)

# Answer
> 6 votes
Commerce Kickstart 2 includes the following function, which uses hook\_username\_alter() to alter the display of the username to be the billing name, which is what it sounds like you're seeing here.

The easiest way around this would be to just delete this function, which is located in "/profiles/commerce\_kickstart/modules/commerce\_kickstart/commerce\_kickstart\_user/commerce\_kickstart\_user.module" from you're Drupal site's root directory.

```
/**
 * Implements hook_username_alter().
 */
function commerce_kickstart_user_username_alter(&$name, $account) {
  if (!empty($account->uid) && module_exists('commerce_addressbook')) {
    if ($billing_profile_id = commerce_addressbook_get_default_profile_id($account->uid, 'billing')) {
      $billing_profile = commerce_customer_profile_load($billing_profile_id);
      if (!empty($billing_profile->commerce_customer_address[LANGUAGE_NONE][0]['name_line'])) {
        $name = $billing_profile->commerce_customer_address[LANGUAGE_NONE][0]['name_line'];
      }
    }
  }
}

```

---
Tags: users, commerce
---


# Question
Title: Multiple copies of the same content shown due to voting
I have made an image gallery using views. I want to create a vote option for each image. I used the Rate module and I've created a rate button which looks something like this

I used the yes/no widget and changed the option to this

In my gallery view I've selected the `Content:Votes` relationship and changed the `value type` to `options` and `vote tag` to `normal vote`

The problem is multiple copies of the same content appear in the gallery when the votes are increased. How can I fix this issue? or is there any other way to do this?

# Answer
> 1 votes
You can do it at least in 4 different ways that I can think of:

1. You can have a quick fix if you change the show to Content | Teaser or any other display of show: content
2. You can enable `Use aggregation:Yes` under Advanced menu.
3. Check if any of your fields have multiple values, like more than 1 images in your case which is a gallery. and use `grouping fields` to fix it.
4. in your multi value field (probably your image field) under `Multiple field settings` check `Display all values in the same row` and then beneath the fields, set Display `1` value(s) starting from `0` and you should be good to go.

**Update:** 5. Use Views Grouping Row Limit module to limit the output of each grouped row.

# Answer
> 4 votes
Hmm.. On the right side, go to **Advanced**, **Other**, then **Query Settings**.

Select the checkbox for "Distinct", and click Apply.

According to the help note:

> This will make the view display only distinct items. If there are multiple identical items, each will be displayed only once. You can use this to try and remove duplicates from a view, though it does not always work. Note that this can slow queries down, so use it with caution.

There are more options past that if it doesn't work.. making it more strict, for example. But as the help note mentions.. this doesn't always work.

# Answer
> 0 votes
I had to use the Views Distinct module. Added NID to list of fields, exclude from display and then use filter repeat in the Views Distinct Settings. Funny thing is I had to increase the number of items in the pager to more than the actual number of images, else not all show up.

---
Tags: views, rating
---


# Question
Title: How to trigger / launch a colorbox programatically?
I would like to launch a colorbox right after an user has successfully saved a new node.

The content of the colorbox is a drupal block which would contain instructions asking the user to share that newly created node to their social media.

**I am able to set up a link which loads the block into the colorbox when the link is clicked.**

I would like, however, to programatically call the "link clicking" event. So, how do I trigger, by JQuery or otherwise, a colorbox from my custom form submit handler?

# Answer
> 3 votes
Install colorbox module. Read its README.txt to find out how to build links for loading inline and iframe content in a colorbox.

Set the id #cbox\_trigger\_on\_page\_load for your link and place it somewhere in your page and hide it with CSS.

If you are loading inline content, place the content in a block and hide the block too with CSS.

The mechanics of how to place the hidden colorbox link on the right page is not really what the question is about, is it?

So, lets stick with how to trigger the colorbox.

```
/**
 * Implements hook_preprocess_html();
 */
function MYMODULE_preprocess_html(&$variables) {
  // The overlay content from the site in an iframe should have cbox_overlay
  // as first path argument.
  // i.e. http:/mywebsite.com/cbox_overlay/content-title.

  // This will prevent a triggering loop.
  $is_cbox_overlay = FALSE;
  if (arg(0) == 'cbox_overlay') {
    $is_cbox_overlay = TRUE;
  }

  $settings = array(
    'is_cbox_overlay' => $is_cbox_overlay,
  );
  drupal_add_js(array('MYMODULE' => $settings), array('type' => 'setting'));

  drupal_add_js(drupal_get_path('module', 'MYMODULE') . '/js/colorbox_onpageload.js', array(
    // Making sure our JQuery code runs after colorbox's.
    'scope' => 'footer',
    'weight' => '15'
  ));
}

```

In the /js/colorbox\_onpageload.js file:

```
(function ($) {
  Drupal.behaviors.MYMODULE = {
    attach: function (context, settings) {
      if (!settings.MYMODULE.is_cbox_overlay && $('#cbox_trigger_on_page_load').length) {
        $('#cbox_trigger_on_page_load')[0].click();
      }
    }

};})(jQuery);

```

# Answer
> 0 votes
You can do it by **Rules**.

Create an action of redirect user to newly created node on "**When a new node is saved**".

Create a **path redirection** action to the freshly created node with some query argument appended e.g. node/10?clbox=10

Now render a block using page.tpl.php or with our custom module to check if the $\_GET\['clbox'\] exists in the url, the colorbox should popup.

Condition can be this way

```
<?php
if(isset($_GET['clbox']) && is_numeric($_GET['clbox'])){
$nid = $_GET['clbox'];
?>
  <script>
    jQuery(document).ready(function() {
       hr = "path to a page with  ?<?php print $nid ?>";
        jQuery("a.customclass").click(
          function(ev) {
            ev.preventDefault(); //To prevent redirection
            var hr = jQuery(this).attr("href");
            jQuery.colorbox({iframe: true, href: hr , innerWidth: 500, innerHeight: 400});
          });
      });
 </script>
<? }

```

Hope it will help

# Answer
> 0 votes
In my thinking, using JavaScript and PHP together in a condition is old school. We used this method in time of PHP4.

However, in Drupal you have a more efficient method of doing this. All you need is a custom module and some js and some alters.

First you need to alter the node submission form to add custom path redirect.

```
/**
 * Implements hook_form_BASE_FORM_ID_alter().
 */
function CUSTOM_MODULE_form_node_form_alter(&$form, &$form_state, $form_id) {
  if ($form['#node']->type == 'custom') {
    $form['actions']['submit']['#submit'][] = 'custom_node_submit_redirect';
  }
}

function custom_node_submit_redirect($form, &$form_state) {
  $form_state['redirect'] = array(
    'node/' . $form['#node']->nid,
    array(
      'query' => array('cbox' => TRUE),
    ),
  );
}

```

Then, in your custom module you need to add hook\_preprocess\_page.

```
/**
 * Implements hook_preprocess_page().
 */
function CUSTOM_MODULE_preprocess_page(&$variables) {
  if ($node = menu_get_object()) {
    $variables['node'] = $node;
    if ($node->type == 'custom' && isset($_GET['cbox'])) {
      drupal_add_js(drupal_get_path('module', 'CUSTOM_MODULE') . '/scripts.js', 'module');
    }
  }
}

```

So here you added a JavaScript to the page if the node object is present. In your JavaScript file, you can add your custom callback to open up the colorbox.

```
Drupal.behaviors.CUSTOM_MODULE_behaviour = function (context)
{
  // callback to open cbox.
};

```

I hope this solves it.

---
Tags: 7, javascript
---


# Question
Title: Create custom form and store form data into database
I am start working with **Drupal** just some days ago. I am really a amateur in Drupal . I just want to know how can I create a form in Drupal with textbox or check-boxes and store the value of the form in the database.

**Like a registration form script in PHP**.

# Answer
Creating the module structure The first step in creating the module is to create a folder for the module. You should put this in `"sites/all/modules/{name of your module}."` Keep in mind that whenever I say "{name of your module}," you should insert the name of your module. For example, we will use the module directory `"sites/all/modules/form_example."`

Now, create two empty text files called `"{name of your module}.module"` and `"{name of your module}.info."`

These two files are required by your module. The .info file contains information about what your module does, while the .module file contains the actual code including hooks. Hooks are functions with special names that will be called by Drupal when actions occur. For example `"form_example_menu()"` is called when menu information is gathered. In many examples, you will see names such as `"hook_menu()"` or `"my_theme_menu()"` and in these cases `"my_theme"` and `"hook"` should be replaced by the name of your module or theme.

Build the basic module files

Here is what we will put into the form\_example.info file. This tells Drupal and users about your module.

```
core = "7.x"
description = "An example module used to learn module development and forms creation."
name = "Form Example Module"

```

There are more options that you can put in the .info file, but the ones above should be added.

Here is the start of our form\_example.module file. This will create a very basic form that only has one field, a submit button.

```
<?php
function form_example_form($form, &$form_state) {

  $form['submit_button'] = array(
    '#type' => 'submit',
    '#value' => t('Click Here!'),
  );

  return $form;
}
?>

```

Note: Do not include the last "?\>" part of the PHP code and leave a trailing blank line at the end of the file. This is the Drupal standard.

The module right now contains one function that will create a form. It is important to note that the function takes the inputs $form, and a reference &$form\_state. This function will be called when Drupal tries to build the form `"form_example_form."`

The process for creating a form is mainly two steps. The first is to build an associative array $form that contains all the fields. The second step is to return that $form variable.

To add a field, you set the variable $form\[{name of your field}\] = array(); Each field can then have a number of attributes, such as `"#type"` and `"#value."` Most of these attributes are named with a proceeding "#" sign.

The field we added above is a submit button with the text "Click Here!" on the button. Note that t() will output text and is a Drupal function that plays nice with translation.

Now that we have a form, we need to add two more function: form\_example\_form\_validate, and form\_example\_form\_submit. These two functions are hook functions that will be called when Drupal validates the form and when it submits the form (assuming it validated).

form\_example.module:

```
<?php
function form_example_form($form, &$form_state) {

  $form['submit_button'] = array(
    '#type' => 'submit',
    '#value' => t('Click Here!'),
  );

  return $form;
}
function

form_example_form_validate($form, &$form_state) {
}
function

form_example_form_submit($form, &$form_state) {
}
?>

```

You will note that these three functions take the same variables. $form is the original form information and can be seen as the original structure of the form. $form\_state holds all of the submitted values as well as other information, some of which you can add yourself. These two functions need to named similar to the other form, but with "validate" and "submit" at the end.

We want to see the form!!! We will add a menu link to this form.

```
form.example.module

<?php
function form_example_menu() {
  $items = array();

$items['examples/form-example'] = array( //this creates a URL that will call this form at "examples/form-example"
    'title' => 'Example Form', //page title
    'description' => 'A form to mess around with.',
    'page callback' => 'drupal_get_form', //this is the function that will be called when the page is accessed.  for a form, use drupal_get_form
    'page arguments' => array('form_example_form'), //put the name of the form here
    'access callback' => TRUE
  );
  return

$items;
}
function

form_example_form($form, &$form_state) {

  $form['submit_button'] = array(
    '#type' => 'submit',
    '#value' => t('Click Here!'),
  );

  return $form;
}
function

form_example_form_validate($form, &$form_state) {
}
function

form_example_form_submit($form, &$form_state) {
}
?>

```

Now enable your module and try to access the link. You will probably need to clear the cache.

Add more functionality to the form.

Now we will add one more field to the form.

```
form_example.module

<?php
function form_example_menu() {
  $items = array();

$items['examples/form-example'] = array( //this creates a URL that will call this form at "examples/form-example"
    'title' => 'Example Form', //page title
    'description' => 'A form to mess around with.',
    'page callback' => 'drupal_get_form', //this is the function that will be called when the page is accessed.  for a form, use drupal_get_form
    'page arguments' => array('form_example_form'), //put the name of the form here
    'access callback' => TRUE
  );
  return

$items;
}
function

form_example_form($form, &$form_state) {

 $form['price'] = array(
    '#type' => 'textfield', //you can find a list of available types in the form api
    '#title' => 'What is Your Price?',
    '#size' => 10,
    '#maxlength' => 10,
    '#required' => TRUE, //make this field required
  );

$form['submit_button'] = array(
    '#type' => 'submit',
    '#value' => t('Click Here!'),
    ),
  );

  return $form;
}
function

form_example_form_validate($form, &$form_state) {
}
function

form_example_form_submit($form, &$form_state) {
}
?>

```

Here we have added a new textfield and made it required. We have also set the maximum length. You'll see if you try to submit the form, that Drupal will automatically produce an error for the user if they don't fill in the required fields. We will add some more validation in the next step.

Add validation

```
form_example.module

<?php
function form_example_menu() {
  $items = array();

$items['examples/form-example'] = array( //this creates a URL that will call this form at "examples/form-example"
    'title' => 'Example Form', //page title
    'description' => 'A form to mess around with.',
    'page callback' => 'drupal_get_form', //this is the function that will be called when the page is accessed.  for a form, use drupal_get_form
    'page arguments' => array('form_example_form'), //put the name of the form here
    'access callback' => TRUE
  );
  return

$items;
}
function

form_example_form($form, &$form_state) {

 $form['price'] = array(
    '#type' => 'textfield', //you can find a list of available types in the form api
    '#title' => 'What is Your Price?',
    '#size' => 10,
    '#maxlength' => 10,
    '#required' => TRUE, //make this field required
  );

$form['submit_button'] = array(
    '#type' => 'submit',
    '#value' => t('Click Here!'),
    ),
  );

  return $form;
}
function

form_example_form_validate($form, &$form_state) {
  if (!($form_state['values']['price'] > 0)){
    form_set_error('price', t('Price must be a positive number.'));
  }
}
function

form_example_form_submit($form, &$form_state) {
}
?>

```

You will now see that the form will not submit unless price is a positive number. We do this by checking the value of price, in $form\_state\['values'\]\[{name of your field}\]. There are similar variables for all of your fields.

We then set an error with form\_set\_error. Adding this error will alert Drupal that the form did not pass validation.

What to do when your form is submitted? From this point, you will want to either save the form data, send an email, or display some information. That is beyond the scope of this How To at this point.

I have built some module "tools" or "calculators" using the above method and included the calculation steps in the submit function. You can set the variable "$form\_state\['rebuild'\] = TRUE;" in the submit function so that Drupal does not clear the form. You can therefore edit the $form\_state to change a "markup" field type to have your output.

This can also be done with AJAX so that the form displays the calculated values without a page load. That gets a little more complicated and may be added as a separate How To.

Conclusions Hopefully this is helpful for people interested in writing a module, or adding a form to a module.

Reference: How to Make a Simple Module with a Form and Menu Link
> 4 votes

---
Tags: forms, database
---


# Question
Title: Pagination for image field in one node page
I made a custom node type with following fields:

* Title
* Body
* Image (Unlimited)

I need to have a few pages from this content type and on each page I need to print the title field, the body and all images, but I need a pagination for the image field - lets say 9 images per page. (pagination only for one field in current node).

Is that possible without using Views, and using theming? For example, making a custom "field--field-images.tpl.php" template file, but instead of using the following code, printing the field with Pagination.

```
foreach ($items as $delta => $item):
  print render($item);
endforeach;

```

# Answer
You can use the CCK Pager project.

> CCK Pager allows to page the item list of any CCK field with multiple values.
>
> The module extends others CCK formatter by paging the field item list; setting the number of elements per page and pager type (full or mini) can be made per field. It only works with versions of CCK \>= 6.x-2.5.

Look at this demonstration, and if you are using Drupal 7, follow the status of these issues.
> 1 votes

# Answer
If you are looking for a solution compatible with Drupal 7, a good alternative to CCK Pager would be to embed a view that prints the paginated field content, as pointed out in this blog post.
> 1 votes

---
Tags: theming, entities, paging
---


# Question
Title: Unattended automatic security updates / upgrades
What is the best way to get Drupal to automatically perform security updates? And are people commonly employing such a method?

For motivation, consider this: Drupal just released a PSA about a recent vulnerability saying:

> *...You should proceed under the assumption that every Drupal 7 website was compromised unless updated or patched before Oct 15th, 11pm UTC, that is **7 hours** after the announcement.*

Fortunately I caught this one and performed the update manually one hour after the announcement. But what if I hadn't? I'd like to have an automatic update process in place to give me some piece of mind.

And I'd like for this automatic upgrade system to only apply security updates. (It just doesn't seem worth the risk to bother with potentially breaking some functionality after an update, unless the update is critical.)

# Answer
> 7 votes
Please also keep in mind there are '0-day' vulnerabilities out there, which can be used to compromise your website even before Drupal publishes a security advisory and corresponding patch. And that even if you use an automated update for Drupal core, there still will be a time window in which your site was vulnerable.

The best way to deal with these kind of issues is therefore to have all your Drupal code in a version control system - Subversion or Git for example. This way you can easily:
\- identify when there has been an intrusion with a status command (this will show you all modified files in your source files)
\- reverting these changes, and therefore repair all harm done, by resetting the source tree to your latest commit

The only downside is that you have a little more work to do with each update, as you need to commit all changes back to your repository after each code change. But this is a very small price to pay for the added benefits and piece of mind this provides.

# Answer
> 0 votes
There's a huge discussion regarding this. Follow up https://www.drupal.org/node/2367319 and decide.

---
Tags: security, upgrading
---


# Question
Title: Remove order from Field Collection set in form
I am using the Field Collection and Field Collection Fieldset modules to group a set of elements in my form. But what i see in the form is an Order column for the fieldset items, which i would like to hide, as shown in the below screenshot.

I have tried a lot to figure out if i can hide the Order from the backend, but i could not find a setting for it anywhere. So i am now looking forward to use a hook, to hide it. I also checked the field level structure using Devel module and `dpm($form);` but i have no idea on how to accomplish this. Can anyone help me?

# Answer
Well, as Rupesh suggested in his comment, i was able to use CSS for hiding the Order column in my form:

First, i specified an ID for the fieldset field in my module's **node\_form\_alter()** function:

```
$form['field_user_details']['#attributes'] = array('id' => 'user_details');

```

Then in my CSS, i used these lines to hide the Order column:

```
#user_details table th:nth-child(2) { display: none; } /* Hide the Order column Label */
#user_details table td.delta-order { display: none; } /* Hide the Order column */

```
> 0 votes

---
Tags: 7, entities
---


# Question
Title: How can I pass an empty case subject from Webform CiviCRM integration to CiviCRM?
I am using Drupal 7 and CiviCRM 4.4.2. I have created a form with Webform CiviCRM integration that creates a new case. However, the case subject should be generated in CiviCRM, based on a standard pattern. The code replaces {contactName}-{caseType}-{caseId} with the values in the civicrm\_post hook. How do I set the default value of the case subject in the Webform whilst not showing the field on the webform?

# Answer
In the webform, give the field the default value that you want to use, and then change the field widget to 'Hidden' so that the field is not exposed to the user on the form. The default value will then be submitted, and subsequently modified/overridden by your hook.
> 2 votes

---
Tags: webforms, civicrm
---


title: Theme rendering

text:
# Question
Title: Theme rendering
I have a question. I am using commerce kickstart and i want to display field group under the pictures and text. Now in node--product--type.tpl.php are the attributes for rendering.

The code I am using is the following.

```
     <div class="container-24 grid-8 prefix-1">
    <div<?php print $content_attributes; ?>>
      <?php
        // We hide the comments and links now so that we can render them later.
        hide($content['comments']);
        hide($content['links']);
        print render($content);
      ?>
    </div>
  </div>
  <div class="container-24 grid-24 clearfix">
   <div<?php print $content_attributes; ?>>
      <?php
        // We hide the comments and links now so that we can render them later.
       print render($content['comments']);
      ?>
  </div>

```

How can I put field group (I have created 3 tabs) in `<div class="container-24 grid-24 clearfix">`?

I don't know how to find `print render($content['???']);` where *????* stands for the attribute.

# Answer
You can group fields using field group module.

These are the steps on how to use field group module.

1. Download the module at https://drupal.org/project/field\_group
2. Enable the module
3. Go to the manage display settings, where you want to add your field group
4. At the bottom of the page you will see add new group fill up the field and label of the field group; after that you can now drag and drop the field inside the field group that you created
> 1 votes

# Answer
Ok, In the 'node--product--type.tpl.php' file.

I got it working by the principle of hide in the first container and render where you want it. For me (using commerce kickstart 2)it looks like this:

```
<div class="container-24 grid-10 prefix-2 clearfix">
 <?php
print render($content['title_field']);

print render($content['product:field_images']); ?>
  </div>

  <div class="container-24 grid-11 prefix-1">

 <div<?php print $content_attributes; ?>>
      <?php
    // We hide the comments and links now so that we can render them later.

hide ($content['group_koffie']);

hide($content['comments']);
        hide($content['links']);
        print render($content);
      ?>
    </div>
  </div>
  <div class="container-24 grid-22 prefix-1 clearfix">

    <?php
print render($content['group_koffie']);

print render($content['comments']);

    ?>

```

An extra thing to be aware of is that (again in my case) you have to name the field ($content\['group\_koffie'\]) when it is a **display-field**. (or (**$content\['field\_regio'\])** if it is not a group but a single field)

When it is a **product-item/ variation-field** you name the field **($content\['product:field\_images'\])** Took me a long stare to find that.
> 0 votes

---
Tags: entities, commerce
---


# Question
Title: CiviCRM Profile form buttons showing but not linked in Drupal profile
We are using CiviCRM profiles to allow members to update addition information. We have marked these profile forms in CiviCRM as 'View/Edit Drupal Account' and 'Drupal User Registration. The buttons appear (and disappear if you remove these settings) in the user profile editing screens. When the buttons are clicked on the user is taken to their Drupal profile, not the screens to capture the CiviCRM data as per this screen shot.

This was working on this site. What changed? We did a general drupal upgrade. Drupal 7.19, CiviCRM 4.2.

Thanks Interlated

# Answer
> 1 votes
Based on what you found in the menu\_router table, perhaps Page Manager is throwing a spanner in the works here? There's a good post about Page Manager here: https://drupal.stackexchange.com/a/35187/38865

# Answer
> 1 votes
Just a guess, but try opening the Advanced field set at the bottom of the Edit Profile Settings page, and deselect requiring creation of Drupal user account. You might get more responses if you posted more info on the fields in the profile, for example, what you expect to see.

---
Tags: users, civicrm
---


# Question
Title: Displaying content type in translated languages
So i have a Content Type named "My content type" (a simple form) and it has 5 fields.Now the default language of the field names is in English.\[i.e feild1 is 'Name'\]. I have translated the field names using the translation interface into 20 different languages.And when users fill out the form the field names are in their respective and/or preferred language.I have created a custom page template for "My content type",and print the `$content` of the form there,but it is English (in other words,the field names are displayed as they are written in the content type itself).

My question : How can i display the results of the filled form so that the field names are in a specific translated language ?

A little visual example :

(this is how the "My content type" results are displayed, atm) :

```
First Name : lorem
Last name : ipsum
Age : 55
Hobbies : lorem ipsum

```

(and i want the display the field names in a specific translated language,i.e. German)

```
Vorname : lorem
Familienname : ipsum
Alter : 55
Hobbys : lorem ipsum

```

This would be a sinch to do if i could use views (but sadly i can't,client specific rule)

If anyone can help ,i'd greatly appreciate it :)

# Answer
> 0 votes
Since you wrote a custom template for your content type. I think the problem would be rendering fields without any specific language

For Example:

In your Template to print a field:

```
$field_language = field_language('node', $node, 'body');

<?php print($node->body[$field_language][0]['value']); ?>

```

Since drupal 7 uses **Entity translation** . You need to select language for specific fields instead of node.

---
Tags: i18n-l10n
---


# Question
Title: In nodereference field of a content type, Is it possible to show the content type name added with the autocomplete results?
In nodereference field of a content type, Is it possible to show the content type name added with the autocomplete results ?

## Example :

I have a content type named Article which has a node reference field (Related content -\> field\_related\_documents), So that this article will referenced to other nodes.

While creating an article, by entering 'help' in 'field\_related\_documents' I am getting autocomplete results (titles of referenced nodes) like below

```
helpsystems - rules
Decision management Help
Using help menu
Help support glossary

```

Instead, I like to show results like below

```
Page | helpsystems - rules
HelpSystems | Decision management Help
Page | Using help menu
Document | Help support glossary

```

ie) autocomplete results should display title of other nodes added with their related content type.

How should i achieve this ?

# Answer
I created a new custom Module nodereference\_patch with below hook

```
/*
 * Altering nodereference/autocomplete menu using menu alter
 */
function nodereference_patch_menu_alter(&$items) {
  $items['nodereference/autocomplete']['page callback'] = 'nodereference_patch_new_nodereference_autocomplete';
}

```

Then, I copied the nodereference\_autocomplete function into your custom module, changing it's name to nodereference\_patch\_new\_nodereference\_autocomplete.

Then I changed this line:

```
$matches[$row['title'] ." [nid:$id]"] = '<div class="reference-autocomplete">'. $row['rendered'] . '</div>';

```

to

```
$matches[$row['type'] . " | " . $row['title'] . " [nid:$id]"] = '<div class="reference-autocomplete">' . $row['type'] . " | " . $row['rendered'] . '</div>';

```

I copied \_nodereference\_potential\_references function from nodereference.module to custom module and renamed it as \_nodereference\_patch\_potential\_references

Then I changed the following line as

```
$references = _nodereference_potential_references_standard($field, $string, $match, $ids, $limit);

```

to

```
$references = _nodereference_patch_potential_references_standard($field, $string, $match, $ids, $limit);

```

I copied \_nodereference\_potential\_references\_standard from nodereference.module to custom module and renamed it as \_nodereference\_patch\_potential\_references\_standard

Then I added 'type' element to $references\[\]. ie) changed following array from

```
$references[$node->nid] = array(
    'title' => $node->node_title,
    'rendered' => check_plain($node->node_title),
);

```

to

```
$references[$node->nid] = array(
    'title' => $node->node_title,
    'type' => $node->node_type,
    'rendered' => check_plain($node->node_title),
);

```
> 1 votes

---
Tags: 7, hooks, nodes
---


# Question
Title: Hash method not providing password that is stored in database
I created a custom form for the registration, but I am not getting how to store the password in hash format in the database.

I am using the following code, but I am not getting the value Drupal saves in the database for the password.

```
require_once DRUPAL_ROOT . '/' . variable_get('password_inc', 'includes/password.inc');
echo user_hash_password('taliadmin');

```

Why am I getting a different value?

# Answer
> 2 votes
That's pretty much the point. `user_hash_password` uses `_password_generate_salt`, which in turn uses `drupal_random_bytes`. This means hash returned will always contain randomization and is designed not to return the same result twice. Or at least do it as rarely as possible, because there is 2^(6\*8) possible outputs of 6 random bytes.

To test passwords, Drupal uses `user_check_password`. This function extracts salt from stored password and applies it to the one user provided.

Note that by design Drupal does not have any function that would allow to recreate hashes perfectly, and it's not possible to write one (without using original hash to extract salt, that is). You can get pretty close if you need to, copying logic from `user_check_password`, but it is actually better to leave salt changing as much as possible.

---
Tags: entities, users
---


# Question
Title: How to set a rule that assigns a user to a specific Organic Group after the checkout process
I´m using rules, organic groups and drupal commerce modules.

I´ve set a rule that creates a new user after the anonymous completes the checkout process.

I want the rule to assign the user to a specific group (OG). I can´t find the way to do it. I´ve added a screenshot of what are the available options,a nd it seems that there aren´t enough available selectors to do that.

Is there a way to add the user using php? How? I´ve added the print screen after setting Action: Add entity to group.

# Answer
For reference, this type of use case (selling access to an organic group) would be best handled now using the Commerce License framework, that has been designed specifically for this type of use cases.

We don't have integration with Organic Groups yet, but it seems straightforward to do in the framework.
> 1 votes

# Answer
There is a step-by-step tutorial to do exactly what you want at http://s1l.org/selling-access-organic-groups-drupal-commerce

Also this would indeed be the perfect case for using the Commerce License framework. There is Commerce License OG module now.
> 1 votes

---
Tags: commerce, rules, organic-groups
---


title: Add drush alias with arguments

text:
# Question
Title: Add drush alias with arguments
I'm working with drush & git and I would like to create a custom drush alias to perform a "git pull" action on a remote server.

This is possibile creating a drushrc.php file in drush home directory with this command:

```
$options['shell-aliases']['git-checkout'] = '!git checkout';

```

So if I run

```
drush @mysite.test git-checkout

```

the system performs a "git checkout" on the test server.

The problem is that I would like to send parameters, like:

```
$options['shell-aliases']['git-checkout'] = '!git checkout %branch';

```

and so:

```
drush @mysite.test git-checkout my_custom_branch

```

should checkout a specific branch.

Is there a way to do this?

# Answer
> 4 votes
Drush will pass any extra argument in the shell alias to the command. So define the shell alias as:

```
$options['shell-aliases']['git-checkout'] = '!git checkout';

```

and simply run

```
drush @mysite.test git-checkout my_custom_branch

```

# Answer
> 0 votes
Maybe the solution is to create not an alias, but a custom command for `drush` (here are the instructions).

# Answer
> 0 votes
You can use special shell alias replacements such as `{{sitealias-item}}`, `{{%pathalias-item}}` or special `{{@target}}`, which is replaced with the name of the site alias used.

Or maybe instead of trying to create complex alias, try creating a command file called `COMMANDFILE.drush.inc` (as already suggested by arrubiu).

---
Tags: drush
---


# Question
Title: Validation and Setting value for Multi-value fields
Consider for a content type, there is a text field with multiple values capability activated.

1. How can I check its values by $form\_state inside the Validate/Submit function?
2. How can I set its values by $form\_state inside the Validate/Submit function?

The single code line for each of them would be enough for me to see, Thanks.

Further discussion:

I need to set/check the MULTI-VALUE fields' values. It's related to the DELTA value and ... but I don't know how clearly I can do it!

# Answer
Clearly, for any multi-value field there is a delta value inside each fields' table in Drupal Database, which corresponds to the index of the value for that entity instance.

According to this knowledge, the structure of the form\_state variable for a multi-value field with two values (e.g. X and Y) is:

```
[field_FIELD_NAME] => Array
                (
                    [und] => Array
                        (
                            [0] => Array
                                (
                                    [value] => X
                                    [_weight] => 0
                                )
                            [1] => Array
                                (
                                    [value] => Y
                                    [_weight] => 0
                                )

                            [add_more] => Add another item
                        )

                )

```

\[0\] and \[1\] are delta values for each value of this filed in the corresponding entity instance. For setting the values of a multi-value filed in FORM submit/validate hook, you should do as follows (consider again we have two values X and Y):

```
$form_state['values']['field_FIELD_NAME']['und'][0]=array("value"=>'X',"_weight"=>0);
$form_state['values']['field_FIELD_NAME']['und'][1]=array("value"=>'Y',"_weight"=>1);

```

**The above lines ought to be written inside the VALIDATE hook.**

For reading values for validation, do as follows:

```
$values=$form_state['values']['field_FIELD_NAME']['und'];

foreach ($values as $key => $value) {
  if($value['value']...
}

```
> 1 votes

# Answer
You can do this with `hook_node_validate()` function.

```
function hook_node_validate($node, $form, &$form_state) {
  if ($node->type == '[your_content_type]') {
    // $node : Changed value of Node
    // $form_state['node'] : Original Values if Editing a node
  }
}

```
> 0 votes

---
Tags: 7, forms
---


title: Searching a range by another range

text:
# Question
Title: Searching a range by another range
We are developing a Drupal website for displaying properties. Each property has a minimum and maximum size that is available. The user can search with a minimum and maximum size also.

We need help trying to work out how to setup the View in Drupal 7. For example, a user might search for properties with min size 10,000 sq ft and max size 50,000 sq ft. The following properties would match:

* Property 1 - min size 13,000 sq ft, max size 48,000 sq ft
* Property 2 - min size 10,000 sq ft, max size 50,000 sq ft
* Property 3 - min size 20,000 sq ft, max size 20,000 sq ft
* Property 4 - min size 9,000 sq ft, max size 51,000 sq ft

How should we set this up in the Drupal View? The content type has a min\_size and max\_size already.

# Answer
> 1 votes
Set up two exposed filters (exposed filters show on the view itself, with the user able to set their own value) one for the min\_size field and another for the max\_size field.

When setting up the exposed filters you'll have a choice "expose operator." With that choice you can allow the user to choose the operator (e.g. less than, greater than, greater than or equal to, etc.). The end user can use either of the exposed filters or both.

You'll need to be pay attention to your label choices and the help text you create to make sure what you come up with is easy to use and returns the expected results.

---
Tags: views
---


# Question
Title: Changing user picture HTML output on user profile
How do I customise the HTML output for the user picture on a user profile? I can output it in user-profile.tpl.php with `<?php print $user_profile['user_picture']['#markup'];?>`. However this still leaves the original user picture output there too. How do I remove this? The answer in Disable displaying user picture in page--user.tpl.php won't work as that deletes $user\_profile\['user\_picture'\], which I'm using.

For an example of this, see http://dev.effectivealtruismhub.com/user/tom-ash . The top, left-floated image is the one I've manually output with `<?php print $user_profile['user_picture']['#markup'];?>`. But the right floated one is the one that Drupal auto-generates, in the wrong place in the HTML to be positioned right. How can I remove this auto-generated HTML?

# Answer
> 4 votes
Hmmm, it sounds like you likely left the following line of code in user-profile-tpl.php:

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

```

Remove the above line of code.

The duplicate image will go away. And so will anything else in the profile.

You'll need to add back each individual item that you actually want via the same method you used to add just the pic, but for other fields in the profile:

```
<?php print $user_profile['user_picture']['#markup'];?>

```

If you are using the Panels module, this is trivial to do without touching any code or needing to dive into the $user\_profile array.

---
Tags: theming
---


# Question
Title: Programatically adding Taxonomy text field
This code is throwing a *FieldException: Attempt to create a field of unknown type text. in field\_create\_field() (line 111 of C:\wamp\www\local.test\modules\field\field.crud.inc).*

```
field_cache_clear();

//Create the appropriate field type
$field = array(
    'field_name' => 'stock_exchange',
    'type' => 'text',
    'module' => 'text',
    'active' => '1',
    'cardinality' => '1',
    'settings' => array(
        'max_length' => 64
    )
);
field_create_field($field);

$instance = array(
    'field_name' => 'stock_exchange',
    'entity_type' => __DEFAULT_VOCAB_MACHINE_NAME,
    'bundle' => __DEFAULT_VOCAB_MACHINE_NAME,
    'label' => 'stock_exchange',
    'description' => 'stock_exchange',
    'required' => false,
    'widget' => array(
        'type' => 'text_textfield'
    ),
);

```

At my wits end here trying to figure out why this won't work. Have tried clearing cache and it's not that.

For some reason it's not accepting a basic text field.

Any ideas?

# Answer
The only way to achieve adding a text field to a Taxonomy Vocabulary is to place it in the *hook\_enable()* function of your module.

If it's outside of that the "Text" module won't be loaded and you'll receive the error above.

**If anyone has a way around that please let me know.**
> 0 votes

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


# Question
Title: D2D file migration cannot processes a number of rows?
In my Drupal 6 site I have 147490 files in the database. On my Drupal 7 site I am using D2D migrate module to import them. The number of Items it sees is exactly the same, 147490. However, it will not processes 5683 of them. 112229 import successfully and 29578 fail (because the file no longer exists on the server, that's fine). When re-running the migration, it will not processes the remaining 5683.

Here is my migration class:

```
  $file_arguments = $common_arguments + array(
    'machine_name' => 'Files',
    'description' => t('Migration of files from Drupal 6'),
    'user_migration' => 'User',
    'default_uid' => 1,
    'source_dir' => 'http://lcl.legacy-d6.com/sites/default/files',
    'destination_dir' => 'public://',
  );

  Migration::registerMigration('Files', $file_arguments['machine_name'], $file_arguments);

```

I am then extending the class with an include: *file\_migration.inc*

```
class Files extends DrupalFile6Migration {
  public function __construct(array $arguemnts) {
    parent::__construct($arguemnts);

  }

  public function prepareRow($row) {
    if (parent::prepareRow($row) === FALSE) {
      return FALSE;
    }

    $filepath  = $row->filepath;
    $new_filepath = str_replace('/var/www/html/liv-dir/production/', '', $filepath);
    $new_filepath = str_replace('/var/www/html/lcl.legacy-d6.com/htdocs/', '', $new_filepath);
    $row->filepath = $new_filepath;

    return TRUE;
  }

}

```

EDIT: I was able to create a snippet that finds all of the missing Ids however I was not able to figure out why they are not being processed.

```
    set_time_limit(0);
    $unprocessed_ids = array();
    db_set_active('legacy');
    $get_fids_query = Database::getConnection('legacy')->select('files', 'fi');
    $get_fids_query->fields('fi', array('fid'));
    $result = $get_fids_query->execute();
    while ($fid = $result->fetchField()) {
      db_set_active();
      $check_migration_query = Database::getConnection('default')->select('migrate_map_files', 'mfi');
      $check_migration_query->fields('mfi', array('sourceid1'));
      $check_migration_query->condition('sourceid1', $fid, '=');
      $check_migration_result = $check_migration_query->execute();
      $check_migration = $check_migration_result->fetchField();
      if ($check_migration === FALSE || is_null($check_migration) || !isset($check_migration)) {
        $unprocessed_ids[] = $fid;
      }
      db_set_active('legacy');
    }
  }

```

UPDATE: The only fix I could find that actually worked was waiting for the migration to run its course and then rollback a small number of rows, and then run through the migration again with --update flag set. Depending on the envioronment I was running on (local vs pantheon) I would have to do this between 5-20 times.

I still want to know why this was happening.

# Answer
> 2 votes
I just faced the same issue, and have a suspicion what the cause may be, though have not tested it.

I ran a migration of files in manual batches, e.g.

```
drush migrate-import MyMigration --limit="100 items"

```

several times. After the last batch (for which I did not specify an item limit, i.e. it should have imported all remaining unprocessed items), `migrate-status` still showed almost 900 unprocessed items. All calls thereafter to `migrate-import` would process 0 items, even with the `--update` flag -- which I thought should have either imported or updated (accordingly) ALL items...

Just as you did, I then queried for the source IDs it would not process. Upon inspection I noticed that large sets of them had the same exact timestamp (specifically, `file_managed.timestamp` column in the database). I recalled that Migrate can use a specified field to store a highwater mark for each migration, such that future import runs will only process items whose value of that field is greater than the stored highwater mark from previous runs. So for files, the `timestamp` value is used by default (per Migrate D2D implementation -- see `DrupalFile7Migration::__construct()`), and the query is ordered by `timestamp ASC` to cooperate with this.

I realized that the items it would not process were definitely older than the stored highwater timestamp (which is that of the newest item imported). Why then did Migrate not process those in an earlier batch, based on the query's order-by? Well... if many of my files had the *same exact* timestamp, the results of the query were not guaranteed to be in the same order across different runs. So if I was working with a limit of 100 items per run, but the results were not consistently ordered, it's possible some items never ended up falling within the batch (range of results) that was actually being imported at the time.

I'm not entirely sure if this could account for nearly 900 unprocessed images, but it's a thought.

**Workaround**

You can import items regardless of their status vs. the highwater mark by using the `--idlist` argument. So since you've queried to find the source IDs that won't process, just pass them as a comma-delimited string and I think it should work no matter what. Example:

```
drush migrate-import MyMigration --idlist="538,2891,485"

```

**Actual fix? (untested)**

If my suspicion is correct, then probably the solution is to order by not only timestamp, but additionally by fid, which is guaranteed unique, and thus the results order will be exactly the same every time. In your migration subclass, override `query()` and after calling the parent implementation, add `$query->orderBy('fid', 'ASC')`. This sets secondary ordering.

---
Tags: files, migrations
---


# Question
Title: How do I in code add new field values to a D8 content entity?
How do I in code, create a new field value, add it to a content entity, and then have it saved to the DB?

Field API is dead. Long live Entity Field API! clearly shows how to read values, but doesn't mention inserts/updates.

# Answer
I'm not sure what you mean with "field value", do you mean field items with multiple values?

It's the same as reading them, nothing special:

```
// Those are identical, not specifying [0] results in that using by default.
$entity->some_field->value = 'Whatever';
$entity->some_field[0]->value = 'Whatever';

// To add a value for the second item:
$entity->some_field[1]->value = 'Something';

// And persist to DB:
$entity->save();

```

Edit, the following script works for me and gives me the following output:

```
<?php
use Drupal\node\Entity\Node;

$node = Node::create(array('type' => 'article'));
$node->field_tags->target_id = 5;
var_dump($node->field_tags->getValue());

$node->field_tags[] = 6;
$node->field_tags[] = array('target_id' => 7);
var_dump($node->field_tags->getValue());

unset($node->field_tags[1]);
var_dump($node->field_tags->getValue());

```

Output:

```
array(1) {
  [0] =>
  array(1) {
    'target_id' =>
    int(5)
  }
}
array(3) {
  [0] =>
  array(1) {
    'target_id' =>
    int(5)
  }
  [1] =>
  array(1) {
    'target_id' =>
    int(6)
  }
  [2] =>
  array(1) {
    'target_id' =>
    int(7)
  }
}
array(2) {
  [0] =>
  array(1) {
    'target_id' =>
    int(5)
  }
  [2] =>
  array(1) {
    'target_id' =>
    int(7)
  }
}

```

The delta is off then in the last example, but this will probably be fixed in https://www.drupal.org/node/2164601, which might also affect how the code above works..
> 4 votes

# Answer
Here's what I've ended up doing. In my examples, I'm adding and removing an entity reference.

How to add a new field value:

```
// Insert a new field value:
$field = 'field_name';
$fieldItems = $entity->$field->getValue();

$entity->$field->setValue(
  array_merge(
    $entity->$field->getValue(),
    array($target_entity)
  )
);
$entity->save();

```

I found no way of removing field items directly, so instead I overwrite all of them.

```
// Removing a field value. In this example, an entity reference.
foreach ($fieldItems as $delta => $fieldItem) {
  if ($fieldItem['target_id'] === $target_entity_id) {
    unset($fieldItems[$delta]);
    $entity->$field->setValue($fieldItems);
    $entity->save();
    break;
  }
}

```
> 1 votes

---
Tags: entities, 8
---


# Question
Title: Reset frontpage after changing it to user
I wanted my drupal site content to only be accessed by users who login.
I have a front-page which works fine: "mysite.com/" I want users to be re-directed to: "mysite.com/user" or "mysite.com/?q=user"

So, I went into the Admin \> Site Configuration \> and changed the front page to be /user

Unfortunately, my home page is exactly the same, no change there, and now I can't access the login to get back in as an Admin.

So, there are two questions:

1) How do I go into the database to reset this setting by hand, or is there a php file I have to go into?

2) Once I get my home page back, and the /?q=user page working again, how can I force users to that page to login before anything that happens.

This is Drupal 7 ... I remember Drupal 5 and 6 being so much easier to manage.

I am also using the MD Apline theme if that matters ....

Thanks for any help! Tom

# Answer
> 1 votes
That's a pickle. This should get you out of it:

`drush vset site_frontpage node`

Or if you don't have access to drush (why would you use drupal without drush?) you can run this sql:

`DELETE FROM variable WHERE name = 'site_frontpage'`

# Answer
> 0 votes
I suggest you look at the LoginToboggan module. Rather than replacing your front-page with a system form (which seems like a bad idea, since that form will give "access denied" to authenticated users) you can set loginToboggan to display a login form on any page that anonymous users do not have access to.

---
Tags: uri
---


title: Google Analytics setup not working

text:
# Question
Title: Google Analytics setup not working
I am trying to setup a Google Analytics property. I have done this before and have had no problems. However this time I am setting it up though the drupal module rather than manually inserting the code. I have my tracking ID and everything filled out, and I inspect the page and I can see the tracking code is installed. However my tracking code isnt being picked up by Google Analytics. This is what it says:

```
Status: Tracking Not Installed

```

I have enabled debugging for the module, and all seems to be sending correctly. Here is the log:

```
Initializing Google Analytics. analytics_debug.js:10
Running command: ga("create", "UA-49353541-2", "auto") analytics_debug.js:10
Creating new tracker: t0 analytics_debug.js:10
Auto cookieDomain found: "carbonfunding.co.uk" analytics_debug.js:10
Running command: ga("send", "pageview") analytics_debug.js:10

Sent beacon:
v=1&_v=j30d&a=1343148915&t=pageview&_s=1&dl=http%3A%2F%2Fwww.carbonfunding.co.uk%2F&ul=en-us&de=UTF-8&dt=Carbon%20Funding%20%7C%20Th…_u=MCCAAEQAI~&jid=&cid=2073925826.1413195127&tid=UA-49353541-2&z=327379316

 analytics_debug.js:10
_j1              (&jid)  analytics_debug.js:10
adSenseId        (&a)   1343148915 analytics_debug.js:10
apiVersion       (&v)   1 analytics_debug.js:10
clientId         (&cid) 2073925826.1413195127 analytics_debug.js:10
encoding         (&de)  UTF-8 analytics_debug.js:10
flashVersion     (&fl)  15.0 r0 analytics_debug.js:10
hitType          (&t)   pageview analytics_debug.js:10
javaEnabled      (&je)  1 analytics_debug.js:10
language         (&ul)  en-us analytics_debug.js:10
location         (&dl)  http://www.carbonfunding.co.uk/ analytics_debug.js:10
screenColors     (&sd)  24-bit analytics_debug.js:10
screenResolution (&sr)  1920x1080 analytics_debug.js:10
title            (&dt)  Carbon Funding | The ECO people analytics_debug.js:10
trackingId       (&tid) UA-49353541-2 analytics_debug.js:10
viewportSize     (&vp)  1903x955

```

I read that it can take up to 72 hours before Google will pick up the tracking code, but I also read that at least the real-time view should be picking myself up on the site. I have also disabled do-not-tack everywhere and no prevail.

Why is this the case?

Thanks, Darryl

# Answer
Adding Google Analytics using the module is not difficult. Please check this YouTube Video "Adding Google Analytics" it will walk you on the process of how to set-up your Google Analytics on your Drupal site. In addition it will to provide you the steps on how to set-up this video will give useful information about the different setting.

If you want to make sure that your website contain the Google Analytics you can check the output of your website (as an anonymous) and you should have something similar to this...

Usually takes few minutes to Google Analytics to recognize your website.

```
<script>
  (function(i, s, o, g, r, a, m) {
    i["GoogleAnalyticsObject"] = r;
    i[r] = i[r] || function() {
      (i[r].q = i[r].q || []).push(arguments)
    }, i[r].l = 1 * new Date();
    a = s.createElement(o), m = s.getElementsByTagName(o)[0];
    a.async = 1;
    a.src = g;
    m.parentNode.insertBefore(a, m)
  })(window, document, "script", "//www.google-analytics.com/analytics.js", "ga");
  ga("create", "UA-xxxxx-1", "auto");
  ga("send", "pageview");
</script>

```
> 1 votes

---
Tags: 7, google-analytics
---


# Question
Title: EntityReference and custom field but not Title
By default EntityReference (auto-complete) works with Title, is it possible to use another field (f.x. from selected Content Type)?

I also tried to create a view and use it (it worked well when you selected value) however once you save a Node and reload, it display Title again.

How could I change that and display my own field?

# Answer
> 4 votes
I believe you are looking for the Entity Reference autofill module.

Please excuse me if I misunderstood your need.

---
Tags: entities
---


# Question
Title: Force users to always log in and show no content
I am using Drupal 7.31 and I installed the MD Alpine theme. I have a site which loads a video on the front page. I want to hide this front page. When users come to my site, I want them to be redirected to the login form.

I tried changing the home page to /user and that was a huge mistake. I did manage to undo this. I also went into the permissions and removed any permission for the anonymous user, including the permission to view published content.

I know I have seen this question before, and it seems like there might be a module that can fix that. I am willing to make some configuration change.

# Answer
> 1 votes
On the Structure \> Blocks page, configure the Main Content block. Within the Roles section, check Authenticated User.

Move the User Login block in the Content region. This allows the Login screen to appear even if they are not logged in.

If you want to redirect them to the login page, you can install the Rules module and create a rule that whenever an anonymous user loads a page, and the page path is not user\*, then redirect them to /user.

---
Tags: 7, users
---


# Question
Title: Can drupal be installed on a subdomain and used on the main domain?
I was thinking about installing Drupal on admin.myexample.com for clients to access an add and edit news posts & products.

Then just using myexample.com as the main site. Calling the database and entries to their pages with PHP/SQL.

Is this practical?

I've been trying to learn my way around Drupal, I know this wouldn't be a way to learn. I'm much more comfortable writing the pages up myself than manipulating Drupal pages (at this point in time.)

# Answer
> 3 votes
Yes, you can have Drupal run in subdomain and have a completely different web site coded on the domain root.

Just make sure that the subdomain is directed at the Drupal root. To be clear, the Drupal root directory is the one that contains the following files:

authorize.php CHANGELOG.txt COPYRIGHT.txt cron.php .gitignore .htaccess includes index.php INSTALL.mysql.txt INSTALL.pgsql.txt install.php INSTALL.sqlite.txt INSTALL.txt LICENSE.txt MAINTAINERS.txt misc modules profiles README.txt robots.txt scripts sites themes update.php UPGRADE.txt web.config xmlrpc.php

# Answer
> 1 votes
With Drupal (and many other CMSs) you don't need to have a separate domain for the admin area. Users simply login at domain.com/user/login.

If you especially want to use admin.domain.com as the login URL for users then a redirect would do fine, it is a kindof cool address.

But if you are thinking of writing your own code to get the content from the Drupal database for your main site then you are (just slightly) under-using Drupal. It is both the Content Management and Content Display platform and you would be creating your own version of the theme layer and hooks etc (might be fun though - definitely faster :).

The only advantages I could see in spreading out the admin (logged in) area of Drupal across to another domain would be in using a website caching service or some custom security for some reason.

So my advice is:

Yes, you can install Drupal on a sub domain, it is a domain in itself. But no, don't bother having an admin domain and writing your own code to get the content from the database. Use Drupal for what its good at.

---
Tags: database, subsites
---


# Question
Title: Adding users to organic groups in CiviCRM
I have a site which uses Organic Groups, specifically with CiviCRM. I want to add a user to a group and I am having issues. The group is marked as closed. I want to how to either

* add a user to a existing group
* open up a closed group

I haven't been able to figure out how to do either of these.

# Answer
As @Graham says in his comment, you may want to use the CiviCRM OG Sync module provided with CiviCRM. If your interest is more in coding this, check out how the module does it at https://github.com/civicrm/civicrm-drupal/blob/7.x-master/modules/civicrm\_og\_sync/civicrm\_og\_sync.module.
> 1 votes

---
Tags: organic-groups, civicrm
---


title: Rewrite id of a exposed filter block?

text:
# Question
Title: Rewrite id of a exposed filter block?
Hi there I'm trying learn how to rewrite a #id of an exposed filter block (ie. a searchbar filtering a list view. Is there an easy way to do this?

Isn't something that is possible to do with rules?

(i would like to get an answer with an example of how to do the rewrite inc. an example of a syntax as I'm no guru on php or rules either for that matter :)

# Answer
> 0 votes
To rewrite the ID of the block (if you *really* want to), you would either use a preprocess function or a custom template file.

Looking at the preprocess function for blocks **template\_preprocess\_block()** found here.

https://api.drupal.org/api/drupal/modules!block!block.module/function/template\_preprocess\_block/7

You can see how the ID is created: `$variables['block_id']` and what the theme suggestions are: `$variables['theme_hook_suggestions']`

You should be able to create a function in you themes template.php as follows:

```
function mytheme_preprocess_block(&$variables) {
  if ($variables['block_id'] == 'old_id') {
    $variables['block_id'] = 'new_id';
  }
}

```

However, with a filterblock, there might be some special relationship to the view that might be damaged, I'm not sure, but either way, you do not need to use Rules.

---
Tags: views, rules
---


# Question
Title: How To Display Image instead of Taxonomy name using Views to display my nodes?
I Have Entity Module and already have a Taxonomy Vocabulary with terms and an Image Field created. Each term has a unique image.

I Have a Content Type with a Term Reference field set to allow multiple selections of my Vocabulary.

I now want to have my Nodes displayed in a Views Table, Title, Node Image, and Taxonomy terms as images rather than their names.

How do I make this possible? Here is a link to what the site currently is (HTML Table rather than a view - very limiting and slow for updating). http://dev.destinationsound.net/

The different color circles are what will be taxonomy terms.

Drupal 7

Note: This is not for a taxonomy term page but rather a list of nodes that have taxonomy terms associated with them.

# Answer
> 1 votes
1. Create a view of the appropriate nodes
2. Set the view output type to be "table"
3. Create a "relationship" in the view between node and taxonomy term
4. Now you can add the image field from the term to your views output
5. If you use multiple vocabularies, add a filter to select just the vocabulary you are interested in.

If you don't already have the imagecache module installed, I recommend it as it will let you control the size of the displayed image.

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


# Question
Title: Calendar Module: Calendar block with mini-calendar to show next month instead of current
I am using the Calendar module (http://drupal.org/project/calendar).

One of the default block (called **Block**) in the Calendar module gives you the option to embed a mini-calendar as a block on your site. I would like this mini-calendar to show a future month instead of current month.

Does anybody know how to do it?

Thanks.

# Answer
> 1 votes
You can adjust the Contextual Filter for this block. Instead of providing a default value of "Current date" you can set it to "PHP Code" and use the following:

```
return date('Y-m',strtotime('+1 month'));

```

# Answer
> 0 votes
Maybe it is still actual. Just change date in contextual filter WHEN THE FILTER VALUE IS NOT AVAILABLE Provide default value to Y-m format (PHP - return '2014-02', Fixed value - 2014-02).

---
Tags: views, blocks, datetime
---


title: PHP Output in module

text:
# Question
Title: PHP Output in module
I am creating a module that is outputting a static php page into my Drupal install. Here is my module file:

```
<?php

function mymodule_menu() {
$items = array();

$items['live_amplified/hello_world'] = array(
'title' => 'Live Amplified',
// describe the page for the menu system.  site visitors will not see this
'description' => 'Simple custom hook_menu() implementation.',
// function that is called when visiting the new path
'page callback' => 'drupal_get_form',
'page arguments' => array('static_page_form'),
'access arguments' => array('access content'),
'type' => MENU_NORMAL_ITEM,
 );

return $items;
}

/**
* Implements hook_form().
*/
function static_page_form($form, &$form_state) {
// Add CSS and JS
drupal_add_css(drupal_get_path('module', 'mymodule') . '/static_page.css');
// Import your static HTML page
$form['html'] = array(
'#type' => 'item',
'#markup' => file_get_contents(drupal_get_path('module', 'mymodule') .'/static_page.php'),
);
return $form;
}

```

In my static\_page.php I have written my HTML, but when I try to add any PHP the browser doesn't recognize it. It doesn't output anything. I have tried just echo test and still nothing.

# Answer
> 2 votes
You don't need to use a form items markup attribute just to print some HTML. Instead, change your menu item to a simple page function, not a drupal\_get\_form eg

```
$items['live_amplified/hello_world'] = array(
  'title' => 'Live Amplified',
  'description' => 'Simple custom hook_menu() implementation.',
  'page callback' => 'hello_world_page',
  'page arguments' => array('static_page_form'),
  'access arguments' => array('access content'),
  'type' => MENU_NORMAL_ITEM,
);

```

and add a simple function to return some markup

```
function hello_world_page() {
  return "Hello World";
}

```

But as @Adam Balsam described, if you have a lot of content and want to parse another PHP file, you would do it using `file_get_contents()` but Drupal already has a way of dealing with this that uses it (although it may be convoluted)

You would use hook\_theme.

First you need to declare your implementation, this does two things: tells Drupal to look for a template file (the file you want to render) at some location, and it exposes your template to prerocessing for adding variables.

Declare your theme

```
/**
 * Implements hook_theme().
 */
function mymodule_theme($existing, $type, $theme, $path) {
  return array(
    'helloworld' => array(
      'template'  => 'hello-world',
      'path'      => drupal_get_path('module', 'mymodule') . '/templates',
      'arguments' => array('node' => NULL),
    ),
  );
}

```

Create a preprocess function to give it some variables

```
function mymodule_preprocess_helloworld(&$vars) {
  $vars['who'] = "World";
}

```

Create a template file hello-world.tpl.php in /mymodule/templates/ with the content

```
<h2>Hello <?php print $who; ?> </h2>

```

Call it from where ever you like, in this case a menu page.

```
function hello_world_page() {
  return theme('helloworld');
}

```

At first it may seem a bit convoluted but it allows you to create templates with variables and exposes theme to themeing so other modules and themes can change both the variables and the markup.

# Answer
> 2 votes
This is just a slightly different way to do it than @user1081275's approach.

My situation was that I wanted to turn off the PHP Filter module for security reasons and I had several pages that had PHP in the body field.

I created a module that I put at sites/all/modules called "customphppages'. It had the basic .info and a directory inside called 'pages' where there would be one tpl.php file for every page on the web site that I wanted to create this way.

The tpl.php files are just for the content. You don't need to copy page.tpl.php (like I did the first time)... just your content goes in the tpl.php file.

The example shows the declaration of two pages for the site.

The following is from customphppages.module

```
<?php
/*
 *Implementation of hook_menu().
 */

function customphppages_menu() {

  $items['movies/the-wizard-of-oz'] = array( //this is the URL, what comes after example.com/
    'title' => 'The Wizard of Oz', // this is the page title
    'page callback' => 'page_oz', // function name... can be anything
    'access callback' => TRUE, // this means no access control for page
    'type' => MENU_CALLBACK, // the same for every new page
  );
   $items['books/brave-new-world'] = array(
    'title' => 'Brave New World',
    'page callback' => 'page_brave',
    'access callback' => TRUE,
    'type' => MENU_CALLBACK,
  );
  return $items;
}

/*
 * Implementation of hook_theme().
 */
function customphppages_theme(){
  return array(
    'woz_template' => array( //function name called below
      'template' => 'woz', // what comes before '-tpl.php' in the file name for the file with the content. So the file would be at sites/modules/customphppages/pages/woz.tpl.php
      'path' => 'sites/all/modules/customphppages/pages' //path to folder containing tpl.php.
    ),
    'brave_template' => array(
      'template' => 'brave',
      'path' => 'sites/all/modules/customphppages/pages'
    ),
  );
}
/*
 * One function here for each page. Function names are
 * derived from the 'page callback' value in the
 * $items array. The quoted argument for theme()
 * is the key in in the custom array in customphppages_theme() function.
 */
function page_oz() {
  return theme('woz_template');
}

function page_brave() {
  return theme('brave_template');
}

```

---
Tags: theming
---


title: how to set date_info->granularity

text:
# Question
Title: how to set date_info->granularity
Is there anywhere in the administrators area can I set $vars\['view'\]-\>date\_info-\>granularity ?

With the recent updates to Drupal 7.32 the date format of the calendar module heading has changed from \[month\]\[year\] to \[day\],\[month\]\[day number\],\[year\] which looks silly.

I assume granularity has changed from 'month' to 'day', but I can't find where to change it back.

Is this associated with the fixed bug number 355058?

# Answer
Here is the quick workaround for the issue:

**STEP 1:** Edit `modules/date/date_views/theme/theme.inc` and go find line 165.

**Change these two lines:**

```
$format_with_year = variable_get('date_views_' . $granularity . 'format_with_year', 'l, F j, Y');
$format_without_year = variable_get('date_views_' . $granularity . 'format_without_year', 'l, F j');

```

To these two lines:

```
$format_with_year = variable_get('date_views_' . $granularity . '_format_with_year', 'l, F j, Y');
$format_without_year = variable_get('date_views_' . $granularity . '_format_without_year', 'l, F j');

```

**Note: the only difference is one underscore character added to each line.**

Upload the changed file back to your web server.

**STEP 2:** Go to `(YOUR_WEBSITE)/admin/config/regional/date-time/date-views` and click Save. If you get permissions errors, try clearing caches.

**Before:**

**After:**
> 0 votes

---
Tags: datetime
---


# Question
Title: Adding JS to a Drupal 8 theme (replacement for drupal_add_js)
In Drupal 7, I can use `drupal_add_js` within a theme's *template.php* file as a `theme_preprocess_html(&$vars)` function:

```
   drupal_add_js(drupal_get_path('theme', 'mytheme') . '/js/scripts.js',
        array(
          'group' => JS_THEME,
          'preprocess' => TRUE,
          'weight' => '999',
        ));

  $vars['scripts'] = drupal_get_js();

```

In Drupal 8, I've tried converting this using `attached` in my theme's *.theme* file as such:

```
  $vars['#attached']['js'] = array(
    array(
      'data' => drupal_get_path('theme', 'mytheme') . '/js/scripts.js',
      'options' => array(
        'group' => JS_THEME,
        'preprocess' => TRUE,
        'every_page' => TRUE,
      ),
    ),
  );

```

... but that did not work and there were no errors in watchdog / console or otherwise.

According to the D8 API page for `drupal_add_js`:

> Deprecated - as of Drupal 8.0. Use the #attached key in render arrays instead.

There was not much more info that that however. It seems that `drupal_add_css` will also use this method. I know it's still early days for Drupal 8 but I was hoping to get a jump on this.

# Answer
> 9 votes
It seems you can use `hook_preprocess_page` with attached as such:

```
function MYTHEME_preprocess_page(&$vars, $hook) {
  $path = drupal_get_path('theme', 'MYTHEME');
     // Render the main scripts file.
  $local_js = array(
    '#attached' => array(
      'js' => array(
        $path . '/js/scripts.js' => array(
          'group' => JS_THEME,
          'weight' => 9999),
      ),
    ),
  );
  \Drupal::service('renderer')->renderRoot($local_js);
}

```

This works great (*theme.inc* uses this method), note the extra nested array around the weight.

# Answer
> 4 votes
The key point in the documentation is this bit

> Use the #attached key **in render arrays** instead.

Emphasis mine.

The `$variables` array in a theme/preprocess function isn't a render array, it's just an array holding variables. To use `#attached` you'll need something like this in the preprocess function:

```
$vars['foo'] = array(
  '#markup' => '<p>Bar</p>',
  '#attached' => array(
    'data' => drupal_get_path('theme', 'mytheme') . '/js/scripts.js',
    'options' => array(
      'group' => JS_THEME,
      'preprocess' => TRUE,
      'every_page' => TRUE,
    ),
  ),
);

```

And this in the template file:

```
{ foo }

```

In other words, more or less the same as in Drupal 7 (at this point in time, at least).

`hook_preprocess_html()` is likely not the right place for this code by the way; don't forget the js/css files are actually rendered in that template, so it's too late to add any more `hook_preprocess_page()`, `hook_preprocess_node()` or equivalent will probably get you more reliable results.

See the Twig best practices - preprocess functions and templates page for more information on preprocessing variables.

# Answer
> 4 votes
As of Drupal 8.0.x-beta2 you can attach CSS and JS from preprocess functions.

See https://www.drupal.org/node/2352319

# Answer
> 2 votes
In this example you are using a real render array and not one that is rendered in the function itself.

This way other modules, themes etc can alter it.

```
/**
 * Implements hook_page_alter().
 */
function db_jacket_page_alter(&$page) {
  $page['#attached']['js'][] = drupal_get_path('theme', 'db_jacket') . '/js/jquery.image-depth.js';
}

```

# Answer
> 0 votes
Though the OP is about Drupal 8, this could be done in a similar way in Drupal 7 without using `drupal_add_js()` to start getting used to not having `drupal_add_js()` around:

```
/**
 * Implements hook_preprocess_page().
 */
function YOURMODULE_preprocess_page(&$variables) {
  $module_path = drupal_get_path('module', 'YOURMODULE');
  $variables['page']['content']['#attached']['js'][$module_path . '/js/YOURMODULE.js'] = array();
}

```

Options can be defined in the empty array, see https://api.drupal.org/api/drupal/includes%21common.inc/function/drupal\_add\_js/7.

---
Tags: theming, 8, javascript
---


# Question
Title: hook_form_alter Add wrapping div around label and input
Using hook\_form\_alter, for each field I want to wrap a div around the label and the input, leaving the help text (description) separate. Can hook\_form\_alter do this? Seemingly I can only add prefix and suffix to the wrapping div.

# Answer
You have to implement theme\_form\_element to achieve desired goal.

It returns HTML for a form element.

Each form element is wrapped in a DIV container
> 0 votes

---
Tags: forms
---


# Question
Title: Hide node "edit" tab for certain content types and roles
I am trying to hide node "edit" tab for certain content types and roles without removing or disabling access to the edit pages. An edit button is going to be created manually and displayed on node pages.

Used below snippet but it disables access to the edit pages too.

```
/**
* Set up a new permission for tabs.
* Grant access under admin -> user management -> permissions
*/
function mymodule_permission() {
  return array(
    'view hidden tabs' => array(
      'title' => t('Node tabs visibility'),
      'description' => t('Grant access to node tabs.'),
    ),
  );
}

/**
* Implementation of hook_menu_alter().
* Show/hide tabs according to permission settings.
*/
function mymodule_menu_alter(&$items) {
$items['node/%node/edit']['access callback'] = 'user_access';
$items['node/%node/edit']['access arguments'] = array('view hidden tabs');
}

```

Also tried using this code, which kinda works but disables edit tab on all content types and for all roles.

```
function mymodule_menu_alter(&$items) {
$items['node/%node/edit']['type'] = MENU_CALLBACK;
}

```

**Obejective:** Hide node "edit" tab for certain content types and roles in D7.

# Answer
I had the same issue and could solve that using `template_preprocess_page(&$variables)`.

Open `template.php` under `[yoursite]/themes/[your-theme]`

For example if you're using `bartik` theme and want to hide tabs (`View and Edit`) for `Article` content type for `Editor` role.

Paste the following code in your template.php

```
/**
 * Remove tabs on article content type
 */
function bartik_preprocess_page(&$variables, $hook)
{
    if (!empty($variables['node']) && $variables['node']->type == 'article' && in_array('editor', $variables['user']->  roles))
    {
    $to_be_removed = array('node/%/edit', 'node/%/view');
    foreach ($variables['tabs'] as $group_key =>$tab_group)
        {
            if (is_array($tab_group))
            {
                foreach ($tab_group as $key =>$tab)
                {
                    if (isset($tab['#link']['path']) && in_array($tab['#link']['path'], $to_be_removed))
                    {
                    unset($variables['tabs'][$group_key][$key]);
                    }
                }
            }
        }
    }
}

```

Clear your site cache and test.

This removes the `View` and `Edit` tabs on Article node pages for editor roles users. But they can access those pages via URL.

Hope this helps.
> 2 votes

---
Tags: 7, routes
---


title: variable in HREF not working correctly

text:
# Question
Title: variable in HREF not working correctly
I am trying to create a link in a Drupal views-view-fields.tpl that links to the original content but for some reason it's not working. The code I have tried:

```
<a href="<?php $fields['path']->content; ?>">Read more</a>

```

and

```
<?php $link = $fields['path']->content;?>
 <a href="<?php $link ?>"> Read more</a>

```

as well as adding single quotes. The above points the rendered link to the current page/ view. When I echo $link\_path i get /?q=node/1544 , which is correct.

I have also tried to create the URL by using

```
$link = $GLOBALS['base_url'] . '/node/' . $node->nid;
<a href="<?php $link ?>"> more </a>

```

The above shows the correct link when I echo it but, again in the rendered link it points to the current page/ drupal view.

What am I missing? I have to add that I only have about 3 months Drupal/PHP experience so still lots to learn.

Thanks :)

# Answer
The secure alternative would be to use l() to generate the link. In your current code, it's very likely that you've created a security problem.

`l('More', $fields['path']->content)` would be better.

But in answer to your original question. you are missing echo statement here

```
<a href="<?php echo $link ?>"> more </a>

```
> 2 votes

---
Tags: views, theming
---


# Question
Title: Copying a CiviCRM/Drupal install from one server to another (got error)
I've tried copying a a CiviCRM/Drupal install from 1 server to another. I copied all the files within the drupal root, and the database, and changed the database details in both Drupal's settings.php file and CiviCRM's civicrm.settings.php file. Drupal now works fine - copying this over appears to have worked, and I've done so succesfully with the same method many times. However, CiviCRM is not fully working. When I visit the main CiviCRM admin page (ie. http://cea-crm.philosofiles.com/civicrm/ on my server) I see CiviCRM's sidebar boxes (indicating it's working to some extent) but, to the right of them, see:

> Page not found
>
> The requested page "/civicrm/" could not be found.

When I click on any sidebar box link, such as 'My Contact Dashboard', I likewise see:

> Page not found
>
> The requested page "/civicrm/user?reset=1" could not be found.

Presumably I've missed some change I needed to make to reflect my new server setup? I can't *see* anything in civicrm.settings.php I still need to change, e.g. I've added lines like `define( 'CIVICRM_UF_BASEURL' , 'http://cea-crm.philosofiles.com/' );` and `$civicrm_root = '/home/myusername/public_html/d7/sites/cea-crm.philosofiles.com/modules/civicrm';`

# Answer
> 5 votes
If you have Drush installed, you can also use the following command to update some of those settings:

`drush civicrm-update-cfg`

It will try to update the URL and directory settings, which is pretty equivalent to the URL: "http:///index.php?q=civicrm/admin/setting/updateConfigBackend&reset=1".

After that, you can use the API to flush various CiviCRM caches which may be using that data:

`drush civicrm-api system.flush`

# Answer
> 1 votes
Moving CiviCRM from one server to another can be a real pain. You need to make sure that you don't copy the data in the CiviCRM cache tables of the database and then review CiviCRM settings after the move using messy URLs. CiviCRM unfortunately saves a lot of server config data in the database that you need to clear out to successful make the transition.

This forum post has helped me a lot in the past:-

http://forum.civicrm.org/index.php?topic=15052.0

# Answer
> -1 votes
This page on the CivicRM wiki: http://wiki.civicrm.org/confluence/display/CRMDOC/Moving+an+Existing+Installation+to+a+New+Server+or+Location is very helpful on moving an installation to a different server.

Also you can override lots of the settings by putting override staements into civicrm.settings.php as described on this wiki page: http://wiki.civicrm.org/confluence/display/CRMDOC/Override+CiviCRM+Settings

---
Tags: civicrm
---


# Question
Title: Update database with update module disabled
I have recently inherited a site which needs protecting from the recent security exploits. The site has not been very well maintained but the hosting company can provide me with a database dump from 6th October.

Trouble is, the database dump has the update module disabled. When I try to restore the site and upgrade to the latest core version\* I am prevented because updating is disabled.

Is there a way of enabling the update module via the database? I am pretty new to drush and do not yet have it enabled on the server.

\*Actually it's an early version of Commerce Kickstart 2.

# Answer
> 0 votes
Doh. Update wasn't working for me because I didn't exist on the system. Silly mistake

---
Tags: database
---


# Question
Title: Disabling some modules installed via a feature
Is it possible to disable a module that was installed via a feature?

For example, I'm using a theme that came with a feature that installed a lot of modules, I realized that I don't need a bunch of the modules, but I can't disable them in the module page (the 'enabled' checkbox can't be toggled anymore).

Is it possible to just remove the feature but keep each individual modules configuration?

# Answer
> 0 votes
As far as I know, you can’t.

But, if you are 100% sure that these modules are not used by any component of your system you can do it in a *hacky* way. Only if you patch the feature’s `.info` dependencies and then revert it.

If it’s not very important to disable these modules (let’s say conflict with something?) do not do that!

---
Tags: 7, features
---


# Question
Title: How to query for entities without a value for a specific field?
Using EntityFieldQuery it is pretty easy to query for entities with a given value for a specific field. But I fail to find a way to query for entities without a value for a given field. Let's say I have an optional Taxonomy Reference field on all my content type. I can query the nodes associated with a given taxonomy term using:

```
$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'file')
  ->fieldCondition('field_tags', 'tid', $tid)
  ->pager($limit);
$results = $query->execute();

```

But how would I query for all nodes not associated with any terms (ie. which have no value for the `field_tags` field). I tried setting `$tid` to `NULL` and `$query->fieldCondition('field_tags', 'tid', $all_tids, 'NOT IN')` without success.

# Answer
The SQL implementation of EntityFieldQuery doesn't support this, because it builds the query using `INNER JOIN`s instead of `LEFT JOIN`s. I consider this a bug, please open an issue in the core queue.
> 3 votes

# Answer
Redefine class EntityFieldQuery:

```
class GrabberEntityFieldQuery extends \EntityFieldQuery
{
    protected $absent = array();

    function finishQuery($select_query, $id_key = 'entity_id')
    {
        if ($this->age == FIELD_LOAD_CURRENT) {
            $tablename_function = '_field_sql_storage_tablename';
            $id_key = 'entity_id';
        }
        else {
            $tablename_function = '_field_sql_storage_revision_tablename';
            $id_key = 'revision_id';
        }

        $table_aliases = array();

        reset($this->fields);
        $key = key($this->fields);
        $field = current($this->fields);
        $tablename = $tablename_function($field);
        $field_base_table = $tablename . $key;

        $key = count($this->fields) + 1;

        foreach($this->absent as $field) {
            $tablename = $tablename_function($field);
            // Every field needs a new table.
            $table_alias = $tablename . $key;
            $table_aliases[$key] = $table_alias;

            $select_query->leftJoin(
                $tablename,
                $table_alias,
                "$table_alias.entity_type = $field_base_table.entity_type AND $table_alias.$id_key = $field_base_table.$id_key"
            );

            $select_query->where("$table_alias.$id_key IS NULL");

            $key++;
        }

        return parent::finishQuery($select_query, $id_key);
    }

    public function absentFieldCondition($field) {
        $field_definition = field_info_field($field);
        $this->absent[] = $field_definition;
    }
}

```

Usage:

```
$query = new GrabberEntityFieldQuery();
$query
    ->entityCondition('entity_type', 'node')
    ->deleted(FALSE);

// absent field
$query->absentFieldCondition('non_existent_field_name');

```

Nodes without the field 'non\_existent\_field\_name' will be selected.

That's all.
> 0 votes

---
Tags: 7, entities
---


title: File browse CCK field

text:
# Question
Title: File browse CCK field
Is there a CCK field where I can add a link to a file, not an upload but something that will save the link as a URI.

# Answer
Try the IMCE for FileField module. I've tested this module and working fine. It seems this is the module what you're looking for

> IMCE for FileField allows users to select files from IMCE File Browser. It supports FTP uploaded files by automatically registering them as IMCE files thus making them usable in a FileField.

**Step-1:**

Go to your filefield settings and Enable 'Allow users to select files from IMCE File Browsers for this field

**Step-2:**

Go you Manage Display settings of your content type and select FORMAT as URL to file

**Step-3:**

In node add / node edit form you can browse the *previously uploaded files* (from server) by clicking on 'Open File Browser' link.

So the file link will be displayed at node output for the uploaded file.
> 1 votes

---
Tags: 7, entities, navigation, media
---


# Question
Title: Views all data export included image name/path
I have a View. In my view Image, Product Id, etc are shown. I want to export all the data of that View in the form of doc file or CSV or excel sheet, in the tabular form if it store the data in the form of doc or csv.

My condition is that : For image field atleast image name/image path stored.

Is there any module?

# Answer
> 2 votes
You can achieve that using the Views data export module.

> This module is designed to provide a way to export large amounts of data from views. It provides a display plugin that can rendered progressively in a batch. Style plugins are included that support exporting in the following types:
>
> * CSV
> * Microsoft
> * XLS
> * Microsoft DOC
> * Basic TXT
> * XML.

---
Tags: views, importing-exporting
---


title: Views form page with input fields

text:
# Question
Title: Views form page with input fields
How can I make Views form page with such input fields?

Such view can really help to change meanings of some node field all at once.

# Answer
> 2 votes
Editable Views should do what you are trying to accomplish. It won't allow you to drag the items up/down, but it will allow you to update multiple fields at once.

https://www.drupal.org/project/editableviews

> Editable Views lets you create Views where the fields can be edited. Fields show both the current value and a form to edit it. A 'Save' button allows saving of all the entities shown in the View.

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


# Question
Title: 4095 Selectors Limit on IE. How to split the Drupal 7 CSS compressed files?
Here is my problem. Using Sass (from Zen theme) and on top of that Brunch, our compressed css file has over 4095 Selectors and is then compressed by Drupal (and still has over 4095 selectors in one files).

Do you know if there is a way to tell Drupal to compress files in smaller files in order to avoid the 4095 selector limit per files ?

# Answer
I found a very interesting module that can handle the 4095 limit for drupal compressed files and many other css and js related things

Advanced CSS/JS Aggregation Module
> 1 votes

# Answer
Lets say your `my_theme.info` have

```
stylesheets[all][] = css/my_theme_1.css
stylesheets[all][] = css/my_theme_2.css
stylesheets[all][] = css/my_theme_3.css
stylesheets[all][] = css/my_theme_4.css

```

And you don't want to aggregate these files in a single one (exceed IE limit 4095 selectors)(also I assume that is already minified by Brunch)

Remove the above lines from your `.info` or comment out.

Then add an html preprocess function (on the main template.php or if you have an html.preprocess.inc file)

```
function my_theme_preprocess_html(&$variables) {
  drupal_add_css(drupal_get_path('theme', 'my_theme') . '/css/my_theme_1.css', array('preprocess' => FALSE));
}

```

The `drupal_add_css` will add the css but `'preprocess' => FALSE` will prevent Drupal to aggregate them.

(It's a bit hacky but it works)
> 1 votes

---
Tags: theming
---


title: Set the template for the frontpage

text:
# Question
Title: Set the template for the frontpage
How do I change the Drupal 8 frontpage template, so it doesn't use the regular page.html.twig template?

# Answer
> 26 votes
Enable `twig_debug` and you will see HTML comments surrounding the output that tell you what template suggestions are available. In this case you will get output like:

```
<!-- THEME DEBUG -->
<!-- THEME HOOK: 'page' -->
<!-- FILE NAME SUGGESTIONS:
   * page--front.html.twig
   * page--node.html.twig
   x page.html.twig
-->
<!-- BEGIN OUTPUT from 'core/modules/system/templates/page.html.twig' -->

```

Naming your template **page--front.html.twig** will use that template for only the homepage.

---
Tags: theming, 8
---


# Question
Title: Pulling #hashtags and displaying them on site
I see that you can you the Activity Stream module to pull feeds from twitter and other social media sites. Well how could I pull a predefined #hashtag from ANY social meida site and present it in a feed on my drupal site.

Example:

Hashtag is #NCAABasketball

From bjones on Twitter: Saw KU beat UNC's butt. Love #NCAABasketball

From jbean on Google+: Love #NCAABasketball !

From ktghram on Instagram:

I'm at the game! "picture:" #NCAABasketball

It doesn't have to be like this, but would this be possible with out the user posting or tweeting to my account?

Any suggestions?

# Answer
This is possible using the dev branches of a few modules put together:

feeds, \>= 7.x-2.0-alpha8+56-dev

feeds\_oauth, \>= 7.x-1.0-beta3+2-dev

feeds\_jsonpath\_parser, \>= 7.x-1.0-beta2+12-dev

I think there are a few other necessary modules you'll need to have installed, like oauth, ctools, feeds\_ui. One of the most important things is that you need to register an app at dev.twitter.com, and get an API key / secret. You put that into the feeds setup (admin/structure/feeds/FEED\_NAME/settings/OAuthHTTPFetcher). When you setup your feed, you will want to choose the HTTP OAuth fetcher (oauth2 does not work) as the Fetcher type.

You create a new feed importer.

Additionally, you'll want to create a content type like "tweet" and add the fields you want to parse (like author, date, name, body, location).

Back in the feeds setup, setup your mapping, and create several jsonpath\_parser maps to your respective fields. After that, click "settings" under JSONPath parser, to map your json contexts to your fields.

It should be something like this:

Context: $.statuses.\*

Title: id\_str

body: text

etc, etc, etc

Finally, once this is all setup, you can go to SITEURL.com/import and input your search string, which will look like this:

https://api.twitter.com/1.1/search/tweets.json?q=%23HASHTAG

Anyway, I hope this is helpful. I realize that my answer could be better organized, but it should give the gist as to how this is done.

For my "tweet" content type, I have the default setup to be NOT published, so that I can moderate what actually shows up on my site.

One more caveat is that non UTF-8 strings (common in foreign languages for example) will error out and break your feed importer (which should run on cron automatically). Ideally you want to sanitize the input before writing it into the database anyway.

Here's the PHP you can put into a quick custom module to sanitize the input of the body field for example. You want to make sure your jsonpath\_parser:ID matches the ID you setup in the node-processor settings.

```
<?php

/**
 * Implements hook_feeds_after_parse().
 */
function feeds_custom_feeds_after_parse(FeedsSource $source, FeedsParserResult $result) {
//dpm($source); // look at source variables, requires devel
//dpm($result); // look at result variables, requires devel

  foreach ($result->items as $delta => $item) {
    $result->items[$delta]['jsonpath_parser:1'] = utf8_encode($item['jsonpath_parser:1']);
  }
}

```
> 1 votes

# Answer
You can use Twitter Pull module...

Project page says

> Twitter Pull is a small module, the only purpose of which is to allow super-easy embedding of public twitter data like: a user timeline or **twitter search results by hashtag** or a search term. The emphasis is on making these very specific tasks as easy and straightforward as possible. The purpose of the module is not to be an end-all solution for Twitter.
> -1 votes

---
Tags: feeds
---


title: User Login block missing

text:
# Question
Title: User Login block missing
It vanishes suddenly without any notifications today. I am using Drupal 7 with "Mix and Match" theme. I used to working this morning.

Website shows no error at all.

I have tried the following to get it back:

1. Find the block table in the database and tried to modify the visibility of the user, login of current theme entry - not working
2. At admin-\>structure-\>blocks, under the current theme. The "User login" is already under sidebar first. I tried remove it and add back, changing the weight - not working
3. In the other themes the user login block does not show up either, including the default theme Bartik.
4. Repeat the above steps with a `drush cc all` command. Not working.

What else could I try to get it back?

# Answer
Anyway, I found the problem. It was the permission setting. I should set it to "no restriction" rather than restrict to every tick-able role (because guest is not there to tick)
> 1 votes

---
Tags: blocks, users
---