# Question
Title: How do I override/theme Views REST Export display field?
I have a REST Export view display setup in Drupal 8, delivering node fields.

The challenge: I want to theme/tweak/alter the output of JSON or HAL\_JSON for and image field. Currently, it's rendering this in JSON:

```
"field_feature_image":"  <a href=\"http:\/\/mysite.com\/app\/sites\/default\/files\/images\/feature\/huygens.jpg\"><img src=\"http:\/\/christopherstevens.cc\/app\/sites\/default\/files\/styles\/large\/public\/images\/feature\/huygens.jpg?itok=cmIzLkJp\" width=\"480\" height=\"480\" alt=\"Huygens Probe (Illustration)\" typeof=\"foaf:Image\" class=\"image-style-large\" \/>\n\n<\/a>\n"

```

I would prefer it to look like this (taking out all the HTML):

```
"field_feature_image":"http:\/\/mysite.com\/app\/sites\/default\/files\/images\/feature\/huygens.jpg"

```

Where's the best place to start? I don't see any views theme options when specifying a REST Export display. Should I create a module of some sort? Is there a theme option?

# Answer
> 7 votes
Here's one option:

Add a new relationship in the view for the field (field\_feature\_image in your case)

Add new field for "File: URI" using this new relationship

Use the File URI formatter, and also enable the "Display the file download URI" option

This method may not be ideal for fields with multiple values. I am still working out the best method to do that using the core tools in Drupal 8.

---
Tags: views, entities, 8, theming
---


title: Is there any theme record count?

text:
# Question
Title: Is there any theme record count?
Is there any theme record count? Like: "Showing 1 to 10 of 186 records".

So that the user sees the number of pages and total number of records of a query (EntityFieldQuery).

Something made my drupal like theme pager, that we use like this:

```
//...
$query = new EntityFieldQuery();
//...
$query->pager(10);
//...
$content .= theme('pager');
//...

```

# Answer
> 1 votes
No, but you can easily make one yourself by implementing `hook_theme()`.

---
Tags: paging, database
---


# Question
Title: error when trying to clear the cache in drupal
I was going to use mailchimp module to create my newsletter but an error revealed saying that i should install the version 2.0 of librairies, so i delete both modules, started again,that worked just fine .

When i went to settings of mailchimp, this error revealed:

> 1)Fatal error: Call to undefined function mailchimp\_signup\_entity\_access() in C:\Users\user\Sites\devdesktop\drupal-7.37\sites\all\modules\entity\entity.module on line 657

So , i tried to clear caches ,another error revealed:

> 2) i-Warning: Invalid argument supplied for foreach() in drupal\_schema\_field\_types() (line 7159 of C:\Users\user\Sites\devdesktop\drupal-7.37\includes\common.inc).
>
> ii-Notice: Undefined variable: field\_types in drupal\_schema\_field\_types() (line 7162 of C:\Users\user\Sites\devdesktop\drupal-7.37\includes\common.inc).
>
> iii-Warning: array\_keys() expects parameter 1 to be array, null given in drupal\_schema\_fields\_sql() (line 7179 of C:\Users\user\Sites\devdesktop\drupal-7.37\includes\common.inc).
>
> and Recoverable fatal error: Argument 2 passed to SelectQuery::fields() must be of the type array, null given, called in C:\Users\user\Sites\devdesktop\drupal-7.37\includes\entity.inc on line 317 and defined in SelectQuery-\>fields() (line 1301 of C:\Users\user\Sites\devdesktop\drupal-7.37\includes\database\select.inc).

any help please!

# Answer
> 0 votes
If the on option is grey, it means the module is required by another one. Deleting it will cause other modules to break. The correct thing to do would be to disable the depending modules, then disable the main modules and then go to the 'uninstall' tab and uninstall the module.

But for now try running update.php (drush updb) first and see if it helps. If not. Uninstall the modules properly, install the previous versions, disable and uninstall the previous versions and then install new versions again.

This works in most cases.

# Answer
> 0 votes
The fatal error was gone after I enabled the mailchimp\_lists module. I would also agree that a dependency to mailchimp\_lists would be needed and just in case it could help anybody else or could be considered by maintainers, I went ahead and created a quick patch for that.

Please find attached to this comment a patch against commerce\_mailchimp-7.x-1.x at e0a57df, which adds a dependency to the mailchimp\_lists module to prevent the fatal error: Call to undefined function mailchimp\_lists\_load\_multiple\_by\_name. File attached as: commerce\_mailchimp-undefined-function-mailchimp\_lists\_load\_multiple\_by\_name-2075931-2.patch. It is surely a very small patch, but at least it could prevent users from having a bad surprise with a fatal error, when module is already not that intuitive to configure....

---
Tags: commerce, caching
---


# Question
Title: How do I ensure the Content-Type header is present?
I need to set my Content-Type header to "application/json; charset=utf-8" in Services responses.

I have tried `drupal_add_http_header()` in my callback, in `_services_request_postprocess_alter()` and in a custom ServicesFormatterInterface:

```
class ServicesJSON_UTF8Formatter implements ServicesFormatterInterface {
  public function render($data) {
    // json_encode doesn't give valid json with data that isn't an array/object.
    if (is_scalar($data)) {
      $data = array($data);
    }

    drupal_add_http_header('Content-Type', 'application/json; charset=utf-8');

    return json_encode($data, JSON_UNESCAPED_UNICODE);
  }
}

```

Sometimes the header gets set, and sometimes it comes back just "application/json" without my addition. Where can I set this to make certain my header makes it into the response?

# Answer
Try this ( at the end of Your service callback function ):

```
drupal_add_http_header('Content-type','application/json; charset=UTF-8');

echo drupal_json_encode($response);

```
> 1 votes

---
Tags: 7, services
---


# Question
Title: How to get $nid inside hook_menu_alter function
I'm trying to show or hide a menu tab based on whether my node meets a certain condition. In my hook\_menu\_alter I can't seem to get the $nid even though I was under the impression that the menu\_alter fired after node load...

I've been googling for a day now and trying different solutions, but just can't seem to access the $nid.

When I print arg(0) or $\_GET\['q'\] I get the result "admin\_menu/flush-cache" instead of "node/62" even though I'm on a node page... what am I missing?

# Answer
> 2 votes
Menus are cached; unless you have something funky going on, loading a node won't rebuild that cache (it would be frightfully expensive to do so).

You need to make 'live' decisions in a callback, e.g.

```
function MYMODULE_menu_alter(&$items) {
  $items['foo']['access callback'] = 'MYMODULE_access_callback';
}

function MYMODULE_access_callback() {
  $node = menu_get_object();
  if ($node && $node->bar) {
    return TRUE; // Allow access.
  }

  return FALSE; // Default for anything that doesn't match your criteria.
}

```

The above is a contrived example, real-world will be different depending on exactly what you need to do.

---
Tags: routes
---


# Question
Title: How to send a custom Solr Query using Search API Solr
I'd like to send custom solr query (preferably in hook\_init) using Search API Solr to a specific URL.

Something like:

```
function hook_init() {
  $url = "admin/luke?show=schema";
  $solr = new SearchApiSolrService(); // must have an instance of SearchApiServer
  // $httpTransport->performHeadRequest($url);
  // $response = _sendRawGet($url);
  drupal_set_message(print_r($response, TRUE));
}

```

How I can do achieve that? Is there any live example?

Thank you.

# Answer
From version RC4 you can use makeServletRequest() to generate custom solr queries. See some examples on GitHub.

Here are some code examples:

```
  // Ping example
  // class_exists('Apache_Solr_Service') ?: spl_autoload_register('_search_api_solr_autoload'); // make sure that SolrPhpClient class is loaded (use only for <=rc3)
  $server = search_api_server_load('my_solr_server'); // CHANGE THIS
  $solr = new SearchApiSolrService($server);
  $result = $solr->ping();
  drupal_set_message(print_r($result, TRUE));

  // Simple search query (not fully tested)
  // class_exists('Apache_Solr_Service') ?: spl_autoload_register('_search_api_solr_autoload'); // make sure that SolrPhpClient class is loaded (use only for <=rc3)
  $server = search_api_server_load('my_solr_server'); // CHANGE THIS
  $index = search_api_index_load('my_index'); // CHANGE THIS
  $query = new SearchApiQuery($index);
  $query->keys('foo');
  $query->fields(array('title'));
  $solr = new SearchApiSolrService($server);
  $result = $solr->search($query);
  drupal_set_message(print_r($result, TRUE));

  // Custom path example for rc4 and above (not fully tested)
  $server = search_api_server_load('my_solr_server');
  $uri = SearchApiSolrConnection::LUKE_SERVLET . "?show=schema"; // or any other custom URL
  $connection = $server->getSolrConnection(); // or: new SearchApiSolrService($server)
  $response = $connection->makeServletRequest($uri);
  drupal_set_message(print_r($response, TRUE));

  // Example for assembling the right URL
  $server = search_api_server_load('my_solr_server');
  $url = 'http://' . $server->options['host'] . ':' . $server->options['port'] . $server->options['path'];

```

Above code tested in hook\_init with Drupal 7 and Search API Solr \[rc3\].

---

**Acquia**

If you're using Acquia, you can use Acquia-Search-Proxy which allows you to send custom queries against Acquia Search (Apachesolr + Search API Solr). See also my fork of Acquia-Search-Proxy which include some extra improvements.

Example custom queries via CLI:

```
PATH_INFO="/admin/ping" php search-proxy.php
PATH_INFO="/admin/luke" QUERY_STRING="show=schema" php search-proxy.php
PATH_INFO="/select" QUERY_STRING="q=foo" php search-proxy.php
PATH_INFO="/admin/file" QUERY_STRING="contentType=text/xml;charset=utf-8&file=schema.xml" php search-proxy.php

```
> 12 votes

# Answer
I've seen an example in a presentation at http://nickveenhof.github.io/devdays\_solr\_wizardry/#/click-recipes-search-api. I don't understand every line of code (I mean - why does he add a 'bundle' filter and remove it again?) but I still hope it helps.

```
$solr = apachesolr_get_solr();
$query = apachesolr_drupal_query("custom", array('q' => 'mykeys'), 'sort_label asc', 'search/path');
$query->setSolrsort('sort_name', 'desc');
$query->addFilter('bundle', (article OR page));
$query->removeFilter('bundle');
$query->addParam('fq', "bundle:(article OR page)");
$query->addParam('fq', "field_date:[1970-12-31T23:59:59Z TO NOW]");
$resp = $query->search();

```
> 6 votes

# Answer
SearchApiQuery offers a pretty complete tool to build custom queries.

Some code example :

```
  global $language;
  $term = 'TERM_TO_SEARCH_IN_THE_TITLE';

  // Select an index.
  $index = search_api_index_load("default_multilingual_node_index");
  $query = new SearchApiQuery($index);

  // Build a filter.
  $filter = $query->createFilter('OR');
  $filter->condition('type', 'article', '=');
  $filter->condition('type', 'blog_post', '=');
  $query->filter($filter);

  // Conditions.
  $query->condition('title_field', $term, '=');
  $query->condition('language', $language->language, '=');
  $query->sort('timestamp_field');

  // Fetch results.
  $results = $query->execute()['results'];

```
> 2 votes

# Answer
In order to add facets to your query, use setOption

```
$query = new SearchApiQuery($index);
$query->keys('');
$query->range(0,0);
$query->fields(array());
$query->setOption('search_api_facets',array(array('field'=>'field_country')));
$solr = new SearchApiSolrService($server);
$result = $solr->search($query);

```
> 2 votes

---
Tags: search
---


title: Changing Item title

text:
# Question
Title: Changing Item title
After giving permission to specific users to see the admin menu (those users can see only 2 items on the admin menu, items are 2 custom modules i've created) I'm trying now to change the items titles if the user is not the admin.

Example : admin can see : 'all users profils' (it shows list of all users) but user A can see on the admin menu : 'my profil' where he can see only his profil (his profil is contained on the admin "all users profils"

this is my hook\_menu\_alter function :

```
function MyModule_menu_alter(&$items){

    global $user;
    if($user->uid = 1){ //if admin
    $items['admin/editor']['title'] = 'all profils';}
    else{ //if logged user
        $items['admin/editor']['title'] = 'My Profil'; //show same table but only with user information (not all users table)
    }

}

```

P.S. The code below show only one item

# Answer
Since the menu is already coming from your custom module, you do not need to implement hook\_menu\_alter, alter hooks are implemented to avoid hacking of core/contrib modules.

Back to your problem, assume your already implemented hook\_menu looks like

```
  function mymodule_hook_menu() {
    $items['your/admin/menu'] = array(
      'title' => t('Test title'),
       // Add Title Callback
      'title callback' => '_mymdoule_title_callback',
      'title arguments' => array(1),
      'type' => MENU_NORMAL_ITEM,
      'access arguments' => array('access content'),
      'page callback' => 'function_content_callback',
    );
  }

/**
 * Title Callback for your Menu Item.
 */
function _mymdoule_title_callback() {
  global $user;
  if(in_array('administrator',$user->roles)) {
    return "Title for admin";
  }else {
    return "Title for non admin";
  }
}

```
> 2 votes

# Answer
hook\_menu\_alter will only be called when the menu cache is cleared.

You can't use this method to change anything on a per-user basis.

I'd suggest you do this at the theme level, in your theme's template.php:

```
function MYTHEME_preprocess_menu_link(&$vars) {
  global $user;
  if($vars['element']['#href'] == 'admin/editor' && $user->uid != 1) $vars['element']['#title'] = "My Profile";
}

```
> 0 votes

---
Tags: users
---


# Question
Title: What should I use to implement a shopping cart process?
I'm developing a website for a group of human resource professionals.

The customer wants a way for people to go to their site and do the following:

1. If they have a job listing they want to post to the website, they'll click on a "Post a Job" link.
2. The job submitter will then fill out the content for a job posting
3. Before the job can go online, the job poster will have to pay a fee to have it posted
4. Once the payment is received, the job posts to the website

I'm curious if anyone has any experience with this, and if so, what would you use to build it? It's a fairly simple shopping cart experience I suppose. It's certainly not like a store or anything. But, I don't have previous experience with something like this.

Can anyone guide me down the correct path?

# Answer
Here are a few typical solutions for implementing an online store:

However, as per your "*Simple shopping cart experience*", it looks like none of these is what you're looking for. So here are some other modules you may want to look at (excerpts are from their project pages):

* Basic Cart:

> ... a very simple shopping cart / checkout process for Drupal, that just sends 2 emails after each order. Along with the shopping cart, this module also provides a block where you can view your cart's content. It's ideal for small websites with only a few products or other content types being sold, for example touristic offers.
* Rules:

> Allows site administrators to define conditionally executed actions based on occurring events (known as reactive or ECA rules).
* Flag:

> Flag is a flexible flagging system that is completely customizable by the administrator.

The 'Basic Cart' implements the cart, while with the 'Rules' and 'Flag' modules you can implement appropriate business logic (which does not require any PHP coding skills).

If you're not familiar (enough/yet) with Rules, then checkout the 32 (!!!) great, and free, video tutorials Learn the Rules framework, organised in 7 chapters.

Possibly also the similar set of 8 video tutorials about the Flag module, often considered as a natural complement to the Rules module.
> 0 votes

---
Tags: 7
---


# Question
Title: "Disabled" regions re-enable after navigating away and back from module page
I have a form module that I would like to have on its own page, with no header, footer, etc.. I thought I was successful with adding hook\_menu() and a page callback to render the form's block, then added hook\_page\_alter() to cycle through all available regions and unset them:

```
function mymodule_menu () {
  $menuitems['myform-page'] = [
    'title' => 'Survey Form',
    'page callback' => 'mymodule_form_page',
    'access callback' => TRUE,
    'type' => MENU_CALLBACK,
  ];
  return $menuitems;
}

function mymodule_form_page (&$page) {
  dpm($GLOBALS['_GET']['q']);
  $current_path = $GLOBALS['_GET']['q'];
  if ($current_path === 'myform-page') {
    $module = 'mymodule';
    $delta = 'mymodule_block';
    $block = block_load($module, $delta);
    $form_page = _block_get_renderable_array(_block_render_blocks(array($block)));
    return $form_page;
  }
}

function mymodule_page_alter (&$page) {
  $current_path = $GLOBALS['_GET']['q'];
  if ($current_path === 'myform-page') {
    $regions = ['top','header','footer_1','footer_2'];
    foreach($regions as $region) {
      foreach($page as $key => $value) {
        if ($region === $key) {
          unset($page[$key]);
        }
      }
    }
  }
}

```

After all of that, I clear cache and visit the "myform-page", er, page. All the undesired regions are gone (though their HTML wrapper DIVs are still rendered, but I'm okay with hiding those with CSS). I leave that page, going to the front page, for example, then manually type in the address for "myform-page" in the browser and hit enter. The header and footer regions are back!

The "mymodule\_page\_alter" function only runs once and never again until I clear cache again. The "mymodule" block loads, looks, and functions exactly how I want it to, except for the regions returning when I navigate back to the page. I've reproduced this in a virtual OS environment, so I'm afraid I done goofed. I just don't know where. I've tried using hook\_theme() to load a simple page template per info found here: PHP Output in module ...with varying results, ultimately with the undesired regions still showing up. Would anyone know why the page alter hook stops working after executing once? I'd appreciate everyone who can point me in the right direction.

# Answer
> 1 votes
I believe I resolved my issue. Both the page callback function and mymodule\_page\_alter function were in a mymodule.pages.inc file that is linked to in the mymodule\_menu function. Drupal doesn't like the hook being in the .inc file, so I moved it to the .module file, cleared cache, and reloaded the page. The form's page seems to be loading the content I want to see and nothing else, even after navigating away from the page and coming back to it later.

Lesson learned -- I'll just keep all API hooks in the module file unless taught to do otherwise. Or, unless hooks being outside of the .module file isn't possible anyway.

---
Tags: 7, theming, blocks, caching
---


# Question
Title: How to edit markup on existing pages using version 4 of the CKeditor library in Drupal 6?
I installed/enabled CKeditor version 4 (from its download page) to use it in a Drupal 6 site. It's working fairly well with one exception: editing markup on existing pages doesn't work.

What happens is, that old pages won't accept the changes. It's baffling: the code is correct and it shows up in the source, but it's not rendering on the page for nodes that were created before I installed CKeditor 4. For example, I have a line with a line break at the end of it, but the line breaks aren't showing up.

But for *new* pages, the line break works just fine. It's only the old nodes where it's not showing up.

And if I uninstalled CKeditor version 4 and go back to CKeditor version 3, the issue disappears.

Any ideas or recommendations?

# Answer
CKEditor Version 4.x is known to have 'some' issues, at least when used in DRupal. The issue you described in the question here is probably one of them. And it doesn't matter if you use the CKEditor 'module', or the WYSIWYG 'module' (in combination with the CKEditor 'JS library'). Because for both modules these issues exist.

In my experience, going back to CKEditor 3.6.x version (or never upgrading from 3.x to 4.x) has always been the best "compromise", since in the 3.x versions these issues seem to not exist.
> 0 votes

---
Tags: 6, wysiwyg
---


title: Drupal Commerce Total Order Weight

text:
# Question
Title: Drupal Commerce Total Order Weight
I am writing a custom module to add surcharge values to a commerce order at the time of UPS shipping calculations. I am trying to find a way to access the total weight of the order.

I thought I would be able to access the weight from the array returned by:

`entity_metadata_wrapper('commerce_order', $order);`

Unfortunately it's not present in the data that I can see.

Does anyone know how I can access the total weight of an order or are these generated dynamically when the UPS shipping process is called?

# Answer
> 1 votes
I believe it is generated when it's needed, and not stored. But, after looking at the Commerce Order Weight Token module, you can get the weight using the following:

```
$weight = commerce_physical_order_weight($order);

```

# Answer
> 1 votes
Drupal Commerce itself doesn't require products to have weights, so there is no way for it to know what an order's total weight might be. However, the Commerce Physical Product module does at this support. I'm actually using that module for a project now and will be ensuring it has complete Rules support for the various API functions that determine whether or not an order / a particular line item is shippable and how much an order / a particular line item weighs.

---
Tags: commerce
---


# Question
Title: Splitting Drupal commerce order for easier shipping
During shipping we generally need to split the orders based on the availability of the products. Considering the order contains two products but only one product is available, we would like to split the order such that we can ship one product now and we can ship the the product later. Both split orders will contain same address and other details.

Are there any module that does this?

# Answer
> 2 votes
I'm not sure you need to consider this as order splitting. I'm working on a project currently that will make use of the Commerce Shipment module to handle splitting an order into shipments for fulfillment. It can accommodate either a single shipment per order or multiple if necessary.

---
Tags: commerce
---


# Question
Title: Editting field collections with service api
I am trying to build an phonegap app which uses data of a drupal site. I need to update some informations with using app. For example I have nodes and users need to update field\_collections of a node. My nodes have field collection as:

```
"field_bundle_news":{
    "und":[
    {
        0:{ target_id: "308" }
    }]
}

```

I want to add some additional items or remove some of them with using service api. For example if I use put method with using "/node" endpoint I can edit some data of that node but I can not edit field collections.

Could anybody give me information about this problem with examples because actually I dont know drupal well I am learning it with implementing a mobile app.

# Answer
You must send acceptable field structure in order to create or edit the node

try to understand the field structure through Implementing hook\_node\_insert in custom module and watchdog the inserted node via watchdog and you will have the structure drupal uses to insert then build it when you create/edit node through services

```
function hook_node_insert($node){
  watchdog('node', json_encode($node));
}

```

after adding a node of the same type open dblog in your project and see that log, you could use pro.jsonlint to understand it well

Hope that helps
> 0 votes

# Answer
Field collections are actually separate entities. They get attached to nodes, but the collections themselves exist separately. When you look at the endpoint for the node, you see that it just gives you an entity ID as the value.

There's a sandbox module that could potentially help: https://www.drupal.org/sandbox/graber/2141747

Another alternative is to write your own resource endpoint that abstracts the field collection entity away for your specific project. In this example, you'd want to start with the noderesource.module file, as you wouldn't need your own schema definition: https://www.drupal.org/node/783460
> 0 votes

---
Tags: entities
---


title: Bootstrap search form wrapper alter

text:
# Question
Title: Bootstrap search form wrapper alter
I am using the 7.x-3.0 version of Bootstrap and have sub themed it. I want to change wrapped div, add 'input-group-sm' to the class bit I can't not figure out how to override it. if I add search-block-form.tpl.php to my sub theme I can access and alter that but the code I need is in bootstrap-search-form-wrapper-func.php I have copied that to my sub theme with no success. I have tried replicating the same file structure as Bootstrap 'mytheme/theme/bootstrap/bootstrap-search-form-wrapper.func.php', I have tried putting just in my templates dir.

My last attempt was trying to follow the instructions on theme registry alters: https://www.drupal.org/node/2224003 which I have as this:

```
function CFbootstrap_theme(&$existing, $type, $theme, $path) {
  $hooks['CFbootstrap_hook'] = array(
    'CFbootstrap_search_form_wrapper' => array(
      'render element' => 'element',
    ),
  );

  bootstrap_hook_theme_complete($existing, $theme, $path . '/theme');
  return $hooks;
}

```

Nothing works, what I am doing wrong? How do I override this \*.func.php?

# Answer
> 2 votes
OK, I have this figured out, I think I just got confused by instructions and getting ramped up again on the ways of Drupal. Anyway just to leave a clear answer. All subthemes will be called *MYTHEME*. In my template.php in my subtheme I altered the form and then added hook to my new form wrapper:

```
function MYTHEME_form_alter(&$form, &$form_state, $form_id) {
if($form_id) {
    switch ($form_id) {
        case 'search_form':
            dpm($form);
            $form['basic']['keys']['#theme_wrappers'] = array('MYTHEME_search_form_wrapper');
            break;
    }
  }
}

function MYTHEME_theme(&$existing, $type, $theme, $path) {
  $hooks = array(
      'MYTHEME_search_form_wrapper' => array(
      'render element' => 'element',
      'file' => 'MYTHEME-search-form-wrapper.func.php',
    ),
  );

  return $hooks;
}

```

In this I copied the original wrapper file and made my changes, you could just copy the method and add it to your template.php anyway here's that method, referenced earlier as '*MYTHEME-search-form-wrapper.func.php*':

```
function MYTHEME_MYTHEME_search_form_wrapper($variables) {
  $output = '<div class="input-group input-group-sm">';
  $output .= $variables['element']['#children'];
  $output .= '<span class="input-group-btn">';
  $output .= '<button type="submit" class="btn btn-default">';
  // We can be sure that the font icons exist in CDN.
  if (theme_get_setting('bootstrap_cdn')) {
    $output .= _bootstrap_icon('search');
  }
  else {
    $output .= t('Search');
  }
  $output .= '</button>';
  $output .= '</span>';
  $output .= '</div>';
  return $output;
}

```

Key here is having the subtheme name twice in the method call. The instructions I found on this didn't give an explanation on why that needs to be. I'll try to find relevant information.

# Answer
> 0 votes
The array structure is wrong, since it should be the following.

```
  $hooks['CFbootstrap_search_form_wrapper'] = array(
    'render element' => 'element',
  );

```

What they show as `'theme_key'` doesn't mean `'<put here your theme short name>_key'` but `'<put here the theme function name>'`. See for example the implementation of `hook_theme()` done from the Node module, which contains the following code.

```
 return array(
    'node' => array(
      'render element' => 'elements',
      'template' => 'node',
    ),
    'node_search_admin' => array(
      'render element' => 'form',
    ),

    // …
  );

```

Notice also that calling `bootstrap_hook_theme_complete($existing, $theme, $path . '/theme')` is not anymore necessary with the Bootstrap theme 7.x-3.1.

---
Tags: hooks, theming
---


# Question
Title: How to remove the RSS feed icon form the content listing pages?
I need to remove the syndication icon because I'm either not going to syndicate or I want to do it my own way.

# Answer
If it's just the feed icon you need to kill, you could always just comment out or delete the line:

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

```

from page.tpl.php?
> 7 votes

# Answer
If you have Omega theme comment out this line

```
<?php if ($feed_icons): ?><div class="feed-icon clearfix"><?php print $feed_icons; ?></div><?php endif; ?>

```

It is in region--content.tpl.php
> 2 votes

# Answer
better bet is to use David Norman's (deekayan) Jammer module.

Install it and then enable the following module's:

1. Feed Icon Jammer
2. Feed Jammer

the first, of course, removes the icon, and the second prevents the front page from being published as an RSS feed. Thank you
> 2 votes

# Answer
See Port to Drupal 7; a Drupal 7 version of RSS permissions is in the works and may already have some of the functionalities you require.
> 0 votes

# Answer
As marblegravy correctly suggest you should indeed remove the link from your theme. This is different for each theme, but for example in Bartik you can remove the following line in page.tpl.php:

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

```

Just search for *RSS* or *feed* and you should find the link.

Additionally to prevent some smart crawler from accessing the feed, you can block access to it by implementing hook\_menu\_alter in a custom module. E.g. as follows:

```
/**
 * Implements hook_menu_alter().
 */
function MYCUSTOMMODULE_menu_alter(&$items) {
  $items['rss.xml']['access callback'] = FALSE;
}

```

For more fine grained control I recommend the module RSS permissions
> 0 votes

---
Tags: 7
---


title: drush uli command goes to wrong domain

text:
# Question
Title: drush uli command goes to wrong domain
I'm new to the command line, having trouble understanding why the uli drush command is taking me to the wrong domain.

On Pantheon, the dev site address is: dev-example.pantheon.io

I've successfully installed drush and all the aliases I need. However, when I enter this command:

```
drush @pantheon.example.dev uli

```

It takes me to wrong domain: wrongsite.com/user/reset/1/1....A/login

It should be: dev-example.pantheon.io/user/reset/1/1....A/login

I can login as user1 if correct the domain in the address bar. But what's happening here and how do I fix default domain?

Thanks!

# Answer
This one was more obvious than I thought. Client added bogus domains to the dev environment which caused the uli to go to the wrong site.
> 1 votes

# Answer
I just tested this using Drush 5, 6 and 7 on Pantheon (using Drush 7 locally), and also Drush 5, 6 and 7 locally (using Drush 7 on Pantheon), and all of those combinations worked for me.

Drush decides what domain to use by consulting the value of the --uri option. This is provided by the Pantheon aliases that you downloaded, so you might want to try downloading them again, just in case something is wrong in the alias file.

To test the alias, try `drush @pantheon.example.dev status`, and check the value of the `Site URI` line.

To select which version of Drush you are using, see this blog post on Drush policy files. Note that you must be using Drush 7 locally for this technique to work.
> 0 votes

---
Tags: drush
---


# Question
Title: Entity field query issue to correctly sorting my results
I have field `order` in my content type, in which I have assigned numeric values for my 21 products in order to sort them in ascending order. Results should be displayed like the below order as I expect:

```
1
2
3
4
5
6
7
8 and so on to 21.

```

But products are displaying in the following order:

```
1
10
11
12
13
14
15 up to 19 then
2
20
21
3
4
5
6 up to 9

```

I dont know why. Here is my snippet.

```
 $query = new EntityFieldQuery();
 $query->entityCondition('entity_type', 'node');
 $query->fieldOrderBy('field_order', 'value', 'ASC');
 $query->entityCondition('bundle', 'my_content_type');
 $query->pager(8,0);
 $query->propertyCondition('status', 1);

```

# Answer
> 0 votes
I can't make Molot's comment an answer, but I'll post one for posterity (and to close out this question).

The issue involves your data field type, integer vs. string. When the field is a string, sorting in SQL query will place the rows in lexicographic order, where the first character value is given precedence. When the field is an integer, sorting in SQL query will place the rows in numeric order, where the entire value of the number is used.

---
Tags: 7, database
---


title: Send an email from Drupal interface?

text:
# Question
Title: Send an email from Drupal interface?
How can I send an email from the D7 UI to specified email addresses?

I want to type in some text, type in some recipient addresses, and click send to send it from the site's address.

# Answer
An easy way could be using Rules and a custom content type.

The content type should have a title which can be used as the email title, a body for email body, and a field to hold email address(es) (or perhaps a reference field to site users or roles).

Then configure a new rule. Select new content event, add a filter to restrict to defined content type, then as an action select send email. Map the proper inputs and you are done.
> 1 votes

# Answer
There are innumerable ways to accomplish this. If you don't need to track the outgoing mail (keeping a copy on the server), I would do it this way:

* in a custom module, create a custom form containing the email elements (to, body, etc) inside a custom page
* use a module such as Simple Mail to create the actual mail

> A module to simplify sending emails with Drupal.
>
> There are many great modules for complex email handling and sending scenarios, or email templating, and Drupal core handles emails pretty well by itself. However, for many sites, a radically simplified email sending system is helpful.

This is probably a more advanced method fo accomplishing this, but if you haven't yet, and want to get into custom module creation, this is farely simple and would prove a good starter project. This has an advantage of being small and lightweight
> 1 votes

# Answer
Drupal isn't exactly meant as an email client, instead try doing it in a Drupal way.

For example:

* Enter a username for a recipient, add body, then send. Give Views Send a shot.
* Go to a user page, add body, then send. As in the bundled contact module.
> -1 votes

---
Tags: emails
---


# Question
Title: Catch the selection of the values in select/drop-down-box prior to the node submission
I have a Drupal 7 custom module with a couple of select/drop-down-boxes. Is there a hook to catch the selection of the values in those boxes prior to the submission of the content node? I am looking for a hook before the hook\_node\_submit occurs.

Thanks, Derek

# Answer
You might be looking for hook\_node\_presave()

> Act on a node being inserted or updated.
>
> This hook is invoked from node\_save() before the node is saved to the database.

To attach a custom submit handler, create a custom module and do something like this:

```
function my_module_form_alter(&$form, $form_state, $form_id)
{
  if($form_id == 'form_abc')
  {
    $form['#submit'][] = "my_module_form_submit_handler";
  }
}

function my_module_form_submit_handler($form, &$form_state)
{
  drupal_set_message("The form is being submitted, do some extra stuff now...");
}

```
> 0 votes

---
Tags: 7, hooks
---


# Question
Title: how to view data row table related to user only?
Good day, I need to create a view, which only shows data related to the user logged in user. When I have a user called "john smith", I create a contents as I like, BUT I don't want other users to see them.

A content can have multiple input from different users, so ONLY admin can see all content. while, each user, can only see his OWN content which he posted him self.

Think of it like a database system, where each student can add projects for his own records, but each student can see ONLY his own.

I tried looking around first, and I came across this question https://stackoverflow.com/questions/20840490/drupal7-filter-view-based-on-current-users-roles which seemed bit related, but I got lost in the too much explanation because they not entirely related to what I want to achieve.

In user roles permission, I perfectly found (add content, edit own content) but its missing one more thing which I want.."view own content"!!

I think it has something to do with filed permission, or something like when adding a content, set its permission to be view my that user only.

In coding the view to show ONLY table rows related to the that user, maybe something like this:

```
global $user;
if (in_array (student_field_name  == $user))
//view the row related to that user;

if (in_array('administrator', $user->uid))
//show ALL data rows available

```

To summarize, I want the user to be able to SEE his own data only. while admin will be able to see ALL content view of that page.

# Answer
> 3 votes
To create a view that is limited to content created by the current user (logged in) and Admin:

* create the view as you normally would
* Under Advanced, Relationship, create a relationship to Content:Author
* Create a Filter, User:Current, Logged in Yes, using the author relationship
* Create a filter, Author ID = admin
* Create a Filter Group (click on arrow next to Add on Filter Criteria)
* 'Create a new filter group' and make it look something like this:

This will limit the view to content only created by the currently logged in user and/or Admin, but does not limit access to the nodes themselves, for that you will need a module such as Node Access:

> Nodeaccess is a Drupal access control module which provides view, edit and delete access to nodes. Users with the 'grant node permissions' permission will have a grant tab on node pages which allows them to grant access to that node by user or role. Administrators can set default access controls per content type, and also define which roles are available to grant permissions to on the node grants tab.

# Answer
> 1 votes
In the View, add a contextual filter on Author: Uid, and use the following settings:

**WHEN THE FILTER VALUE IS NOT AVAILABLE:**

Provide default value Type: PHP Code

Use the following code:

```
global $user;

if (
    in_array('administrator', $user->roles) ||
    in_array('editor', $user->roles)
)
{return -1;}
else
{return $user->uid;}

```

**WHEN THE FILTER VALUE IS AVAILABLE OR A DEFAULT IS PROVIDED**

Specify validation criteria Validator: PHP Code

Use the following code:

```
if ($argument == -1)
{return FALSE;}
else
{return TRUE;}

```

Action to take if filter value does not validate: Display all results for the specified field (this is what will give admins access to all results) And that's it!

Notes:

Compared to my initial settings, the relationship (Content: Author) isn't needed anymore; neither is the "Author" filter (which was brought in by the relationship anyway).

Apparently, for Drupal 6 the condition in the first PHP snippet should rather be if (in\_array('super user', array\_values($user-\>roles))).

---
Tags: 7, views, users
---


# Question
Title: "This version is not compatible with Drupal 8.x and should be replaced."
The below theme files, which are the only files I have in my theme folder called 'Lychee', throw the error (in the 'Uninstalled themes' section of /admin/appearance):

> This version is not compatible with Drupal 8.x and should be replaced.

How should I resolve this? I followed this guidance: https://www.drupal.org/node/2349827

lychee.info.yml

```
name: Lychee
description: 'Mobile first theme.'
type: theme
core: 8.x
libraries:
  - lychee/global-styling
regions:
  - navbar: 'Navigation bar'
  - parallax: Parallax
  - content: Content

```

lychee.libraries.yml

```
global-styling:
  version: 1.x
  css:
    theme:
      assets/css/styles.css: {}

```

# Answer
Your regions section is slightly off. It should be:

```
regions:
  navbar: 'Navigation bar'
  parallax: Parallax
  content: Content

```

Note the removal of the `-` in front of each region.
> 1 votes

---
Tags: theming, 8
---


# Question
Title: Drupal 7: Display Latest Revision's Author on the Admin Content Overview page with Admin Views Module
Does anyone know the methodology to display the author of the latest content revision, using the Admin Views module on the content overview page (e.g. /admin/content)?

It's easy enough to display the initial author, or the VID of the latest revision, but I'm not sure how to create the relationship to the author of that latest revision and then display it.

Thanks!

# Answer
You need to add a relationship (Advanced \> Relationships) for "Content Revision: User". Make a note of the name of the relationship.

Add a field for "User: Name" and then make sure the relationship matches that of the relationship you added.
> 4 votes

---
Tags: views, nodes, users
---


# Question
Title: Drush installed globally via composer as root user, but how to access Drush with ordinary user?
By following the instructions on the Drush git page:

composer global require drush/drush:6.\*

I have Drush up and running (it seems to live in /root/.composer/vendor/drush/drush). But I imagine I shouldn't be running it via root. So how do I run it as my ordinary shell users?

When I try running drush it says command not found. Although it lets me use Composer. I tried installing Drush again through Composer while logged in as ordinary user without any luck. The Drush folder is also inaccessible..

# Answer
> 7 votes
To install for all users on the server:

```
curl -sS https://getcomposer.org/installer | php
mv composer.phar /usr/local/bin/composer
ln -s /usr/local/bin/composer /usr/bin/composer

git clone https://github.com/drush-ops/drush.git /usr/local/src/drush
cd /usr/local/src/drush
git checkout 7.0.0-alpha5  #or whatever version you want.
ln -s /usr/local/src/drush/drush /usr/bin/drush
composer install
drush --version

```

Personally I don't bother making the composer symlink from `/usr/local/bin` to `/usr/bin` and made the drush symlink to `/usr/local/bin` (rather than `/usr/bin`) as I have `/usr/local/bin` in my $PATH but YMMV...

Source: http://docs.drush.org/en/master/install/

---
Tags: drush, composer
---


# Question
Title: How to show different view templates for different taxonomy terms?
I'm using Drupal 7, and I had a vocabulary "Destinations". Under this vocabulary, I had terms with 2 levels. For example:

* ASEAN
-- Brunei
-- Indonesia
-- Laos
* EUROPE
-- Spain
-- Greence
-- Portugal

For all 1st level taxonomy terms of this vocabulary (ASEAN, EUROPE), I want to display them as a view, with child taxonomy. Eg:

* ASEAN
-- Brunei (term name & description)
-- Indonesia (term name & description)
-- Laos (term name & description)
* EUROPE
-- Spain (term name & description)
-- Greence (term name & description)
-- Portugal (term name & description)

For all 2nd level taxonomy terms, I want to display nodes which have the term. Eg:

* Brunei
-- Package 1
-- Package 2
* Spain
-- Package 3
-- Package 4

Is there any way I can configure the views to display result as above?
It might have something to do with contextual filter, but I don't know how to configure the parameters.

Any idea on how to achieve this?

# Answer
in child tpl of views taxonomy term check the parent of tid. if parent value is 0 then show data like "Brunei (term name & description)" And if parent not 0 then show like "Package 1"
> 0 votes

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


title: Shorten feed_item links on the fly

text:
# Question
Title: Shorten feed_item links on the fly
I am using ***feeds*** module. The site structure creates a new **feed\_item** for each item in the parsed rss

I want that upon the arrival of each ***feed\_item***, the link be shortened. I read about few related modules, but all require manual intervention.

I am ready to insert some api function into the feeds module, but where to insert it exactly, that is out of my knowledge. Please help.

Currently using ***Shurly***

# Answer
> 0 votes
Done using 'Shurly' and 'feeds\_tamper\_php' module.

After enabling both the modules, add

> Execute PHP Code

plugin to

> Feed Importer's field\_url

.

Execute the following code:

```
$shortUrl = shurly_shorten($field);
return $shortUrl['shortUrl'];

```

---
Tags: feeds
---


title: Edit message when new user created

text:
# Question
Title: Edit message when new user created
In configuration\>Account settings page, at the bottom of page under E-mails first option `Welcome(new user created by administrator)`, here I want to edit the body section and need to include link for my custom page `/unsubscribe`. I have gone through the available tokens but I did not fine any clue

# Answer
You might be looking for `[site:url]`. Alternatively, there is also `[site:url-brief]`
> 1 votes

---
Tags: 7
---


# Question
Title: Possible display options in Drupal views
I am a newbie into Drupal 7.
I am learning D7 views. I exported a view and found :

```
$handler->display->display_options['access']['type'] = 'perm';

```

with no permission array to specify the user group who can access this view.
Which user group does it take by default? Also, in my custom view in code I have replaced it with following:

```
$handler->display->display_options ['access']['type'] = 'role';
$handler->display->display_options['access']['role'] = array(
    3 => '3',
);

```

It is working fine. I want to know all possible values of $handler-\>display-\>display\_options this array. Where can I find all these options? Is there any documentation available for this?

# Answer
> 0 votes
Restrictions to access view can be set through Views UI to "role", "permission" or "none". See this page in Views documentation.

As for "role", those are IDs of different roles on your website. You can find those IDs in adiministration *admin/people/permissions/roles* \- just hower over role edit link, number is in its URL.

---
Tags: views
---


# Question
Title: Checkout a specific dev version of module using git
I want to checkout a specific dev version of the feeds module using git. I have a site which is using feeds 7.x-2.x-dev. On the modules admin page the module version number is reported as `7.x-2.0-alpha8+99-dev`.

I have cloned the feeds module repo but can't work out how to checkout that specific version. I tried using `git checkout 7.x-2.0-alpha8+99-dev`, but it didn't work. I guess if I knew the commit number I could check it out, but not sure how to easily work this out other than manually reviewing the commit log and working out what was the 99th commit after alpha8. I am hoping there might be an easier way.

Would appreciate any suggestions.

# Answer
This is more a git question than Drupal, but you can use `rev-list` command to retrieve a list of commit hashes since the `7.x-2.0-alpha8` tag. Using the tail command you can reverse the list to show the first 100 commits (I think the `+XX-` scheme is an offset from the first commit) then filter that down to the last result (which should be `+99-dev` commit).

```
git rev-list 7.x-2.0-alpha8^..HEAD  | tail -r -n 100 | tail -n -1

```
> 2 votes

---
Tags: version-control
---


# Question
Title: Drupal sites/default/settings.php issue on pantheon
I am a complete noob at this site business, and I'm facing what seems to be a very simple problem with my drupal site (hosted on pantheon):

I don't know where this file located nor how to copy it to the other .php files (whose location I also don't know). I would really appreciate *detailed* help.

# Answer
> 1 votes
On Pantheon you can simply go to your codebase where the root of Drupal installation is placed you will find directories like `includes, misc, modules, themes` and `sites` from here you need to go into `sites/default/` you will a file named `default.settings.php` you need to copy this file and place at the same location with name `settings.php`.

This is the main configuration file of your website and all config settings will go here.

---
Tags: 7
---


# Question
Title: How I can get nodes of type basic page of current month only in drupal views
I want to create a view which display result of current month only. If I will add post date field in filter then what operator I will choose and how i can get results.

# Answer
> 1 votes
Add 'Filter criteria' with the next settings

# Answer
> 0 votes
Create a date filter using the post or create date with a granularity of **month** and then in the relative date field, set it to be equal to **now** and that should do it.

---
Tags: views, 7
---


title: Updating to Drush 7 on OSX

text:
# Question
Title: Updating to Drush 7 on OSX
I had a working drush 5.6 (manually installed) on OSX (Yosemite) and decided I wanted to upgrade to the latest drush 7 version. I ended up with version 6.0-dev.

I followed the installation isntructions and decided to use homebrew to install composer and drush. So far so good, but the thing is, I can't seem to get to the latest "master" dev version: I'm stuck on 6.0-dev.

I tried different ways like:

```
brew install --HEAD drush
brew switch drush HEAD

```

and:

```
composer global require drush/drush:dev-master
composer global update

```

My composer.json looks like this:

```
{
    "require": {
        "drush/drush": "dev-master"
    }
}

```

which drush:

```
/usr/local/bin/drush

```

drush status:

```
 PHP executable        :  /usr/bin/php
 PHP configuration     :
 PHP OS                :  Darwin
 Drush version         :  6.0-dev
 Drush configuration   :
 Drush alias files     :  /Users/albert/.drush/aliases.drushrc.php

```

Any ideas?

# Answer
> 1 votes
You should add to your `~/.bashrc` file the additional PATH, e.g.:

```
# Add a Composer's global bin directory if exists.
which composer >/dev/null && export PATH="$HOME/.composer/vendor/bin:$PATH"

```

It should come first before your other drush. See my full .bashrc for details (bash4 syntax).

---

Alternatively install `drush` by specifying `COMPOSER_BIN_DIR`, like:

```
COMPOSER_BIN_DIR=/usr/local/bin composer global require drush/drush:dev-master

```

Assuming that `/usr/local/bin` is already in your `PATH`.

# Answer
> 0 votes
Upgrading to Drush 7

* Remove old Drush : brew uninstall drush.
* Install Composer : curl -sS https://getcomposer.org/installer | php && mv composer.phar /usr/local/bin/composer
* Get drush from homebrew : brew install --HEAD drush
* After that command has run, check the drush version : brew info drush
* If it's still on 6.x (which it shouldn't be), check to the HEAD version by running : brew switch drush HEAD
* Composer Install : cd /usr/local/Cellar/drush/HEAD/libexec && composer install
* Check your work : drush cc drush ; drush --version ;

---
Tags: drush
---


# Question
Title: Meeting Request With Webform submissions
I'm trying to send meeting request to user after they submit a webform.

In this webform, they can fill in a start date and stop date (for exemple).

And I would like to get the value of start date in the webform to use it in my meeting request.

I can send this meeting request with the code below:

```
function sendIcalEvent($from_name, $from_address, $to_name, $to_address,     $startTime, $endTime, $subject, $description, $location)
{
$domain = 'domain.tld';

//Create Email Headers
$mime_boundary = "----Meeting Booking----".MD5(TIME());

$headers = "From: ".$from_name." <".$from_address.">\n";
$headers .= "Reply-To: ".$from_name." <".$from_address.">\n";
$headers .= "MIME-Version: 1.0\n";
$headers .= "Content-Type: multipart/alternative; boundary=\"$mime_boundary\"\n";
$headers .= "Content-class: urn:content-classes:calendarmessage\n";

//Create Email Body (HTML)
$message = "--$mime_boundary\r\n";
$message .= "Content-Type: text/html; charset=UTF-8\n";
$message .= "Content-Transfer-Encoding: 8bit\n\n";
$message .= "<html>\n";
$message .= "<body>\n";
$message .= '<p>'.$description.'</p>';
$message .= "</body>\n";
$message .= "</html>\n";
$message .= "--$mime_boundary\r\n";

$ical = 'BEGIN:VCALENDAR' . "\r\n" .
'PRODID:-//Microsoft Corporation//Outlook 10.0 MIMEDIR//EN' . "\r\n" .
'VERSION:2.0' . "\r\n" .
'METHOD:REQUEST' . "\r\n" .
'BEGIN:VTIMEZONE' . "\r\n" .
'TZID:Romance Standard Time' . "\r\n" .
'BEGIN:STANDARD' . "\r\n" .
'DTSTART:16011028T030000' . "\r\n" .
'RRULE:FREQ=YEARLY;INTERVAL=1;BYDAY=1SU;BYMONTH=11' . "\r\n" .
'TZOFFSETFROM:+0200' . "\r\n" .
'TZOFFSETTO:+0100' . "\r\n" .
'TZNAME:Romance Standard Time' . "\r\n" .
'END:STANDARD' . "\r\n" .
'BEGIN:DAYLIGHT' . "\r\n" .
'DTSTART:16010325T020000' . "\r\n" .
'RRULE:FREQ=YEARLY;INTERVAL=1;BYDAY=2SU;BYMONTH=3' . "\r\n" .
'TZOFFSETFROM:+0200' . "\r\n" .
'TZOFFSETTO:+0100' . "\r\n" .
'TZNAME:EDST' . "\r\n" .
'END:DAYLIGHT' . "\r\n" .
'END:VTIMEZONE' . "\r\n" .
'BEGIN:VEVENT' . "\r\n" .
'ORGANIZER;CN="'.$from_name.'":MAILTO:'.$from_address. "\r\n" .
'ATTENDEE;CN="'.$to_name.'";ROLE=REQ-PARTICIPANT;RSVP=TRUE:MAILTO:'.$to_address. "\r\n" .
'LAST-MODIFIED:' . date("Ymd\TGis") . "\r\n" .
'UID:'.date("Ymd\TGis", strtotime($startTime)).rand()."@".$domain."\r\n" .
'DTSTAMP:'.date("Ymd\TGis"). "\r\n" .
'DTSTART;TZID="Romance Standard Time":'.date("Ymd\THis", strtotime($startTime)). "\r\n" .
'DTEND;TZID="Romance Standard Time":'.date("Ymd\THis", strtotime($endTime)). "\r\n" .
'TRANSP:OPAQUE'. "\r\n" .
'SEQUENCE:1'. "\r\n" .
'SUMMARY:' . $subject . "\r\n" .
'LOCATION:' . $location . "\r\n" .
'CLASS:PUBLIC'. "\r\n" .
'PRIORITY:5'. "\r\n" .
'BEGIN:VALARM' . "\r\n" .
'TRIGGER:-PT15M' . "\r\n" .
'ACTION:DISPLAY' . "\r\n" .
'DESCRIPTION:Reminder' . "\r\n" .
'END:VALARM' . "\r\n" .
'END:VEVENT'. "\r\n" .
'END:VCALENDAR'. "\r\n";
$message .= 'Content-Type: text/calendar;name="meeting.ics";method=REQUEST'."\n";
$message .= "Content-Transfer-Encoding: 8bit\n\n";
$message .= $ical;

$mailsent = mail($to_address, $subject, $message, $headers);

return ($mailsent)?(true):(false);
}
$from_name = "webmaster";
$from_address = "webmaster@domain.tld";
$to_name = "Name";
$to_address = "user@domain.tld";
$startTime = $date;
$endTime = "07/01/2015 02:00";
$subject = "Test Subject";
$description = "description";
$location = "FlowLine";
sendIcalEvent($from_name, $from_address, $to_name, $to_address,$startTime,$endTime, $subject, $description, $location);

```

So I use this code in my confirmation page.

BUT I would like that startime = \[submission:values:date\]... (date is a webform field name)

How can I make it possible? Maybe using the confirmation page is not the wright way...

I am not a developer, I would like to modify the webform code the less I can.

EDIT: I achieve this, like this:

* In the webform, I configure a Custom URL redirecting to a Basic Page.
* The Basic Page contain the PHP code to generate the appointment.
* In the custom URL, I use all the \[submission:values:\] I need.
* In the PHP script, I get the submission I need with some $\_GET\[var\];

# Answer
I have never worked with WebForms before, I normally build forms from scratch, but it does have a number of hooks available, you can see them here:

The general idea, would be to use something like `hook_webform_component_presave()`-

* Create a new custom module (this can be at theme as well, but module spans all themes); custom\_ical\_event is the module's short name I use in this exammple

custom\_ical\_events.info

```
name = Custom iCal Event
core = 7.x
description = Automatically sends an iCal Event after a webform submission

```

custom\_ical\_events.module

```
function custom_ical_event_webform_component_presave(&$component) {
  dpm($component);  // retrieve devel information for component array

  if (//form is the form you want) {
    // set data elements, $component contains the form submission data
    // input custom code, or better yet, a call to a function that incorporates
    // the custom code
  }
}

```
* You will need to do some sleuthing to get the correct information. I included a call to `dpm()` from the Devel module.

> A suite of modules containing fun for module developers and themers

Basically, you will need to check an element inside the component variable array to make sure you are looking at the correct form, and then access the data, which will depend on your set up of the webform itself, so I can't be more specific. `dpm()` will show the array structure, you just need to use the correct element (i.e. `if ($component->type == 'my_webform_type') ...`).

* Once everything looks good, remove the `dpm($component);` line.
> 1 votes

# Answer
I would imagine you will need to use hook\_mail\_alter to alter the properties of the outgoing e-mail, but I don't expect it to be easy or straightforward.

You may want to take a look at the Mime Mail module to try and understand how that module alters outgoing messages to allow HTML messages as by default Drupal only sends messages as plain text.
> 0 votes

---
Tags: webforms
---


# Question
Title: Customise Webform Email Submission Data 2
I had read some info from this content: How to use \[submission:values\] in Email template in Webforms

Submitted on \[submission:date:long\]
Submitted by user: \[submission:user\]
Submitted values are: \[submission:values\]

The results of this submission may be viewed at: \[submission:url\]

Name: \[submission:values:name:nolabel\] Address: \[submission:values:address:nolabel\]

I add last two code in the email setting, but it only print name: and address:

I also try this %email\_values %email\[name\], but it print out as string.

What wrong with my code?

Many Thanks.

# Answer
Are those fields inside a fieldset? This has tripped me up a few times.

Fields in a fieldset need to be \[submission:values:fieldset-name:name:nolabel\]
> 1 votes

---
Tags: 7, webforms, emails
---


# Question
Title: Memcache module is working but with a strange error
I have Memcache enabled both on Drupal and the server... It seems to be configured fine on the server-end (both by port & Settings.php).

If am being accurate, PSI grades even went up in about 4-5 points... So seemingly my site does use Memcache... And yet, Cron gives a strange error:

> PECL Memcache version 2.2.5 is unsupported. Please update to 3.0.6 or newer.

Tried to Google the error (or part of it) and found just nothing... I've also spoke with the server's support team and one of them told me to ignore this error... I'm not sure if this is the right thing to do... Will glad for the advice of Veteran drupal developers...

# Answer
"Not supported" doesn't necessarily mean that it shouldn't work at all. I guess in this case it only means you shouldn't complain in case something breaks.

You may want to check if you can install a newer version of Memcache on your platform, just to be sure and future-proof.
> 2 votes

---
Tags: caching
---


title: Captcha module configuration

text:
# Question
Title: Captcha module configuration
I am using the CAPTCHA module on my user registration form. I need to alter the error message from *What code is in the image? field is required.* to *My custom text*.

Is there any hook to alter the error message, or some other way to change it?

# Answer
Install the String Overrides module, search for the string, and replace it with your custom one.
> 0 votes

# Answer
Use the String Overrides module.

> Provides a quick and easy way to replace any text on the site.
>
> **Features**
>
> Easily replace anything that's passed through t() Locale support, allowing you to override strings in any language Ability to import/export \*.po files, for easy migration from the Locale module Note that this is not a replacement to Locale as having thousands of overrides can cause more pain then benefit. Use this only if you need a few easy text changes.
> 0 votes

---
Tags: 7
---


title: Documents as a node/block/field

text:
# Question
Title: Documents as a node/block/field
I'm working on my first Drupal site.

Using FileViewer I can load a PDF saved in a field, for viewing of various types. I haven't found something that does the same for Word Docs, Excel, etc.

Does anyone know of something that works in Drupal 7 to load documents other than PDF like FileViewer does inside a browser? Or like Scribd does (Scribd is hosted. I am behind a firewall with limited access for users. So I don't want to use a Scribd like service.)

# Answer
It seems that FileViewer has been folded into a module called PDF, which uses JavaScript to render PDF files.

So the next logical question is: How do you render Word docs, like Google Docs? And the answer is: Google Docs Integration module, which lets you show a list of Google docs, but doesn't let you display the documents.

Web searches give up nothing else.

Good luck...
> 1 votes

# Answer
You can use this plugin Embedded Google Docs Viewer

There are steps you should take:

1. Go to Structure -\> Content Types -\> YOUR\_TYPE -\> Manage Fields
2. Add a new field with type "File"
3. Go to Manage Display -\> YOUR NEW FIELD -\> Format and change it to Embedded Google Docs View

Your content will be displayed in an IFrame.
> 1 votes

# Answer
This question in Stack Overflow might help you: reading-writing-a-ms-word-file-in-php.

Note that that solution talks about a PHP interface to Microsoft office, not a Drupal module.
> 0 votes

---
Tags: 7, files
---


# Question
Title: Example of writing Latitude Longitude to a Geofield?
I need to write a lat/lon value to a Geofield and I can't figure out how to set the field. I would prefer to do this using EntityMetadataWrapper.

# Answer
And the answer:

```
    $entity_metadata_wrapper = entity_metadata_wrapper('node', $node_object);

    $data = array(
       'lat' => 44,
       'lon' => -93
    );

    $entity_metadata_wrapper->field_position->set($data);

```
> 5 votes

# Answer
Set Geofield using EntityMetadataWrapper if you only have the Longitude & Latitude information. (2015):

```
  $geofield_data = geofield_compute_values(array(
        'lat' => [Latitude],
        'lon' => [Longitude]
  ), GEOFIELD_INPUT_LAT_LON);

  $entity_metadata_wrapper->field_position->set($geofield_data);

```

When a geofield is saved using the provided widgets, these values are passed through the geofield\_compute\_values function in order to compute dependent values. By default dependent values are computed based on WKT, but this may be overriden to compute values based on other columns. For example, geofield\_compute\_values may be called like so:

```
geofield_compute_values($values, GEOFIELD_INPUT_LAT_LON);

```

This will compute the wkt field (and all other fields) based on the lat/lon columns, resulting in a point. As a developer this is important to remember if you modify geofield information using node\_load and node\_save. Make sure to run any modified geofield instances through geofield\_compute\_values in order to make all columns consistent.

See docs (bottom) for more details: http://cgit.drupalcode.org/geofield/plain/README.txt?id=7.x-1.x
> 4 votes

# Answer
This can be done without entity\_metadata\_wrapper() as:

```
$node_object->position[LANGUAGE_NONE][0] = array(
  'input_format' => GEOFIELD_INPUT_LAT_LON,
  'geom' => array('lat' => 44, 'lon' => -93),
);

```

(I know you said "preferably with EntityMetadataWrapper", but I just thought I'd throw this in for reference.)
> 1 votes

---
Tags: location
---


# Question
Title: Organic groups - The OG groups of the logged in user
I need to list all users from organic groups in which the current (logged in) user is an administrator member.

I manage to list all users from groups where current user is member (using relationship - OG membership: OG membership from User and contextual filter - The OG groups of the logged in user), but I can not manage to get only groups where the current user has administrator privileges.

Some idea?

Thank you.

# Answer
> 0 votes
You should try to use a contextual filter in views and add a Relation to the OG Roles.

1. Click on the advanced section in your view.
2. Add the contextual filter "Content: Groups audience (og\_group\_ref)"
3. Then select "Provide default value"
4. Choose "The OG groups of the logged in user" in the dropdown field
5. Add a relation "OG Roles from membership"
6. Add a filter "OG Role name" and choose the role you want to have

---
Tags: views, organic-groups
---


title: SagePay iFrame Theme Integration

text:
# Question
Title: SagePay iFrame Theme Integration
I am using the SagePay Integration Module. I have created template file for the cart summary / overview (page--cart.tpl). I have also crated hooks to alter forms on the next two pages mytheme\_form\_commerce\_checkout\_form\_checkout\_alter and mytheme\_form\_commerce\_checkout\_form\_review\_alter and configured template files for them using the mytheme\_theme hook. The templates are commerce-checkout-form-review.tpl.php and commerce-checkout-form-checkout.tpl.php.

Next I created a template file for the payment page, page--checkout--payment.tpl.php.

SagePay is configured to (only) use Sage Pay Server Integration - specifically **Display payment form in an iFrame** (can be found at /admin/commerce/config/sagepay).

After investigating the $page variable using Deval/kpr I decided to render

```
$page ['content']['content']['content']['system_main']

```

Here is a copy of the code in the template file (page--checkout--payment.tpl.php).

```
<?php if (isset($page['header'])) {?>
  <?php print render($page['header']); ?>
<?php }?>

<?php kpr ($page); ?>

<div class="content checkOutForm">
  <h2>PROCESS PAYMENT</h2>

  <table width="100%" border="0" cellspacing="5" cellpadding="5">
    <tbody style="color:#000;">
    <tr style="color:#000;line-height: 40px;">
          <th width="20%" align="center">YOUR BASKET</th>
          <th width="20%" align="center">BILLING DETAILS</th>
          <th width="20%" align="center">PAYMENT OPTION</th>
          <th width="20%" align="center"><strong>PROCESS PAYMENT</strong></th>
          <th width="20%" align="center">CONFIRMATION</th>
    </tr>
    </tbody>
  </table>

<p></p>

<?php print render($page ['content']['content']['content']['system_main']); ?>

</div>

<?php if (isset($page['footer'])) {?>
  <?php print render($page['footer']); ?>
<?php } ?>

```

The problem is this. The line

```
<?php print render($page ['content']['content']['content']['system_main']); ?>

```

renders the iFrame, but once that is done, the rest of the page does not get rendered. So the last part which needs to render the page\[footer\] is not executed.

I tried to save a copy of page\[footer\] at the beginning of the file, and then render this copy, but same result - footer does not get rendered.

I am assuming either the $page variable is lost / corrupted during the iframe render (unlikely), or the code stops executing after the iframe is rendered and we never get to the footer part (probably - but not sure why).

If I remove the line to render the iFrame, then footer prints out just fine.

My question is this - how I can render the SagePay iFrame form (in an iFrame) ensuring all relevant form fields (hidden, links, etc) is rendered correctly, and still render this inside one of my template files.

# Answer
So I had a couple of people asking about this here and on drupal.org - so I figured it would be easier to just tell you what I did.

in commerce\_sagepay/inc/commerce\_sagepay\_server.inc around line 120 there is a piece of code that reads:

```
  '#markup' => '<iframe style="width: 600px; height:500px" scrolling="no" frameborder="0" name="iframe_sagepay" id="iframe_sagepay" src="' . url('commerce_sagepay/sagepay_waiting_page') . '" />',

```

I changed this line to

```
  '#markup' => '<iframe style="width: 600px; height:500px" scrolling="no" frameborder="0" name="iframe_sagepay" id="iframe_sagepay" src="' . url('commerce_sagepay/sagepay_waiting_page') . '"></iframe>',

```

in other words - explicit close the iframe tag. It solved the problem for me.

Hope this helps someone.
> 0 votes

---
Tags: theming, commerce
---


# Question
Title: how to hide the facet api block if it has only one item?
I have to hide the Drupal facet API block if it has only one item. Is there any settings available or should I go with any hooks?

# Answer
Use the module facetapi\_bonus and you will get an option to hide a facet if the view has only X item(s)

This setting can be accessed through 'facets \> configure filters'
> 1 votes

# Answer
I tried this and it works for me.

function MYCUSTOMMODULE\_block\_view\_alter(&$data, $block) {

```
if($block -> module == 'facetapi' && !empty($data)){
    $key = $data['content']['#contextual_links']['facetapi'][1][2];
    $count = count($data['content'][$key]['#items']);
    if($count <= 1){
        unset($data['content']);
    }
 }

```

}

This is a generic one where it affects for all facets blocks site wide which I need.
> 0 votes

---
Tags: search, blocks
---


# Question
Title: How to redirecting add to cart form in drupal commerce programatically?
I just wants to redirect the add to cart form to a different page. After click on add to cart button i do not wants to go cart page. i just want to go thank you page.

for that i am altering the form

```
 if($form_id == 'commerce_cart_add_to_cart_form_1'){
            $form['submit']['#value'] = t("Submit Event");
            $form['#submit'][]= 'post_event_save';
    }

```

by using the above code i am able to redirect to post event save page but it will not stop in that page again redirect cart page after executing this post\_event\_save function.

## what i have tried post\_event\_save function

```
drupal_goto();
$form_state['redirect'] = false;
$form_state['rebuild'] = TRUE;

```

by printing the form\_state variable

```
[#validate] => Array
                (
                    [0] => commerce_cart_add_to_cart_form_validate
                    [1] => tasteusa_commerce_add_to_cart_form_validate
                )

            [#submit] => Array
                (
                    [0] => commerce_cart_add_to_cart_form_submit
                    [1] => post_event_save
                )

            [#after_build] => Array
                (
                    [0] => commerce_cart_add_to_cart_form_after_build
                    [1] => context_form_alter_node_after_build
                    [2] => test_commerce_after_build
                )

```

# Answer
> 3 votes
Check if you have any redirect rules enabled under `admin/config/workflow/rules`, which is force redirecting you to cart page.

As a solution you can have your custom redirection rule and disable the existing redirection rule, an example redirection rule which redirects to node/2 path after adding product to cart.

```
{ "rules_add_product_to_cart_redirect" : {
    "LABEL" : "Add Product to Cart Redirect",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "TAGS" : [ "add-to-cart-redirect" ],
    "REQUIRES" : [ "rules", "commerce_cart" ],
    "ON" : { "commerce_cart_product_add" : [] },
    "DO" : [ { "redirect" : { "url" : "node\/2" } } ]
  }
}

```

In case you import the above remember to change the redirect path from node/2 to your thank-you page.

---
Tags: commerce, forms
---


title: How to remove comma from taxonomy tags

text:
# Question
Title: How to remove comma from taxonomy tags
I want to style my taxonomy tags value. Actually In this Tags accepts comma separated value, so if I am rendering it on page it comes along with the comma.

I want separate values without comma.

How can I do that?

# Answer
Hope you are using views to display the nodes. If so, then click on the tags field in the Fields and in the "MULTIPLE FIELD SETTINGS" give space in the separator.
> 1 votes

---
Tags: taxonomy-terms
---


# Question
Title: How can I display a confirmation message after someone subscribes via simplenews?
I want to show a message after users submit their email in Simplenews block.

Currently when the user clicks on the subscribe button, the page is refreshed and no message shows ups.

Instead, I prefer to show a message with javascript in modal or something.

Any help/suggestions?

# Answer
Consider using the Rules module to implement this. And enable the `Simplenews rules` module (a sub-module of Simplenews).

Then create a rule like so:

* **Event**: "A user has been subscribed".
* **Action**: "Show a message on the site" (located within "System").
> 2 votes

---
Tags: emails
---


# Question
Title: looking for a complete documentation for Drupal's database schema - need to have some overview
well dear buddies,

i am pretty new to drupal. Just set up a drupal commons

now i 'd like to add some data to my drupal, and i dont really understand the database model/scheme. Can somebody point me to some documentation? For example i need to understand the role of node, vocabulary, and all the tables and what is tid,vid,nid fieds... Then i could add data the sql way.

Of course I don't think complete documentation for Drupal's database schema exists. Well does any body have a very very first attempt:

An ongoing attempt with comments for Drupal 6 can be seen here http://drupal.org/node/79874

An analysis with SchemaSpy i found here http://webdevgeeks.com/schemaspy/index.html

and overview i have seen here. http://upsitesweb.com/sites/upsites.co/files/drupal7\_model\_0.png

well who can give more hints - i love to hear from you - Again: i want to have some overview on the options i have to extend the group (running on http://www.schulcenter.org \- and see here http://schulcenter.org/?q=group/schulen )

How can i configure / extend the groups (/on the database-level)? How can i configure / extend the groups (/on the database-level)?

i wanna creat the following fields - (derived from the following shedule https://scraperwiki.com/scrapers/austrian-schools/ ) see the names of the collumns

* name
* adresse
* schultyp
* homepage
* ergänzender schulname
* beschreibung
* schwerpunkte

can this be done best in groups !? Can i this set in the groups. Or should i do that in the so called - organic-groups

**Note:** as you see the site schulcenter.org should give an overview on schools with a certain amount of data from the profile: the adress, the website..

* a little image (a thumbnail of the website - shown in a block,)
* a little description (approx 200 characters) what the site /the school does - some special programmes or something like that...

How to achieve this !? Love to hear from you any and all help will greatly be appreciated

love to hear from you zero

# Answer
Check Drupal's Schema API. Here is the link to it. Also the Book "Pro Drupal Development" has an excellent chapter on Working with Databases.You might find that one useful too.
> 2 votes

# Answer
There are two answers to your question.

1) Open up a drupal installation in a file browser. Go to `drupal/modules/node`. The core node module does two things: a) It implements an entity under the entity API (not to be confused with the Entity API contrib module), and it creates the Node API. Most people trying to create content types in code will use the Node API. Adventurous people will use the Entity API.

So... Look at `/drupal/modules/node/node.install`. This file implements hook\_schema(), which shows an abstracted version of the DB schema used by node, helpfully documented (to some degree anyway). If you want to hack around with nodes in SQL, then this is a good place to start learning the system.

2) Disregard answer #1. Use the Node APIs and Field APIs to manipulate Drupal data. This gives you the benefit of everyone's eyes on bugs, and not needing to update your code (as much) for future updates and upgrades. Poke around `node_example`, `nodeapi_example`, and `field_example` in the Examples project. This gives you good code to emulate/copy/paste.

HTH.
> 2 votes

# Answer
My favorite resource on Drupal's schema is Padraig O'Sullivan's Digging into Drupal's Schema:

http://posulliv.github.io/2012/08/02/drupal-er-diagram/
> 0 votes

---
Tags: views, database, 7
---


# Question
Title: Best way to export Commerce orders, line items, and customer profiles from live to dev?
I've got a massively diverged commerce development site, and I'd like to import all of the orders, line items, users, and customer profiles that have happened on the production site into my development site and then push the database back up to production.

I exported a bunch of tables and then ended up with a significantly borked dev site. Hmm.

I can continue to tweak my tables, but is there a better way to do this?

# Answer
I ended up exporting the tables from Sequel Pro using the "DROP TABLE IF EXISTS" syntax and then importing them (see screenshot).

If you don't use the DROP TABLE syntax (I believe this is the option in phpmyadmin) then just delete the tables before importing.

Basically, I spent a half an hour browsing the field\_data\_fieldname tables and others to see what sort of content they had and if they were pertinent to orders, line items, or users. I erred on the side of more db tables rather than less.

One of my field\_data\_fieldname fields was shared with other entity types, in addition to commerce\_order, and so rather than clobber the incoming values, I had to create INSERT queries. Using Sequel Pro cut and paste did that for me. Make sure to get the field\_revisions\_fieldname table as well.

Make sure you empty out your cart before you import, else the cart will point to a possibly non-existent order and throw an entity metadata wrapper exception.

Here's the full list of tables:

```
`commerce_customer_profile`;
`commerce_customer_profile_revision`;
`commerce_line_item`;
`commerce_order`;
`commerce_order_revision`;
`commerce_payment_transaction`;
`commerce_payment_transaction_revision`;
`field_data_commerce_customer_address`;
`field_data_commerce_customer_billing`;
`field_data_commerce_customer_shipping`;
`field_data_commerce_line_items`;
`field_data_commerce_order_total`;
`field_data_commerce_shipping_service`;
`field_data_commerce_total`;
`field_data_commerce_unit_price`;
`field_data_message_commerce_body`;
`field_data_message_commerce_line_item`;
`field_data_message_commerce_order`;
`field_data_message_commerce_payment`;
`field_data_message_order_display_name`;
`field_data_message_text`;
`field_revision_commerce_customer_address`;
`field_revision_commerce_customer_billing`;
`field_revision_commerce_customer_shipping`;
`field_revision_commerce_shipping_service`;
`field_revision_commerce_total`;
`field_revision_commerce_unit_price`;
`field_revision_field_phone_number`;
`og_role`;
`og_role_permission`;
`og_users_roles`;
`users`;
`users_roles`;

```
> 1 votes

---
Tags: commerce, importing-exporting
---


# Question
Title: If a vocabulary and a view have the same machine name, will they conflict when exporting to a same feature?
In other word, does the machine name of every type of Drupal object has its own scope? Do we need use some prefix?

# Answer
A vocabulary is an entity; before Drupal 8, a View is not. So ID collisions will never be a concern, they're different types of object, and treated as such. If a View *was* an entity (like in D8), then its properties would be unique to its entity-type, so there's still no concern.

Addressing this specifically:

> does the machine name of every type of Drupal object has its own scope?

If you consider a "Drupal object" to be an entity provided by the core API, then yes. Views doesn't use it, but its data is in a separate DB table so there's nothing to worry about. YMMV with different contrib modules, but usually if a features integration has been written, you can pretty much assume it's going to work at that most basic level.
> 3 votes

# Answer
If it's in a different table it's in a different scope. If it allowed you to set a similar machine name you are obviously in a different scope. If you go to a node page and try to create similar machine names you will get an error while adding the field.

`taxonomyTable.same_machine_name` is different from `viewTable.same_machine_name`

No they wont conflict when exported from features. on the features page it shows different sections like taxonomy terms, nodes, strongarm, image styles ect.. anything that could be related then it auto detects anything related and you can select what you want to go with it. That's why it's important to have unique machine names so you know right away what you are working with. When using features try to avoid using the same machine names; but you can get away with it
> 4 votes

---
Tags: 8
---


# Question
Title: Passing Settings from page.tpl to Javascript: Uncaught TypeError: Cannot read property
I want to pass this to my js file :
in **page.tpl**

```
<?php
$my_settings = array(
    'message' => $message,
);

drupal_add_js(
    drupal_get_path('theme', 'sizin') .'/js/anim.js',
    array('my_settings' => $my_settings),

    'setting');
?>

```

in **anim.js**

```
var message = Drupal.settings.my_settings.message;

```

i got this error from chrome:

```
Uncaught TypeError: Cannot read property 'message' of undefined

```

Any Help/Idea ?

and i've read this : Retrive $message variables in javascript file

# Answer
> 1 votes
You need two line to add your code. Before one line to add js data settings:

```
$my_settings = array(
  'message' => $message,
);

drupal_add_js(array('my_settings' => $my_settings), 'setting');

```

and one line function to add file js

```
drupal_add_js(drupal_get_path('theme', 'sizin') .'/js/anim.js', 'file');

```

And better you don't write code in file tpl. You cand add js file, js settings in hook\_preprocess\_page(). It's drupal standard and clean tpl file.

---
Tags: 7
---


# Question
Title: How to save multi date and time in node programmatically?
I want to save multi Date value in a node programmatically.

```
$node->field_event_date['und'][0]['value'] =?;
$node->field_event_date['und'][0]['value2'] =?;

```

getting the below value after print the form\_state

```
[field_event_date] => Array
                        (
                            [und] => Array
                                (
                                    [0] => Array
                                        (
                                            [show_todate] => 1
                                            [value] => Array
                                                (
                                                    [date] => 07/02/2015
                                                    [time] => 10:30AM
                                                )

                                            [value2] => Array
                                                (
                                                    [date] => 07/02/2015
                                                    [time] => 12:30PM
                                                )

                                        )

                                )

                        )

```

Getting error

```
$node->field_event_date['und'][0]['value'] =
    $form_state['input']['line_item_fields']['field_event_date']['und'][0]['value']['date'];

$node->field_event_date['und'][0]['value2'] = $form_state['input']['line_item_fields']['field_event_date']['und'][0]['value2']['date'];

```

But i need both date and time. I think i need to combine date and time and convert it into time stamp to save but do not understand how to combine and convert.

# Answer
If converting the two is your problem following may help you

```
foreach ($form_state['values']['field_event_date']['und'] as $key=> $value) {
  $node->field_event_date['und'][$key]['value'] = strtotime($form_state['values']['field_event_date']['und'][$key]['value']['date'] . ' ' . $form_state['values']['field_event_date']['und'][$key]['value']['time'])
}

```

strtotime() should be good enough.

I am assuming you are doing node\_save() some where.
> 1 votes

---
Tags: nodes, datetime
---


# Question
Title: Flexslider only showing to logged in users
My flexslider is only showing to logged in users. I'm using a view in a block and I've checked that the block is showing for all user roles. The View "Access" permissions are set to anyone that can view published content. Changing the Access value to "none" didn't seem to make any difference. The admin user still sees it, but anonymous users don't... Any suggestions ?

# Answer
> 0 votes
Not really a decent answer I'm afraid folks, but it turned out to be a conflict with the "Taxonomy Term Status" module.

The Flexslider was showing taxonomy terms, but when the term status module was turned on (which allows taxonomy terms to be "unpublished") The whole slider stopped being displayed.

# Answer
> 1 votes
I was having the same problem with Flexslider.

After checking all the permissions issues, I remembered that the content for my slides was "unpublished". I switched it to "Published" and, VOILA! It worked.

It's a common practice to have the slides "unpublished", so I don't know why this makes a difference, but it did.

---
Tags: 7, users, javascript
---


title: Views disappear upon logout

text:
# Question
Title: Views disappear upon logout
I haven't touched any default permissions for views in my site but they disappear for anonymous and authenticated users. In permissions 'view published content' is enabled for the mentioned roles. I have even tried rebuilding the permissions but no use.

I also checked permissions in views i.e, `Access` option in Block Settings and tried all combinations of it's options but still no use.

All other contents (shown through `print render($page['content'])`) are fine and displays upon logout but it's only the views that disppear.

I'm using Drupal 7.

I don't know what seems to be the problem, and what else to try.

# Answer
I solved the problem by enabling the `Disable SQL Rewriting` option in `Query Settings` in my views. This action might have some security implications so lets hope for the best for now.

You can find the discussion here.
> 1 votes

# Answer
I was having the same problem with Flexslider.

After checking al lthe permissions issues, I remembered that the content for my slides was "unpublished". I switched it to "Published" and, VOILA! It worked.

It's a common practice to have the slides "unpublished", so I don't know why this makes a difference, but it did.
> 0 votes

---
Tags: views, nodes
---


# Question
Title: The connection to the server was reset after trying to log as admin to Drupal
I did upgrade on Drupal 7 and imported these sites and database from localhost to another server. On localhost everything works well, on the server I can´t log to Drupal as admin. After entering password every browser shows similar message:The connection to the server was reset while loading page. When I want to change address in browser after that I have to delete all history, cookies, cache, etc., otherwise it writes the same message. I changed base\_url, cookie\_domain in settings.php, deleted cache and session tables in database. It didn't help.

**Notes**:

* Putting `/?=admin` doesn't work, I am redirected to homepage, even on my localhost page where I can login `.htaccess` has the same content as old `.htaccess`
* My pages are on web hosting. I am not sure if I can restart webserver by myself.
* About server log messages: any special thing except of missing of `favicon.ico` in folder. I repaired it.
* I tuned the `.htaccess` file. I don't see effect for a while. Maybe after server restart?
* I don´t have Coder module.
* my web hosting doesn't allow me increase stack size. Is this problem always connected with some Drupal module? Is somewhere some list of Drupal modules which causes page reset after admin login? Code module isn't my case.

This problem was finally solved by Php upgrade on the side of hosting server!

# Answer
> 2 votes
# Restart webserver

Might be a webserver issue. Try restarting you webserver and check if it solves your issue.

# Check server logs

If that doesn't help either, check your webserver's error log to see if there is any special error message in these that helps.

# Tune the .htaccess file

Modified the .htaccess file and replace the default clean URL rewrites with this:

```
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} !=/favicon.ico
RewriteRule ^(.*)$ index.php?q=$1 [L,QSA]

```

# Coder module

1. **Option a**: Remove the Code module

A complete different reason for this issue is Coder makes Drupal go to "Connection was reset" browser error. So if you have the Coder module installed/enabled, then disable and uninstall it and ALSO remove that module from the module folder.
2. **Option b** (if using WAMP): increase the stack size

Be aware that `preg_match_all` uses the stack which may be too small. PHP crashes and then Apache crashes (and restarts). The fix is to increase the stack size to match a default Linux PHP Apache setup. To do so, increase the Apache stack size to 8MB by adding a line to the end of `httpd.conf` (surrounded by a `IfModule mpm_winnt_module` and matching `/IfModule` tag):

> ThreadStackSize 8388608

After restarting the webserver you can then use any version of the Coder module (and other modules which have this issue ...).

More details: https://www.drupal.org/node/1597820#comment-6094060

---
Tags: 7, users, migrations, .htaccess, upgrading
---


# Question
Title: How can I create a custom html tag in the CKeditor wysiwyg editor?
I've created a custom HTML tag that pulls information from my database and displays it. Basically it uses `preg_match_all` to parse the body of articles for `<profiletag>Person Name</profiletag>` and replaces this tag with html of the person's profile.

Now what I want is to allow my writers to insert this HTML (`<profiletag>Person Name</profiletag>`) from the WYSIWYG editor rather than having to go into the source and insert a tag into the html. When they write `<profiletag>` etc. in the WYSIWYG editor obviously it gets all messed up. I'm looking for something like \[profile\]Person Name\[/profile\] markup for them to include these tags in the WYSIWYG side.

Is this possible, and if so how can I implement this functionality?

# Answer
What you need is a custom filter. Filters are the check boxes you can set on input formats like 'Filtered HTML' and 'Full HTML'.

There is an example available in the examples module: https://www.drupal.org/project/examples

Basically, you need this:

1) You need to implement hook\_filter\_info() to let Drupal know there is a new filter 2) You need to a function to process the input. This is where you can use your regex.

I highly suggest looking at the examples module or any other modules that use filters.
> 1 votes

---
Tags: 7, wysiwyg
---


# Question
Title: How can i change the confirm page text in simplenews
how can I change this text or translate it:

```
Are you sure you want to add s*****@y*****.com to the sizing mailing list?

You can always unsubscribe later.

```

this is the page after click on confirm link in email ?

I've tried string override module but it can't change that .

# Answer
> 1 votes
A grep on the simplenews module shows the text is coming from simplenews.subscription.inc file from following code.

on around line #582

```
/**
 * Generate the confirm subscription form.
 *
 * @see simplenews_confirm_add_form_submit()
 */
function simplenews_confirm_add_form($form, &$form_state, $mail, $newsletter) {
  $form = array();
  $form['question'] = array(
    '#markup' => '<p>' . t('Are you sure you want to add %user to the %newsletter mailing list?', array('%user' => simplenews_mask_mail($mail), '%newsletter' => _simplenews_newsletter_name($newsletter))) . "<p>\n",
  );
  $form['mail'] = array(
    '#type' => 'value',
    '#value' => $mail,
  );
  $form['newsletter'] = array(
    '#type' => 'value',
    '#value' => $newsletter,
  );

  return confirm_form($form, t('Confirm subscription'), '', t('You can always unsubscribe later.'), t('Subscribe'), t('Cancel')
  );
}

```

since it is a form, you can simply implement hook\_form\_alter() to override 'question' field markup from your custom module, something of following sort

```
function my_module_name_form_alter(&$form, &$form_state, $form_id) {
  if($form_id == 'simplenews_confirm_add_form') {
      $form['question'] = array(
       '#markup' => t('Your Custom Confirmation Message Here'),
      );
  }
}

```

---
Tags: 7, emails
---


# Question
Title: Anonymous users can't use personal contact forms
I'm using the core Contact module, with personal contact forms on profile pages. I set both the permissions "Visit user profile" and "Use users' personal contact pages" for anonymous users, but I still just get a 403 when trying to view a user's contact page when logged out.

I am using Pathauto (and Subpathauto) for user profiles; I don't think that's the issue but it's worth mentioning.

Also, this is occurring on Drupal 7.

# Answer
Assuming that the anonymous users are not trying to access user/0/contact (which would not be an ordinary case), the reasons why they cannot access the contact for a an authenticated user A are essentially 3:

* User A didn't enable the contact form
* The setting for enabling the contact form for user A has not been yet saved
* The anonymous user sent too much messages

In the first two cases, it's the access callback for the user's contact form that block the access, using the following code. (See the comment before the code.)

```
// If the requested user has disabled their contact form, or this preference
// has not yet been saved, do not allow users to contact them.
if (empty($account->data['contact'])) {
  return FALSE;
}

```

In the third case, it's the form builder that returns an *access denied* page.

```
// Check if flood control has been activated for sending e-mails.
  $limit = variable_get('contact_threshold_limit', 5);
  $window = variable_get('contact_threshold_window', 3600);
  if (!flood_is_allowed('contact', $limit, $window) && !user_access('administer contact forms') && !user_access('administer users')) {
    drupal_set_message(t("You cannot send more than %limit messages in @interval. Try again later.", array('%limit' => $limit, '@interval' => format_interval($window))), 'error');
    drupal_access_denied();
    drupal_exit();
  }

```

Notice that in last case, the default limit is 5 messages in a hour, and that limit is cumulatively valid for any user sharing the same IP, as `flood_is_allowed('contact', $limit, $window)` executes the following code.

```
if (!isset($identifier)) {
  $identifier = ip_address();
}

```

If you are not seeing any error message from Drupal ("You cannot send more than \[…\]") and the enabled theme or any module is not hiding the error messages, I would assume the users didn't enable their contact form, or the setting to enable the contact form was not yet saved.
> 4 votes

# Answer
Contact Form will not work for existing users, when I say existing users I mean users who are before turning on contact module and adding configurations. Check under `admin/config/people/accounts` Creating new user, and then try accessing the page.
> 2 votes

---
Tags: users, emails
---


# Question
Title: Font Awesome not working when using HTTP
We have 2 subdomains for a website in order to test our development before moving to production. This is our structure:

* subdomainA.mysite.com
* subdomainB.mysite.com
* mysite.com

When I enter to subdomainB.mysite using http protocol (`http://subdomainB.mysite.com`) the font awesome icons are not being displayed. Instead of that in the console shows up this:

> Font from origin `http://subdomainB.othersubdomain.mysite.com` has been blocked from loading by Cross-Origin Resource Sharing policy: The 'Access-Control-Allow-Origin' header has a value `http://someWebService.ws` that is not equal to the supplied origin. Origin `http://subdomainB.mysite.com` is therefore not allowed access.

With respect to "`othersubdomain`", that corresponds to another subdomain used for other applications and it shouldn't be interfering with subdomainB.

Now, if I enter the site using https (`https://subdomainB.mysite.com`) the icon fonts are being displayed and nothing goes on the console, which is good.

On the other hand, when I test in our first subdomain (`subdomainA.mysite.com`) either I am testing with http or https the iconfonts load fine.

We have the module CDN off in subdomainA and on in subdomainB. At first I thought this was the problem but I turned off the module in subdomainB, cleared registry and test for awhile and the problem remained the same.

Lastly, we have the font awesome library inside the core of our drupal installation so we are not calling this library from a remote location.

# Answer
Not exactly sure if this is the issue, but when I've had CORS errors with web fonts the following Apache directive in **.htaccess** has worked for allowing any Origin for those files:

```
<IfModule mod_headers.c>
  <FilesMatch "\.(eot|otf|tt[cf]|woff)$">
    Header set Access-Control-Allow-Origin "*"
  </FilesMatch>
</IfModule>

```
> 0 votes

---
Tags: cdn, http-request
---


title: Drupal Pay user for X amount by Admin

text:
# Question
Title: Drupal Pay user for X amount by Admin
I have this project that an agent(user) is having a commission on every product that they are selling. The admin should pay the commission through the back end side by using the payment information (paypal email or any) provided by the agent.

What module should I use on this one?

# Answer
Checkout the Commerce Affiliate module that is used with Drupal Commerce (or UC Affiliate if you're using Ubercart).
> 0 votes

---
Tags: 7, commerce
---