# Question
Title: I'm on drush version 6 & can't do a drush status on my drupal8 site, whats the story?
drush status says I'm on drush version 6 How can I get drush to work with Drupal8 ? Do I have to grab a later version of drush directly from github? Any directions for this? Thanks.

This is the error message I'm getting when trying to run drush against my drupal8 install:

Drush 6.0 does not support Drupal . See http://drupal.org/project/drush for more \[error\] information.

# Answer
This is a known bug in Drush 6.0.0 that was caused when Drupal 8 changed the way that the Drupal VERSION constant was defined. This has been fixed in the master branch on GitHub; currently, the only way to use Drush with Drupal 8 is to clone the master branch directly. There should be a 6.1.0 release out shortly to address this.

For more information, see:

https://github.com/drush-ops/drush/issues/63

**UPDATE:** I mis-spoke above. Drush 6.x supported Drupal 8 until the recent release of Drush 6.0.0. Now, only the master branch (Drush 7) supports Drupal 8. So, there is no way to get Drush 6 to work with Drupal 8; you must use the master branch. When 6.1.0 comes out, Drush will correctly tell you that Drush 6.1.0 does not support Drupal 8.
> 3 votes

---
Tags: drush
---


title: entire teaser as link to node

text:
# Question
Title: entire teaser as link to node
I would like to use the whole tease as a link to the node. I could google (and adapted) the following code but still not working.

following line: scripts\[\] = js/new\_teaser.js is added in the ".info" file of my theme (Business) and this code to the "new\_teaser.js":

```
$(document).ready(function(){

    $(".node-teaser").click(function(){
      window.location=$(this).find("a").attr("href"); return false;
    });

    });

```

the class of my teaser is ".node-teaser" and the "NoScript" addin of my browser is switched off. I assumes that the problem is in the JS code.

Drupal 7, theme Business

**Could someone help me please?**

**EDIT:** as far as I can see, there is no link to the new\_teaser.js file in the source code of the page... (even if the file is in the js/ folder and in the theme .info file

# Answer
Something like this should work. Add it to your template.php file. Using preprocess\_node gives you a little more control so you aren't just arbitrarily loading the script on every page.

```
function THEMENAME_preprocess_node(&$variables) {
  if ($variables['type'] == 'blog' && $variables['view_mode'] == 'teaser') {
    drupal_add_js($theme_path.'/js/new_teaser.js');
  }
}

```
> 0 votes

---
Tags: javascript, navigation, nodes
---


# Question
Title: In D7 how do I get JUST the value of a field in a view field template?
This is at the top of the template file:

```
/**
 * @file
 * Default simple view template to all the fields as a row.
 *
 * - $view: The view in use.
 * - $fields: an array of $field objects. Each one contains:
 *   - $field->content: The output of the field.
 *   - $field->raw: The raw data for the field, if it exists. This is NOT output safe.
 *   - $field->class: The safe class id to use.
 *   - $field->handler: The Views field handler object controlling this field. Do not use
 *     var_export to dump this object, as it can't handle the recursion.
 *   - $field->inline: Whether or not the field should be inline.
 *   - $field->inline_html: either div or span based on the above flag.
 *   - $field->wrapper_prefix: A complete wrapper containing the inline_html to use.
 *   - $field->wrapper_suffix: The closing tag for the wrapper.
 *   - $field->separator: an optional separator that may appear before a field.
 *   - $field->label: The wrap label text to use.
 *   - $field->label_html: The full HTML of the label to use including
 *     configured element type.
 * - $row: The raw result object from the query, with all data it fetched.
 *
 * @ingroup views_templates
 */

```

I was hoping "raw" was just the value in the field, but I think it's the entity id. PLEASE tell me there is a straight-forward way to get just the value of the field from this template!

Thanks!

# Answer
> 1 votes
Should be able to access the field's value with: $row-\>\_field\_data\['nid'\]\['entity'\]-\>field\_YOUR\_FIELD\_NAME\['und'\]\[0\]\['value'\]

# Answer
> 1 votes
If you have devel installed then add `dpm($field);` to the template and see if the field array contains the value itself (if I remember right - it isn't). The second step (if the field array doesn't contain the value) will be to use `dpm($view);` ,and in the view array you have the value for sure (I think it is something like `$view->$row['field_name'][0]['value']` )

# Answer
> 0 votes
You can use below code to render the fields into views template using below code.

```
$fields['title']->content

```

In above code `title` is name of the field. You can get the field name for the view's fields as below:

* Go to Administration » Structure » Views
* Edit your views
* In the field section, click on last field in the views and check "Rewrite the output of this field" in the REWRITE RESULTS" section.
* In the "REPLACEMENT PATTERNS" section, you will find the list of all fields which are placed before this field and this field also.

---
Tags: 7, views
---


title: HTML5 Flowplayer

text:
# Question
Title: HTML5 Flowplayer
I'm working with videos using flowplayer. My video plays in a Flash player, but I want it to be in HTML5. How do I play flowplayer videos in HTML5?

# Answer
Video.js

> Is a HTML5-based video player with a built-in Flash fallback for older browsers. This means that videos can be played on nearly all devices and operating systems, provided the right codecs are used.

This module is a support module for Video.js. It doesn't contain Video.js itself, but integrates it with the File, Link and Video modules after you've installed it.

or

**Projekktor** (HTML5 Video Player) with **flash support**

> A free, open source (GPL) HTML5 based video player written in Javascript. It solves cross browser and compatibility issues, adds eye candy and provides extremely powerful non standard features.

Check Out the DEMO

```
HTML5 Native Video (with flash fallback)

File extension  Type
.ogv    video/ogg
.webm   video/webm
.ogg    video/ogg
.anx    video/ogg
.mp4    video/mp4

Flash Video

File extension  Type
.flv    video/x-flv
.flv    video/flv
.mp4    video/mp4
.mov    video/quicktime
.m4v    video/mp4

```
> 1 votes

---
Tags: files
---


# Question
Title: Specific localization server for a module
Hello fellow Drupal developers...

When installing a new language, the Localization Update module downloads the necessary (.po) files from Drupal's localization server. However, is there a way to specify where a module should download this from?

This shouldn't be for ALL of the modules, but only a package of modules or just one single module.

Is there a hook, or some sort of info configuration we can place in the module's .info file?

# Answer
> 1 votes
You can specify an alternative source for translations in .info file in different ways:

```
l10n server = http://example.com

l10n url = http://example.com/path/to/l10n_server.xml

l10n path = http://example.com/path/to/%core/%project/%project-%release.%language.po

```

If your localization server is based in l10n\_server module, `l10n server` is enough.

If you're not using l10n\_server but a custom solution, you may want to provide `l10n url` key with the url to a custom-build xml file to inform l10n\_update about where to get translation updates from.

Lastly, if you're not using l10n\_update and you're not planning to generate such an update xml file, you can pass the path to the .po file with `l10n path`, you can use some placeholders in this path, as shown above.

For more information, see l10n\_update's README.txt and docstrings for l10n\_update\_build\_projects().

---
Tags: hooks, i18n-l10n
---


# Question
Title: How to prevent fake drupalcommerce orders
We have a website developed using drupal commerce.All listing and details pages of products are custom made ones.Not drupal views.We have a issue with fake orders.We are getting nearly 1000 fake orders from this site.Doing nothing but only adding products to the cart.I can see that its from whole website.

We have used a hyperlink as add to cart button.Is there any problem with this?

This site is open for anonymous users.When we restrict the site only for registered users these fake orders dramatically reduce.I meant 0 fake orders.

Cant guess whats going on with this.Have installed some spam prevention drupal modules but no luck.

Any one suggest a method to prevent this.

Thanks

# Answer
Your problem is due to robots, in particular spam robots (spambots). I've monitored these pests closely on my site for some time, and found that spambots (such as *XRumer*) will click on *anything* that's clickable. I doubt that you need to be concerned about spammers of the human kind.

There is nothing wrong with the suggestions from Strae, but don't expect spambots such as *Xrumer* to respect tags such as `rel="nofollow"`. (Nice robots such as *googlebot* do, so if your fake orders are from nice robots *only*, this will fix it.).

In my experience, the single most successful measure to filter out spambots is to add *effective* CAPTCHA to the site. If the user is not logged in yet, the CAPTCHA must be present in the order submit form. If a new user register, the CAPTCHA must be present in the registration form. (You don't need to use CAPTCHAs in the order submit form for logged in users). If you set up a CAPTCHA, don't bother with "math challenge", "leave this field blank" and "ReCAPTCHA" - *XRumer* knows how to solve those.

On my site, the Captcha Riddler is by far the most successful robot guard. Even blatantly obvious "riddles", such as: "What is Justin Bieber's first name?" stops the spambots.

PS: If your site is big enough, your "riddles" and their answers will probably be added to the knowledge base of *XRumer* and other spambots. But if you run a small site you will probably be able to fly under the radar for a long time with "riddles" you create yourself (and you just watch the logs and retire and replace any "riddle" that is cracked by a spambot).
> 2 votes

# Answer
> We have used a hyperlink as add to cart button.Is there any problem with this?

Yep.

Links feeds crawlers and spammers: while the first one only follow the links, so you could try adding `rel="nofollow"` to your links, spammers will also submit forms (even if I never seen spammers using the `add to cart` forms, is possible)

As you noticed, make the user register and login can be one solution, if you can't do that, i'll do the steps above:

1. add `rel="nofollow"` to your links
2. if point 1 doesnt work, remove the links and find another way (forms, or divs triggered via javascript)
3. if point 2 fails too, make your users sign up.

Tip: is normal to have orders that remain in the cart for long time: if the user doesnt sign up, the session will expire soon or later and if he come back to buy after, let's say, 1 week, probably Drupal will create another cart/order.

We have a maintenance cron that delete all the cart order of anonymous users older than 1 month; even if this doesnt solve the problem, maybe is a little help ;)

\** UPDATE \**

Yesterday I got a situation like yours, where the add to cart must be a link and not a form (really big list of items). To prevent fake orders (I remembered your situation), i wrote a small module where if the user is logged in, the item get added to the cart, oterwise the user get redirected to the item's page (where I can then use captcha, honeypots, whaterver)

Hope it can helps.
> 1 votes

---
Tags: commerce
---


title: Anonymous user access

text:
# Question
Title: Anonymous user access
I want all the users to access the custom defined url. But now I got error message as Access Denied, my code is as follows, I tried clearing both drupal and browser cache. Please help me,

```
function hbrowse_menu() {
  $items = array();
  $items['browse/restaurants'] = array(
    'title' => t('Browse Restaurants'),
    'page callback' => 'list_restaurants',
    'access arguments' => array('access content'),
    'access callback' => TRUE
  );
  $items['browse/cuisines'] = array(
    'title' => t('Browse Cuisines'),
    'page callback' => 'list_cuisines',
    'access arguments' => array('access content'),
    'access callback' => TRUE
  );
  return $items;
}

```

hbrowse is my module name.

# Answer
Just remove `access arguments`, when the callback is set to `TRUE` you dont need any parameters:

```
$items['browse/restaurants'] = array(
  'title' => t('Browse Restaurants'),
  'page callback' => 'list_restaurants',
  'access callback' => TRUE,
);

```
> 2 votes

# Answer
Try using

```
  $items['browse/restaurants'] = array(
    'title' => t('Browse Restaurants'),
    'page callback' => 'list_restaurants',
    'access arguments' => TRUE,
  );

```
> 0 votes

---
Tags: 7
---


# Question
Title: How to hide certain fields to a user if they aren't referenced in a field on the node?
I have a content type which has a full content and teaser display. It has a number of fields, and one of the fields on it is an Entity Reference field which references users (called field\_registered\_users with unlimited values allowed).

If a user views the node and they aren't referenced within the field then I want to hide certain fields on the node.

How do I do this? Should I do it in the template file or through a custom module? I also want to display a block on the page instead of the fields if this is the case.

# Answer
business logic never in tpl.

You could use hook\_node\_view($node, $view\_mode, $langcode).

In my opinion the cleanest and the most drupal way would be to create a custom formatter (mymodule\_field\_formatter\_info) in which you should pass the returned value (1 or 0) of your business logic to the #access property of the field

Regards.
> 1 votes

---
Tags: entities, users
---


# Question
Title: How can I add template suggestions by UUID?
I'm looking for a solution to migrate content between environments (*dev-\>staging-\>production*) and currently I think I'll use UUID and Node Export (as far as I see UUID Features is still in alpha and isn't recommended by the community).

Sometimes I want to use template files or hooks (e.g. `theme_preprocess_node`) specific to a node created on my dev and then to upload the changes to production - this thing is impossible with the use of nids, but must be possible with uuids. Is there any way out of the box to add theme\_hook\_suggestions by uuid, or do I need to implement it on my theme?

Thanks.

# Answer
You should add a hook in your template.php, like this:

```
function MYTHEME_preprocess_node(&$vars) {
  if ($vars['node']->uuid == '12345') {
    $vars['theme_hook_suggestions'][] = 'my-best-tpl';
  }
}

```
> 1 votes

---
Tags: theming, nodes
---


title: Sending a newsletter more than once?

text:
# Question
Title: Sending a newsletter more than once?
Is it possible to re-send a newsletter once it's been sent?

I am using a Simplenews module and the Subscriptions module).

# Answer
go to phpmyadmin database -\>

go to table -\> ' simplenews\_newsletter '

Sent newsletter will have status 2, pending will have 1 and not sent will be 0.

edit and change the status of that newsletter to 0

Hurrey!!!! send it again :)
> 1 votes

---
Tags: emails
---


title: Drupal form #states using OR

text:
# Question
Title: Drupal form #states using OR
I am trying to make a part of my form display depending on the state of a select box. The select box code is:

```
$form['product_type'] = array(
    '#type' => 'select',
    '#title' => t('Product Type'),
    '#options' => array(
      'a' => t('a'),
      'b' => t('b'),
      'c' => t('c'),
    ),
    '#required' => TRUE,
  );

```

I then have a field when I only wan to show it when the value is b or c.

```
$form['problem'] = array(
    '#type' => 'textarea',
    '#title' => t('Problem'),
    '#states' => array(
      'visible' => array(
        array(
           ':input[name="product_type"]'=> array('value' => 'b'),
           ':input[name="product_type"]'=> array('value' => 'c'),
        ),
      ),
    ),
  );

```

What is happening is that what ever the last value in the page is being used. I have found the following pages https://api.drupal.org/api/drupal/includes%21common.inc/function/drupal\_process\_states/7 & https://drupal.org/node/1464758 but am still lost.

# Answer
it is no right at all, this is the right way to make an OR:

```
$form['problem'] = array(
  '#type' => 'textarea',
  '#title' => t('Problem'),
  '#states' => array(
    'visible' => array(
      array(
        ':input[name="product_type"]'=> array(
          array('value' => 'b'),
          array('value' => 'c'),
        ),
      ),
    ),
  ),
);

```

Regards
> 2 votes

# Answer
Try putting your condition like this (instead of 2 different entries):

```
$form['problem'] = array(
    '#type' => 'textarea',
    '#title' => t('Problem'),
    '#states' => array(
        'visible' => array(
            ':input[name="product_type"]'=> array(
                'value' => 'b',
                'value' => 'c',
            ),
        ),
    ),
);

```
> 0 votes

---
Tags: javascript
---


title: Adding dynamic ajax fields

text:
# Question
Title: Adding dynamic ajax fields
I am trying to add new fields based on the select list. I am using the following code

```
function my_action_plan_from($form, &$form_state) {
  $form['#tree'] = TRUE;
  $result = db_query('Select * from my_action_plan_settings ORDER BY action_type');
  $records = array();
  $i = 0;
  foreach ($result as  $record) {
    $action_lists = array_merge($records, preg_split('/[\r\n]+/', trim($record->point_of_action), -1, PREG_SPLIT_NO_EMPTY));

    $form[$action_name] = array(
      '#type' => 'select',
      '#options' => $action_lists,
      '#attributes' => array('class' => array('enabled-for-ajax')),
      '#ajax' => array(
        'callback' => 'get_next_steps',
        'wrapper' => 'item-action-'. $record->action_id,
        'method' => 'append',
      ),
    );

  }

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

  return $form;
}

function get_next_steps($form, &$form_state) {
      $newform['date'] = array(
        '#type' => 'textfield',
        '#size' => 20,
      );
      $newform['note'] = array(
        '#type' => 'textarea',
      );

      $newform['percent'] = array(
        '#type' => 'textfield',
      );
      return $newform;
}

```

It works fine with adding new fields based on selection, but the problem is the new fields added does not appear in $form\_state. The values does not get submitted to submit handler, am i doing something wrong?

*** MODIFIED CODE ***

Maybe i was wrong at explaining, sorry, i have posted the modified code and yes i am creating the form in my\_action\_plan\_form(). I am not trying to use $form\_state for a permanent store, I was using it to create new fields in my\_action\_plan() but the problem is if i set a value $form\_state\['storage'\] = "foobar" in get\_next\_step(), the value is not passed to my\_action\_plan(). $form\_state\['storage'\] becomes empty in my\_action\_plan().

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

  $form['#tree'] = TRUE;

  $trigger_element = !empty($form_state['triggering_element']['#name']) ? $form_state['triggering_element']['#name'] : FALSE;

  foreach ($result as  $record) {
    $action_lists = array_merge($records, preg_split('/[\r\n]+/', trim($record->point_of_action), -1, PREG_SPLIT_NO_EMPTY));
    $action_name = "action_name_" . $record->action_id;

    $form[$action_name] = array(
      '#type' => 'fieldset',
    );

    if (empty($form_state['my_action_plan'][$action_name])) {
      $form_state['my_action_plan'][$action_name] = array();
    }

    if($trigger_element && $trigger_element == $record->action_id ) {
      if(!array_search($form_state['triggering_element']['#value'], $form_state['my_action_plan'][$action_name])) {
        $form_state['my_action_plan'][$action_name][] = $form_state['triggering_element']['#value'];
      }
    }

    $form[$action_name]['select'] = array(
      '#type' => 'select',
      '#options' => $action_lists,
      '#attributes' => array('class' => array('enabled-for-ajax')),
      '#ajax' => array(
        'callback' => 'get_next_steps',
        'wrapper' => $action_name . "-id",
      ),
    );

    if(count($form_state['my_action_plan'][$action_name]) > 0) {

        for ($i=0; $i < count($form_state['my_action_plan'][$action_name]); $i++) {

            $option = $form_state['my_action_plan'][$action_name][$i];

            $form[$action_name][$option] = array(
              '#type' => 'fieldset',
            );

            $form[$action_name][$option]['date'] = array(
              '#type' => 'textfield',
              '#size' => 20,
            );

            $form[$action_name][$option]['note'] = array(
              '#type' => 'textarea',
            );

            $form[$action_name][$option]['percentage'] = array(
              '#type' => 'textfield',
            );

            $submit_id = $action_name . '-' . $option . '-submit';
            $form[$action_name][$option]['submit'] = array(
              '#type' => 'fieldset',
            );

            $form[$action_name][$option]['submit'] = array(
              '#type' => 'fieldset',
            );

            $form[$action_name][$option]['submit']['value'] = array(
               '#type' => 'button',
              '#value' => 'Save ',
              '#ajax' => array(
                 'callback' => 'save_step',
                 'wrapper' => $submit_id,
              ),
            );
      }
  }

  return $form;
}

function get_next_steps($form, &$form_state) {
    return $form[$form_state['triggering_element']['#parents'][0]];
}

```

Please help

Deepak

# Answer
You should create all the form elements in `my_action_plan_form()`.

Use ajax callback function only to change some form elements values.

**Example:**

```
/**
 * My action plan form.
 */
function my_action_plan_form($form, &$form_state) {

  $form['#tree'] = TRUE;

  // some basic form elements
  // ...

  // set the variable to determine
  // whether the new form elements should be created or not.
  if (empty($form_state['new_form'])) {
    $form_state['new_form'] = FALSE;
  }

  // create new form elements
  if ($form_state['new_form']) {

    $form['date'] = array(
      '#type' => 'textfield',
      '#size' => 20,
    );

    $form['note'] = array(
      '#type' => 'textarea',
    );

    $form['percent'] = array(
      '#type' => 'textfield',
    );
  }

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

  return $form;
}

/**
 * Ajax callback.
 * It's only to determine what part of the form should be returned.
 * It allows making one-time changes, but is useless for permanent ones.
 */
function get_next_steps($form, &$form_state) {
  $form_state['new_form'] = TRUE;
  $form_state['rebuild'] = TRUE;
}

```
> 1 votes

---
Tags: forms, ajax
---


# Question
Title: drupal_alter() ignores more complex function names when the hook is called
I have a module named wlm that calls `drupal_alter()` as follows.

```
drupal_alter('abc', $ref, $arg1, $arg2);

```

This works perfectly for a function like the following.

```
function wlm_abc_alter(&$ref, $arg1, $arg2) { };

```

However, it breaks/does nothing if the function is similar to the following one.

```
function wlm_this_is_some_extra_detritus_abc_alter(&$ref, $arg1, $arg2) { };

```

I want to be able to call this alter function several times within my wlm module, but because the naming convention seems to be limited to `module_hook_alter()` I can only use it once, which is less than desirable. Is this an intentional design pattern; or is it a mistake; or am I just missing something obvious?

Is it possible to do something like the following, where `$my_func_name` is delivered dynamically?

```
drupal_alter($my_func_name . '_abc', $ref, $arg1, $arg2);

```

# Answer
It's intentional - a module should only be able to implement a single hook once, and the naming convention requires that the function be called `modulename_hookname_alter()`. Drupal isn't ignoring your more-verbose function name, but since it doesn't match the name of the hook, it's never going to call it.

You can create other hooks though, based on whatever makes sense to your use case. For example if your module had a bunch of contexts you might create `hook_abc_CONTEXT_alter()`, and invoke it like so

```
foreach (mymodule_contexts() as $context_name) {
  $hook_name = 'abc_' . $context_name;
  drupal_alter($hook_name, $ref, $arg1, $arg2);
}

```

But I think that's as close as Drupal core will let you get to the pattern you're trying to implement.
> 3 votes

# Answer
If mymodule is the short name of the module, abc is the name of the alter hook, then the implementation of that alter hook for that module is the `mymodule_abc_alter()`. Any other function of that module is not considered an implementation of that alter hook.

You could do as drupal\_prepare\_form() does, however.

```
  // Invoke hook_form_alter(), hook_form_BASE_FORM_ID_alter(), and
  // hook_form_FORM_ID_alter() implementations.
  $hooks = array('form');
  if (isset($form_state['build_info']['base_form_id'])) {
    $hooks[] = 'form_' . $form_state['build_info']['base_form_id'];
  }
  $hooks[] = 'form_' . $form_id;
  drupal_alter($hooks, $form, $form_state, $form_id);

```

In your specific case, the code would be similar to the following one.

```
drupal_alter(array('abc', 'this_is_some_extra_detritus_abc'), $ref, $arg1, $arg2);

```

If you have a function that returns you all the possible variants of that alter hook, then you could use a call like the following one.

```
drupal_alter(wml_get_abc_variants(), $ref, $arg1, $arg2);

```

In this case, `wml_get_abc_variants()` should return a string or an array containing strings.

As side note, `drupal_alter()` in Drupal 8 is deprecated in favor of `Drupal::moduleHandler()->alter()`. A Drupal service that receives the module handler as DIC, and that saves it in a property (e.g. `moduleHandler`), should use code similar to `$this->moduleHandler->alter()`.
> 1 votes

---
Tags: 7, hooks
---


title: Embedding views in tpl files

text:
# Question
Title: Embedding views in tpl files
I need an advice. Is there any downsides when embedding views in the page/node tpl files like the following:

`<?php print views_embed_view('course_videos', 'block_1'); ?>` and this `<?php $key = views_get_view_result('course_videos', 'block_2'); ?>` in the node.tpl files

I am little bit concerned cause I've read several articles saying you must not query the db or use a complex php logic in the tpl files. Everything's working like a charm now. The site is still not in production though...

Thank you in advance!

# Answer
> 6 votes
Including views in tpl is going backwards. Drupal allows you to use views as pages and as blocks. You can apply templates to that pages and blocks, and you can put blocks in regions. By calling views from template, you are messing with theme registry and cache logic. It might be not an issue if site is small, and both read and write volumes are low, but it will result in pages being out of sync on heavy loaded site.

Instead of outputting view directly, make a region, output it in template file, and put a views block inside.

Using views\_embed\_view in a preprocess function in template.php might be OK. Opinions and experience with it can vary, and I would try to avoid it, but certainly it does not mess with cache or theme registry like using it in tpl would.

---
Tags: views, theming, performance
---


# Question
Title: Drupal 7 Views 3 Datefield Output Theming
I'm having trouble rewriting the output of datefield in Drupal 7 Views - php is not my strong point.

Just for reference I'm using the latest stable versions of Date, Views, and D7, and the theme framework I'm using is Omega 3.

On my content type I want to change the way the date is displayed. I've created a custom date type, but I don't have the ability to style it the way I'd like due to it all being wrapped in the same container.

I've drilled down in to my theme information and pulled out the template that handles the date field for my view and I'm trying to rewrite it so that it's wrapped in its own divs and I can then apply classes and style it. Here is what I have

EDIT: This is what I'm currently using.

```
<?php

/**
 * @file
 * This template is used to print a single field in a view.
 *
 * It is not actually used in default Views, as this is registered as a theme
 * function which has better performance. For single overrides, the template is
 * perfectly okay.
 *
 * Variables available:
 * - $view: The view object
 * - $field: The field handler object that can process the input
 * - $row: The raw SQL result that can be used
 * - $output: The processed output that will normally be used.
 *
 * When fetching output from the $row, this construct should be used:
 * $data = $row->{$field->field_alias}
 *
 * The above will guarantee that you'll always get the correct data,
 * regardless of any changes in the aliasing that might happen if
 * the view is modified.
 */
?>

<?php
$timestamp = strtotime(
    $row->{$field->['field_event_date']->raw});
$ev_month = format_date($timestamp, 'custom', 'F');
$ev_day = format_date($timestamp, 'custom', 'd');
?>

<div class="upcoming-date">
<span class="month"><?php print "$ev_month"; ?></span>
<span class="day"><?php print "$ev_day"; ?></span>
</div>

```

Unfortunately is producing a ton of errors and I'm not sure how to resolve them. Here is a sample.

```
warning: date_timezone_set() expects parameter 1 to be datetime, boolean given in format_date() (line 2014 of /var/www/vhosts/.../drupal/includes/common.inc).
warning: date_format() expects parameter 1 to be datetime, boolean given in format_date() (line 2024 of /var/www/vhosts/.../drupal/includes/common.inc).
warning: date_timezone_set() expects parameter 1 to be datetime, boolean given in format_date() (line 2014 of /var/www/vhosts/.../drupal/includes/common.inc).
warning: date_format() expects parameter 1 to be datetime, boolean given in format_date() (line 2024 of /var/www/vhosts/.../drupal/includes/common.inc).
warning: date_timezone_set() expects parameter 1 to be datetime, boolean given in format_date() (line 2014 of /var/www/vhosts/.../drupal/includes/common.inc).
warning: date_format() expects parameter 1 to be datetime, boolean given in format_date() (line 2024 of /var/www/vhosts/.../drupal/includes/common.inc).
warning: date_timezone_set() expects parameter 1 to be datetime, boolean given in format_date() (line 2014 of /var/www/vhosts/.../drupal/includes/common.inc).
warning: date_format() expects parameter 1 to be datetime, boolean given in format_date() (line 2024 of /var/www/vhosts/.../drupal/includes/common.inc).
warning: date_timezone_set() expects parameter 1 to be datetime, boolean given in format_date() (line 2014 of /var/www/vhosts/.../drupal/includes/common.inc).
warning: date_format() expects parameter 1 to be datetime, boolean given in format_date() (line 2024 of /var/www/vhosts/.../drupal/includes/common.inc).
warning: date_timezone_set() expects parameter 1 to be datetime, boolean given in format_date() (line 2014 of /var/www/vhosts/.../drupal/includes/common.inc).
warning: date_format() expects parameter 1 to be datetime, boolean given in format_date() (line 2024 of /var/www/vhosts/.../drupal/includes/common.inc).
warning: date_timezone_set() expects parameter 1 to be datetime, boolean given in format_date() (line 2014 of /var/www/vhosts/.../drupal/includes/common.inc).
warning: date_format() expects parameter 1 to be datetime, boolean given in format_date() (line 2024 of /var/www/vhosts/.../drupal/includes/common.inc).
warning: date_timezone_set() expects parameter 1 to be datetime, boolean given in format_date() (line 2014 of /var/www/vhosts/.../drupal/includes/common.inc).
warning: date_format() expects parameter 1 to be datetime, boolean given in format_date() (line 2024 of /var/www/vhosts/.../drupal/includes/common.inc).
warning: date_timezone_set() expects parameter 1 to be datetime, boolean given in format_date() (line 2014 of /var/www/vhosts/.../drupal/includes/common.inc).
warning: date_format() expects parameter 1 to be datetime, boolean given in format_date() (line 2024 of /var/www/vhosts/.../drupal/includes/common.inc).
warning: date_timezone_set() expects parameter 1 to be datetime, boolean given in format_date() (line 2014 of /var/www/vhosts/.../drupal/includes/common.inc).
warning: date_format() expects parameter 1 to be datetime, boolean given in format_date() (line 2024 of /var/www/vhosts/.../drupal/includes/common.inc).
warning: date_timezone_set() expects parameter 1 to be datetime, boolean given in format_date() (line 2014 of /var/www/vhosts/.../drupal/includes/common.inc).
warning: date_format() expects parameter 1 to be datetime, boolean given in format_date() (line 2024 of /var/www/vhosts/.../drupal/includes/common.inc).
warning: date_timezone_set() expects parameter 1 to be datetime, boolean given in format_date() (line 2014 of /var/www/vhosts/.../drupal/includes/common.inc).
warning: date_format() expects parameter 1 to be datetime, boolean given in format_date() (line 2024 of /var/www/vhosts/.../drupal/includes/common.inc).
warning: date_timezone_set() expects parameter 1 to be datetime, boolean given in format_date() (line 2014 of /var/www/vhosts/.../drupal/includes/common.inc).
warning: date_format() expects parameter 1 to be datetime, boolean given in format_date() (line 2024 of /var/www/vhosts/.../drupal/includes/common.inc).
warning: date_timezone_set() expects parameter 1 to be datetime, boolean given in format_date() (line 2014 of /var/www/vhosts/.../drupal/includes/common.inc).
warning: date_format() expects parameter 1 to be datetime, boolean given in format_date() (line 2024 of /var/www/vhosts/.../drupal/includes/common.inc).
warning: date_timezone_set() expects parameter 1 to be datetime, boolean given in format_date() (line 2014 of /var/www/vhosts/.../drupal/includes/common.inc).
warning: date_format() expects parameter 1 to be datetime, boolean given in format_date() (line 2024 of /var/www/vhosts/.../drupal/includes/common.inc).
warning: date_timezone_set() expects parameter 1 to be datetime, boolean given in format_date() (line 2014 of /var/www/vhosts/.../drupal/includes/common.inc).
warning: date_format() expects parameter 1 to be datetime, boolean given in format_date() (line 2024 of /var/www/vhosts/.../drupal/includes/common.inc).
warning: date_timezone_set() expects parameter 1 to be datetime, boolean given in format_date() (line 2014 of /var/www/vhosts/.../drupal/includes/common.inc).
warning: date_format() expects parameter 1 to be datetime, boolean given in format_date() (line 2024 of /var/www/vhosts/.../drupal/includes/common.inc).
warning: date_timezone_set() expects parameter 1 to be datetime, boolean given in format_date() (line 2014 of /var/www/vhosts/.../drupal/includes/common.inc).
warning: date_format() expects parameter 1 to be datetime, boolean given in format_date() (line 2024 of /var/www/vhosts/.../drupal/includes/common.inc).
warning: date_timezone_set() expects parameter 1 to be datetime, boolean given in format_date() (line 2014 of /var/www/vhosts/.../drupal/includes/common.inc).
warning: date_format() expects parameter 1 to be datetime, boolean given in format_date() (line 2024 of /var/www/vhosts/.../drupal/includes/common.inc).
warning: date_timezone_set() expects parameter 1 to be datetime, boolean given in format_date() (line 2014 of /var/www/vhosts/.../drupal/includes/common.inc).
warning: date_format() expects parameter 1 to be datetime, boolean given in format_date() (line 2024 of /var/www/vhosts/.../drupal/includes/common.inc).
warning: date_timezone_set() expects parameter 1 to be datetime, boolean given in format_date() (line 2014 of /var/www/vhosts/.../drupal/includes/common.inc).
warning: date_format() expects parameter 1 to be datetime, boolean given in format_date() (line 2024 of /var/www/vhosts/.../drupal/includes/common.inc).
warning: date_timezone_set() expects parameter 1 to be datetime, boolean given in format_date() (line 2014 of /var/www/vhosts/.../drupal/includes/common.inc).
warning: date_format() expects parameter 1 to be datetime, boolean given in format_date() (line 2024 of /var/www/vhosts/.../drupal/includes/common.inc).
warning: date_timezone_set() expects parameter 1 to be datetime, boolean given in format_date() (line 2014 of /var/www/vhosts/.../drupal/includes/common.inc).
warning: date_format() expects parameter 1 to be datetime, boolean given in format_date() (line 2024 of /var/www/vhosts/.../drupal/includes/common.inc).
warning: date_timezone_set() expects parameter 1 to be datetime, boolean given in format_date() (line 2014 of /var/www/vhosts/.../drupal/includes/common.inc).
warning: date_format() expects parameter 1 to be datetime, boolean given in format_date() (line 2024 of /var/www/vhosts/.../drupal/includes/common.inc).
warning: date_timezone_set() expects parameter 1 to be datetime, boolean given in format_date() (line 2014 of /var/www/vhosts/.../drupal/includes/common.inc).
warning: date_format() expects parameter 1 to be datetime, boolean given in format_date() (line 2024 of /var/www/vhosts/.../drupal/includes/common.inc).
warning: date_timezone_set() expects parameter 1 to be datetime, boolean given in format_date() (line 2014 of /var/www/vhosts/.../drupal/includes/common.inc).
warning: date_format() expects parameter 1 to be datetime, boolean given in format_date() (line 2024 of /var/www/vhosts/.../drupal/includes/common.inc).
warning: date_timezone_set() expects parameter 1 to be datetime, boolean given in format_date() (line 2014 of /var/www/vhosts/.../drupal/includes/common.inc).
warning: date_format() expects parameter 1 to be datetime, boolean given in format_date() (line 2024 of /var/www/vhosts/.../drupal/includes/common.inc).
warning: date_timezone_set() expects parameter 1 to be datetime, boolean given in format_date() (line 2014 of /var/www/vhosts/.../drupal/includes/common.inc).
warning: date_format() expects parameter 1 to be datetime, boolean given in format_date() (line 2024 of /var/www/vhosts/.../drupal/includes/common.inc).
warning: date_timezone_set() expects parameter 1 to be datetime, boolean given in format_date() (line 2014 of /var/www/vhosts/.../drupal/includes/common.inc).
warning: date_format() expects parameter 1 to be datetime, boolean given in format_date() (line 2024 of /var/www/vhosts/.../drupal/includes/common.inc).
warning: date_timezone_set() expects parameter 1 to be datetime, boolean given in format_date() (line 2014 of /var/www/vhosts/.../drupal/includes/common.inc).
warning: date_format() expects parameter 1 to be datetime, boolean given in format_date() (line 2024 of /var/www/vhosts/.../drupal/includes/common.inc).
warning: date_timezone_set() expects parameter 1 to be datetime, boolean given in format_date() (line 2014 of /var/www/vhosts/.../drupal/includes/common.inc).
warning: date_format() expects parameter 1 to be datetime, boolean given in format_date() (line 2024 of /var/www/vhosts/.../drupal/includes/common.inc).
warning: date_timezone_set() expects parameter 1 to be datetime, boolean given in format_date() (line 2014 of /var/www/vhosts/.../drupal/includes/common.inc).
warning: date_format() expects parameter 1 to be datetime, boolean given in format_date() (line 2024 of /var/www/vhosts/.../drupal/includes/common.inc).
warning: date_timezone_set() expects parameter 1 to be datetime, boolean given in format_date() (line 2014 of /var/www/vhosts/.../drupal/includes/common.inc).
warning: date_format() expects parameter 1 to be datetime, boolean given in format_date() (line 2024 of /var/www/vhosts/.../drupal/includes/common.inc).
warning: date_timezone_set() expects parameter 1 to be datetime, boolean given in format_date() (line 2014 of /var/www/vhosts/.../drupal/includes/common.inc).
warning: date_format() expects parameter 1 to be datetime, boolean given in format_date() (line 2024 of /var/www/vhosts/.../drupal/includes/common.inc).
warning: date_timezone_set() expects parameter 1 to be datetime, boolean given in format_date() (line 2014 of /var/www/vhosts/.../drupal/includes/common.inc).
warning: date_format() expects parameter 1 to be datetime, boolean given in format_date() (line 2024 of /var/www/vhosts/.../drupal/includes/common.inc).
warning: date_timezone_set() expects parameter 1 to be datetime, boolean given in format_date() (line 2014 of /var/www/vhosts/.../drupal/includes/common.inc).
warning: date_format() expects parameter 1 to be datetime, boolean given in format_date() (line 2024 of /var/www/vhosts/.../drupal/includes/common.inc).
warning: date_timezone_set() expects parameter 1 to be datetime, boolean given in format_date() (line 2014 of /var/www/vhosts/.../drupal/includes/common.inc).
warning: date_format() expects parameter 1 to be datetime, boolean given in format_date() (line 2024 of /var/www/vhosts/.../drupal/includes/common.inc).
warning: date_timezone_set() expects parameter 1 to be datetime, boolean given in format_date() (line 2014 of /var/www/vhosts/.../drupal/includes/common.inc).
warning: date_format() expects parameter 1 to be datetime, boolean given in format_date() (line 2024 of /var/www/vhosts/.../drupal/includes/common.inc).
warning: date_timezone_set() expects parameter 1 to be datetime, boolean given in format_date() (line 2014 of /var/www/vhosts/.../drupal/includes/common.inc).
warning: date_format() expects parameter 1 to be datetime, boolean given in format_date() (line 2024 of /var/www/vhosts/.../drupal/includes/common.inc).
warning: date_timezone_set() expects parameter 1 to be datetime, boolean given in format_date() (line 2014 of /var/www/vhosts/.../drupal/includes/common.inc).
warning: date_format() expects parameter 1 to be datetime, boolean given in format_date() (line 2024 of /var/www/vhosts/.../drupal/includes/common.inc).
warning: date_timezone_set() expects parameter 1 to be datetime, boolean given in format_date() (line 2014 of /var/www/vhosts/.../drupal/includes/common.inc).
warning: date_format() expects parameter 1 to be datetime, boolean given in format_date() (line 2024 of /var/www/vhosts/.../drupal/includes/common.inc).
warning: date_timezone_set() expects parameter 1 to be datetime, boolean given in format_date() (line 2014 of /var/www/vhosts/.../drupal/includes/common.inc).
warning: date_format() expects parameter 1 to be datetime, boolean given in format_date() (line 2024 of /var/www/vhosts/.../drupal/includes/common.inc).
warning: date_timezone_set() expects parameter 1 to be datetime, boolean given in format_date() (line 2014 of /var/www/vhosts/.../drupal/includes/common.inc).
warning: date_format() expects parameter 1 to be datetime, boolean given in format_date() (line 2024 of /var/www/vhosts/.../drupal/includes/common.inc).
warning: date_timezone_set() expects parameter 1 to be datetime, boolean given in format_date() (line 2014 of /var/www/vhosts/.../drupal/includes/common.inc).
warning: date_format() expects parameter 1 to be datetime, boolean given in format_date() (line 2024 of /var/www/vhosts/.../drupal/includes/common.inc).
warning: date_timezone_set() expects parameter 1 to be datetime, boolean given in format_date() (line 2014 of /var/www/vhosts/.../drupal/includes/common.inc).
warning: date_format() expects parameter 1 to be datetime, boolean given in format_date() (line 2024 of /var/www/vhosts/.../drupal/includes/common.inc).
warning: date_timezone_set() expects parameter 1 to be datetime, boolean given in format_date() (line 2014 of /var/www/vhosts/.../drupal/includes/common.inc).
warning: date_format() expects parameter 1 to be datetime, boolean given in format_date() (line 2024 of /var/www/vhosts/.../drupal/includes/common.inc).
warning: date_timezone_set() expects parameter 1 to be datetime, boolean given in format_date() (line 2014 of /var/www/vhosts/.../drupal/includes/common.inc).
warning: date_format() expects parameter 1 to be datetime, boolean given in format_date() (line 2024 of /var/www/vhosts/.../drupal/includes/common.inc).
warning: date_timezone_set() expects parameter 1 to be datetime, boolean given in format_date() (line 2014 of /var/www/vhosts/.../drupal/includes/common.inc).
warning: date_format() expects parameter 1 to be datetime, boolean given in format_date() (line 2024 of /var/www/vhosts/.../drupal/includes/common.inc).
warning: date_timezone_set() expects parameter 1 to be datetime, boolean given in format_date() (line 2014 of /var/www/vhosts/.../drupal/includes/common.inc).
warning: date_format() expects parameter 1 to be datetime, boolean given in format_date() (line 2024 of /var/www/vhosts/.../drupal/includes/common.inc).
warning: date_timezone_set() expects parameter 1 to be datetime, boolean given in format_date() (line 2014 of /var/www/vhosts/.../drupal/includes/common.inc).
warning: date_format() expects parameter 1 to be datetime, boolean given in format_date() (line 2024 of /var/www/vhosts/.../drupal/includes/common.inc).
warning: date_timezone_set() expects parameter 1 to be datetime, boolean given in format_date() (line 2014 of /var/www/vhosts/.../drupal/includes/common.inc).
warning: date_format() expects parameter 1 to be datetime, boolean given in format_date() (line 2024 of /var/www/vhosts/.../drupal/includes/common.inc).
warning: date_timezone_set() expects parameter 1 to be datetime, boolean given in format_date() (line 2014 of /var/www/vhosts/.../drupal/includes/common.inc).
warning: date_format() expects parameter 1 to be datetime, boolean given in format_date() (line 2024 of /var/www/vhosts/.../drupal/includes/common.inc).
warning: date_timezone_set() expects parameter 1 to be datetime, boolean given in format_date() (line 2014 of /var/www/vhosts/.../drupal/includes/common.inc).
warning: date_format() expects parameter 1 to be datetime, boolean given in format_date() (line 2024 of /var/www/vhosts/.../drupal/includes/common.inc).
warning: date_timezone_set() expects parameter 1 to be datetime, boolean given in format_date() (line 2014 of /var/www/vhosts/.../drupal/includes/common.inc).
warning: date_format() expects parameter 1 to be datetime, boolean given in format_date() (line 2024 of /var/www/vhosts/.../drupal/includes/common.inc).

```

It's my understanding that due to the nature of the way the datefield handles the date it needs to be converted to a unix timestamp so that's the first part, then the second part is trying to take that output and rewrite it so that it's in a custom format so I can isolate the individual parts for styling.

can any of the PHP gurus help me out here?

# Answer
> 0 votes
I've found a solution, though there are currently some problems with the module and I'm working on that part now. However, the question is answered by using the custom formatters module - https://drupal.org/project/custom\_formatters \- and using that to format the date field in Views. Would prefer to have a template/coded solution, but this addresses my immediate need of getting custom formatting for the date field. There was another Stack Exchange that addressed this previously also here: how do I add extra classes to a date field at views?

# Answer
> 0 votes
The variable $fields does not exist in the context of the template. Take a look at the comment, it tells you what variables are available.

---
Tags: 7, datetime
---


# Question
Title: What configuration is required to use date_views with a field?
I have a custom entity "referral" which is available for views:

```
function mymodule_entity_info() {
  return array(
    'referral' => array(
      'label' => t('Referral'),
      'controller class' => 'EntityAPIController',
      'views controller class' => 'EntityDefaultViewsController',
      ...
    ),
  );
}

```

The `mymodule_referral` table has a field `referred_at` which is a timestamp (stored as an int); I'd like to add a filter on this field to my view. I've got it displaying and filtering correctly with `hook_views_data_alter` and `views_handler_*_date`, but I'd prefer popup date selectors.

I understand that the `date_views` submodule of `date` should do what I want, but I can't find proper documentation on how to use it.

```
function mymodule_views_data_alter(&$data) {
  ...
  $data['mymodule_referral']['referred_at']['filter'] = array(
    'real field' => 'referred_at',
    'handler' => 'date_views_filter_handler',
  );
}

```

doesn't seem to be sufficient, because it displays in the view edit page as

```
FILTER CRITERIA

    Referral: Referred_at (Missing date fields!) | Settings

```

If I open the settings there's a compulsory field

```
DATE FIELD(S) *
Select date field(s) to filter.

```

with no options to select.

The only reference I can find to the "Missing date fields!" error message talks about `hook_date_api_fields`, but that hook doesn't seem to exist in 7.

What configuration am I missing?

# Answer
> 0 votes
In addition to mapping `'handler'` to `'date_views_filter_handler'` you need to tell `date_views` that the field is a date:

```
function mymodule_views_data_alter(&$data) {
  ...
  $data['mymodule_referral']['referred_at']['filter'] = array(
    'handler' => 'date_views_filter_handler',
    'is date' => TRUE,
  );
}

```

In the filter settings for `referred_at` you will now see `referred_at` as an option for "DATE FIELD(S)", and if you select it then it will work as expected.

---
Tags: 7, views, datetime
---


# Question
Title: Adding ajax to text field in node edit form
I have created a content type "Type A" and added three fields to content type. I want to display value in third field equal to (value of first field - value of second field).

I want to implement the same using ajax functionality. I have created a custom module and alter the "node form" and add ajax to field 1 but ajax is not working on change event of textfield.

Code Snippet:

```
function employee_login_form_alter(&$form, &$form_state, $form_id){

    $form['field_total_value']['#prefix'] = '<div id="calculate-total-value">';
    $form['field_total_value']['#suffix'] = '</div>';

    $form['field_value_first']['#ajax'] = array(
        'callback' => 'employee_login_ajax',
        'wrapper' => 'calculate-total-value',
        'method' => 'replace',
        'event' => 'change',
    );

    $form['field_value_first']['und'][0]['#ajax'] = array(
        'callback' => 'employee_login_ajax',
        'wrapper' => 'calculate-total-value',
        'method' => 'replace',
        'event' => 'change',
    );

}

function employee_login_ajax(&$form, &$form_state) { //print_r($form); exit;
  print_r($form_state['values']);
}

```

# Answer
You don't need ajax, you can do this with jQuery or javascript. Something like this might work.

First, create an external js file and set up your change events.

```
jQuery(document).ready(
    function()
    {
        jQuery("#field2").change(subtract_fields);
        jQuery("#field1").change(subtract_fields);

        function subtract_fields()
        {
            if (jQuery("#field1").value != "" && jQuery("#field2").value != "")
            {
                return jQuery("#field1").value - jQuery("#field2").value;
            }

            return "";
        }
    }
);

```

Next, load the external js file using drupal\_add\_js.

Clear your cache and voila.
> 2 votes

# Answer
In ajax callback you are not supposed to print form part you want updated. You are supposed to return form part that needs updating. And you can set field's value using `$form_state['input']`.

```
function employee_login_ajax(&$form, &$form_state) {
  $form_state['input']['field_total_value'] = $your_value;
  return $form['field_total_value'];
}

```

Ah, and don't forget `<input>` usually does not support `change` event. You can use one of the following instead:

* `keyup`
* `blur`
* maybe `input`, this one depends on browser

Or don't set `['#ajax']['event']` at all, to let Drupal decide.
> 2 votes

---
Tags: 7, forms, ajax
---


# Question
Title: Webforms Ajax File Upload Issue with IE7 and IE8
The file upload fields in my webform work everywhere except IE7 and IE8. When I click the upload button I get a js alert that says the following

"An error has occurred while attempting to process /file/ajax/submitted/nameofmyuploadfield/form-reallylongrandomstring:"

I've tried several different versions of jQuery through the jQuery Update module but to no avail. I even tried the webform module right out of the box on a new drupal instance and got the same error. I'm having a hard time believing webform file uploads were never meant to work on IE7 and IE8 but that seems to be the reality of my situation. Please share some wisdom about overcoming this issue.

here is an example to the out-of-the-box webform file upload not working in IE7 and IE8 http://bonkmas.com/vids/node/4

# Answer
> 0 votes
I've managed to solve this weird issue, the root cause was relatively easy to find once you have the correct tools to debug. Which is an issue in IE7/8. My issue was related to Adaptive Image Styles, and it now works with that disabled.

The answer here: IE8 Debugging (stack overflow) helps equip us with a bit better debugging capability in IE8.

Set a watch on e, and check to see what the error throws to see if that gives any hints in where to look next.

Now the problem I specifically encountered comes from /misc/ajax.js so open up this file and make the following changes starting line 239:

```
//try {
    if (ajax.form) {
      // If setClick is set, we must set this to ensure that the button's
      // value is passed.
      if (ajax.setClick) {
        // Mark the clicked button. 'form.clk' is a special variable for
        // ajaxSubmit that tells the system which element got clicked to
        // trigger the submit. Without it there would be no 'op' or
        // equivalent.
        element.form.clk = element;
     // }

      ajax.form.ajaxSubmit(ajax.options);
    }
    else {
      ajax.beforeSerialize(ajax.element, ajax.options);
      $.ajax(ajax.options);
    }
  }
  //catch (e) {
    // Unset the ajax.ajaxing flag here because it won't be unset during
    // the complete response.

    ajax.ajaxing = false;

    alert("An error occurred while attempting to process " + ajax.options.url + ": " + e.message);
  //}

```

This removes the try/catch since they were obscuring where the error was coming from in the IE inspector. Now set breakpoints on each one of those variables and set a watch on ajax. Hit upload on your page and continue through the errors checking each variables, then as it hits an error the Console should take you to which ever file is throwing the error.

Hope this helps you.

---
Tags: 7, ajax, webforms, javascript, files
---


# Question
Title: When should I use methods, get() and magic offset
There are three different ways to get an entity value, for example the node content type.

* `$node->type->value`
* `$node->getType()`
* `$node->get('type')`

Which one should I use?

# Answer
> 10 votes
If there is a specific method - as for `$node->getType()` \- I'd recommend using this one. Obviously that's never the case for dynamic stuff like fields - for that `$node->type->value` would be the recommendation.

Edit: `$node->get('type')` is just a more verbose variant of `$node->type` \- both get you the "type" field object.

# Answer
> 7 votes
A specific method IMO is always preferred because of the `@return` typehint. You can't really typehint the return of a `get('foo')`. And, magic will always be slower and also an unknown to IDEs on what is returned. (Note that every time we are talking IDEs we are also talking possible bugs -- not just the IDE but the programmer has no knowledge of what's in a variable.)

---
Tags: 8, entities
---


title: Automatic creation of users

text:
# Question
Title: Automatic creation of users
I have a big problem. I don't know why, but every day are created users in my site. It's not a normal registration because I have disabled the block for login/registration in my site. The users' status is locked and they are many.

What can I do?

# Answer
Disabling block is pointless. You need to truly disable registration itself. Go to *Administration » Configuration » People* and under *Who can register accounts?* select *Administrators only*. If that's not enough, make sure you have all security updates installed.

Note: exact path to this setting may be a bit different in Drupal 6 or 8, but you should be able to find it easily enough.
> 1 votes

# Answer
It's probably spam. You should install a captcha module on the user registration form, like CAPTCHA module
> 0 votes

---
Tags: users
---


title: Use of textimage module

text:
# Question
Title: Use of textimage module
how can we convert the contents of the article into image format using textimage module in drupal 7.

Suppose, we are viewing a article in some textformat (ie default format of drupal) and if we want to see the contents of article in image format.

# Answer
Check Textimage 7.x-3.x

It provides a field formatter for long text. Be aware that very large text may create memory issues.

From README.TXT:

via Content Type field display formatters

* Access 'Content type' administration features via Administration-\> Structure-\>Content Types
* Select the content type for which you want to manage a Textimage field (e.g. Article, Basic page, etc.)
* If you need to create a new field, in the 'Manage Fields' tab, add a new field of type 'Text' (or 'Long text', or 'Long text and summary') or 'Image'
* In the 'Manage Display' tab, select a 'Textimage' format for the field created above (or any existing one)
* Click on the gear icon
* Select from the dropdown displayed the image style you want to use to represent the content as a Textimage
> 1 votes

---
Tags: 7, media
---


# Question
Title: Line breaks in site name but not in title tag
For design purposes I need line breaks in a multilingual site name. I have managed to do so by adding `<br />` tags in the site name variable. But they show in the title within the html head tag and I don't know how to get rid of them.

I am using a custom Zen subtheme to which I have added the html.tpl.php file. In that I have tried the following approaches to no avail:

```
<title><?php print preg_replace('/<br \/>/iU', '', $head_title); ?></title>

<title><?php print strip_tags($head_title); ?></title>

<title><?php $head_title = str_replace('<br />', '', $head_title);
  print $head_title; ?></title>

```

Please excuse any profanities I may have committed in the use of php, I am no coder. Any ideas are most welcome.

# Answer
I think I have found a way, albeit it might not be a very orthodox one, but just in case anybody else is facing a similar situation, here it is:

In your theme's html.tpl.ph, edit the title tag into something like this:

```
<title><?php print strip_tags($head_title); ?></title>

```

Then, in your theme's template.php, add this:

```
function YOUR-THEME-NAME_preprocess_html(&$vars) {
      global $theme_path;
      // Add conditional CSS for IE7 and below.
      drupal_add_css($theme_path . '/css/ie.css', array('group' => CSS_THEME, 'browsers' => array('IE' => 'lte IE 7', '!IE' => FALSE), 'preprocess' => FALSE));
      $vars['head_title'] = implode(' | ', array(drupal_get_title(), variable_get('site_name') . ' ' . variable_get('site_slogan')));
    }

```

In my case I ended up removing the `<br />` tags from the site name since they were showing all over, not just on the page title but also on emails, reports, etc. What I did instead was leave the first line as the site name and put the two following in the site slogan, with a `<br />` line break. Then I used some css and the previous theme function so that everything looks as it should.
> 0 votes

# Answer
Here is what I just found: There is no tags in the title, it's just a string. So the fix is quite simple.

in the html.tpl.php replace:

```
<title><?php print $head_title ?></title>

```

With this:

```
<title><?php
$break_tag = array("<br />");
$simple_space = array(" ");
$new_head_title = str_replace($break_tag, $simple_space, $head_title);
print $new_head_title;
?></title>

```

Hope it helps.
> 1 votes

---
Tags: theming
---


title: preprocessing markup

text:
# Question
Title: preprocessing markup
I have a file called template.php and inside the template file I have a preprocessor but I have two problems I don't know if the preprocessor is loading and if the code in the file is right.

The code inside the file is

function template\_preprocess\_field(&$vars) { kpr($vars); //Uncomment to output the $vars array. }

At this stage all I am trying to do is see if I can get the node to give me some feedback but I get nothing. The nodes I am testing this on does have three fields

# Answer
> 2 votes
Your template file should reside in the `sites/all/themes/mytheme/ directory`. Not in the `templates` subdirectory. Furthermore, your preprocess function should be named `mytheme_preprocess_field()`. Be sure to clear your cache.

You might want to perhaps also look at the Devel Themer module. It should provide information on the preprocess function being used and so on. I'm unsure how well it works with Drupal 7. But it's worth your time if it does.

# Answer
> 0 votes
Definitely, definitely get the Devel Theme module. It can be a great help in Drupal 7 when digging through the arrays on that page so you won't make any mistakes. It will give a simple list of the field names you can then call.

---
Tags: 7, theming
---


# Question
Title: View users contributed content in profile
I have users that have profiles using Profile2 module. I created a content type called Projects. A user can add a project, it has fields: title, description, and file. I would like to add a view to the users profile page that lists all of their Projects.

How can I connect the profile to the content author and use a contextual filter to get only that users content when viewing their profile?

Any help is greatly appreciated.

**Edit:** An example to clarify: If user1 is logged in and views his profile he will see a list of his projects.

If user1 views user2's profile he will see a list of user2's projects.

# Answer
> 1 votes
In the views UI

* Your view must be a view of nodes
* Then, add a relationship with the node's author (the relation is: Content: Author)
* Then, add an other relationship : select **user** and check **profile**. Then you can use the profile node in Contextual filters or Filter criteria. The technic part is that it is a relationship of relationship ;)

---
Tags: users, views
---


# Question
Title: Display Custom User Profile Fields in a Block on All of Their Published Pages
I have created a role, and have added additional fields to their profile using Profile 2. The fields are part of the location module, and are just basic contact info (address and phone number). They are also able to chose a name, which is used in the url for both their profile and content.

So, when a user creates their account, the url is site.com/their-name. When the user adds content the URL is site.com/their-name/content.

My goal is to display their contact info in a block on all pages they publish. I was able to do this for their profile page with the following view (see attached image). However, I would like this block to appear on all pieces of content that they author.

# Answer
> 0 votes
You should take a look at the Context module.

> Context allows you to manage contextual conditions and reactions for different portions of your site. You can think of each context as representing a "section" of your site. For each context, you can choose the conditions that trigger this context to be active and choose different aspects of Drupal that should react to this active context.
>
> Think of conditions as a set of rules that are checked during page load to see what context is active. Any reactions that are associated with active contexts are then fired.

Or a simpler solution might be to change your path from "their-name/content" to "user/their-name/content" and only show the block on "user/\*/content".

# Answer
> 0 votes
I think, you have not added correct contextual filter in the views. You should add `Content: Nid` contextual filters into your views, which will filter the current node, then add relationship `Content: Author` into your views which will add relationship between current node and its author.

# Answer
> 0 votes
I ended up being able to figure it.

1. Add Content:Author relationship.
2. Add (author) User: Profile relationship.
3. Add contextual filter (author) User: Uid
4. WHEN THE FILTER VALUE IS NOT AVAILABLE \> Provide default value \> Content ID from URL
5. Select "Also look for a node and use the node author"

---
Tags: views, users
---


# Question
Title: Run hook_init on every page except AJAX page executions
In my hook\_init functions I often check what the current page is before loading js or css files and in some cases control actions on module stored session info based on values in the session and the current path.

The module I'm currently working on stores extra information for orders users choose to use Checkout by Amazon to pay for. I haven't spent the time to figure out how to make CbA work as a payment method yet so right now I have to alter the Ubercart checkout form to include their widgets and then hijack the form submission to handle the API calls and build its own review and completion pages.

I store the necessary information in a module specific session variable. If the user reviews their order then goes back out to any other page, I keep the session going, only destroying the order so it can be rebuilt when they go to checkout again.

Now the issue I'm having is that I have two cases where the whole session needs to be reset.

1. If the user completes the order then moves to any page other than the order complete page
2. If the user goes to any page other than the checkout page from the review page

The second is usually handled because they'll likely hit the shopping cart page to checkout again if they go somewhere else (I'll be adding a tracker to force people to the cart page if they leave the review page sometime soon).

The issue I'm having is that I am doing this with code like the following:

```
function uc_cba_init(){
  if(strpos($_SERVER['REQUEST_URI'], '/amazon/') !== FALSE || (arg(0) == 'cart' && !arg(1))){
    if(isset($_SESSION['uc_cba']['order']['complete'])){
      // if on order complete page, remove unnecessary session items for the order, including cart products
      // otherwise delete the module session
    }
  }else if(isset($_SESSION['uc_cba']['order']['complete'])){
    // remove unnecessary session items, cart products, and module session
  }
}

```

The problem with this is that there are a lot of ajax calls flying around and they tend to trigger the init function which means that when the user reaches the order complete page, the ajax call just before that page clears out the session which destroys the order complete information (no order id given to the user for reference or any other instructions for managing their order).

My question would be, is there a simple way to ensure the init only executes its code if the page it is being executed from is not being called from an AJAX hit?

I can test for the shopping cart page, checkout pages and node pages but that won't be fool proof since it won't catch views, taxonomy and other module generated pages that do not have a source path of node/X.

# Answer
You can check if you're processing an AJAX request or not in your hook\_init() and skip your code if you need it.

```
function uc_cba_init(){
  if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
    // Is an AJAX request...
  }
  else {
    // Is not an AJAX request...
  }
}

```

Hope it helps!
> 1 votes

---
Tags: 7, ajax, hooks
---


title: returning #disabled in ajax callback

text:
# Question
Title: returning #disabled in ajax callback
This is taken from the examples module(http://drupal.org/project/examples). More specifically in the 'Generate textfields' ajax section. The form attempts to demonstrate an ajax call by presenting 2 checkboxes and generating a textfield based on which checkbox was clicked.

This is the ajax callback. We have a textfield with key 'first\_name'.

```
function ajax_example_autotextfields_callback($form, $form_state) {
  $a = $form['first_name'];
  $a['first_name']['#value'] = 'foobar';
  $a['first_name']['#disabled'] = TRUE;
 return $a;
}

```

The form rendered has value textfield with value 'foobar' as expected, but the textfield is not disabled? How come?

# Answer
You can accomplish that using ajax\_command\_invoke.

Here is an example using your own code:

```
function ajax_example_autotextfields_callback($form, $form_state) {
  // $a = $form['first_name'];
  // $a['first_name']['#value'] = 'foobar';
  // $a['first_name']['#disabled'] = TRUE;
  // return $a;

  return array(
    '#type' => 'ajax',
    '#commands' => array(
      // First we add the disable attribute into the html input tag.
      // which makes the the input field inaccessible.
      ajax_command_invoke('#WRAPPER_SELECTOR input', 'attr', array('disabled','disabled')),
      // Then we grey it out by adding the form-disabled CSS class.
      ajax_command_invoke('#WRAPPER_SELECTOR .form-item', 'addClass', array('form-disabled')),
    ),
  );
}

```

You can instead grey out using CSS attributes by calling ajax\_command\_css
> 6 votes

# Answer
I found another solution (if you don't want to use ajax commands).

```
function ajax_example_autotextfields_callback($form, $form_state) {
  $a = $form['first_name'];
  $a['first_name']['#value'] = 'foobar';
  $a['first_name']['#attributes']['disabled'] = 'disabled';
 return $a;
}

```
> 3 votes

---
Tags: forms, ajax
---


# Question
Title: Is there any way to know if it is the first visit of a Anonymous User?
I'd like to know if is there any way to know if it is the first visit of a Anonymous User?

If so, can I fire up a rule to redirect the visitor to other page.

# Answer
Why not set a cookie when folks visit, then you can check for whether they have the cookie. No cookie = first time visitor.
> 1 votes

# Answer
Yes there is a way;

In the Global $user check for `access` if its set to 0, the user is never logged in to the site.

```
function mymodule_user_login(&$edit, $account) {
  if ($account->access == 0) {
    // The user has never logged in before.
  }
}

```

**When i posted the answer the question was like this https://drupal.stackexchange.com/revisions/66946/1**
> 0 votes

# Answer
You can manage it by inserting cookies in the user's browser. After that check, it has cookies or not and do your further things. :)
> 0 votes

---
Tags: 7
---


# Question
Title: is there a place in the .info file to set a url to check for updates?
I created a custom theme to serve as the base for all my company's future drupal projects, that includes all of our base requirements. The sites will live on different servers, and each site will have it's own subtheme.

Drupal themes compare versions w/ the drupal projects server to check for updates.

I do not want to submit my company's theme to the drupal.org, as it has company specific features.

The goal is to be be able to update the theme in a "local" central repository, and have the various drupal sites check for version updates.

* is there a place in the .info file to set a url to check for updates?

The version number is pretty easy to set.

# Answer
> 2 votes
Yes, you can use `project status url`:

> Allows module maintainers to define a URL to check for updates to their module using the Update status module. No module released on drupal.org should define this parameter. URL should point to an XML feed that accepts requests in the form of http://my.domain.com/projects/{project}/{core}. In that example, project status url should be set to http://my.domain.com/projects.

See Writing module .info files (Drupal 7.x) for full details.

# Answer
> 2 votes
Have you read the docs?

> **project status url (Only used for custom modules not submitted to drupal.org)**
>
> Allows module maintainers to define a URL to check for updates to their module using the Update status module. No module released on drupal.org should define this parameter. URL should point to an XML feed that accepts requests in the form of http://my.domain.com/projects/{project}/{core}. In that example, project status url should be set to http://my.domain.com/projects.

---
Tags: 7, theming, version-control
---


title: Feeds import and related fields

text:
# Question
Title: Feeds import and related fields
I have a content type with an entity reference field (I suppose a term reference field would work as well). The target type is a taxonomy term. The taxonomy term has a name and ID field (among others). My feeds source that I would like to import has the taxonomy ids that I can import but I'd like to display the name not the id. My problem is I can't get the feeds map correctly unless I have a list of names in my feeds source, not ids.

Thanks Sharon

# Answer
I've figured it out. If I import the ID field as GUID when adding the taxomony terms, then I can select that as an option when I import into my content type :)
> 0 votes

---
Tags: taxonomy-terms, feeds, importing-exporting
---


# Question
Title: How to make an uploaded video visible on the node page in drupal 7
I have created a CCK named **sample** with a field name **VIDEOS** of type **file**. I have added a video of CCK type Sample. But it only showed a url after the node is saved.

Instead of displaying the file name how to make the video playable on the same page.

I installed jwplayer in libraries. I tried changing display type From **Generic** to **JWplayer**

Was trying since past 2 days using video module, VideoJS. But did not succeeded. Please help.

**UPDATE**

here is the result which i got when working with **Video** module

It is returning empty data with Play button on it. No video is displayed

**UPDATE**

A small progress,Tried **Flow Player** flv videos are able to play. but mp4 is not playing. It simply shows a black screen.

# Answer
> 1 votes
Have you tried using the Video module. You can create field type video insted of type file and then upload and render with the player you have configured.

# Answer
> 1 votes
Have you tried setting the display to "rendered File" in the display settings for the content type? If uploading as a file, might work for you.

---
Tags: 7, files, entities
---


# Question
Title: Why doesn't $row->path output its value?
I made a view with a relationship, showing:

* Title of the node
* Title of the referenced node
* Path of the referenced node

These values display as expected, but if I create a PHP field with the following code in the output, it only displays titles.

```
echo 'Title: '. $row->title.'<br />';
echo 'Title 1: '. $row->title_1.'<br />';
echo 'Path: '. $row->path.'<br />';

```

Why?

# Answer
It is a known issue with views\_php. You should be able to access the field information through the $data variable though. If you have Devel installed just run `dpm($data)` in place of your code above and see how to access the field information.

For what it is worth, it is generally considered bad practice to store php code in the database. I would suggest taking a look and seeing if there is any way you can accomplish what you are after with a template file override or some other means. If the only thing you are trying to accomplish is concatenation of those 3 fields with labels, you can do that with a regular views 'custom text' field and the tokens views provides.
> 2 votes

# Answer
I propose you should use either a tpl.php for your view or if you really want to insert code there, do something like:

```
$node = node_load($row->path); // im guessing it shows you the node id

echo 'Title: ' . $node->title;
...
echo 'Path: ' . drupal_get_path_alias('node/' . $node->nid);

```
> 1 votes

---
Tags: views
---


# Question
Title: Adding/Editing Node tab links through preprocess method
When editing/adding/removing tab links to a Node page (View/Edit) is there a quick way doing this with a `hook_preprocess` method and not via creating a module to alter them? Such as using `hook_process_page()` and then editing the `$title_prefix` array since this is where they are stored.

Example: I created a module for editing the contextual links, but what if I wanted to skip creating a module and directly inject my changes in the `template.php` via `hook()`.

```
function mymodule_contextual_links_view_alter(&$element, &$items) {
      $element['#links']['new-links'] = array(
        'title' => 'Add something new',
        'href' => url('/admin/config/add/something/new', array('absolute' => TRUE)),
      );
    }

```

# Answer
> 0 votes
All `_alter()` hooks can be implemented by themes as well as modules, so in that specific case you can just use

```
function mytheme_contextual_links_view_alter(&$element, &$items) {
  ...

```

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


title: Respond.js not working

text:
# Question
Title: Respond.js not working
Ive made sure my CSS files are being aggregated but respond.js isnt working.

Here is my site: http://smartpeopletalkfast.co.uk/cc/

Ive tried both the module (currently enabled) and also using the Zen themes built in option to use respond.js.

Ive added this for debugging, so when media queries are working the page is blank for desktop sized displays.

```
@media all and (min-width: 720px) {
  body {
    display: none;
  }

```

# Answer
I had 'Debug info' turned on in my coumpas.app. Disabling this made it work.
> 0 votes

---
Tags: theming
---


# Question
Title: How to solve these errors after running update.php?
I´ve updated my D6 site to Drupal 7. Even after running several times the update.php script, there are two errors still out there:

The following updates returned messages:

**system module**

Update #7061

> Failed: DatabaseSchemaObjectExistsException: Table system\_update\_7061 already exists. in DatabaseSchema-\>createTable() (line 657 of /home/liga/public\_html/includes/database/schema.inc).

**votingapi module**

Update #7201

> Failed: DatabaseSchemaObjectDoesNotExistException: Cannot change the definition of field votingapi\_vote.content\_type: field doesn't exist. in DatabaseSchema\_mysql-\>changeField() (line 454 of /home/liga/public\_html/includes/database/mysql/schema.inc).

Note: I have Voting API module installed in D6, but I haven´t upgraded it yet.

This is what I´ve done: I´ve deactivated the module in D6, I´ve upgraded everything, and I haven´t updated the module nor try to use it, yet. Maybe the second error will go away when I do upgrade Voting Api to d7. but how about the first error?

Any thoughts will be greatly appreciated. Thanks!

**UPDATE: I´ve updated my site to the latest D7 version (7.22 - 2013-Apr-03), and Votingapi module to it´s latest stable version (7.x-2.11 - 2013-Mar-22), and the issues remain exactly the same.**

# Answer
> 2 votes
My approach when this happens is to look at the table structure in a clean install of D6 to figure out what fields *should* be there, and compare that to the table structure in the current site. The issue is occurring because the update script has found something unexpected, so you need to figure out what that is.

In some cases, I've renamed the problematic table in the current database so I've got a copy, created a new table with the correct structure, and then copied the data from the backup table into the new table. I'm on a Mac, and Sequel Pro lets you do this via a handy GUI very easily.

In others, I've looked at the specific update script noted in the error to see what changes to the database it's trying to make - comparing that to the current version of the table can help identify why it's not allowing the update to occur.

This approach usually allows me to most database issues I encounter during upgrades.

---
Tags: 7, updating
---


title: Different ways to template a node

text:
# Question
Title: Different ways to template a node
I'm pretty new at Drupal (about two weeks), but I'm starting to see the huge amount of possibilities. It is a fine piece of engineering.

I've got a content type, called Products, which is shown in a panel pane and also has a page for itself. I want to output fields differently in both situations, but tweaking the node--product.tpl.php I've realized that I modify both the node in the content pane AND the page.

Is there any way that I can template the two of them in different ways?

Thanks, Hector

# Answer
> 0 votes
Hector,

You are probably best off reading about View modes: http://pingv.com/blog/custom-drupal-7-view-modes-different-ways-see-your-content

I would create a new view mode for your in-content-pane display, then theme it separately in it's own template file.

# Answer
> 0 votes
I have been working on Drupal for about 2 years and I have found these two modules to be absolutely the best tools to template a node:

Display Suite: https://drupal.org/project/ds Panelizer: https://drupal.org/project/panelizer

---
Tags: nodes, panels
---


# Question
Title: Display only banners for a specific month
I need to create a View that will display a banner **for a specific month (regardless of the year).**

I create a field for that called, DisplayMonth, which holds an integer (so September is 9).

I would like for that banner image to change automatically for 2014. **Any september month, no matter what year**, it will display the record with DisplayMonth = 9.

# Answer
> 1 votes
Create a contextual filter against the field that holds the month number. Provide a default value of PHP code:

```
return date('n');

```

Now only those nodes will display in September that have 9 as the month number.

---
Tags: views
---


# Question
Title: Alter date field granularity on exposed filter mid-request
I have an exposed filter on a date value that has it's granularity set to month, so it shows possible year and month values in the form. If I select just a year, no results are returned, even though I know there are posts that should be retrieved based on the year. If I then specify a month, all posts from that month and year are returned.

I need to be able to return results from the entire year when just year is selected. I'm thinking there might be a way to alter the granularity somehow during the request based on whether or not the month was specified? Any thoughts?

# Answer
> 1 votes
Working solution thus far:

```
/**
 * Impliments hook_form_views_exposed_form_alter
 *
 * Used to change exposed date filter to year only, as this is not available in the views UI
 */
function bain_views_form_views_exposed_form_alter(&$form, $form_state)
{
    if( $form['#id'] == 'views-exposed-form-news-items-page')
    {
        // dpm($form_state['input']['date']['value']);
        if (isset($form_state['input']['date']['value'])
            && empty($form_state['input']['date']['value']['month']))
        {
            // Switch date formatter to year only
            $form['date']['value']['#date_format'] = 'Y';
            // Add extra validator to handle filter submit
            $form['#validate'][] = 'bain_views_views_exposed_form_validate';
        }
    }
}

/**
 * Custom validator for exposed date filter
 */
function bain_views_views_exposed_form_validate(&$form, &$form_state)
{
    if ($form['#id'] == 'views-exposed-form-news-items-page')
    {
        $handlers = &$form_state['view']->filter;
        $date_handler = $handlers['field_news_date_value'];
        // dpm($date_handler);
        if (!empty($date_handler->options['exposed'])
            && isset($form['date']['value']['#type'])
            && $form['date']['value']['#type'] == 'date_select'
            && $form['date']['value']['#date_format'] == 'Y')
        {
            $date_handler->options['granularity'] = 'year';
            $date_handler->format = 'Y';
        }
    }
}

```

---
Tags: views
---


# Question
Title: Cannot use feeds to import into data tables where the primary key is multiple
I am using Data Module to create tables in Drupal. Now, I need to import some data through CSVs, for this I want to use Feeds Module. My table consists of more than one primary key i.e. a group of fields together forms a primary key.

Is there any way to import the data for such a case using feeds? Coz my understanding is that feeds cannot import data if the primary keys are not restricted into a single column.

# Answer
> 0 votes
The simplest thing to do would be to use Feeds Tamper's Rewrite plugin to combine the unique fields in your source into one field and then map that to the GUID.

https://drupal.org/node/1539224 could use some help as well for supporting this properly.

---
Tags: 7, feeds
---


# Question
Title: Custom function doesn't get triggered by hook_cron()
I have set up some FeedImporters and I've linked some custom batch imports to these FeedImporters. But for some reason, the function isn't triggered when running the cron... I'm wondering why. Anyone who can help me out on this one?

I've linked some custom functions to be triggered after the import:

```
/*
 *  Initialize hook_feeds_after_import()
 */
function my_module_feeds_after_import(FeedsSource $source) {
    _my_custom_function();
}

function _my_custom_function() {
    // Define fields
    $fields  = array('field1', 'field2', 'field3');

    // Trigger Batch for import
    batch_set(_start_my_batch('myfile', 'mytable', $fields));
}

```

And then my custom batch import:

```
function _start_my_batch($file, $table, $fields) {
    $batch = array(
      'operations'        => array(
        array('_import_csv_to_database_batch', array($file, $table, $fields)),
      ),
      'finished'          => '_import_csv_to_database_finish',
      'title'             => t("Import data in the $table-table"),
      'init_message'      => t("Feed is starting ($table)."),
      'progress_message'  => t('Processed @current out of @total.'),
      'error_message'     => t('Feed has encountered an error.'),
      'file'              => drupal_get_path('module', 'batch_example') . '/batch_example.inc',
    );

    batch_set($batch);
}

```

the `_import_csv_to_database_batch` is a custom batch import by the book. But for some reason, when I run following cron function, the `_my_custom_function()` isn't even triggered...

```
function my_module_cron() {
    _my_custom_function();
    watchdog('my_module', 'feed cron');
}

```

So why is that and how can I configure my cron to trigger this?

# Answer
Can you change:

```
function _my_custom_function() {
    // Define fields
    $fields  = array('field1', 'field2', 'field3');
    // Trigger Batch for import
    batch_set(_start_my_batch('myfile', 'mytable', $fields));
}

```

Into

```
function _my_custom_function() {
    // Define fields
    $fields  = array('field1', 'field2', 'field3');
    $function = '_start_my_batch';
    $batch = $function('myfile', 'mytable', $fields);
    // Trigger Batch for import
    batch_set($batch);
}

```

I think you should check every functions separately (hook\_cron, batch function..) and make sure they work. After that put on the same place and play. The Example Module also is the very good place for doing this kind of stuff.
> 1 votes

# Answer
You cannot perform batch jobs from cron. The Batch API requires user interaction to work.

As mentioned above, the Queue API is what you want to use for cron jobs.
> 0 votes

---
Tags: 7, feeds, cron
---


# Question
Title: Categorize Feeds with taxonomy terms automatically
I want to fetch the content from various RSS sources into my site to display them in a section. I have installed the Feeds module and created the feed to fetch from, along with the Content Type that will host the fetched news, but I'd like to categorize them in order to display then in different groups using Views (i.e.: 'news', 'technology', 'sports', etc.).

Is there any way to tell the Feeds module to add a value to the generated node's "Category" field (whether this is a taxonomy term or text field)?

# Answer
> 0 votes
If you add a term reference field to the feed node, you can map the value to the feed item node (inheriting values). The term can then be added when creating the feed node.

---
Tags: 7, feeds
---


title: <img> tag is not being parsed

text:
# Question
Title: <img> tag is not being parsed
This is the RSS I want to import. I want to write mapping to fetch the `<img>` tag within the `<description>` tag. When I import I get this.

```
 xpathparser:3 :
   <description><img
   src="http://www.moneycontrol.com/news_image_files/2013/a/acquisitions_yahoo_tumblr.jpg"
   alt="Tumblr had $16.6 mn in cash when Yahoo acquired it" title="Tumblr had $16.6 mn in
   cash when Yahoo acquired it" border="0" width="75" height="75" align=" left"
   hspace="5"/> The deal for Tumblr was the largest since Yahoo Chief Executive Marissa
   Mayer took the role in July with a focus on reversing a long decline in Yahoo's
   business and web traffic. The deal also made Tumblr founder and CEO David Karp, 27, a
   multimillionaire.</description>

```

What should be the xpath to get the `<img>` source?

I've tried Feeds Tamper to convert `<` to `<` and `>` to `>`and the following xpaths, but nothing works.

```
   //img/@src
   description[1]
   description/img
   description/img/@src

```

I am using Drupal 7.

# Answer
> 1 votes
This cannot be done the way you are trying. HTML embedded in XML is no different than regular text in XML. XPath has no way to look inside the HTML to query it.

There is some work being done, essentially adding another parsing step, https://drupal.org/node/1459870.

---
Tags: feeds
---


# Question
Title: How can I re-write feeds xpathparser data?
I have a feed content type with an author(s) field. Some of the nodes have several authors, so I am able to explode the data into an array with feeds tamper. However, I'd also like to re-write the author entries from LAST\_NAME, FIRST\_NAME to FIRST\_NAME LAST\_NAME. Before I dive into writing a plugin, I was wondering if there were another option for this, it seems like a common use case.

# Answer
You can use the REGEX find/replace plugin in Feeds Tamper to do it.

Find: `([^,]+),\s*([^,]+)`

Replace: `$2 $1`

Note: The above regex is more-or-less a guess and assumes that there are no commas in the FIRST\_NAME or LAST\_NAME.
> 1 votes

---
Tags: feeds
---


# Question
Title: Using oauth_common in a module to authenticate with a web service?
I'm wanting to use my Drupal 7 site to communicate with an external API that must be authenticated via 3-legged OAuth.

It seems there's a lot of documentation around about using Drupal as the OAuth provider (Via the OAuth project), but very little about using its API to do things like authenticate a Drupal site with an external web service. There's an old complete tutorial, but this doesn't list any of the functions that oauth\_common provides, nor even really any code with how to build an OAuth session with the module.

Any help? Moreover, is there a "Drupal Way" of creating OAuth sessions?

(If it helps, I'm doing stuff with Magento and using the examples here as a base.)

# Answer
Have you ever try to use OAuth Connector. It allows us to create the comsumer/application/connection to Twitter, Facebook... or another Drupal website. For my own purpose. I used that for fetch the data from Drupal 6 Services 3 by using this module in Drupal 7 and some extra code and it worked fine.
> 3 votes

---
Tags: 8, authentication-authorization
---


# Question
Title: What is exactly access arguments used for in hook_menu?
I have read the link : hook\_menu

Snippet from the page

> **"access callback"**: A function returning TRUE if the user has access rights to this menu item, and FALSE if not. It can also be a boolean constant instead of a function, and you can also use numeric values (will be cast to boolean). Defaults to user\_access() unless a value is inherited from the parent menu item; only MENU\_DEFAULT\_LOCAL\_TASK items can inherit access callbacks. To use the user\_access() default callback, you must specify the permission to check as 'access arguments' (see below).
> **"access arguments":** An array of arguments to pass to the access callback function, with path component substitution as described above. If the access callback is inherited (see above), the access arguments will be inherited with it, unless overridden in the child menu item.

But Still unclear about what access arguments are actually used for ? Are the access arguments the permissions ?

# Answer
Access arguments is the key for an array which contains the user permission. This means that current user must have this permission to access this page.

We can use already defined user permision or can create new permission for our menu item.

If you go to permission page (Administer \>\> User Management \>\> Permissions), you can see the list of string you might use for access arguments.

If you want to create new permission for your menu item, you can implement `hook_permission` in your module.
> 2 votes

---
Tags: 7, routes
---


# Question
Title: user_login_block doesn't display message
I have created an installation profile. On one page i have added block using `user_login_block` form.

Now on the page there are other blocks also present.

Now when i submit the form without username and password, it should show me the form error, but it shows this message on next page reload.

I have checked `$message` variable is printed on the page also.

When i write any wrong password and try to login it will not show wrong username password message at that time, but when i reload the page second time at that time message will appear.

Has anyone faced such kind of situation. ?

Thanks in advance..

# Answer
I successfully managed and fix it. The code i was using to display the login block was as below

```
print drupal_render(drupal_get_form('user_login_block'));

```

This block used to generate the login block for the login functionality.

Now i tried to render the messages using theme\_status\_messages() function.

To fix the issue i created a function in my **template.php** file named **THEMENAME\_get\_login\_block()**.

In this function i added the `theme_status_messages()` function for the displaying the messages. So my function looked like given below.

```
function THEMENAME_get_login_block() {
    $form = drupal_render(drupal_get_form('user_login_block'));
    $messages = theme_status_messages();
    return $form.$messages;
}

```

And to render the block i used `print THEMENAME_get_login_block();`

This solved my problem. But still i am curious to know the root cause of such kind of events. Any suggestions are welcomed....
> 1 votes

---
Tags: forms, users
---


# Question
Title: How to avoid user to vote up/down after selecting best answer?
I am using answers, best answer and vote up/down module. But, i am not getting how can this be done? Any suggestion.....

# Answer
You need to read `vud.api.php` from Vote Up/Down module, and create own module using it.

Implement `function hook_vud_access($perm, $entity_type, $entity_id, $value, $tag, $account)`. Make it return `NULL` if best answer was not selected, and `FALSE` if it was.
> 1 votes

---
Tags: rating
---


title: White page after enabling modules

text:
# Question
Title: White page after enabling modules
I installed a pure Drupal on Windows/IIS6 share host, and uploaded several modules in (sites/all/modules). When I want to enable some module together, my administrative pages become white, but front page and other pages work normally.

# Answer
> 11 votes
Take a look at The White Screen of Death (Completely Blank Page) to learn more about the WSOD and how to troubleshoot it.

# Answer
> 3 votes
I guess your `display_errors` in php.ini is Off, enable it and you'll see your errors instead of white screen

# Answer
> 1 votes
Check if there is any space in the top of module file before `<?php`.

# Answer
> 0 votes
It's definitely not the best idea to work with Drupal on IIS in first place, however for situation with white screen you've described - I'd say it looks like it's not enough resources (RAM) dedicated to PHP / Drupal.

Solution for this either to increase RAM available for PHP / Drupal or, as option, enable modules via Drush, not admin interface. Thing is that Drush not working *that well* on Win / IIS platform.

Try checking the normal windows error log if IIS or PHP throw an error.

---
Tags: 6, wsod
---


title: Access $user object on comments

text:
# Question
Title: Access $user object on comments
I use the following snippet in template.php to access user profile fields on comment.tpl.php. `$persianName` works fine when the user is administrator, and returns nothing for the anonymous users. Actually, when I use `dsm($variables)` in anonymous viewing, I see that all UIDs are set to 0.

```
function apblog_preprocess_comment(&$variables) {
  $user = $variables['user'];
  $user = user_load($user->uid);
  $persianName = field_get_items('user', $user, 'field_user_pname');
  if ($persianName) {
    $variables['persianName'] = $persianName[0]['safe_value'];
  }
  else {
    $variables['persianName'] ='';
  }

  // …
}

```

# Answer
> 1 votes
For Drupal, anonymous users are all associated with the user account having ID equal to 0. It is a particular account, since it doesn't have a user profile; if you try to access it, you get an Access Denied error. (I took the screenshot as user #1; seeing that account is not a matter of user permissions.)

As consequence, the anonymous user account doesn't have any field attached to it, since you cannot edit it. That is understandable, as that account is referring to more than one user.

As side note, the `$user` variable you are accessing is referred to the user who is currently logged-in. If you want to get the user account for the user who wrote the comment, you should use the following code.

```
$account = user_load($comment->uid);

```

# Answer
> 1 votes
In drupal by default anonymous users have **UID=0** , and you just need if **$user-\>uid==0** set your variable to what you want , some string like "mehman" ,

because of doing little changes in your code I use inverse checking of uid value ( the are as the same ,

```
if ( $user->uid ==0 )  $variables['persianName'] ='mehman';

```

or

```
if ( $user->uid !=0 ) ...... else  $variables['persianName'] ='mehman';

```

)

```
function apblog_preprocess_comment(&$variables) {
  $user = $variables['user'];
  $user = user_load($user->uid);
  $persianName = field_get_items('user', $user, 'field_user_pname');
  if ($user->uid !=0) {
    $variables['persianName'] = $persianName[0]['safe_value'];
  }
  else {
    $variables['persianName'] ='';
  }

  // …
}

```

**I hope this work to you**

be win ;)

# Answer
> 0 votes
anonymous users with uid = 0 is default behaviour.

Regards

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