# Question
Title: I install ultimate cron and I saw that errors
I have all this error but when i am running cron without cron ultimate all run perfect but with cron ultimate i got that errors... Could anyone help i really need help here:

```
    exception 'PDOException' with message 'SQLSTATE[42000]: Syntax error
    or access violation: 1064 You have an error in your SQL syntax; check
    the manual that corresponds to your MySQL server version for the right
    syntax to use near '))' at line 1' in
    /var/www/html/drupal7.36/includes/database/database.inc:2171
    Stack trace:
    #0 /var/www/html/drupal7.36/includes/database/database.inc(2171): PDOStatement->execute(Array)
    #1 /var/www/html/drupal7.36/includes/database/database.inc(683): DatabaseStatementBase->execute(Array, Array)
    #2 /var/www/html/drupal7.36/includes/database/query.inc(858): DatabaseConnection->query('DELETE FROM {er...', Array, Array)
    #3 /var/www/html/drupal7.36/sites/all/modules/bla/includes/bla.functions.inc(245): DeleteQuery->execute()
    #4 /var/www/html/drupal7.36/sites/all/modules/bla/bla.module(56): bla_clean()
    #5 [internal function]:bla_cron()
    #6 /var/www/html/drupal7.36/sites/all/modules/ultimate_cron/ultimate_cron.module(941): call_user_func('bla_...')
    #7 [internal function]: _ultimate_cron_run_hook('bla_...', Array)
    #8 /var/www/html/drupal7.36/sites/all/modules/background_process/background_process.module(574): call_user_func_array('_ultimate_cron_...', Array)
    #9 /var/www/html/drupal7.36/sites/all/modules/background_process/background_proces
    s.module(503): background_process_service_execute('uc:error_log_ji...', false)
    #10 [internal function]: background_process_service_start('uc%3Aerror_log_...')
    #11 /var/www/html/drupal7.36/includes/menu.inc(519): call_user_func_array('background_proc...', Array)
    #12 /var/www/html/drupal7.36/index.php(21): menu_execute_active_handler()
    #13 {main}

function blabla_clean() {
  $number = variable_get('blabla_number_select');
  // Keeps values equal to the number that user had selected.
  $query = db_select('blabla', 'j')
    ->fields('j')
    ->range(0, $number)
    ->orderBy('j.timestamp', 'DESC');
  $ids = $query->execute()->fetchCol();

  // Deletes all the other values.
  db_delete('blabla')
    ->condition('wid', $ids, 'NOT IN')
    ->execute();
}

```

# Answer
> 4 votes
The issue isn't Ultimate cron, per se. It's your custom `bla` module; it's running some function called `bla_clean()` that's building a Delete SQL query with broken syntax. When executed, it's producing the error.

You're using the NOT IN operator incorrectly. Here's a post that demonstrates a NOT IN within a query.

---
Tags: 7, cron
---


# Question
Title: How to add a custom field to personal campaign page - Civicrm
I'm using Drupal 7 and Civicrm 4.4.1 and I enabled the Personal Campaign Pages so individuals can create campaigns. It comes with the standard default fields such as Title, Goal Amount, Welcome, and Your Message. I would like to add another field to that form which I can then access through views to display in a table.

The field I'd like to add is called sponsor, so I could then show the sponsor when listing a view of all Personal Campaign pages. I've tried creating a custom field dataset and applying it to the Contribution type that I'm using, but I didn't have any success.

Any ideas on how to create a custom field for these pages?

# Answer
At this time, you cannot currently add custom data to Personal Campaign Pages (see the list at example.org/civicrm/admin/custom/group?action=add&reset=1). If you wanted to do that, your best bet would be to write the code (or pay someone to write the code) that does this, and get this contributed back into CiviCRM.
> 5 votes

# Answer
https://drupal.org/node/2234823

> **Using CiviCRM Custom Data Profiles**
>
> If your Drupal website is integrated with CiviCRM, you have an opportunity to bring much more personalized content into the Drupal user profile page through CiviCRM's Contact Record Fields. The most straight forward way to bring CiviCRM contact record data to the Drupal user profile page is by configuring the appropriate CiviCRM Custom Data Profiles to be visible in the Drupal user profile page. This can be done by being logged in with permissions to administer CiviCRM, navigating to CiviCRM -\> Administer -\> Custom Data and Screens -\> Profiles. Edit the Profile you would like to expose in the user profile page and adjust the setting for it to be used for: View/Edit Drupal User Account. You can also use these settings to remove CiviCRM content from the Drupal user profile page by un-setting it to be used for the Drupal User Account.
> 1 votes

# Answer
Here's a patch to add custom field capability for PCP pages....

This diff is against CiviCRM 4.5.0

Doesn't output the custom fields on the template, but you can figure that part out :)

This will allow you to add custom field groups to the PCPs, and save values to them on PCP add/edit pages....

```
diff -r original/civicrm/CRM/Core/BAO/CustomGroup.php new/civicrm/CRM/Core/BAO/CustomGroup.php
1102a1103,1104
>       case 'Pcp':
>         $tableName = 'civicrm_pcp';
1168a1171
>       case 'Pcp':
1521a1525
>
1698a1703,1704
>       case 'Pcp':
>         return 'civicrm_pcp';
1721a1728
>
diff -r original/civicrm/CRM/Core/SelectValues.php new/civicrm/CRM/Core/SelectValues.php
179a180
>       'Pcp' => ts('Personal Campaign Pages'),
diff -r original/civicrm/CRM/Custom/Form/CustomData.php new/civicrm/CRM/Custom/Form/CustomData.php
54c54
<   ) {
---
>   ) {
145c145
<     }
---
>     }
diff -r original/civicrm/CRM/PCP/BAO/PCP.php new/civicrm/CRM/PCP/BAO/PCP.php
85c85,92
<
---
>     //start custom field code addition
>     //store custom data
>     if (!empty($params['custom']) &&
>       is_array($params['custom'])
>     ) {
>       CRM_Core_BAO_CustomValueTable::store($params['custom'], 'civicrm_pcp', $dao->id);
>     }
>     //end custom field code addition
diff -r original/civicrm/CRM/PCP/Form/Campaign.php new/civicrm/CRM/PCP/Form/Campaign.php
63a64,87
>
>     //start custom field code additions
>     //check for custom data type.
>     $this->_cdType = 'Pcp';
>     $this->assign('cdType', FALSE);
>     if ($this->_cdType) {
>       $this->assign('cdType', TRUE);
>       $this->set('type', 'Pcp');
>       $this->set('entityID', $this->_pageId);
>       $this->set('cgcount', 1);
>       CRM_Custom_Form_CustomData::preProcess($this);
>     }
>     //end custom field code additions
>
>         // when custom data is included in form.
>     if (!empty($_POST['hidden_custom'])) {
>       $this->set('type', 'Pcp');
>       $this->set('entityID', $this->_pageId);
>       $this->set('cgcount', 1);
>       CRM_Custom_Form_CustomData::preProcess($this);
>       CRM_Custom_Form_CustomData::buildQuickForm($this);
>       CRM_Custom_Form_CustomData::setDefaultValues($this);
>     }
>
70c94,99
<
---
>     //load only custom data defaults.
>
>     if ($this->_cdType) {
>      $defaults = CRM_Custom_Form_CustomData::setDefaultValues($this);
>     }
>
93c122
<
---
>
103a133,140
>     $this->assign('customDataType', 'Pcp');
>     $this->assign('entityID', $this->_pageId);
>
>     if ($this->_cdType) {
>       CRM_Custom_Form_CustomData::buildQuickForm($this);
>     }
>     //lets assign custom data type and subtype.
>
229c266,274
<
---
>
>        //process custom data.
>     $customFields = CRM_Core_BAO_CustomField::getFields('Pcp', FALSE, FALSE);
>     $params['custom'] = CRM_Core_BAO_CustomField::postProcess($params,
>       $customFields,
>       $this->_pageId,
>       'Pcp'
>     );
>
232d276
<
Only in new/civicrm: groupcountsearch.txt
diff -r original/civicrm/templates/CRM/PCP/Form/Campaign.tpl new/civicrm/templates/CRM/PCP/Form/Campaign.tpl
97a98,120
>
> {* load the custom data *}
> {if $cdType}
>     {include file="CRM/Custom/Form/CustomData.tpl"}
> {else}
>
> {* include custom data js *}
> {include file="CRM/common/customData.tpl"}
>
> {literal}
> <script type="text/javascript">
>   CRM.$(function($) {
>     {/literal}{if $customDataSubType}
>       CRM.buildCustomData( '{$customDataType}', {$customDataSubType} );
>     {else}
>       CRM.buildCustomData( '{$customDataType}' );
>     {/if}
>     {literal}
>   });
> </script>
> {/literal}
>
> {/if} {* load custom data *}
99a123
>

```
> 0 votes

---
Tags: 7, views, civicrm
---


title: Accessing Drupal array values

text:
# Question
Title: Accessing Drupal array values
I'm noobing my way through countless websites trying to find an answer to accessing a value in a Commerce field array.

I somehow managed to throw together the following code to retrieve a value for a workflow rule I'm writing:

```
$product_id = $current_line_item->commerce_product;

```

The result is: `array(1) { ["und"]=> array(1) { [0]=> array(1) { ["product_id"]=> string(2) "14" } } }`

I can't figure out how to get any deeper into the array than that. I need to return the product\_id value in this array.

Can anyone guide me on the best way to do this?

# Answer
> 1 votes
Devel is super useful to help you figure out these type of things.

Once enabled, you can write `dpm($product_id)` and it will print out a nice organized structure of the array. From there, you can click on any item and it will show you how you can access the item like `['und'][0]['product_id']` in your example.

Depending on what exactly you're trying to do, there may be different ways to get the info you need.

---
Tags: entities, commerce
---


# Question
Title: Table creation in install module returns error
I am trying to create a table using a custom module in the install file:

```
function leave_tracker_schema() {
  $schema = array();
  $schema['leave_balance'] = array(
    'description' => t('The base table for employee leave balance.'),
    'fields' => array(
      'lid' => array(
        'description' => 'The primary identifier for a row.',
        'type' => 'serial',
        'unsigned' => TRUE,
        'not null' => TRUE),
      'eid' => array(
        'description' => 'The tocken got from employee data.',
        'type' => 'varchar',
        'length' => 255,
        'not null' => TRUE,
        'default' => 0),
      'casual' => array(
        'description' => 'The casual leave balanace of employee.',
        'type' => 'int',
        'not null' => TRUE,),
      'sick' => array(
        'description' => 'The sick leave balanace of employee.',
        'type' => 'int',
        'not null' => TRUE,),
      ),
    'indexes' => array(
      'node_changed'        => array('changed'),
      'node_created'        => array('created'),
      ),
    'primary key' => array('lid'),
    );
  return $schema;
}'

```

but this returns an error when I install the module

> 'PDOException: SQLSTATE\[42000\]: Syntax error or access violation: 1072 Key column 'changed' doesn't exist in table: CREATE TABLE {leave\_balance} ( `lid` INT unsigned NOT NULL auto\_increment COMMENT 'The primary identifier for a row.', `eid` VARCHAR(255) NOT NULL DEFAULT 0 COMMENT 'The tocken got from employee data.', `casual` INT NOT NULL COMMENT 'The casual leave balanace of employee.', `sick` INT NOT NULL COMMENT 'The sick leave balanace of employee.', PRIMARY KEY (`lid`), INDEX `node_changed` (`changed`), INDEX `node_created` (`created`) ) ENGINE = InnoDB DEFAULT CHARACTER SET utf8 COMMENT 'The base table for employee leave balance.'; Array ( ) in db\_create\_table() (line 2720 of /var/www/html/cybpedia/includes/database/database.inc).'

# Answer
> 1 votes
In your `indexes` element you're specifying 2 columns, `changed` & `created`, that don't exist. You need to have these columns added to your `fields` element or remove the indexes.

---
Tags: hooks
---


# Question
Title: Two Blocks for sort filter Views -- Drupal 7
I have a view in Drupal 7 with results including a field of date and another with price, I need to sort the results by means of these two fields when I click on the appropriate link (not button or dropbox radio), but the trick is I need add the different **sort filter** into two separate blocks, because each block will have a different per user context.

Besides the filters should be links. Any idea how to work this?

# Answer
I dun really get what you mean. I presume you are trying let admin or user to able to do sorting.

I have two ideas

Under format change from unformatted list to table. At this case you are able to do sorting by click table header.

Another one is under sort criteria, add any content you want to sort and select expose.

If I wrong, can show me any example??
> 0 votes

---
Tags: 7, views
---


title: Related Products block

text:
# Question
Title: Related Products block
Hai am working on an ecommerce site using ubercart module. I have created a view for listing products in a particular category. each product direct to a page which consists of its details and add to cart buton. In the bottom of this page i have a related products block which list all the other products in this category.but in this block it repeats the main product once more. how can i remove it? can anyone help me to solve this issue?

# Answer
1. You need to add a Contextual Filter field w/c would be the **Content: Nid**
2. In contextual filter Content: Nid configuration, under **WHEN THE FILTER VALUE IS NOT IN THE URL**, use *Content ID from URL* for the **Type**.
3. In contextual filter Content: Nid configuration, scroll down and toggle open the **More** fieldset and check **Exclude**
> 0 votes

---
Tags: ubercart
---


# Question
Title: Change content color based on Date Range
I am building a website using Drupal 7, Views, Rules, Ctools, Panels, etc.

I need to change the content color based on the date. The idea is that each quarter's reports have a different color to make them easier to sort over the life of the student.

Any ideas on how to achieve this?

# Answer
In your theme, you can implement `hook_preprocess_page(&$variables)` were you can retrieve the currently displayed content (if any) as `$variables['node']`. From there, you can retrieve the value of a date field using `field_get_items()` and use that value to assign classes to the `<body>` of the page in `$variables['classes_array']`.

```
function THEME_preprocess_page(&$variables) {
  if (($node = $variables['node']) && ($node->type == 'report')) {
    if ($items = field_get_items('node', $node, 'field_report_date')) {
      $variables['classes_array'][] = drupal_clean_css_identifier('report-month-' . format_date($items[0], 'custom', 'F'));
    }
  }
}

```
> 0 votes

# Answer
Maybe consider the ThemeKey module? From its project page (bold markup added here):

> ... allows you to define simple or sophisticated theme-switching rules which allow automatic selection of a theme depending on current path, taxonomy terms, language, node-type, and many, many other properties.
>
> In combination with Drupal's theme inheritance you can easily achieve features like:
>
> * a **date/time-selected** Christmas theme
> * ...

So by using like 1 theme variation for each quarter you could get the job done, no?
> 0 votes

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


title: User restrictions- field comparision

text:
# Question
Title: User restrictions- field comparision
In my site, I have various fields for user registration along with image captcha. Though I get fake registrations at least 3 per day. I found that "**username**" and "**address**" fields are **identical** by value in all those registrations. Is there any way to **deny access** to those registrations?.

# Answer
Use Botcha. This will effectively prevent bot submissions. Don't use short term adjustments for Drupal defaults unless you've used your site for long time.
> 0 votes

---
Tags: users
---


# Question
Title: How to configure a different main menu for each language on a multilingual site?
I have set up multilingual options on my site, and have a lot of pages in two languages.

I can't work out how to have a different main menu for the two languages. Under `Structure->Menu->Settings`, it says "Source for the Main links", and I'm adding all menu links to the "Main menu" there. However, this means I just get one big menu with all the items in both languages.

What I want is when the page is in English, the main menu is in English, and when in Chinese, the main menu is in Chinese. How to set that up?

# Answer
Make sure the **i18n Menu Translation** sub-module is enabled (it is one of the Internationalization sub-modules).

Edit the menu to be translated, by navigating to admin/structure/menu/manage/main-menu/edit (for the "main menu"). From there it should be possible to select the **translation mode** you want, e.g. *Translate and Localize*.

After doing so, when editing a menu link, there should be a new link **Translate** to actually translate the menu entry. Refer to the Multilingual Guide for (way) more details.

Miltilingual sites are really fun in D7 (way better then it was in D6, and D8 promises to become more easy to configure). Typical variations (with similar solutions) of this "menu" topic are:

* **translations of blocks**, which requires the Block Languages (i18n\_block) submodule to be enabled.
* **translations of taxonomies**, which requires the Taxonomy Translation (i18n\_taxonomy) submodule to be enabled.
> 1 votes

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


# Question
Title: Top 10 priorities in performance optimization of a complex Drupal site
I read a lot about many ways to improve drupal site performance optimization, but I did not find a clear indication of the top 10 most relevant modifiations for optimizing the performance of a complex site.

I currently am working to optimize a very complex site that has completely grown out of hand and needs serious modification because current page load speed is about 4 to 6 seconds for authenticated users. The website is mostly being used by authenticated users. The only access restriction is present through the Organic Groups module.

Current state:

* 90 node types
* 140 select boxes checked on the admin/modules page
* 63 Vocabularies
* 240 views (excluding the additional views displays)
* 30 rules,
* 50 rules components
* 130 node panel variants
* 10,000 lines of css (excluding the omega base theme and modules style sheets)

What is the most important to start with, in general?

# Answer
> 1 votes
I won't talk about APC and other Apache optimization tricks.

In in experience:

1. Enable caching for Views and reduce use of Views
2. Enable Javascript and CSS compression
3. Minimize the modules. Disable unused ones. In production I disable as UI's .. the following script will give you some help.
4. Most of bottleneck comes from Mysql. I suggest you optimize it and I found this post useful.

**Disable User Interface Modules**

When not developing you can safely disable Field UI, Rules UI, Views UI, dblog etc. Also I'm sure but we should also be able to disable CKEditor/FCKEditors.

This is what I use in a script:

```
drush dis --yes admin_menu advanced_help backup_migrate content_type_overview  dashboard diff environment_indicator field_ui help module_filter rules_ui search term_merge update views_bulk_operations views_ui vppr  field_ui  rules_admin devel site_audit  drupalgeddon l10n_client taxonomy_manager dblog

```

---
Tags: performance
---


# Question
Title: Display entityreference field in search-result.tpl
The entityreference field (field\_parent) shows up in node.tpl using `print render($content);`, but isn't displayed in search-result.tpl. My search-result.tpl looks like this right now:

```
<li class="<?php print $classes; ?>"<?php print $attributes; ?>>

  <?php print render($title_prefix); ?>

  <h3 class="title"<?php print $title_attributes; ?>>
    <a href="<?php print $url; ?>"><?php print $title; ?></a>
  </h3>

  <?php print render($title_suffix); ?>

    <div class="submitted">
    <div class="imported-text">Imported on <?php print $info_split['date']; ?>.</div>
    </div>

    <div class="hr"></div>

    <div class="content">
    <div class="comments-link"><a href="<?php print $url; ?>">Comments</a></div>
    <div class="other-content">

    <div class="field-name-field-download"><a href="<?php print $result['node']-> field_download[LANGUAGE_NONE][0]['url'] ?>">Download</a></div>
    <div class="field-name-field-lipsum"><span class="lipsum">Lipsum:</span> <?php print $result['node']-> field_lipsum[LANGUAGE_NONE][0]['value'] ?></div>

    </div>
    </div>

</li>

```

I tried using `<?php print $result['node']-> field_parent[LANGUAGE_NONE][0]['value'] ?>` but it gives me the error "Notice: Undefined index: value in include() (line 25 of ...\search-result.tpl.php)."

`<?php print $result['node']-> field_parent[LANGUAGE_NONE][0]['entity'] ?>` gives

Recoverable fatal error: Object of class stdClass could not be converted to string in include() (line 25 of ...\search-result.tpl.php).

`<?php print $result['node']-> field_parent[LANGUAGE_NONE][0]['entityreference'] ?>`

Notice: Undefined index: entityreference in include() (line 25 of ...\search-result.tpl.php).

# Answer
I solved this by using teaser view as my search result. My search-result.tpl file now looks like:

```
<li class="<?php print $classes; ?>"<?php print $attributes; ?>>

<?php $v = node_view($result['node'], 'teaser'); print render($v); ?>

</li>

```
> 0 votes

---
Tags: entities, search
---


# Question
Title: How to get the field values with EntityQuery?
I am working on a query filtering form that lists entities. I have various 'range' fields and I would like to display the min and max values. Is it possible to retrieve field values with EntityQuery?

For example I want to filter nodes whose NIDs are between 10 and 50 but I would also like to see which NID is the lowest and which is the highest so I can change my input accordingly.

Or better, imagine a commerce product price. I would like to see products whose price is between 10€ and 50€ but I would like to see what is the range that I can operate with(ie. from 0.99€ for the cheapest product, up to 150€ for the most expensive product).

I am thinking that with EQ this is possible only by having two queries - one for the min value and one for the max value, sort it by desired field, load a single entity and retrieve the value from the entity object. This solution is very ineffective(\< performance) and since I am already using EQ I don't want to move back to basic queries just for this since that would make EQ obsolete for me.

# Answer
> For example I want to filter nodes whose NIDs are between 10 and 50 but I would also like to see which NID is the lowest and which is the highest

```
$result = \Drupal::entityQueryAggregate('node')
  ->aggregate('nid', 'MIN', NULL, 'nid_min')
  ->aggregate('nid', 'MAX', NULL, 'nid_max')
  ->condition('nid', [10, 50], 'BETWEEN')
  ->execute();

```

`$result[0]['nid_min']` and `$result[0]['nid_max']`
> 2 votes

# Answer
No, it is not possible.

There is no API to get values of specific fields. Views also doesn't do that anymore, it always loads entities as well.
> 3 votes

---
Tags: entities, 8, database
---


# Question
Title: Flexslider with Link - using Flexslider Field Collection
I am using Flexslider with Flexslider Field Collection.

This is working.

But now I need to include Links for each slide. And only found help when using Views.

Is there a way to include links to each slide without Views?

# Answer
> 1 votes
Just found it:

my Slider-Field-Collection ("field\_slide") has:

```
[Label] -[Field Type] - [Widget]
Title- Text - Text field
Body - Long text - Text area
Image - Image - Media file selector
link - Link - Link

```

Display settings:

```
[Field] - [Format]
Image - Image Link Formater - Settings: Link image to: link (field_link)

```

in my content type I use that "field\_slide" (embedded) and on display settings: Flexslider

This makes it easy to create content and add unlimited images (as slides) without creating each slide as a node.

---
Tags: javascript
---


# Question
Title: How to implement a nomination process for nodes?
I want to implement a nomination process. Users should be able to

1. Nominate existing Nodes of type 'course'.
2. Nominate new content that should later be of type 'course'.

All nominations should be listed somewhere.

What's the best way to do this?

For **1.** I thought about using the Flag module and then just make a view where all nodes with nomination flag are listed.

For **2.** I'm not sure, maybe I use webforms and the admin has to transfer it into a node of type 'course'. But how do I get a list of new AND existing nominated content?

# Answer
> 0 votes
How about using modules Node\_convert, and Flag (which is obviously a must have for what you're looking for)? About Node convert (from it's project page):

> adds a menu tab "Convert" on the node view page, i.e. node/1/convert, which gives the ability to convert the node from its current node type to another node type. The module provides the means to transfer all the field values of the current node type into fields on the destination node type, or discard them.

I'm using Node\_convert already for long time, works great. It allows for implementing a lifecycle (or workflow?) to start from a node that is only just something like an idea (or suggestion, question, issue, abstract, etc). Those ideas that get the highest votings, are the ones that seem to make sense to handle with highest priority. Compare it to a 'Question' with a lot of votes, but with hardly any (or no) answers.

When the node's content evolves (read: the more effort/details added to it), I convert its content type to finished products like (eg) a recipe, a redbook (already from my Drupal 6 days a few years ago).

By combining it with some type of access module (related to either taxonomy or content type) I can make it more restrictive to give access to it. E.g. public to start from, then "authenticated", and in the end only for roles such as "subscribers", "students", etc.

Maybe you also want to consider Fivestar and/or Voting API (I have the impression that "Voting" is a kind of synomym of what you mean with "Nominate").

And of course: use Views as you are considering already. To continue my samples above: using some basics Views reports, you can easily massage it all in a todo list also.

---
Tags: nodes, forms, flags, rating
---


# Question
Title: DrupalTemporaryStreamWrapper::stream_open" call failed in file_unmanaged_save_data()
`DrupalTemporaryStreamWrapper::stream_open` call failed in `file_unmanaged_save_data()`

I do not identify the problem. Could anyone help me?

# Answer
You can solve this by setting up temporary path i.e.

**Goto :**

> Home » Administration » Configuration » Media and fix temporary directory.

or Goto to the path & add temp url :

```
config/media/file-system

```
> 1 votes

---
Tags: stream-wrappers
---


# Question
Title: Help with finding field reference to node title within webform select options view? field reference issue
so I'm trying to implement a similar "sample request" feature like the one in Drupal Steve's tutorial. Drupal 7 Sample Request.

The issue I'm having is that I'm not sure how the field reference is made to the node title within my view. Right now the select list is being generated and is available to my webform, but the list appears unpopulated. I'm provided with an empty select list widget, but no actual options to select

The issue is that the view itself is of a custom commerce content type "posters," with a relationship set on flag, such that I'm not sure what the field reference is to get the title field from my view. Steven mentions reference the node's owner, but I'm not sure what that means. Here is the code from Steve's implementation modified to meet my needs. I basically want to know how to pull the title field out of the view of flagged items, just no idea where to find what the reference to that would be...

```
    function webform_hook_webform_select_options_info() {
   $items = array();
   if (function_exists('webform_hook_user_flag_sample_requests')) {
     $items['webform_hook_user_flag_sample_requests'] = array(
      'title' => t("Sample Requests (User Flag list)"),
      'options callback' => 'webform_hook_user_flag_sample_requests',
     );
   }
   return $items;
 }
 function webform_hook_user_flag_sample_requests() {
   $view = views_get_view('webform_flag_views', TRUE);
   $view->set_display('webform_options');
   $view->execute();
// dpm($view);
   $options = array();

   if ($view->result) {
     $row_class = $view->style_options['row_class'];
     $attributes = $row_class ? " class='$row_class'" : '';
     foreach($view->result as $item) {
       $options[$item->nid] = '<a' . $attributes . '>' . render($item->field_field_img[0]['rendered']) . ' ' . $item->field_title . ' (' . $item->node_title . ')' . '</a>';
     }
     dpm($item);
   }
   else {
     $options[0] = t("Nothing");
   }
   dpm($options);
   return $options;
   }

```

Here is the result of my dpm statement on the $item variable

```
(Object) stdClass
    commerce_product_title (String, 9 characters ) The Rapid
    product_id (String, 3 characters ) 354
    field_data_field_image_commerce_product_entity_type (String, 16 characters )       commerce_product
    _field_data (Array, 1 element)
    field_field_image (Array, 1 element)
    field_field_img (Array, 1 element)

```

I've tried most of the obvious options, but I've been hitting a brick wall.

The DPM of the $options variable only returns the a tag

```
... (Array, 1 element)
(String, 11 characters ) <a> ()</a>

```

Again, many thanks in advance.

# Answer
OK, you're just accessing the wrong (non-existent) properties. You need

```
foreach($view->result as $item) {
   $options[$item->product_id] = '<a' . $attributes . '>' .
       render($item->field_field_img[0]['rendered']) .
       ' (' . $item->commerce_product_title . ')' . '</a>';
 }

```

I removed `$item->field_title` because I don't see it's equivalent in your `$items`. And without knowing what the `field_field_img` is it's impossible to tell if that will work for it as well.
> 1 votes

---
Tags: views, webforms, flags
---


title: db_query question

text:
# Question
Title: db_query question
I'm writing a custom module and trying to use the db\_query functions instead of just doing straight MySQL calls.

Here's my query.

```
$nid = $node->nid;
$result = db_query('SELECT * FROM {field_data_field_room_rates} WHERE field_room_rates_target_id = :nid', array(':nid' => $nid));
drupal_set_message('<pre>'. print_r($result, TRUE) .'</pre>');

```

...and here's what I get back.

```
DatabaseStatementBase Object
(
    [dbh] => DatabaseConnection_mysql Object
        (
            [needsCleanup:protected] =>
            [target:protected] => default
            [key:protected] => default
            [logger:protected] =>
            [transactionLayers:protected] => Array
                (
                    [drupal_transaction] => drupal_transaction
                )

            [driverClasses:protected] => Array
                (
                    [SelectQuery] => SelectQuery
                    [DatabaseTransaction] => DatabaseTransaction
                    [InsertQuery] => InsertQuery_mysql
                    [UpdateQuery] => UpdateQuery
                )

            [statementClass:protected] => DatabaseStatementBase
            [transactionSupport:protected] => 1
            [transactionalDDLSupport:protected] =>
            [temporaryNameIndex:protected] => 0
            [connectionOptions:protected] => Array
                (
                    [database] => my_db
                    [username] => user
                    [password] => pw
                    [host] => localhost
                    [port] =>
                    [driver] => mysql
                    [prefix] => Array
                        (
                            [default] =>
                        )

                )

            [schema:protected] =>
            [prefixes:protected] => Array
                (
                    [default] =>
                )

            [prefixSearch:protected] => Array
                (
                    [0] => {
                    [1] => }
                )

            [prefixReplace:protected] => Array
                (
                    [0] =>
                    [1] =>
                )

        )

    [queryString] => SELECT * FROM field_data_field_room_rates WHERE field_room_rates_target_id = :nid
)

```

if I were querying the SQL manually the query would be:

SELECT * FROM field\_data\_field\_room\_rates WHERE field\_room\_rates\_target\_id =2164

and it would yield back the proper row of items...which this doesn't seem to be giving. All it seems to be giving back is Drupal database info.

What am I doing wrong? :)

# Answer
You need to fecth the results from the `$result` object. See https://www.drupal.org/node/1251174 for reference.

For instance, you might do something like:

```
$row = $result->fetch();

```

Hope it helps,
> 1 votes

---
Tags: 7, database
---


title: Get list of canonical urls?

text:
# Question
Title: Get list of canonical urls?
I have a list of ~2500 pages that I need to get canonical urls for from an old D6 site. The site uses Path\_Redirect.

Using mysql queries I can get a list of nids for the pages I want, but I'm having trouble connecting the nids to the most current path alias. Little help?

# Answer
I'm running into this problem, though I'm not sure we're using Path Redirect. For me, Migrate is bringing in URLs that are non-canonical, and I need to override the query to get the URLs that D6 has decided are canonical.

In D6 the code that does this is drupal\_lookup\_path('alias', $path);

By examining this I determined that if you don't care about language, the bare query is (for node/121):

```
SELECT dst FROM url_alias WHERE src = 'node/121'  ORDER BY pid DESC;

```

The ORDER BY pid DESC is the key part here.
> 0 votes

---
Tags: 6, path-aliases
---


# Question
Title: Views - how to replace the pager with a slider
I have a view of events, and want to display 10 events at a time.

Instead of the clicking the pager, I want the view to cycle to the next 10 events automatically after a set number of seconds - the view will be displayed on a monitor without user interaction.

The views\_slideshow module only allows me to do this with every single item in the view. How would I best approach this - ideally with an existing module.

Please let me know if the question is not clear.

Any help appreciated!

# Answer
> 0 votes
Views Slideshow sounds like the ticket https://www.drupal.org/project/views\_slideshow. FlexSlider might do the same, but also responsively.

---
Tags: 7, javascript, views
---


# Question
Title: Views templates deleted when core updated
Yesterday, I posted a proposal for clarifying the procedure for updating core. But now I find that I messed up in doing my update and I'm not sure how to do it right the next time.

I have a set of Views templates under the Bartik theme. They are in the folder: `<Drupal root>\themes\bartik\templates\views` In the update procedure, this folder is deleted along with the rest of the old core.

I was able to easily restore the views folder from the backup, but I'd like to not have to do that in the future.

Generally, it seems like a bad idea to put custom content in a core folder, but it seems that Views needs the template folder to be under the theme it applies to.

Is there a way to put that views folder under the sites folder or somewhere else outside of the core structure so it won't get deleted when I do an update?

Thanks for your help.

# Answer
> 5 votes
Editing files in themes\bartik\templates\views is hacking core. One ought not to. You should create a subtheme of Bartik and make your changes there. Then an upgrade will not wipe out your changes.

Clear exceptions to the rule for editing core files are robots.txt, .htaccess and web.config.

# Answer
> 0 votes
There is actually quite some information available about updating – at least over at drupal.org.

Here is the page *'Update Drupal Core'* in the Community Documentation at drupal.org and here is a neighbouring page about *'Installing modules and themes'* that may clear some aspects of how and where to put modules and themes etc. But you probably came across these pages.

However – in short: first thing I learnt is to **always** put your custom themes, modules etc. in `sites/all/…` or `sites/default/…` since that's a folder that is not deleted – or at least should not be deleted while updating core.

\[EDIT\] Sometimes you may encounter problems finding the correct name for your tpl file – then drupal won't load it and you'll have the impression that *'it just does'nt worl'*. Views has astally a handy feature listing the suggested tpl names for a specific view – it's just a bit hidden: `Advanced > Theme: Information`.

For further info on naming these pages could also be useful: 'Views template files' and 'Drupal 7 Template (Theme Hook) Suggestions'.

ps: rule of thumb: **don't touch the core!** (That's why it's called *'core'* -- and this applies also to *'core modules'* )

---
Tags: views, updating
---


# Question
Title: Migration of multi-value pictures to user fields
I need to migrate from a WordPress site to a Drupal 7 site where users could upload their own images (like multiple user pictures). I have a CSV file with the User's ID and a serialized array containing the filenames of uploaded pictures (no, really).

Users have a multi-value image field 'field\_user\_pictures'.

After deserializing the array, drupal complains with the error "ltrim() expects parameter 1 to be string, array given". (Presumably because MigrateDestinationFile doesn't handle arrays very well.) Then I tried with just using the first image of the array, and that actually works. What doesn't work, however, is to get drupal to link this sole image to the 'field\_user\_pictures' user field.

I have been trying to get to something like this:

```
 class PictureMigration extends Migration
 {
    public function __construct ($arguments)
        {
        parent::__construct($arguments);

        $source = 'user_pictures.csv';

        $columns = array(
            1 => array('source_userid', ''),
            3 => array('source_serialized', ''),
        );

        $source_key = array('source_userid' => array('type' => 'int', 'not null' => TRUE),);

        $this->source = new MigrateSourceCSV($source, $columns);
        $this->destination = new MigrateDestinationFile('image', 'MigrateFileUri');
        $this->map = new MigrateSQLMap($this->machineName, $source_key, MigrateDestinationFile::getKeySchema());

        $this->addFieldMapping('source_dir')->defaultValue($this->remote_dir);
        $this->addFieldMapping('destination_dir')->defaultValue('public://');
        $this->addFieldMapping('value', 'source_serialized');
      }

  public function prepareRow($row) {
     // snipped
     $row->source_serialized = $this->deserializePhotos($row->source_serialized); // returns array of filenames
    }
}

public class UserMigration extends Migration {
  public class __construct ($arguments) {
    // snipped...
      $this->addFieldMapping('field_user_pictures')->sourceMigration('PictureMigration');
  }
}

```

The first problem is that MigrateDestinationFile doesn't seem to like multi-value values; the second problem is that even when I only use the first filename of the array, it still doesn't get linked to the 'field\_user\_pictures' field...

See also: Migration: Combine Profile2 and file migration -- almost exactly the same issue, but with no valid answer as well.

# Answer
Something is really odd about your code `$this->destination` is a `MigrateDestinationFile` yet `$this->map` is trying to track a `MigrateDestinationNode` .... I've never done anything that way.

I would do the following:

1. Import Users from Wordpress to Drupal.
2. Use your CSV file of legacy UIDs and picture files to run an `update` of the (newly) created Drupal users and insert the images as needed.

I'm doing this now as we speak on a `Document` content type of which there are 120k entries, but only 4k have movie files associated with them so I feel a node revision is a better use the time to import stuff.

This is an example from some work in progress and will not run as-is but it should be a concrete example:

```
class PrezDocumentMediaMigration extends PrezMigration {

  public function __construct($arguments) {
    parent::__construct($arguments);

    $document_fields = array(
      // ... fields ...
    );
    $this->description = 'Update created Documents with audio and video from legacy DB. There are only ~5k of entries.';

    $query = Database::getConnection('default', 'legacy_migration')
      ->select('papers', 'p')
      ->fields('p', $document_fields)
      ->condition('av', 0, '<>');
    // Additional pseudo fields to move data from legacy derived data to drupal.
    $query->addExpression('NULL', 'local_video');
    $query->addExpression('NULL', 'remote_video');
    $query->addExpression('NULL', 'local_audio');
    $query->addExpression('NULL', 'remote_audio');

    $options = array('track_changes' => 1);

    $count_query = Database::getConnection('default', 'legacy_migration')
      ->select('papers', 'p')
      ->condition('av', 0, '<>');
    $count_query->addExpression('COUNT(pid)', 'cnt');

    // We are updating existing content in Drupal.
    $this->systemOfRecord = Migration::DESTINATION;

    $this->source = new MigrateSourceSQL($query, $document_fields, $count_query, $options);
    $this->destination = new MigrateDestinationNode('documents');
    $this->map = new MigrateSQLMap($this->machineName,
                                   array(
                                     'pid' => array(
                                       'type'     => 'int',
                                       'unsigned' => FALSE,
                                       'not null' => TRUE,
                                       'description' => 'Unique content reference legacy document',
                                       'alias' => 'doc',
                                     )
                                   ),
                                   MigrateDestinationNode::getKeySchema()
    );

    // Migration mappings, the documentation for these mappings can be seen at:
    // https://www.drupal.org/node/1133448

    $migrator_user = user_load_by_name('PrezMigrator');

    // Some default values for sanity.
    $this->addFieldMapping('uid')
      ->defaultValue($migrator_user->uid);
    $this->addFieldMapping('revision')
      ->defaultValue(1);
    $this->addFieldMapping('log')
      ->defaultValue('inserted related media from legacy DB on ' . date("l jS of F g:i A.", time()));
    $this->addFieldMapping('promote')->defaultValue(0);
    $this->addFieldMapping('sticky')->defaultValue(0);
    $this->addFieldMapping('revision_uid')->defaultValue($migrator_user->uid);

    // What legacy content are we talking about ?
    // also we want this legacy ID to actually lookup through 2 source migrations.
    $this->addFieldMapping('nid', 'id')->sourceMigration(array('PrezDietNonPresidents','PrezDietPresidents'));

    // Map media files these are multiple value fields. They can accept a PHP array of values.
    $this->addFieldMapping('field_docs_media_videos_local', 'local_video');
    $this->addFieldMapping('field_docs_media_videos_remote', 'remote_video');
    $this->addFieldMapping('field_docs_media_audo_local', 'local_audio');
    $this->addFieldMapping('field_docs_media_audio_remote', 'remote_audio');

    // Each of the above media fields will need the following additional subfields
    // Only 1 is provided as an example to keep this example shorter:
    $this->addFieldMapping('field_docs_media_videos_local:file_class')
      ->defaultValue('MigrateFileUri');
    $this->addFieldMapping('field_docs_media_videos_local:language')
      ->defaultValue(LANGUAGE_NONE);
    $this->addFieldMapping('field_docs_media_videos_local:preserve_files')
      ->defaultValue(FALSE);
    $this->addFieldMapping('field_docs_media_videos_local:file_replace')
      ->defaultValue(FILE_EXISTS_REPLACE);
    $this->addFieldMapping('field_docs_media_videos_local:source_dir')
      ->defaultValue('/var/www/2015/presidency/drupal7-project/build/legacy/htdocs/www/media/');
    $this->addFieldMapping('field_docs_media_videos_local:urlencode')
      ->defaultValue(FALSE);
    $this->addFieldMapping('field_docs_media_videos_local:alt')->defaultValue('');
    $this->addFieldMapping('field_docs_media_videos_local:title')
      ->defaultValue('');

    // List fields not be migrated to destination.
    $this->addUnmigratedDestinations(
      array(
        // ... massive list of fields.
      ));

  }

  public function prepareRow($row) {
    // Always include this fragment at the beginning of every prepareRow()
    // implementation, so parent classes can ignore rows.
    if (parent::prepareRow($row) === FALSE) {
      return FALSE;
    }

    $youtube_format = 3;
    $quicktime_format = 2;
    $audio_format = 1;

    switch ($row->av) {
      case $youtube_format:
        $row->remote_video = $this-> find_remote_video($row->medialink);
        break;
      case $quicktime_format:
        $row->local_video = $this->find_local_video($row->medialink);
        break;
      case $audio_format:
        $row->local_audio = $this->find_local_audio($row->av, $row->medialink);
      default:
        break;
    }
    return TRUE;
  }

  // http://stackoverflow.com/questions/5830387/how-to-find-all-youtube-video-ids-in-a-string-using-a-regex
  protected function find_remote_video($link) {
      $separator = '***';
    $text = preg_replace('~
        # Match non-linked youtube URL in the wild. (Rev:20130823)
        https?://         # Required scheme. Either http or https.
        (?:[0-9A-Z-]+\.)? # Optional subdomain.
        (?:               # Group host alternatives.
          youtu\.be/      # Either youtu.be,
        | youtube         # or youtube.com or
          (?:-nocookie)?  # youtube-nocookie.com
          \.com           # followed by
          \S*             # Allow anything up to VIDEO_ID,
          [^\w\s-]       # but char before ID is non-ID char.
        )                 # End host alternatives.
        ([\w-]{11})      # $1: VIDEO_ID is exactly 11 chars.
        (?=[^\w-]|$)     # Assert next char is non-ID or EOS.
        (?!               # Assert URL is not pre-linked.
          [?=&+%\w.-]*    # Allow URL (query) remainder.
          (?:             # Group pre-linked alternatives.
            [\'"][^<>]*>  # Either inside a start tag,
          | </a>          # or inside <a> element text contents.
          )               # End recognized pre-linked alts.
        )                 # End negative lookahead assertion.
        [?=&+%\w.-]*        # Consume any URL (query) remainder.
        ~ix',
                         '//www.youtube.com/embed/$1' . $separator,
                         $link);
    return explode($separator, $text);
  }

  // other "find" media methods that return filesystem paths and stuff depending on where the media
  // existed in the legacy system.
}

```
> 0 votes

---
Tags: 7, migrations
---


title: Menu and breadcrumbs

text:
# Question
Title: Menu and breadcrumbs
I need the menu bar and breadcrumbs to use different hierarchies. Specifically, I need the menu bar to have:

`Home | Projects | About | Contact`

but I need the breadcrumbs for a project page to be:

`Home > Projects > Project title`

In "Content \> \[Projects page\] \> Edit \> Menu settings \> Parent item", to get "Projects" to show up in the menu bar, I have to set the parent to "\<Main menu\>". But if I do that then the breadcrumbs on a project page become:

`Projects > Project title`

so I lose "Home" in the breadcrumbs.

So the question is, how do I get "Projects" to be in the menu, but allow it to be under "Home" in the breadcrumbs?

I see there are lots of contributed modules for managing menus and breadcrumbs, but I wonder if there's something readily available in core that I don't know about. If not, what is the right module to do this?

Thanks for your help.

# Answer
> 0 votes
I think your best bet is defining custom breadcrumbs for your Project content type:

https://www.drupal.org/project/custom\_breadcrumbs

---
Tags: routes, breadcrumbs
---


# Question
Title: Creating a node with multiple joined fields
I'm sure I used to know how to do this, but now I can't work it out.

I have a content type, lets say it's called "project". A project can have multiple contributors, and for each contributor I need to have two fields, let's say "Name" and "University". Can I set this up as a single Content type?

If not (and I have to have a Content type for the project and a Content type for the contributor, using entity reference to link them), then how do I set it up so it's easy to edit on a single page (i.e. create a new project, click something to add another contributor on the same page)

# Answer
> 1 votes
I'd recommend keeping the contributors separate with their own fields. In order to edit them on the one form you can use a number of different modules. We use Inline Entity form. https://www.drupal.org/project/inline\_entity\_form

# Answer
> 0 votes
If you have fixed contributors then create two fields for each contributor:

```
field_1_contrib1
field_2_contrib2

```

Then use field\_permissions to assign appropriate perms for those fields.

To show author of each field, you can theme each field in the preprocess function in template.php or create a field.tpl.php file.

---
Tags: entities, nodes
---


# Question
Title: Commerce Price: Hide formatted amount if empty
I have a view with a regular commerce price and a discounted one. When using the Raw amounts everything works fine but when I use the formatted ones the hide if empty, Count the number 0 as empty and Hide rewrite if empty even though they are checked the amount of 0,00€ is shown!

What can I do to hide it?

# Answer
This should be fixed in Drupal commerce, but until it gets fixed you could add a custom template file to your theme. Copy `/sites/all/modules/views/theme/views-view-fields.tpl.php` to `/sites/all/themes/[YOUR_THEME]/templates/views-view-fields--[YOUR_PRODUCT_TYPE].tpl.php` and edit it. Add something like: `<?php if($id == 'commerce_price' && empty($row->commerce_price)) continue; ?>` to your template file.

```
<?php foreach ($fields as $id => $field): ?>
  <?php if($id == 'commerce_price' && empty($row->commerce_price)) continue; ?>
  <?php if (!empty($field->separator)): ?>

```

...
> 2 votes

# Answer
```
function MODULENAME_field_attach_view_alter(&$output, $context) {
 /*Remove price if null or has value 0.00*/
    if($context['display']['module'] == 'commerce_price'){
     $field_name = array_keys($output);
       if(!empty($field_name[0])){
            $field_name = $field_name[0];
            if(empty($output[$field_name]['#items'][0]['amount']))
                $output = array();
        }

    }

```

}
> 0 votes

---
Tags: views, commerce
---


# Question
Title: Avoiding PHP timeout when geocoding many addresses - preferred method?
I have a script that's taking in a ton of address data from a CSV, converting it to JSON, and along the way it hits the Google Maps API to get the latitude and longitude of each address. It then writes the whole thing to a .json file that is used by another widget. This works well for small numbers of addresses but some of the files I'm importing have hundreds of addresses. I have considered several ways around this:

* Queues: The problem with this one seems to be that I would have to save an object for each address and I don't want to completely fill up my database with address objects. I would then also have to somehow detect the completion of the queue and retrieve all those objects from the database to generate my complete json file. I worry about whether the server will deal with this well.
* Some other Google Maps API: Am I even using the correct Google Maps API for this? Is there one that can get a bunch of coordinates for a bunch of addresses in one HTTP request? I couldn't find one but that doesn't mean it's not existing.
* Feeds API (or some other core or contrib API for getting tons of data): It occurs to me that my hand-rolled solution might be circumventing some more Drupal-correct way to accomplish this task. Does Drupal offer something for making big batches of HTTP requests that I'm just missing?

So, basically my question is: what's the most Drupalish way to make and process a large number of HTTP requests from a module?

# Answer
I ended up solving this by using the Geocod.io API and the PHP library built for it. It supports batch requests and allows up to 2500 free addresses per day.
> 1 votes

# Answer
It seems to me that your only option is to go with a PHP CLI script implementation. You can learn more here: http://www.php-cli.com/

In PHP in general, whenever you have a long running task, it's best to go with PHP CLI as it doesn't impose a timeout limit and have larger memory limits by default. Note here that PHP CLI and the PHP used to server web pages have different settings that you can manage separately.

Once you have a PHP CLI script in place, setup a standard Linux CRON task to hit that script say every hour or every day.

In the context of Drupal, you might want to check this post: Do I need a cron task for processing a queue? and also check the Elysia CRON module https://www.drupal.org/project/elysia\_cron as they might be helpful but I think in your case you're better of with a standard PHP CLI script.

Also, keep in mind that you can call Drush commands from a PHP CLI script very easily. I have a script that runs updates and CRON automatically on all Drupal instances running on web server and it's a huge advantage. You can also look into implementing your custom Drush commands.

Good luck.
> 1 votes

---
Tags: feeds, google-maps
---


# Question
Title: How to set paragraph margin when editing in CKeditor?
I want to make a subtitle on a page, which needs to be centered and to have no space between it and the title.

In the CKeditor window, I entered the subtitle as the first line of text and centered it. In source, CKeditor represented this as:

```
<p class="rtecenter">...</p>

```

which results in a blank line above. I tried to remove the blank line by changing the above code to:

```
<br><center>...</center>

```

or just

```
<center>...</center>

```

But CKeditor didn't like either of those. It removed the center tag and replaced the `<br>` with `<p>`. I also tried to add an instruction in CSS as either:

```
<p class="rtecenter" style="margin-top:0">...</p>

```

or as:

```
<p class="rtecenter"><span style="margin-top:0">...</style></p>

```

CKeditor also didn't like either of those and just removed the style attribute from the first one and removed the span tag from the second.

I'm not very conversant in CSS, so I'm not sure the above code is properly formed. But the problem is that CKeditor is just removing it so I don't even get a chance to troubleshoot errors in the CSS.

CKeditor seems determined to have that blank line there. How can I get it to let me adjust this spacing between paragraphs (not globally, but on an individual paragraph)?

Thank you.

# Answer
In your example you have:

```
<p class="rtecenter"><span style="margin-top:0">...</style></p>

```

I'm assuming that should be:

```
<p class="rtecenter"><span style="margin-top:0">...</span></p>

```

In general in terms of controlling the space between paragraphs I think the best way to do that is your CSS stylesheet, not really HTML.

Drupal and CKEditor do some HTML manipulation that you may want to checkout - admin/config/content/ckeditor, then choose your profile and click edit. Under appearance you can select/deselect some plugins that you might not need.

In terms of a quick fix though I would think that this would work:

```
<p class="rtecenter" style="margin-top:0; text-align:center;">...</p>

```

But it also depends on what is in your site's stylesheet and your theme.
> 1 votes

# Answer
Seems like CK Editor is stripping out your tags.

Are you using filter html? if so, you should check on CK Editor's allowed tags in `admin/config/content/formats/filtered_html` and add the tags that you need.

If the above doesn't work, check the cleanup and output settings in `admin/config/content/ckeditor/edit/Advanced`
> 1 votes

# Answer
The question does not say if you're using the CKEditor module, or if you're using the WYSIWYG module (in which you then configure the CKEditor 'library').

I always use the WYSIWYG module (to leave the options open for a customer to pick another editor if they'd want, e.g. TinyMCE). If however I select the CKEditor library (using WYSIWYG module), then I've noticed that I must use the (older) 3.6.x version of the CKEditor, since WYSIWYG module seems to not yet support the 4.x version of CKEditor. That is: if I first try the 4.x version of CKEditor, then the WYSIWYG module doesn't find/enable it.

As per the comment "Seems like CK Editor is stripping out your tags." (in another answer), it appears to me that it might be worth trying the WYSIWYG module approach, together with CKEditor 3.6.x library. Another option might be, if you use CKEditor "module", to try to use the 3.6.x version of the "library" (I don't have experience with that combination though).

Curious to hear if this helps ...
> 1 votes

---
Tags: wysiwyg
---


title: Views result sorting using arguments

text:
# Question
Title: Views result sorting using arguments
Is there any option available in Drupal views to sort views result using the arguments provided (contextual filters)

I am trying to integrate a search functionality using views. My problem is that contextual filter will list only matching results, I need all the results but it should sort according to the arguments passed using contextual filters. Is that possible?

I.E. I pass the following string to a contextual NID argument: 1099+1100+1102+1098+1101+1097

I expect the order of the nodes in the view to be the same as the order as passed in through the argument.

# Answer
This is what helped for me.

https://stackoverflow.com/a/2474164/28672

Using the second option to generate the view manually then modifying the array in the result property.

And this is the code I used to sort the results to the argument

```
 // Sort the view based on the argument now we've generated it.
  $results = $view->result;
  $view_argument_array = explode('+', '1099+1100+1102+1098+1101+1097');
  $new_result_order = array();
  foreach ($view_argument_array as $nid) {
    foreach ($results as $result) {
      if ($result->nid == $nid) {
        $new_result_order[] = $result;
      }
    }
  }
  $view->result = $new_result_order;

```
> 1 votes

---
Tags: views
---


title: How to set image as background

text:
# Question
Title: How to set image as background
I am using bartik theme. I have an image that I like to use as background of the home page only. Admin \> appearance \> Bartik \> settings \> I see different colors to set as background. Can I have an image as background instead of the color for the home page. And for other pages I can use a color.

Thanks.

D

# Answer
unless you want to add it to a theme setting so that it can be adjusted by UI, the simplest way is probably to override `page--front.tpl.php` in your theme template directory, and manually add the html to create the background.

For more info on page template naming, see here.
> 0 votes

# Answer
Consider using the ThemeKey module. From its project page (bold markup added here):

> ... allows you to define simple or sophisticated theme-switching rules which allow automatic selection of a theme depending on current path, taxonomy terms, language, node-type, and many, many other properties.
>
> In combination with Drupal's theme inheritance you can easily achieve features like:
>
> * a front-page / "splash" screen
> * ...

So by creating a subtheme of the Bartik theme to be used on the home page, and another subtheme for all other pages, it should achieve your goal, no?
> 0 votes

---
Tags: media
---


# Question
Title: Why is theme.inc looking for view template in calendar module
So I am working on updating a drupal site that was very out of date, I have updated everything to the latest versions. When I updated the Calendar module things started going awry, now most of my views don't display anything. I'm assuming this error is the reason:

```
Warning: include(__custom_path__/sites/all/modules/calendar/views-view-fields.tpl.php): failed to open stream: No such file or directory in theme_render_template() (line 1525 of __custom_path__/includes/theme.inc).

```

I've searched and while there are numerous potential fixes none have worked. The last one I tried, adding a empty version of the *views-view-fields.tpl.php* and that only creates a different error where theme.inc can't find *calendar.views.inc* because it look for it at the path *calendar/calendar.views.inc* instead of *calendar/includes/calendar.views.inc*

Why is it looking for this in calendar instead of views? What can I do to fix this?

# Answer
I cannot reproduce this myself but take a look at

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

It is an old ticket but is for the 7.x-2.x-dev branch and basicly it says disable your module remove the module directory and reinstall it so something like

Will disable the module.

```
 drush dis calendar

```

Will uninstall the module (if the module has a uninstall hook)

```
drush pmu calendar

```

Remove the directory

```
rm -rf __custom_path__/sites/all/modules/calendar

```

Most likely not necessary but wont hurt but will rebuild the registry and clear all cache

```
drush rr
drush cc all

```

Download the newest version of the module

```
drush dl calendar

```

And enable it.

```
drush en calendar

```

It should remove all traces of the old calendar and add a clean copy/install.

I would also do a drush updatedb just to double check if after all that everything is still in order.
> 1 votes

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


title: Add JS to Commerce Add to Cart form

text:
# Question
Title: Add JS to Commerce Add to Cart form
I'd like to add my own JS functions to the Commerce "add to cart" form when a user makes selections on various product attributes.

When the user clicks through the options available, I need to scan the form using JS for the current values of the radiobuttons/selects. I need this to happen as soon as the form elements have changed.

edit: Having some success with the following, however since the form changes every single attribute this makes my javascript function run many, many times.

```
(function($) {
  Drupal.behaviors.watch = {
    attach: function(context, settings) {
      //look at form values here.
      //this fires after each form element is updated

    }
  }
})(jQuery);

```

Forgive me if this question sounds a bit lazy, I am reading the documentation, but I've not seen anything yet.

# Answer
> 0 votes
When you use Drupal's "attach" behaviors, use the provided `context` parameter in your jQuery selectors to limit the selector scope to only the part of the page that is being modified by AJAX:

```
(function($) {
  Drupal.behaviors.watch = {
    attach: function(context, settings) {
      $('.my-input', context).val('foo');
    }
  }
})(jQuery);

```

---
Tags: commerce, javascript
---


title: Override alter.inc in child theme

text:
# Question
Title: Override alter.inc in child theme
Bootstrap.js is breaking a menu plugin I'm using. It's called with this

```
  $bootstrap = $theme_path . '/js/bootstrap.js';
  $js[$bootstrap] = drupal_js_defaults($bootstrap);
  $js[$bootstrap]['group'] = JS_THEME;
  $js[$bootstrap]['scope'] = 'footer';

```

in themes/bootstrap/theme/alter.inc. I tried putting a modified alter.inc inside themes/child\_theme/theme/ but it doesn't work. Is there a function I can use to override it?

# Answer
If you really want to remove bootstrap.js you can do it this way:

```
function YOURTHEME_js_alter(&$js) {
  $bootstrap = drupal_get_path('theme', 'bootstrap') . '/js/bootstrap.js';
  unset($js[$bootstrap]);
}

```

It might fix your menu plugin but it'll remove every drupal specific bootstrap js code (tabs, popovers, tooltips and anchors stuff).
> 1 votes

---
Tags: 7
---


# Question
Title: Add French and Arabic Language in my Website
Can I add multiple languages to my website, such as French and Arabic?

If so, how can I do so?

# Answer
> 0 votes
In case of a D7 site, make sure core module **Locale** is enabled.

Navigate to admin/config/regional/language within your site. On that page use the 'Add language' link. Then select a language you want to be added to your site 'the Language name' drop-down, eg 'French'. Use the Localization update module to enable automatic translation updates.

Repeat this process for adding more then just 1 language.

Refer to Install a language for more details (which also details the steps for D6 and D8).

---
Tags: commerce, i18n-l10n
---


# Question
Title: Picture linked to user's profile in user-picture.tpl.php
D7: In my user-picture.tpl.php template I have the following code:

```
<div class="user-image">
  <?php
    $user = user_load($account->uid);
    print theme('image_style', array('style_name' => 'square', 'path' => $user->picture->uri));
  ?>
</div>

```

This short snippet sets the default, site wide, for the user picture.

When using views, linking the picture is easy. But when not using views, how can I change this so that the picture is linked to the user's profile?

Any help on this would be greatly appreciated. :)

# Answer
`template_preprocess_user_picture()` uses the following code.

```
  $variables ['user_picture'] = '';
  if (variable_get('user_pictures', 0)) {
    $account = $variables['account'];
    if (!empty($account->picture)) {
      if (is_numeric($account->picture)) {
        $account->picture = file_load($account->picture);
      }
      if (!empty($account->picture->uri)) {
        $filepath = $account->picture->uri;
      }
    }
    elseif (variable_get('user_picture_default', '')) {
      $filepath = variable_get('user_picture_default', '');
    }
    if (isset($filepath)) {
      $alt = t("@user's picture", array('@user' => format_username($account)));
      if (module_exists('image') && file_valid_uri($filepath) && $style = variable_get('user_picture_style', '')) {
        $variables['user_picture'] = theme('image_style', array('style_name' => $style, 'path' => $filepath, 'alt' => $alt, 'title' => $alt));
      }
      else {
        $variables['user_picture'] = theme('image', array('path' => $filepath, 'alt' => $alt, 'title' => $alt));
      }
      if (!empty($account->uid) && user_access('access user profiles')) {
        $attributes = array('attributes' => array('title' => t('View user profile.')), 'html' => TRUE);
        $variables['user_picture'] = l($variables ['user_picture'], "user/$account->uid", $attributes);
      }
    }
  }

```

Assuming you just want to use a specific image style for the image, and hard code it in your theme, I would use the following code for `mytheme_preprocess_user_picture()`. (Replace `mytheme` with the short name of the theme.)

```
  $variables ['user_picture'] = '';
  if (variable_get('user_pictures', 0)) {
    $account = $variables['account'];
    if (!empty($account->picture)) {
      if (is_numeric($account->picture)) {
        $account->picture = file_load($account->picture);
      }
      if (!empty($account->picture->uri)) {
        $filepath = $account->picture->uri;
      }
    }
    elseif (variable_get('user_picture_default', '')) {
      $filepath = variable_get('user_picture_default', '');
    }
    if (isset($filepath)) {
      $alt = t("@user's picture", array('@user' => format_username($account)));
      if (module_exists('image') && file_valid_uri($filepath)) {
        $variables['user_picture'] = theme('image_style', array('style_name' => 'square', 'path' => $filepath, 'alt' => $alt, 'title' => $alt));
      }
      else {
        $variables['user_picture'] = theme('image', array('path' => $filepath, 'alt' => $alt, 'title' => $alt));
      }
      if (!empty($account->uid) && user_access('access user profiles')) {
        $attributes = array('attributes' => array('title' => t('View user profile.')), 'html' => TRUE);
        $variables['user_picture'] = l($variables ['user_picture'], "user/$account->uid", $attributes);
      }
    }
  }

```

Doing so, the template file would just need to print `$user_picture`.

Keep in mind that the image style used for the user image is contained in a Drupal variable. I would investigate on how to change that variable for the theme you are using, even though you would then need to change it back for the other themes, in the case your theme is not anymore the active one.
> 2 votes

---
Tags: theming
---


title: User registration form

text:
# Question
Title: User registration form
I am using drupal 7 built in form name `user_register_form`, when clicked on `submit` or `save` button I want to store the value of `uid` column value and `status` value (if the request is active or blocked) to be stored in another table? How can I implement this , can anybody please guide me ..

**UPDATED** My table name is `expiry_user`, `expiry_status` and `expiry_uid` are two columns in my table

```
function mymodule_user_insert(&$edit, $account, $category)
{
db_insert('expiry_user')->fields(array(
'expiry_status' => $account['status'],
'expiry_uid' => $account->uid,
))->execute();
}

```

# Answer
> 0 votes
Use hook\_user\_insert() to take action on the user account after creation:

```
function mymodule_user_insert(&$edit, $account, $category) {
  //@TODO: use $account->uid & $account->status to do stuff
}

```

---
Tags: 7, users
---


# Question
Title: xmlrpc() error: (-1001) unable to parse URL during Drush command
I have an odd error coming from Drush when I perform module updates and other commands (it's most consistently comes from module updates). Near the end of the command execution this message pops up:

> xmlrpc() error: (-1001) unable to parse URL

Some cursory Googling produces that its likely an error popping up in drupal\_http\_request. I'm not sure where however since I'm not too familiar with the Drush code base.

I ran drush with the `--debug` switch for more information but that didn't tell me much other than this message typically pops up after the `drush_cache_command_clear()` being executed.

What is causing this error?

# Answer
Turns out the issue was the APC module. After some testing I was able to isolate the issue during cache clear.

```
[shawnconn@host www]$ drush cc all
'all' cache was cleared.                                                                                [success]
xmlrpc() error: (-1001) unable to parse URL                                                                                [error]
[shawnconn@host www]$ drush dis apc
The following extensions will be disabled: apc
Do you really want to continue? (y/n): y
apc was disabled successfully.                                                                                [ok]
You need to enable the APC module for remote cache clearing to work. Run drush pm-enable apc.                                                                                [error]
[shawnconn@host www]$ drush cc all
'all' cache was cleared.                                                                                [success]
[shawnconn@host www]$

```
> 3 votes

# Answer
It seems likely that you have not correctly specified the URI for your site. You can do this in one of several ways:

1. `--uri=http://example.com` on the commandline.
2. `'uri' => 'http://example.com'` in a site alias.
3. `$options['uri'] = 'http://example.com'` in a drushrc.php file.

For the purpose of most Drush commands, it is sufficient to use the name of the folder that contains the settings.php file as your uri -- or you do not need to specify the uri at all if the sites folder is 'default'. However, some modules will need the full URI, including the http:// protocol, or you will experience problems similar to what you describe above.
> 2 votes

---
Tags: drush, updating
---


# Question
Title: How to alter a views current pager label to node post date
I'm working on a website which features a daily updated "six word story" (a node for each day). I created a view to display the last node/story, with the option to scroll back one day at a time (using AJAX). The view has a full pager.

However, the pager is (of course) displaying "\<\< Previous ... 2 ... Next \>\>". Number 2 would mean "yesterday" (the first result is today's six word story, nr. 2 yesterdays and so on). What I want to do is alter the text (which now is just a number), so it would show the post date of the shown node/story.

I know that the labels can be altered, but there are only four labels (first, previous, next, last). It seems that there is no label in the pager plugin for the current page. Any ideas on how to alter the label without breaking the actual pager itself?

# Answer
> 0 votes
One thing that comes to mind is to override theme\_pager() in your theme's **template.php**. In fact, this post covers how to do that without messing up the first, previous, next, last labels.

---
Tags: views, paging
---


# Question
Title: db_insert error delta "doesn't have a default"
When I execute this code:

```
db_insert('field_data_field_room_rates')
    ->fields(array(
      'entity_type' => 'node',
      'bundle' => 'rooms',
'entity_id' => $roomno,
'revision_id' => 0,
'field_room_rates_target_id' => $mynode->nid
    ))
    ->execute();

```

It returns back an error saying "General error: 1364 Field 'delta' doesn't have a default value". Any quick way to work around this without doing a count to respect the order? I don't want to give it an arbitrary number.

Thanks in advance!

# Answer
Without knowing the circumstances, I think you might better off loading your node, adding to the field array, then using the node save function. But if you want to stick with DB operations, you could retrieve the next highest cardinality with this query:

```
  $next_delta = db_select('field_data_field_room_rates','rates')
    ->fields('rates', array('delta'))
    ->condition('entity_id', $mynode->nid)
    ->condition('revision_id', $mynode->vid)
    ->orderBy('delta','DESC')
    ->range(0,1)
    ->execute()->fetchField() + 1;

```
> 0 votes

---
Tags: 7, database
---


title: How do I add a flat rate?

text:
# Question
Title: How do I add a flat rate?
I have installed the following modules in an existing Drupal site.

* Commerce and Commerce UI
* Customer and Customer UI
* Price
* Line Item and Line Item UI
* Order and Order UI
* Checkout, Payment, Product
* Product Reference
* Cart and Product Pricing
* Tax
* Product UI
* Tax UI
* Payment UI
* Shipping
* Shipping Flat Rate

The shop is working fine as expected.

I'm trying to set up different shipping rates, so I'm following the instructions on the project page for the Flat Rate module. However, when I go to *Store \> Configuration \> Shipping* there is no option to add a flat rate service.

What am I missing?

# Answer
> 1 votes
On *Store \> Configuration \> Shipping* there are few tabs like *Shipping services* and *Shipping methods*; below them, there is another set of tabs which include *Flat rate*. That should be chosen before the *Add a flat rate service* link becomes visible on that page.

---
Tags: 7, commerce
---


# Question
Title: Why and when is feeds_entity_load needed
I have the feeds module enabled and when I load a basic view, it generates 688 calls to the function `feeds_entity_load` which generate as many database query, which degrades the performance.

Why are these call needed ? For me `feeds` is only use to import data, so why is it impacting every single page load ? I'm thinking of deactivating this function but I would like to understand if it's safe to do so.

# Answer
> Why and when is feeds\_entity\_load needed

It isn't.

`feeds_entity_load()` was removed from the Feeds module 3 years ago. It no longer exists in the codebase (download and `grep -nr feeds_entity_load feeds`, the only reference you'll find is in the changelog).

You should upgrade your version of feeds ASAP, you must have an outdated version installed.
> 1 votes

---
Tags: feeds
---


# Question
Title: How to change "New content" text in entity connect autocomplete edit/add buttons?
using entityreference autocomplete widget (field-widget-entityreference-autocomplete) with entity connect I have the buttons "New content" and "Edit content".

How can I just rename them in "New" and "Edit" respectively ? These are coded in the value field of the input, hence I can't change them just with CSS..

I think I could do it on a form specific way using hook\_form\_alter, but I would like to apply it to any form where the widget appear.

I tried already hook\_field\_widget\_form\_alter(&$element, &$form\_state, $context) but then I got lost, I am not sure it's the right place..

# Answer
> 1 votes
In a form alter you can access those two buttons with something like:

```
$field_name = "field_test";
$form[$field_name][LANGUAGE_NONE][0]["add_entityconnect__".$field_name."_0_"]["#value"] = t("New");
$form[$field_name][LANGUAGE_NONE][0]["edit_entityconnect__".$field_name."_0_"]["#value"] = t("Edit");

```

Adapt the name, language and cardinality of the field accordingly.

You can use a basic hook\_form\_alter to affect all forms. The widget creation code is in `entityconnect.form.inc` and it can't be altered (no hooks, no variables).

---
Tags: forms, entities
---


# Question
Title: Display average "Votes: Value" as stars in Views
I have created a table in Views 3 where ratings are averaged according to days of a week. But the ratings are showing as values between 1-100.

How can i convert these values in star rating from 1 to 5? I am unable to make it work either using Rate or Fivestar modules. I would prefer a solution through views ui but dont mind alternatives.

# Answer
It should be easy with a simple theme file.
In the views interface, on the bottom right, you should see "Theme: informtion", click that and you will see relevant theme file names.
Using one like "views-view-field--rating.tpl.php" should work.
> 0 votes

---
Tags: 7, views, rating
---


# Question
Title: How can I extend drush aliases with specific variables?
I like to know if it is possible to extend drush aliases with more specific path variables. Is there anybody who can tell me how to extend the drush example code, that follows below with array for the file system paths for

* temporary files directory
* files directory
* private files directory

So that I don't have to change them manually after every db sync when the dev server has other path settings then the productive server

This may be a silly question but I just looked at the documentation on github and haven't found any details.

# Answer
> 3 votes
The Drush rsync and drupal-directory (dd) commands already supports the functionality you desire, without the need for you to extend your alias files. For example, to copy your files directory:

`drush rsync @live:%files @dev:%files`

To copy a specific folder from your temporary directory:

`drush rsync @dev:%temp/foo @live:%temp`

To change your working directory to the location where the devel modulr is installed:

`cd $(drush dd @dev:%devel)`

---
Tags: drush
---


title: How to use url() correctly?

text:
# Question
Title: How to use url() correctly?
I'm trying to generate a custom token to a prepopulated URL. My code looks like this:

```
        $replacements[$original] = url('user/login', array(
          'query' => array('edit[name]', $account->mail),
          'absolute' => TRUE,
        );

```

The resulting URL looks like this:

http://example.com/en/user/login&edit\[name\]=myemail@example.com

But the `&` should be a `?` because it's the start of a query string. What am I doing wrong?

# Answer
> 3 votes
This should work for you:

```
    $replacements[$original] = url('user/login', array(
      'query' => array('edit' => array('name' => $account->mail)),
      'absolute' => TRUE,
    ));

```

Sidenote: you are naming the argument as `name` but you are passing the mail.

---
Tags: uri
---


# Question
Title: Preventing Authors from entering pre-formatted text into filtered html field
I have a form for my authors to use when entering records. The form has a 'filtered text' description field that also use WYSIWYG.

I'm noticing that some of my authors enter 'bad' text. What I mean is the text they are entering looks like it's been formatted with weird spans and divs from some other text editor (probably word), so that it breaks the formatting of the record when its published.

Anyone know of a way to auto-strip extraneous html when someone inputs a record, or is it just a matter of educating them?

They really don't know anything about HTML at all so a technical solution would be best sadly.

# Answer
If you're using the Filtered HTML text format, it should be stripping out spans/divs that contain inline styling. You can double check this at the **/admin/config/content/formats/filtered\_html** path. Make sure the limit HTML tags box is checked and the **Allowed HTML tags** don't contain any of the HTML elements you're trying to get rid of.

If you're using the CKEditor (I'm not sure of other editors combined with the WYSIWYG module), you have a few other options to scrub bad markup when it's pasted in. You can check this by editing your Filter HTML profile under **/admin/config/content/wysiwyg**.

One the toolbar options contains a Paste from Word button, that allows you to paste Word-copied markup into CKEditor. I tend to avoid this myself, but you might find it useful if your users work with many Word documents.

My prefered option is to use the paste plugin to strip out markup altogether; going this route allows you to restrict your toolbar to HTML elements that will render correctly in both the editor & your theme. You can find this option in paste plugin tab in your WYSIWYG profile page.
> 1 votes

---
Tags: forms, wysiwyg
---


# Question
Title: SSL Issues with Mixed Content and Firefox
my question is about SSL with Drupal. I've uploaded my certs to my server and got everything installed and working correctly. I've set the base\_url to be my https://site domain and also put the following at the top of my htaccess file:

RewriteEngine On RewriteCond %{SERVER\_PORT} 80 RewriteRule ^(.\*)$ https://domain.com/$1 \[R=301,L\]

Everything seems good on all my site pages on IE and Chrome. But Firefox keeps giving me a mixed content warning:

Firefox is blocking content on this page. Some unencyrypted elements on this page have been blocked.

Why would it still be saying this if I have a properly working SSL cert (which I do) and it covers my entire site? Is there a way to get rid of it?

Thanks!

# Answer
When you set `$base_url`, Drupal always uses it in email absolute links and whenever it has to build an absolute URL.

I have many sites running full-HTTPS, with only the $base\_url set to the https URL.

We can't debug your site for you, but check the page source to see if any Javascript files are being served via HTTP. Google Analytics, Google fonts, Google translate widgets, banners, ad serving scripts, CDN-served jQuery, etc.

Header tracking and other debug features won't probably work in your browser because when the page URL is in HTTPS, browsers do not load HTTP assets. You can still check the page source to see the HTTP references.
> 1 votes

---
Tags: ssl, configuration
---


# Question
Title: Call $created variable in content type node template
How can I call the $created variable in my content type node template? I tried the following but it just produces what seems to be a random string of numbers:

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

```

# Answer
The `$created` variable is just a number, but it's not random it is a unix timestamp of the node created date.

Since it is not a render array you do not print it using the render() function, you would just print it like this:

```
<?php print $created; ?>

```

However that is also probably not what you want because you probably want a human readable date/time, not a unix time stamp.

As you can see in the main variable preprocess function for the node template (template\_preprocess\_node()), there is also a variable `$date`, which is a formatted date based on the `$created` variable. That will default to using your website's medium date format.

You can use it like this:

```
<?php print $date; ?>

```

If that is not the format you want you can also manually use the format\_date() function to format it to your requirements like this:

```
<?php print format_date($created, 'short'); ?>

```

or like this for something more custom:

```
<?php print format_date($created, 'custom', 'd/m/Y'); ?>

```

See the php date() documentation for more information on custom date format options.
> 2 votes

# Answer
This can vary from theme to theme so you can look in your template.php for the hook\_preprocess\_node(). This is where you can alter and set variables for your node.tpl.php. The $submitted variable could be used or modified in this case.

```
/**
 * Implements hook_preprocess_node().
 */
function my_theme_preprocess_node(&$variables) {
  // Alter the submitted variable, just on blog type.
  if ($variables['type'] == 'blog') {
    $variables['submitted'] = format_date($variables['created']);
  }
  // Or define a new variable for your node.tpl.php
  $variables['created_date'] = format_date($variables['created']);
}

```

Print the variable in your node.tpl.php

```
<?php print $created_date ?>

```
> 0 votes

---
Tags: 7, theming, nodes, datetime
---


title: Drush Make removes .git folders

text:
# Question
Title: Drush Make removes .git folders
After a silly feeling with drush make and github I found out that all the .git folders (used by git to record history, config, origin location etc ) were removed by drush make and I have heard about this before but didn't come across myself as I was not maintaining the make files.

Specifically drush make removes the .git folder and u can see that if u run it with --debug option

```
Executing: rm -rf '/tmp/drush_make_tmp_1305733094/__git__/__build__/.git'

```

In my make file I am fetching 4 things from git repo because I wish to track development on them, 2 of them are my custom components ( 1 custom module and 1 feature which records all the config) and the other drupal core and media module due to high volume of fixes they receive. The whole purpose seems defeated if I can't have respective .git folders but I am also sure there is a way as others are using drush make with git but couldn't find in my quick search.

Thanks for your time!

# Answer
Pass the "--working-copy" switch to Drush Make.

```
drush make --working-copy site.make

```
> 17 votes

# Answer
And if you're using YAML for your make file, the following will allow you to preserve the .git repository info:

```
projects:

  drupal:
    type: core
    version: 8.0.x
    download:
      working-copy: true

```

And further, if you don't want drush to add in extra information to projects' .info files, make sure you use the `--no-gitinfofile` option when running `drush make`.
> 7 votes

# Answer
On project by project basis, in a make file you can add the option like this

```
projects[project_name][download][type] = git
projects[project_name][download][url] = ssh://git@...etc
projects[project_name][options][working-copy] = TRUE

```
> 3 votes

---
Tags: version-control, drush
---


title: Print Main Menu inside a block

text:
# Question
Title: Print Main Menu inside a block
Very new to Drupal--trying to understand building a dynamic navigation menu for end users to handle. Is it possible to print the Main Menu inside a block I'm using for the header? e.g.

```
<nav id="main-menu" role="navigation" tabindex="-1">
<?php
      print theme('links__system_main_menu', array(
        'links' => $main_menu,
        'attributes' => array(
          'class' => array('links', 'inline', 'clearfix'),
        ),
        'heading' => array(
          'text' => t('Main menu'),
          'level' => 'h2',
          'class' => array('element-invisible'),
        ),
      )); ?>
</nav>

```

Pages render the `<nav>` tag, but nothing inside such as the content (basic pages) that Main Menu definitely contains so far as I can see in `/admin/structure/menu/manage/main-menu`.

I'm using my own sub-theme (derived from Zen, but most regions removed,) so I've been trying the code above (and variations) in a block added to the Header region. Is this not the Drupal convention?

# Answer
> 0 votes
In a custom zen sub-theme I currently use the following code:

```
$menu = menu_navigation_links('main-menu');
print theme('links__main-menu', array('links' => $menu, 'attributes' => array('class'=> 'menu')));

```

This is appliable to any manu – just change the name accordingly. And it's easiely printable wherever I need it (page.tpl.php). It prints a \`ul´ like this:

```
<ul class="menu">
    <li class="menu-966 first"><a href="http://...">Link 1</a></li>
    <li class="menu-959"><a href="…">Link 2</a></li>
    <li class="menu-967 last"><a href="http://.…">Link 3</a></li>
</ul>

```

# Answer
> 0 votes
An alternative solution is to use the menu block module, which lets you easily configure as many different menu blocks as you like.

It gives many options in regards to which menu to use for a block and which levels of that menu to display.

---
Tags: theming, routes
---


# Question
Title: When using the Real Name module, how can I show the original (raw) username in a view?
The Real Name module allows a field in the user profile to be displayed as a user's name instead of the user name set upon registration.

This works great for my site as it allows people to set nicknames without having to worry about them being unique, etc.

However, I want to create a view for administrators that lists the actual (raw) username, not the real name. When I add a **User: Name** field in views, though, the real name is displayed, and I don't see any option for the raw result.

How can I show the raw result in Views when Real Name is installed?

# Answer
> 2 votes
You're right in using the field `User: Name` as there is no explicit Raw name field (only a token). Now in the field settings you must uncheck `Link this field to its user` and `More > Use formatted username`.

If you still want to have a link to the user's profile, do some field rewriting: add `User: uid`, move it above `User: Name`, check `Rewrite results > Output this field as a link` with the path `user/[uid]` or `user/[uid]/edit`.

---
Tags: views, users
---


# Question
Title: Show content of type A in content of type B based on shared taxonomy term using views
I want to show content of type A (products) in the middle of contents of type B(Producers), however I do not want to use Node reference since it's an overkill to make it happen with lots of products.

So far I have a Vocabulary which both content type share, so I thought if I choose a single taxonomy term when creating the contents of each type, I can relate them using views to each other based on that shared taxonomy.

Anyways so far no luck, I appreciate any helps.

# Answer
> 1 votes
Add a block view to show content of type A (products), add a contextual filter `Content: Has taxonomy term ID`, provide default value with PHP:

```
$node = node_load(arg(1));
return $node->field_term['und'][0]['tid'];

```

You can add safeguards, like `is_int(arg(1))`, `is_object($node)`, `$node->type == "product"`, etc. You don't need to if you add the block to a region and set it to be displayed on nodes of type B (producers) only.

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


# Question
Title: How to display the webform submission data in the below format in Views?
I want to display the webform submission data along with some other information in the below mentioned table format (like multiple rows for a particular column inside of a table).

Is it possible with Views, or can anybody suggest a module, if there is such or any other way of getting it? I tried searching but found no module that meets my requirements.

# Answer
> 1 votes
1. Use the Webform MySQL Views module.
2. Then navigate to web form, you will find separate tab MySQL views.
3. Generate one view form the same by navigating to that view.
4. When the view is generated, you will find this view under structure menu, under views section.
5. Then you can display it as you wanted to display, either in grid, unformatted list, tabular format, etc.

As your image seems colourful and in tabular format, you could use CSS classes for that, applying them under *Advance section*.

---
Tags: views, webforms
---


# Question
Title: Why are hook_form_alter updates being reverted?
After I clear all caches I can see my update is effective in the *Create Article* form. Great.

But as soon as I refresh the page, or come to it afresh to create another Article, the unmodified value of `#file_upload_title` re-appears.

This is what I added to `template.php`:

```
function seven_form_article_node_form_alter(&$form, &$form_state, $form_id) {
    $form['field_photo_gallery']['und']['#file_upload_title'] = 'Add a new file or multiiple files';
}

```

# Answer
> 0 votes
The function `seven_form_article_node_form_alter`was correctly named but not placed in the correct file in the correct folder.

The function `seven_form_article_node_form_alter` has to go in `template.php` in a (sub)theme of the administration theme `seven` \- of course - and not in the `template.php` of my "front-end" theme.

The fact that I had a function in there with a prefix other than my from-end theme's should have signalled my mistake.

What mislead me was a quirk of Drupal cache clear. It happens that clearing the Drupal cache actually (and incorrectly) caused my form alterations to be displayed as my function must have been the last one in the chain to have taken effect. It was only after a subsequent page build / refresh that the form alter's effects (correctly) disappeared. So this is a quirk of Drupal cache clear that needs to be taken account of in this edge case.

Consequently I have created an administration sub theme into whose `template.php` file the function now sits (Does it count as one line of code or two? ;-). All is now working as it should.

---
Tags: forms
---


# Question
Title: How can i access variable inside body node(input format:php) from my own module
please can you help me.

I make own simple module and storing actual variable like this:

```
.
..
...
function getip_preprocess(&$vars) {
  global $get_specific_ip;
  $vars['get_specific_ip'] = get_client_ip();
}
...
..
.

```

If i call this variable from page.tpl.php, or node.tpl.php., it works.....

But if im trying to get this variable from inside of body content area, result is empty... If i call function `get_client_ip()`, i will get solution i need to see, but im trying to get it as a variable, like $user.

I tried to make global variable from it `( $GLOBALS['get_specific_ip']; )` , but it aint works.

Please help me how to do it.

Thanks a lot for your answer.

Regards Stein

# Answer
Some comments on your code and question:

1. `global $get_specific_ip;` and `$GLOBALS['get_specific_ip'];` are both the same thing. For more info see http://php.net/manual/en/language.variables.scope.php
2. global variables and the template $vars array are different, so
`global $get_specific_ip;
$vars['get_specific_ip'] = get_client_ip();`
won't actually set a global variable because you're never setting `$get_specific_ip` to anything, it will only set the `$vars['get_specific_ip']` variable, which will make `$get_specific_ip` available in all your templates but not as a global variable.
3. The `getip_preprocess()` does not seem like the best place for this code. IP address is not specific to theme templates and would be best as either a global variable or attached to the existing global `$user` object. In either case `gettip_preprocess()` is not the optimal place because it isn't a global solution.
4. If the function `get_client_ip()` is a custom function of yours you should name space it to your module to avoid possible conflicts with other functions. For example, call it `getip_get_client_ip()`.
5. The variable name `$get_specific_ip` is a little strange because it sounds like an action or function name but it should describe what is stored in it. For example `$client_ip`. That however could also run into name spacing issues so would be better as `$getip_client_ip` or something like that.
6. Note that there is a Drupal function ip\_address() that might possibly be useful to you.

If you really want this available everywhere then you could use hook\_boot() like this:

```
/**
 * Implement hook_boot().
 */
function MODULENAME_boot() {
  // Set the user's IP address to a global variable for use elsewhere.
  global $get_specific_ip;
  $get_specific_ip = get_client_ip();
}

```

Then you can use `global $get_specific_ip;` from anywhere on the site to get that variable.

The use of hook\_boot() means it will run even on cached pages, which is a must for IP detection because you want your code to run and get the current user's IP even if they are getting a cached page. The other side to that is that you need to be careful to try not to use resource intensive code in there because it will always run on every page load.

It's worth noting at this point that whenever doing something with dynamic data like IP address make sure to properly test cached pages to make sure they always function as you would expect.

One last thing is that Drupal core already makes the user's IP address available to you in the global $user object.

So you can also get the IP like this:

```
global $user;
$ip = $user->hostname;

```

So unless you are doing something special in your `get_client_ip()` function it might be better to use that.
> 3 votes

# Answer
i finaly find solution, i dont know why but it works for me only like this:

```
global $ipaddress;

function get_client_ip() {

      global $ipaddress;

        .
..
...
..
.

     return $ipaddress;

}
   $GLOBALS['$ipaddress'] = get_client_ip();

```

Thank you for your help.

regards Izak
> 0 votes

---
Tags: 7
---