# Question
Title: How to set roles of drupal "and" with each other?
I need to show a block to users who have multiple roles. For example: accountant and employee. I do not want to use permissions. I need a simple solution.

is there anyone who can direct me?

# Answer
> 2 votes
You could use hook\_block\_view\_alter() in your theme's template.php

```
function MYTHEME_block_view_alter(&$data, $block) {
  global $user;

  $roles = array('accountant', 'employee');
  $required_roles = array_diff($roles, $user->roles);

  if ($block->delta == 'YOUR-BLOCK-DELTA' && !empty($required_roles)) {
    $data['content'] = $data['subject'] = NULL;
  }
}

```

The array\_diff() here will check that the roles the user needs to have appear in the user's roles array. If either accountant or employee do not appear in $user-\>roles it will set the block's content/subject to NULL and Drupal will not display it.

# Answer
> 1 votes
You can use Context module which has possibility to display content and it supports AND/OR operations for specific conditions (such as role selection).

# Answer
> 0 votes
You can show a block for specific roles on the configurationpage of the block. Navigate to admin/structure/block and click "configure" next to the block you want to set the restrections. Then scroll down to "visibility settings" and select for which roles the block must be visible:

---
Tags: users
---


# Question
Title: How to avoid clearing the cache after every CSS change?
I use D7 and I'm tired of clearing the cache after every css change (I make lot's of changes to my online site, about ten's in a day)... Clearing the cache ten's of times a day consumes too much life time for me and I really had enough of it.. Yes - Even if it is made by the **Admin Menu** module.

Is there any way to temporarily disable the cache or something of the sort?

Notes: Screenshot of my Performance settings attached.

* Clicking ctrl+R never helps
* Clicking ctrl+F5 never helps

# Answer
On the `admin/config/development/performance` page under 'Bandwidth optimization' uncheck "Aggregate and compress CSS files.".

If you're looking for more control https://www.drupal.org/project/advagg/ is what you're looking for. Using the development setting in AdvAgg will detect the changes and push them out automatically.
> 12 votes

# Answer
First thing is to make sure that you've disabled all caches and CSS aggregation in your Performance page.

Then you can activate 'Rebuild theme registry on every page.' option available in Theme development settings which you can find in Admin/Appearance for your default theme.
> 1 votes

---
Tags: theming, caching
---


# Question
Title: How do I change the rate modules output to "# of users like this"?
I am using the Rate module.

The current display for my thumbs up widget is:

```
(thumbs up image) 2 users have voted, including you.

```

I would like to change it to:

```
(thumbs up image) 2 users like this

```

How do I change the default tpl to accomplish this?

```
print $up_button;

if ($info) {
  print '<div class="rate-info">' . $info . '</div>';
}

if ($display_options['description']) {
  print '<div class="rate-description">' . $display_options['description'] . '</div>';
}

```

# Answer
> 2 votes
I haven't used the module. But looking at the code, you essentially need to override the preprocess function in the module which is used to generate the string.

Open `rate.module` in an editor and search for the text string that you are looking to change. In this case, this string would be something like "*have voted*", which should lead you to the function named `rate_preprocess_rate_template_thumbs_up()`. This is the function that you should look to *override*. You can see that the strings are added as part of two `format_plural` calls and should be straightforward to amend in the override function.

You can perform the override either from a custom module or from your theme's `template.php` file. Since the module is using a *preprocess* function to make its changes, I recommend using a *process* function (note the difference in name) when you override it. There should be plenty of documentation and examples available on drupal.org and drupalSE to aid you if you are unfamiliar with overriding.

# Answer
> 0 votes
Use the String Overrides module and add the following to the config:

original: @count users have voted, including you.
replacement: @count users like this.

---
Tags: 7, rating
---


title: How to use geofield migrate extras

text:
# Question
Title: How to use geofield migrate extras
I can not understand how to use migrate\_extras and for example how to use geofield migrate extra support.

I have create a Migration class that work. In my "source" I have 2 "fields" called latitudine and longitudine. I have follow the instruction that I have found in geofiled.inc:

```
$geo_arguments = array(
  'lat' => array('source_field' => 'latitudine'),
  'lon' => array('source_field' => 'longitudine'),
);
// The geometry type should be passed in as the primary value.
$this->addFieldMapping('field_coordinate', 'Point')->arguments($geo_arguments);
// Since the excerpt is mapped via an argument, add a null mapping so it's
// not flagged as unmapped.
$this->addFieldMapping(NULL, 'latitudine');
$this->addFieldMapping(NULL, 'longitudine');

```

But my "test node" is created (via migrate) without "geofileld" field (field\_coordinate). But if I comment the lines above and insert this function:

```
public function prepare($node, stdClass $current_row) {
  $node->field_coordinate = array(LANGUAGE_NONE => array(0 => array(
    'geom' => 'POINT ('.$current_row->longitudine." ".$current_row->latitudine.')',
    'geo_type' => 'point',
    'lat' => $current_row->latitudine,
             'lon' => $current_row->longitudine,
             'left' => $current_row->longitudine,
             'top' => $current_row->latitudine,
             'right' =>$current_row->longitudine,
            'bottom' => $current_row->latitudine,
   )));
}

```

"geofield field" is "created".

Where is my error?

# Answer
> 6 votes
Using arguments is deprecated.

Now you can migrate geofields **without migrate\_extras**.

```
$this->addFieldMapping('field_location', 'point');

```

And in your prepare row

```
public function prepareRow($row) {
 $row->point = 'POINT (' . $row->longitude . ' ' . $row->latitude. ')';
}

```

# Answer
> 2 votes
Ok, I have found the solution.

From geofield.inc: "Primary value passed to this field must be the geometry type of the geofield: Point, LineString, Polygon" But this need to be passed in a different way:

* in the "prepareRow($row)" I need to set "Point" like a current row field:

```
public function prepareRow($row) {
[...]
   $row->geo_type = 'point';
[...]
}

```
* and in the \__construct() function the right line is:

```
$this->addFieldMapping('field_coordinate', 'geo_type')->arguments($arguments);

```

Now it works.

M.

# Answer
> 0 votes
Use of arguments is now deprecated. You will get this error:

> The field mapping arguments() method is now deprecated - please use subfield notation instead.

To migrate geofield (2.0) using **migrate\_extras** apply the patch in https://drupal.org/node/1997316.

Code using subfield notation:

```
$this->addFieldMapping('field_location', 'point');
$this->addFieldMapping('field_location:input_format', 'input_format');
$this->addFieldMapping('field_location:geo_type', 'point');
$this->addFieldMapping('field_location:lat', 'latitudine')
   ->xpath('Latitude');
$this->addFieldMapping('field_location:lon', 'longitudine')
   ->xpath('Longitude');

```

Inside prepareRow():

```
public function prepareRow($row) {
  ...
  $row->geo_type = 'point';
  $row->input_format = 'lat/lon';
  ...
}

```

# Answer
> 0 votes
Got it to work without migrate\_extras:

in your prepareRow() use:

```
 $row->point = 'POINT (' . $row->longitude . ' ' . $row->latitude. ')';

```

and in the construct:

```
$this->addFieldMapping('field_location', 'point');
$this->addFieldMapping('field_location:geom', 'point');
$this->addFieldMapping('field_location:geo_type')->defaultValue('point');

```

---
Tags: 7, migrations
---


# Question
Title: Landing page extension without 404 error
I have a problem concerning a landing page and 404 errors.

**Context :** I have a content type "news", with auto url /news/my-news-title. I have created programmatically a kind of homepage for news, with /news as URL

**What's wrong :** My problem is that if I have a link like /news/aiejaziejfnjdfnj (it doesn't exist), I don't have a 404 error and this is my /news landing page which is shown. What I wish, with you help, is to have a 404 error when I have a non existant URL.

I'm going to show you what I have done, and hope sincerely you'll have an idea of what i'm doing wrong. In a custom module, I have :

```
function mymodule_menu(){
    $items = array();
    $items['news'] = array(
       'title' => "Les news",
       'page callback' => 'landing_page',
       'access arguments' => array('access content'),
    );
    return $items;
}
function landing_page(){
    return "nothing";
}

```

Then, I have a template page--news.tpl.php in which I have write things manually without showing $content (the "nothing").

So, why /news/aizejziej is accepted and is showing /news ? Is it function landing\_page() which is doing something bad by always returning something ?

Thanks in advance for your help/ideas :)

**Edit :** Is it possible to create a node with /news as alias, and then theme it with page--node--\[node-id\].tpl.php (or kind of) ? I'll didn't have my bad hook\_menu and landing\_page thing...

# Answer
> 2 votes
Like @Clive said, Drupal will try to resolve that path if it can. Just put a check in your page callback to see if there's an extra argument. If there is and it's valid the menu router will handle it. Otherwise it will fall back to your defined path, where if it finds something after /news, it will return `drupal_not_found()`. The 'return' is important, otherwise you might see the page render twice.

```
function MYMODULE_menu(){
    $items = array();
    $items['news'] = array(
       'title' => "Les news",
       'page callback' => 'landing_page',
       'access arguments' => array('access content'),
    );
    return $items;
}

function landing_page(){
    if (arg(1)) {
        return drupal_not_found();
    }

    return 'something';
}

```

---
Tags: theming, routes
---


# Question
Title: How can i use bootstrap js library in my theme?
I use bootstrap drupal theme. And i want to use collapse.

I added in theme.info the library path bootstrap.js have cleaned the cache, but after using the following code generates only the button, but the content is not deployed.

```
      <a class="btn btn-primary" data-toggle="collapse" href="#collapseExample" aria-expanded="false" aria-controls="collapseExample">

```

Most likely is not initializing bootsrap.js, please tell me how to fix it?

# Answer
Yes i fixed this problem by using jQuery with more higher version.
> 0 votes

---
Tags: javascript
---


# Question
Title: what is the URL I should use to edit a user account?
I need to edit user account data via services module

I tried `endpoint/user, endpoint/user/UID, endpoint/user/UID/edit, endpoint/user/update, endpoint/user/edit`

with args like in `user_resources.inc`

It returns `404user not registered`

despite successfully loggedin

```
$cookie_session = $logged_user->session_name . '=' . $logged_user->sessid;

// User data
$user_data = array();
$user_data['uid'] = $logged_user->user->uid;
$user_data['data']['name'] = 'test4';

$data = json_encode($user_data);

// cURL code
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://localhost/html/mob/api-    mob/user/".$user_data['uid']);
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($curl, CURLOPT_COOKIE, "$cookie_session"); // use the previously saved session
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen($data), mymodule_get_csrf_header())
);
$response = curl_exec($ch);
$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);

```

what I am missing here or if one could do it via services please provide an example

# Answer
> 2 votes
To *update a user* with Drupal Services, you make a **PUT** call to:

```
?q=[my-endpoint]/user/1.json

```

Replacing `[my-endpoint]` with the machine name of your Service endpoint. Here's some example *JSON* to **PUT**:

```
{
  "uid":"1",
  "name":"bob",
  "mail":"bob@hotmail.com",
  "current_pass":"secret",
  "pass_pass1":"new-secret",
  "pass_pass2":"new-secret"
}

```

You *must* also attach a **header** to your call with a name of `X-CSRF-Token` using a value that can be retrieved here: `?q=services/session/token`

---
Tags: services
---


# Question
Title: Rendering a generic file field containing an image
```
Drupal 7.34
Media 7.x-1.4
Views 7.x-3.8

```

I have a generic file field. Sometimes the uploaded file is an image, and in these cases I want to render it in a View as a thumbnail.

So I do the following:

> * Go to `admin/config/media/file-types`
> * Choose "manage file display" next to Image
>
> + Pick a View Mode, let's say "Small"
>     + Check the box next to the Image display
>     + Pick my desired Image style from the dropdown in the display settings
> * Add the file field to my View
>
> + Choose "Rendered file" formatter
>     + Choose "Small" view mode
>     + hit Apply

…and the view puts a big blank space where the image should be.

I've checked the database, and Drupal has correctly identified my upload as image/jpeg. It opens fine in the browser.

If I choose a different formatter in the view, like Table of files or Generic file, it shows up fine.

If I choose a different formatter in the file display settings, it still shows nothing in the view.

Am I misunderstanding something? What's going on?

# Answer
> 2 votes
Check `admin/config/media/file-types/manage/image/display/media_small` and check that File is actually being displayed and not set hidden.

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


# Question
Title: Why are there two database tables to handle taxonomy terms structure
There is a `taxonomy_term_data` table and there is a `taxonomy_term_hierarchy` table. Why are there 2 tables, instead of them being combined?

taxonomy\_term\_hierachy strucutre

* description of table: Stores the hierarchical relationship between
* field: tid: 'Primary Key: the taxonomy\_term\_data.tid of the term'
* field: parent: 'Primary Key: The taxonomy\_term\_data.tid of the term's parent. 0 indicates no parent.'

taxonomy\_term\_data structure:

* description of table: Stores term information.
* fields: vid, name, description, format, weight

**Question motivation** I am the maintainer of the draggableviews module. Currently module is using just 1 table. Going forward, the module's goal is to mimic taxonomy structure. Tried to search the web for an answer but could not find one.

# Answer
`taxonomy_term_data` is the base table for the taxonomy entity type. It holds ID, property and bundle data for that entity type.

`taxonomy_term_hierarchy` holds the parent/child relationship between taxonomy terms (which of course can be multiple in nature).

You can't store the data for anything more than a one-to-one relationship in the same table, hence the split into two.
> 3 votes

---
Tags: taxonomy-terms, database
---


# Question
Title: How do I remove the ellipsis button in the pager?
I have a view with video and have replaced the links to different pages with a button. However, when there are many videos, an ellipsis (...) appears floating, and I want to remove it. I have the View with full pager but I don't see how to control this to hide it. Thanks!

# Answer
GO to the menu `/admin/config/user-interface/pagerer` and edit your pagerer

and in **Separators** -\> **Configure separators text**. remove the (...)
> 0 votes

# Answer
Create a theme\_pager override in your theme's template.php

```
function MYTHEME_pager($variables) {
  $tags = $variables['tags'];
  $element = $variables['element'];
  $parameters = $variables['parameters'];
  $quantity = $variables['quantity'];
  global $pager_page_array, $pager_total;

  // Calculate various markers within this pager piece:
  // Middle is used to "center" pages around the current page.
  $pager_middle = ceil($quantity / 2);
  // current is the page we are currently paged to
  $pager_current = $pager_page_array[$element] + 1;
  // first is the first page listed by this pager piece (re quantity)
  $pager_first = $pager_current - $pager_middle + 1;
  // last is the last page listed by this pager piece (re quantity)
  $pager_last = $pager_current + $quantity - $pager_middle;
  // max is the maximum page number
  $pager_max = $pager_total[$element];
  // End of marker calculations.

  // Prepare for generation loop.
  $i = $pager_first;
  if ($pager_last > $pager_max) {
    // Adjust "center" if at end of query.
    $i = $i + ($pager_max - $pager_last);
    $pager_last = $pager_max;
  }
  if ($i <= 0) {
    // Adjust "center" if at start of query.
    $pager_last = $pager_last + (1 - $i);
    $i = 1;
  }
  // End of generation loop preparation.

  $li_first = theme('pager_first', array('text' => (isset($tags[0]) ? $tags[0] : t('« first')), 'element' => $element, 'parameters' => $parameters));
  $li_previous = theme('pager_previous', array('text' => (isset($tags[1]) ? $tags[1] : t('‹ previous')), 'element' => $element, 'interval' => 1, 'parameters' => $parameters));
  $li_next = theme('pager_next', array('text' => (isset($tags[3]) ? $tags[3] : t('next ›')), 'element' => $element, 'interval' => 1, 'parameters' => $parameters));
  $li_last = theme('pager_last', array('text' => (isset($tags[4]) ? $tags[4] : t('last »')), 'element' => $element, 'parameters' => $parameters));

  if ($pager_total[$element] > 1) {
    if ($li_first) {
      $items[] = array(
        'class' => array('pager-first'),
        'data' => $li_first,
      );
    }
    if ($li_previous) {
      $items[] = array(
        'class' => array('pager-previous'),
        'data' => $li_previous,
      );
    }

    // When there is more than one page, create the pager list.
    if ($i != $pager_max) {
      if ($i > 1) {
        $items[] = array(
          'class' => array('pager-ellipsis'),
          'data' => '…',
        );
      }
      // Now generate the actual pager piece.
      for (; $i <= $pager_last && $i <= $pager_max; $i++) {
        if ($i < $pager_current) {
          $items[] = array(
            'class' => array('pager-item'),
            'data' => theme('pager_previous', array('text' => $i, 'element' => $element, 'interval' => ($pager_current - $i), 'parameters' => $parameters)),
          );
        }
        if ($i == $pager_current) {
          $items[] = array(
            'class' => array('pager-current'),
            'data' => $i,
          );
        }
        if ($i > $pager_current) {
          $items[] = array(
            'class' => array('pager-item'),
            'data' => theme('pager_next', array('text' => $i, 'element' => $element, 'interval' => ($i - $pager_current), 'parameters' => $parameters)),
          );
        }
      }
      if ($i < $pager_max) {
        $items[] = array(
          'class' => array('pager-ellipsis'),
          'data' => '…',
        );
      }
    }
    // End generation.
    if ($li_next) {
      $items[] = array(
        'class' => array('pager-next'),
        'data' => $li_next,
      );
    }
    if ($li_last) {
      $items[] = array(
        'class' => array('pager-last'),
        'data' => $li_last,
      );
    }
    return '<h2 class="element-invisible">' . t('Pages') . '</h2>' . theme('item_list', array(
      'items' => $items,
      'attributes' => array('class' => array('pager')),
    ));
  }
}

```

There are two chunks you can remove:

```
if ($i > 1) {
  $items[] = array(
    'class' => array('pager-ellipsis'),
    'data' => '…',
  );
}

```

and

```
if ($i < $pager_max) {
   $items[] = array(
     'class' => array('pager-ellipsis'),
     'data' => '…',
   );
}

```
> 0 votes

---
Tags: 7, views, paging
---


# Question
Title: Render a Views table row ID using a field as the ID value
I am trying to apply an ID to table rows in a view using a field as the ID value.

I've copied views-view-table.tpl.php template to my theme template folder and renamed it based on the view I am working with.

I'm using Commerce Kickstart2, and I would like to id the table rows in this view by the SKU of each product.

I added SKU as a field in my view and then render it as a class for the Views Row using replacement patterns for the row class of a table view. (See screen capture).

In my template this is the line that writes the row class:

```
<tr <?php if ($row_classes[$row_count]) { print 'class="' . implode(' ', $row_classes[$row_count]) .'"';  } ?>>

```

I would like to add to that the field SKU as a row ID: id="SKU Value Here".

I have tried a number of ways without success.

after running print\_r($view-\>result); at the top of the template I get this:

Array ( \[0\] =\> stdClass Object ( \[product\_id\] =\> 1 \[commerce\_product\_sku\] =\> sample1 \[field\_data\_title\_field\_commerce\_product\_entity\_type\] =\> commerce\_product \[field\_data\_commerce\_price\_commerce\_product\_entity\_type\] =\> commerce\_product \[\_field\_data\] =\> Array ( \[product\_id\] =\> Array ( \[entity\_type\] =\> commerce\_product \[entity\] =\> stdClass Object ( \[revision\_id\] =\> 1 \[sku\] =\> sample1 \[title\] =\> Product 1 \[revision\_uid\] =\> 1 \[status\] =\> 1 \[log\] =\> \[revision\_timestamp\] =\> 1423407240 \[data\] =\> \[product\_id\] =\> 1 \[type\] =\> product \[language\] =\> und \[uid\] =\> 1 \[created\] =\> 1418869347 \[changed\] =\> 1423407240 \[commerce\_price\] =\> Array ( \[und\] =\> Array ( \[0\] =\> Array ( \[amount\] =\> 1600 \[currency\_code\] =\> USD \[data\] =\> Array ( \[components\] =\> Array ( ) ) ) ) ) \[field\_images\] =\> Array ( \[und\] =\> Array ( \[0\] =\> Array ( \[fid\] =\> 1 \[uid\] =\> 1 \[filename\] =\> tote-1v1.jpg \[uri\] =\> public://tote-1v1.jpg \[filemime\] =\> image/jpeg \[filesize\] =\> 48075 \[status\] =\> 1 \[timestamp\] =\> 1418869347 \[alt\] =\> \[title\] =\> \[width\] =\> 860 \[height\] =\> 842 )  =\> Array ( \[fid\] =\> 2 \[uid\] =\> 1 \[filename\] =\> tote-1v2.jpg \[uri\] =\> public://tote-1v2.jpg \[filemime\] =\> image/jpeg \[filesize\] =\> 52861 \[status\] =\> 1 \[timestamp\] =\> 1418869347 \[alt\] =\> \[title\] =\> \[width\] =\> 860 \[height\] =\> 1251 ) \[2\] =\> Array ( \[fid\] =\> 3 \[uid\] =\> 1 \[filename\] =\> tote-1v3.jpg \[uri\] =\> public://tote-1v3.jpg \[filemime\] =\> image/jpeg \[filesize\] =\> 96645 \[status\] =\> 1 \[timestamp\] =\> 1418869347 \[alt\] =\> \[title\] =\> \[width\] =\> 860 \[height\] =\> 1100 ) ) ) \[title\_field\] =\> Array ( \[und\] =\> Array ( \[0\] =\> Array ( \[value\] =\> Product 1 \[format\] =\> \[safe\_value\] =\> Product 1 ) ) ) \[field\_associated\_product\_diagram\] =\> Array ( \[und\] =\> Array ( \[0\] =\> Array ( \[tid\] =\> 272 ) ) ) \[title\_original\] =\> Product 1 ) ) ) \[field\_title\_field\] =\> Array ( \[0\] =\> Array ( \[rendered\] =\>

If anyone can lend any insight into how to accomplish this, I would appreciate it.

# Answer
Try this to add an id attribute with your SKU based on the $view-\>result output:

```
 <tr <?php if ($row_classes[$row_count]) { print 'class="' . implode(' ', $row_classes[$row_count]) .'"';  } ?> id="<?php print $view->result[0]->commerce_product_sku; ?>">

```
> 0 votes

# Answer
I did this with nodes in the view:

Added nid as a field.

altered the row class code to this:

```
<tr <?php if ($row_classes[$row_count]) { print 'id="' . $row['nid'] . '" '; print 'class="' . implode(' ', $row_classes[$row_count]) .'"';  } ?>>

```

Just use sku where I used nid
> 0 votes

---
Tags: views
---


# Question
Title: How can I specify where an image is uploaded
I have a slideshow block that does a slideshow for a news stories that take two images. An image for the page and a teaser image for the slideshow. but the image never shows up in the slideshow. The image url is sites/default/files/styles/mt\_slideshow/public but the actual location of the image after its uploaded is sites/default/files. so is there a way to force the image to be uploded where this site is looking, or change where the site looks to where the image is uploaded?

# Answer
In your site log in as adminstrator and go to

```
'/admin/config/media/file-system'

```

and you can find the place where you can define your path to save any uploaded files.

for Example your siteis example.com you have to access

"`**example.com//admin/config/media/file-system**`" as Drupal Administrator and you can change the path there.

image URLs messing up

possibly this will give you a answer
> 0 votes

---
Tags: blocks, media
---


# Question
Title: Recieving error: Fatal error: Class 'panels_renderer_standard' not found in
I recently migrated a site from a Drupal 6 install to a fresh Drupal 7 install.

I then installed panels 7.x-3.5. Initially I had an older version of ctools installed, so I had to upgrade from 7.x-1.4 to ctools 7.x-1.6.

I then enabled panels the panels page is not showing up in "Structure". I checked permissions and all the correct permissions have been added.

I then try to flush my cache, and i get this error:

```
Fatal error: Class 'panels_renderer_standard' not found in C:\wamp\www\projects\elaw\sites\all\modules\panels\plugins\display_renderers\panels_renderer_editor.class.php on line 8

```

Here is a picture of the error with a full stack trace:

I can run cron just fine, but trying to clear the cache gives that error. In the modules page "Panels" is enabled.

Before upgrading ctools, I had saved a files/database copy and then tried removing panels from "modules" and adding Panels 3.4 instead. I got the same error.
I then restored my files and database and tried it again but with upgrading ctools instead as mentioned above.

There was also this error that briefly flashed up when I was enabling the module from the "modules" page, after the ctools upgrade.

\********UPDATE\*********

I was able to get the cache to clear by just hitting reload. But, if after the cache clears I try to clear the cache I get the same error. Now the "panels" shows up in Management-\>Structure, but it has a strange error on the top of the page:

```
Notice: Undefined index: rows in page_manager_panels_dashboard_blocks() (line 1251 of C:\wamp\www\projects\elaw\sites\all\modules\ctools\page_manager\page_manager.module).
Warning: Invalid argument supplied for foreach() in page_manager_panels_dashboard_blocks() (line 1251 of C:\wamp\www\projects\elaw\sites\all\modules\ctools\page_manager\page_manager.module).

```

Notice how none of the predefined panel pages are showing up?

I hit clear cache a couple more times (with it giving the "class panels\_renderer\_standard not found bug each time I cleared the cache initially and it clearing after I hit reload), and now the panels page is showing the Predefined Panel Pages, (user page, etc):

I tried creating a new panel page and got this bug:

I can't seem to create a new panel page.

\****END UPDATE\*****

\************************S E C O N D U P D A T E\*****************

I had an idea that perhaps it was a contributed module that was causing the error. I was going to just randomly start disabling contributed modules but I thought I would start with any contributed module that had ANYTHING to do with panels. I found that disabling "Panels Translation" in the "Internationalization" section fixes the problem.

I'm not sure why this was causing the problem, but after disabling it I no longer get the " Fatal error: Class 'panels\_renderer\_standard' not found" error. I am also able to get further in creating new panel pages. I get all the way up to saving and it gives this error:

I have verified that that table is not in the database....

I am on a very tight deadline and would appreciate anyone's insight. Thanks very much for any help.

Sincerely,

David

# Answer
> 0 votes
The problem was that I originally was trying to install panels 7.x-3.5, which required ctools 7.x-1.6. I only had ctools 1.4 installed, so on the modules page the enabling of the panels module was disabled with a warning that ctools \> 1.5 was needed.

There is a bug if you try to install panels 3.5 and don't have the proper ctools version installed. It for some reason won't install the tables for Panels when you enable the panels module, even if you get the proper ctools version or downgrade your panels to a lower version of panels that does not require a ctools upgrade.

Panels was literally refusing to install any tables.

Clearing the cache via the user interface was not enough.

My solution was to start with my project that had ctools 1.4 installed and panels 3.5. Remove Panels 3.5 module from the modules folder, and I truncated every single table in the database that started with cache\_... as well as the cache table. I then installed Panels 3.4 and enabled it, and the database tables for Panels were then installed properly. I can see the template pages in the "Pages" section for Panels and create new Panels with no errors.

You probably don't need to truncate all of the cache\_ tables, but I wasn't sure which ones to try, so I decided on trying all of them as this bug turned into a major headache.

I know at least one other person has had this problem (looking at the Panels module bug section) so I hope this helps someone.

Sincerely,

David

# Answer
> 0 votes
Check your `modules/panels/plugins/display_renderers` folder and make sure there is a file named `panels_renderer_standard.class.php` inside, that's where the class is contained that is supposedly missing.

Try completely replacing the panels module code with a fresh download, that is: **move** the current module folder somewhere else (so you can get it again if you need to) and re-upload the module.

If you're applying any patches, make sure you check them for code that might be deleting, renaming, or disabling the display\_renderer\_standard class.

---
Tags: 7, panels
---


# Question
Title: Views: How to change entity view mode settings when a contextual filter is available?
I have a view it displays a few nodes in teaser mode. The view takes contextual filter and when filter is available I would like the content (node) to be displayed in full view mode. Is this possible?

# Answer
> 1 votes
Just create a view with two page displays.

The first display will be on the path with no arguments and will display teasers.

The second display will be on the same path with an argument such as `thepath/%` and will display full view mode.

When you alter the format and add the contextual filter in the second page, make sure to select it only for that display, otherwise it will overwrite the first display as well.

This is what views displays are for. Use it.

---
Tags: views
---


title: Social share module: confirmation page

text:
# Question
Title: Social share module: confirmation page
I'm looking to add a the social share block only on the confirmation page. Right now it shows up everywhere. Is it possible to control where it goes?

Here's the path to a completed webform. node/1015/done?sid=1516

For Show block on specific pages I added node/\*/done

# Answer
The node/\*/done seems to be the fix. Just thought I'd pass it along.
> 0 votes

---
Tags: webforms, nodes, media
---


# Question
Title: Why is my image with URL that links to external site in a custom block not showing?
I made a custom block in header that houses the following html along with 4 more of the same html for different social media sites:

a href="https://socialmediasite.com" target="\_blank"
img src="/images/socialmedialink1\_icon\_32x32.png" alt="Social Media link" style="width: 32px; height: 32px; border:0"
/a

The problems aren't the links because they do work. The problem is the images aren't showing up and only showing up as broken links so there's a problem with the img src link. I made a folder under root directory named images using my website hosting companies file manager and the images have been uploaded to that folder so I don't know what I'm missing. Am I missing something in the img src or something else before the a href or can it just not be done using only a custom block?

# Answer
> 1 votes
Try using the full site url for the src tags.

Prepend return value of `$base_url` and the rest of your path leading up to the image to your src attribute

# Answer
> 1 votes
exactly the problem is with you img tag src

```
global $base_path;
$themepath = $base_path.drupal_get_path('theme','theme_name');
$img_path = $themepath."/images/image_name.png";
$url = "https://socialmediasite.com";

$img =  "<a href='$url' target='_blank' class='class-name'><img src='$img_path' alt='Social Media link' style='width: 32px; height: 32px; border:0' /></a>";

```

print this where ever you want like

```
print $img;

```

this is the way to get the image src dynamically it will be use full for moving your code from local to servers.

hope this helps :)

---
Tags: blocks, media, navigation
---


# Question
Title: webform block in a page template , inside a colorbox - validation does not show
I created a page tpl for a view where using colorbox inline i\`m displacing a webform block and some additional text.

My problem is that the error messages are not showing. The submission is working but the messages are not shown.

Here is a part of my code inside a view.tpl

```
            <div class='modal' style='display:none'>
                <div id='inline_content_contact' style='padding:10px; background:#fff;'>
                   <?php  print $content; ?>

                   <?php
                       $block = module_invoke('webform', 'block_view', 'client-block-15');
                       print render($block['content']);
                   ?>

                </div>
            </div>

```

I activated the webform ajax and no redirect after in order to stay in colorbox after submission.

Thanks

# Answer
> 0 votes
The error messages are printed in $messages on a normal page, have you tried adding that?

---
Tags: webforms, forms
---


# Question
Title: Having username as a path - Profiles 2 and Pathauto
I have a problem with integrating the Pathauto and Profiles modules. Basically, I would like to have the username as URL, e.g. example.com/username. This should link to the profile page (not the account page). I know how to do it for account (\[user:name\]) however this method does not work for the profile patterns. There is only certain number of patterns available for profile paths and no username I am afraid. I tried node:author:name, but this doesnt work as well?

Can anyone help with this, or suggest any other solution?

# Answer
> 2 votes
you can automatically path save the user name when user access the user/uid page add a submit handler in form alter and

```
$form['#submit'][1] = 'redirect_to_profile_username_page';

```

// here get the user name field

```
function redirect_to_profile_detail(&$form, &$form_state){
$uid = $form_state['build_info']['args'][0]->uid;
$user = user_load($uid);
$clean = $user->name;
      $Alias_1 = get_alias('source','user/'.$uid,1);
        $pathAlias = !empty($Alias_1) ? $Alias_1['alias'] : FALSE;
        if($pathAlias === FALSE){
                path_save($args = array("source" => 'user'.'/'.$uid,"alias" => $clean));
                $pathAlias = drupal_lookup_path('alias',$clean);
        }
       $form_state['redirect'] = $clean;
     }

```

this will redirect the user/uid page to that particular username as url page

here we are creating a aliase for user/uid so when you access sitename/username that user profile page will be loaded.

---
Tags: 7, uri, users, path-aliases
---


# Question
Title: Make user logged in after created by rule
I have an entityform on my Drupal website, which helps me to generate leads. I've configured a rule, creates a new user by that entityform's e-mail and name fields. (Similar scenario is told here.)

I need that user (created by rule) to be logged in, after creation. What should I do?

# Answer
Have a look at the Logintoboggan module. This offers you to login new users immediately.

The LoginToboggan module offers several modifications of the Drupal login system in an external module by offering the following features and usability improvements:

1.Allow users to login using either their username OR their e-mail address.

2.Allow users to login immediately.

3.Provide a login form on Access Denied pages for non-logged-in (anonymous) users.

4.The module provides two login block options: One uses JavaScript to display the form within the block immediately upon clicking "log in". The other brings the user to a separate page, but returns the user to their original page upon login.

5.Customize the registration form with two e-mail fields to ensure accuracy.

6.Optionally redirect the user to a specific page when using the 'immediate login' feature.

7.Optionally redirect the user to a specific page upon validation of their e-mail address.

8.Optionally display a user message indicating a successful login.

9.Optionally combine both the login and registration form on one page.

10.Optionally have unvalidated users purged from the system at a pre-defined interval (please read the CAVEATS section of INSTALL.txt for important information on 12.configuring this feature!).

11.Integrates with Rules module to do various tasks when a user validates via email validation process (see http://drupal.org/node/880904 for an example)
> 1 votes

---
Tags: users, rules, entities
---


# Question
Title: How can I pass a long javascript string to PHP hook_menu in Drupal?
On mysite/build-order I have a long order code that I'm assembling using Javacsript and sending via \_GET in the URL to a hook\_menu page for processing.

It can be as long as this (or longer), and am sending it to the create-order page like this:

```
<script type="text/javascript">
    //...building code
    var orderCode = "sku:OR-4x4>qty:2>prc:55.00>nfo:OR-4x4,sku:CVR>qty:1>prc:50>nfo:OR-4x4,sku:PF>qty:15>prc:2>nfo:OR-4x4 (sdfsdfg),sku:EM>qty:2>prc:12.95>nfo:OR-4x4 (sdfsdfg),sku:SC>prc:25>qty:4>nfo:Some description,sku:DB>qty:10>prc:4>nfo:Some description,sku:ES>qty:10>prc:3>nfo:BlahBlah,sku:OR-4x4>qty:2>prc:55.00>nfo:OR-4x4,sku:CVR>qty:1>prc:50>nfo:OR-4x4,sku:PF>qty:15>prc:2>nfo:OR-4x4 (sdfsdfg),sku:EM>qty:2>prc:12.95>nfo:OR-4x4 (sdfsdfg),sku:SC>prc:25>qty:4>nfo:Some description,sku:DB>qty:10>prc:4>nfo:BlahBlah-visiondelimiter-Phasellus laoreet lorem vel dolor tempus vehicula. Curabitur blandit tempus ardua ridiculus sed magna. Quisque placerat facilisis egestas cillum dolore.-visiondelimiter-eventName";

    var url = '/create-order/' + orderCode;
    window.location.replace(url);
</script>

```

Ive implemented a hook\_menu setup in my custom module called "create\_order\_menu" and it works fine.

```
function mymodule_create_order_menu($ordercode){

    // do stuff with $ordercode

}

```

It all works fine. The only problem is that the order code string passed through the URL can sometimes be twice as long and it trips a 404 Error in the mysite/create-order page. When I shorten the code, it works. When I lengthen it again, it breaks.

Is there a better way to send such a lengthy variable to my hook\_menu page setup?

# Answer
I would suggest that you consider some pretty substantial changes to how you're doing things.

I would recommend using an AJAX request, probably with POST rather than GET, and don't try to do the redirect. Just update the interface with a "success" message for the user.
> 3 votes

---
Tags: javascript, routes
---


# Question
Title: communicate new/changed values between taxonomies
I have a taxonomy called **Species**, and another taxonomy called **Protected Areas**.

Inside of the **Protected Areas** I have a multifield widget (Taxonomy reference pointing to **Species**), where user can select different **Species** present on the Area.

Users are able to manipulate also the **Species** taxonomy, when adding a new Species they are able to choose in which **Protected Area** is this **specie** present. Then, when users do it, I would like to automatically update the user selected **Protected Area** taxonomy (for this Species), adding on the multifield widget the recently added **Species** value.

Even shorter: how to communicate new/changed values between taxonomies.

Some chances to avoid writing my own module? thanks

# Answer
> 1 votes
Unfortunately you are probably stuck writing your own module. You need to implement `hook_taxonomy_term_update` and `hook_taxonomy_term_insert`. In each you can check the item being updated and force a change on any associated terms in the other taxonomy.

The one thing to be careful of is an update spiral. Forcing an update on associated terms will then force an update of the original term, because it is now associated. Because the changes in those two hooks are not committed to the db until the whole mess resolves it will lock up unless you put in a variable to keep it from spiraling.

**For example:**

```
if ($term->tid == args(2)) _update_related_terms($term);

```

should check the term being updated against the current page. If they do not match it won't fire. (I haven't tested this snippet, so test thoroughly!)

Then in **\_update\_related\_terms**

```
function _update_related_terms($term){
  $associated_terms = $term->associated_term_field;
  if (isset($associated_terms['und'][0]['tid']) && $associated_terms['und'][0]['tid'] != ''){
    foreach ($associated_terms['und'] as $key => $value){
      if (isset($value['tid']) && $value['tid'] != ''){
        //check the associated term here.  You could load it, or check the db, or all sort of things
      }
    }
  }
}

```

I know I am using `und` in this example, but it is off the cuff. Again, not tested

Please note: this example is for **d7**.

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


title: Views: Single Image Per Tag

text:
# Question
Title: Views: Single Image Per Tag
For examples purposes. Say I created a content type called ContentX with a image field and term reference field(Tag). I created 4 node(pages) of ContentX. All 4 nodes of ContentX have 1 Image to each node. Two of these nodes of ContentX have a Tag called TagA. Two of these nodes of ContentX have a Tag called TagB.

I then create a view block stating that I want to view content from ContentX. In the view fields I make sure the images field is there. All 4 images of ContentX show.

THE ISSUE: Say I want to show a single image from the 2 nodes with TagA. I go to filters,Content:TagA, check One Of: and bring up my tag which is TagA. HOWEVER instead of showing what I believe to be "One Of TagA", it shows both images of both nodes with TagA Tag.

THE OUTCOME I AM TRYING TO GET: I am trying to get my View to show one image from 2 ContentX nodes with a Tag called TagA and one image from 2 ContentX nodes with a Tag called TagB.

Any help?

# Answer
In views **pagerer** you can limit "**Items to display** " section and give the option as 1 to limit ome image to display from that filter
> 0 votes

---
Tags: nodes, views, media
---


# Question
Title: drupal store and retrieve variable from $_POST array
This is really simple question for the user who are using DRUPAL for many years.But for me it is creating a big issue.

I already made a form using the drupal **form api**.But after submit the form I want to store form data in the "$\_POST" and print the data to another module's page.I get the data on the 2nd page(module's page where I want to show the form data)when I store the data in $\_SESSION or in $\_GET array but not get result when I store data in $\_POST.What is the proper way to store data in $\_POST array and fetch the data in another page?

my submit code is as follows:

```
function create_kavings_create_form_submit($form, &$form_state) {
    //print_r($_POST);die();
    //$_POST['first_name'] = $form_state['values']['first'];
    //$_POST['last_name'] = $form_state['values']['last'];
    //$arr[]=$_POST;
      $options = array(
      'query' => array(
         'first' => $_POST['first'],
         'last' => $_POST['last'],
        )
      );
      $form_state['redirect'] = array('coupon_preview',$options);
}

```

On 2nd page I simplly write the following to print the post array: `print_r($_POST);` But is showing blank.

# Answer
you should use `print_r($_POST['variable_name']);` to get the post values you sent form the form.

and add

```
if(isset($_POST['variable_name']) && !empty($_POST['variable_name'])){
    $values_post = $_POST['variable_name'];
}

```

to avoid unwanted notices.
> 1 votes

# Answer
If I understand your question correctly, in your form's submit handler, you want to capture some of the input from your submitted form, and then use that as input which you then want to POST to another module's form? You can't do that with the standard form redirect, because (via drupal\_goto()), that tells the user's browser to redirect to a new page, but that doesn't work with the POST method.

As an alternative, in your form's submit handler, try canceling the redirect of your form, and using drupal\_form\_submit() to cause a build/submit of the second form; something like this:

```
function create_kavings_create_form_submit($form, &$form_state) {
  $form_state['no_redirect'] = TRUE;
  $submit_these = array(
    'first' => $form_state['values']['first'],
    'last' => $form_state['values']['last'],
  );
  drupal_form_submit('coupon_preview_form', $submit_these);
}

```

With that, you might want to alter the coupon\_preview form to add a submit handler that will redirect the user to the page you finally want them to end up on, since using drupal\_form\_submit will set that form's $form\_state\['programmed'\] to TRUE, which will prevent drupal from redirecting the user as it normally would if they'd submitted the form themselves.
> 1 votes

---
Tags: forms
---


title: What is the best way to store a guid?

text:
# Question
Title: What is the best way to store a guid?
I found that the best way to store a guid is as a char(36) data type for MySQL. What is the equivalent to char(36) in drupal 7?

# Answer
> 0 votes
In terms of core function I don't think there's a lot of choice you can have. You'd have to use the "text" field type and limit to 36 chars.

---
Tags: 7
---


# Question
Title: How can I make a field appears when you check on a checkbox?
I'm making a module and on the administration page there is a form and I want to make one of the fields appears only when user check on a checkbox. Like the option to add a new content to a menu.

# Answer
You can use #states from FormAPI that drupal provides. Below is the link https://api.drupal.org/api/drupal/developer!topics!forms\_api\_reference.html/7#states

Below is the code from drupal form api

```
$form['email_canceled']['settings'] = array(
    '#type' => 'container',
    '#states' => array(
      // Hide the settings when the cancel notify checkbox is disabled.
      'invisible' => array(
       ':input[name="email_canceled_toggle"]' => array('checked' => FALSE),
      ),
    ),
  );

```
> 1 votes

# Answer
Also you can use like this

```
$form['field_image']['#states']['visible'] = array(':input[name="field_checkbox[und]"]' => array('value' => 1));

```

so only when the check box is checked the field image will be displayed otherwise it will be hidden.
> 0 votes

---
Tags: 7, forms
---


# Question
Title: Adding option to one product in Commerce but not to others of the same product type
Ok so my situation is I am developing a website for a takeaway / restaurant and there are a number of products that fall under a product type, lets call this starters product type.

One of these products has the option for couscous or rice.

I would rather not have to list this as 2 listings on the menu and instead have it as one with some kind of option either before or after the person has clicked add to cart.

Are there any modules out there which are close to achieving something like this? Most I have found seem to be directed at product types as a whole.

# Answer
> 0 votes
Here is another solution, one which works better than my suggestion above. Please see this blog post and video tutorial. This is for the module Commerce Pricing Attributes https://vimeo.com/59862366

# Answer
> 0 votes
You can build your restaurant menu based on views, where you list commerce\_products instead of product types(nodes). This will render one row for each variation. You can also add relationship to your product types(nodes) for rendering/grouping/filtering.

You can also render the view of product variations at the product full page. Then the user will see all the possible variations of current product at once.

# Answer
> 0 votes
I have just found an answer to my own question, with the module Commerce Product addon you can infact build product types that add on to other product types but can than be assigned to individual products within that product type rather than across the whole of that product type

Here is a video tutorial

https://www.youtube.com/watch?v=kMNSRYD0OWo

---
Tags: commerce
---


# Question
Title: How to add an autocomplete field to a form
I've got a page that, in response to a button click, brings up a Bootstrap modal form. In that form is a textfield with the standard Drupal autocomplete behavior; it's working fine.

I now want to set things up so that, after a value is put into that field, another mostly-identical autocomplete field is added to the form -- the idea is to let the user specify additional values for the property being handled by this part of the form.

I've hung a jQuery blur handler off the textfield that takes the HTML that ends up in the form for the initial autocomplete form, parameterizes it a bit to avoid duplicate ID numbers, and inserts this updated field into the form when the first field gets a value. This is working fine from an HTML perspective, but the autocomplete behavior is not happening on the added form.

Minor notes:

* After I insert the new field into the form, I re-run `Drupal.attachBehaviors()`, which I thought was going to make this all work. I've also added a delay to make sure the rewriting of the form is completed before `attachBehaviors()` is called, but that has no effect.
* The autocomplete behavior continues to work on the original field after the new field is added to the form.
* The blur handler that does all this stuff to the first autocomplete field is not firing when I blur control from the second, added field.

It looks like some other bit of initialization stuff needs to happen, but I have no clue what it is. Does anybody else? Thanks!

# Answer
Well, that was pretty ugly, and a LOT of guesswork is going on here. But:

When Drupal sets up an autocomplete field, it adds a hidden variable to the form, which (I'm guessing here) is used to track the status of the whole autocomplete thing. If you inspect a rendered form, it will look something like:

```
<input type="hidden" id="edit-field-name-autocomplete"
      value="https://example.com/path/to/autocomplete/handler" disabled="disabled"
      class="autocomplete autocomplete-processed">

```

That `autocomplete-processed` field seems to be the key: I had blindly copied it into my code and made it part of the field I was added to the form. Once I removed it -- `autocomplete-processed`, that is -- autocompletion ran properly on it and all other similar fields.

Whew. Your mileage may DEFINITELY vary.
> 0 votes

---
Tags: 7, forms
---


# Question
Title: How to tell if a Webform field has been hidden by conditional rule
I maintain a contrib module that implements hook\_webform\_submission\_presave. It does some complex stuff which boils down to taking the submitted values and storing them in another database.

Here's the problem: *if the field was hidden we want to treat it differently*. As of Webform 4, conditional fields are built-in to the core webform module. But looking at the submission object, I can't tell the difference between a field that is blank because it was intentionally left blank by the user vs a field that is blank because it was hidden by a conditional rule. In the latter case, we *don't* want to overwrite an existing value in the other database, because the user wasn't telling us "I want this field to be blank" they were in fact telling us nothing about the field because they didn't even see it.

For more information about the scenario see the original issue.

# Answer
> 4 votes
Assuming you know the numeric id of your field (for example let's say it is 5)

If $submission-\>data\[5\] is an array, then the field was submitted. The array may contain an empty string, which means the field was left blank.

If $submission-\>data\[5\] === NULL then the field was not submitted because it was hidden by a conditional rule, or was excluded from the form for another reason (e.g. the user did not have permission to see it).

---
Tags: webforms
---


# Question
Title: Count entitys dependent om field value and as entity reference
I have two node types, Apartment and Building.

Apartment has two fields:
\- "Building" a Entity Reference field that reference to the node type Building
\- "Rooms" a Text List with values 1 room, 2 rooms, 3 rooms etc...

I want to have a View, that lists all Buildings and under each Building it displays how many Apartments WITH specific amount of rooms. Like this:

Building 1
1 x 1 room apartment
5 x 2 rooms apartment
6 x 3 rooms apartment

Building 2
7 x 1 room apartment
3 x 2 rooms apartment
2 x 3 rooms apartment

Is this possible to do with Views, and then HOW to do it?

# Answer
> 0 votes
In general Views Aggregator Plus and Views Calc can both generate tally reports like these.

Unfortuntaley by making `rooms` a `text list` you've basically made it (nearly) impossible for you to easily generate these types of reports. You're question isn't really a Views question, but 1 of how to write a tally report in `SQL`.

Since `rooms` is a simple string, its hard(er) to `SUM` the values to make your report. If the `room` was a `reference` to a `room ID` in another table then SQL, and Views and `aggregation functions` could more easily generate these reports.

> Is this possible to do with Views, and then HOW to do it?

TLDR; Yes, it's possible. It's easier if you make your data into non-string values for aggregation. It's a futile effort to show you how because it's simply too messy in code to work with the data structures you've created.

**EDIT**

If these were numerical numbers for the number of rooms, or room IDs, you could easily use `SUM` aggregation to find the total. Then you would simply use a Views `rewrite substition` to show the output as something like the string `[node-room-sum] x [node-room-size] room(s) aparament` and use tokens derived from your View.

---
Tags: views, entities
---


# Question
Title: Show step-by-step dialogs for helping user with using the site
I built an app with Drupal, and I would like to add step-by-step dialogs to help users learn how to use the app.

I found some boostrap plugins, but I would like to know if there is already a Drupal module that has this functionality.

# Answer
> 3 votes
The modules chrischarlton suggested were fine, but those are unsupported and not maintained.

I recommend using the Boostrap tour module. With this module, you can show popups step-by-step, attach the popups to HTML elements in each step, save the progress of the user, and let the user add feedback to the tour. However, you need to have a boostrap based theme in order to make it work.

# Answer
> 1 votes
Yes, there is.

Here's the relevant modules you'll want to review. Pick the one that fits your exact use case, and let us know how it works out for your site:

1. **Guided Tours** (module) - https://drupal.org/project/guided\_tours
2. **Guidance** (module) - https://drupal.org/project/guidance

One other module that comes to mind is **Tutorials** (module) - https://drupal.org/project/tutorials \- this one allows you to embed help videos, so it's different but you may find it useful on your site.

# Answer
> 0 votes
For the sake of completeness, there are a couple other JQuery integrated projects:

Also note that a Joyride-based tour is included in Drupal 8 core!

---
Tags: 7, users, workflows, forms
---


# Question
Title: hook_page_attachments() not called from mytheme.theme file
I am trying to load an asset library in my Drupal 8 custom theme. I have created the library and can load it via mytheme.info.yml file. However, if I try the load it using hook\_page\_attachments() in the mytheme.theme file, then the function is not called.

I did a search for this function in the Drupal 8 standard installation and it only ever seems to be called from modules. Can hook\_page\_attachments only be called from modules? Any suggestions on why this is not working.

mytheme.theme file content:

```
function mytheme_page_attachments(array &$attachments) {
  $attachments ['#attached']['library'][] = 'mytheme/general-js';
}

```

# Answer
It appears that this function is only callable from a module, as it is listed in Adding stylesheets (CSS) and JavaScript (JS) to a Drupal 8 module but not listed as a valid method in Adding stylesheets (CSS) and JavaScript (JS) to a Drupal 8 theme.

It should be noted that the related function hook\_page\_attachments\_alter() can be called from the theme layer (i.e. can be called from mytheme.theme file).

```
function mytheme_page_attachments_alter(&$page) {
  $page['#attached']['library'][] = 'mytheme/general-js';
}

```

Alternatively one can attach libraries to a page from within hook\_preprocess\_page()

```
function mytheme_preprocess_page(&$variables) {
  $variables['#attached']['library'][] = 'mytheme/cuddly-slider';
}

```

The advantage of these two methods is that it enables one to utilize logic/code to determine whether or not to attach a library to a page.
> 11 votes

---
Tags: theming, 8
---


title: How do I fix these errors?

text:
# Question
Title: How do I fix these errors?
I've been currently developing a module, which was working fine. Now, the console throws an error every time I click a link in the administrator menu.

>

For example, when I click the *Content* link, I get this error.

>

When I click the *Dashboard* link, I get this error.

>

I added the jquery-1.11.2.min.js file with `hook_init()` to make the module work.

```
function myid_init () {
  drupal_add_js(drupal_get_path("module", "myid") . "/js/jquery-1.11.2.min.js");
}

```

How can I fix these errors?

# Answer
> 3 votes
I would wager a guess it's because (or related to) Drupal including it's own version (1.4) of jquery, and you trying to include a second copy at version 1.11.2 - some functionality is deprecated in later versions of jquery, items that drupal and its modules are expecting to find. If you need to increase the version use something like the module Jquery Update instead of your own add\_js and see if that solves it.

> Upgrades the version of jQuery in Drupal core to a newer version of jQuery.
>
> Updates...
>
> Drupal 5 to jQuery 1.2.6
>
> Drupal 6 to jQuery 1.3.2
>
> Drupal 7 to jQuery 1.5.x, 1.7.x, 1.8.x, 1.9.x, 1.10.x and jQuery UI 1.10.2
>
> Drupal 8: TBD

---
Tags: 7, javascript
---


# Question
Title: Can Xdebug be triggered by Drush commands?
I'm running into an issue with my Features modules and installation profile when installing the site with `drush si`. There are a number of probably related issues in the Features issue queue, but none with good solutions. The interesting part (mentioned in some of the issues) is that it works fine when installing the site through the browser, but fails when installing with `drush si`.

I have an idea of what's wrong, but need to confirm it. The only way I can think of confirming it is to step through the code with a debugger (Xdebug is what I have set up). So, is it possible to trigger Xdebug from a command run with Drush? Specifically, can I get Xdebug to kick in when I run `drush si`?

# Answer
> 4 votes
you have to remember that with drush you are (most supposedly) in cli, so this should help :

https://stackoverflow.com/questions/1947395/how-can-i-debug-a-php-cli-script-with-xdebug

also, try running the command with the option -d (--debug) - it should give you quite a lot of info about what is going wrong.

# Answer
> 3 votes
You may use `xdebug_start_trace()` and `xdebug_stop_trace()` XDebug functions to kick off the debugger on demand. Make sure that you've configured XDebug in CLI first (`php -i | grep xdebug`).

Then create new one-liner PHP file as follows (e.g. drush\_xdebug\_start.inc):

```
<?php xdebug_start_trace();

```

Then run the drush as:

```
drush --early="$PWD"/drush_xdebug_start.inc whatever_command_you_need

```

# Answer
> 2 votes
I use XDebug on drush requests all the time.

1. Make sure XDebug is loaded in your CLI php by running `php -i`
2. Make sure your client is listening for XDebug connections, and is doing so on the right port. I have successfully debugged using PHPStorm, Netbeans, and Komodo IDE as clients.

# Answer
> 2 votes
Assuming you have Xdebug configured properly, it's very easy to integrate your IDE to step through code. Just set the environment variable XDEBUG\_CONFIG to "idekey=MYIDEKEY".

Make it easier by setting up an alias for it. this is what I use in my .alias file (tcsh):

```
alias xdebugon 'setenv XDEBUG_CONFIG "idekey=MYIDEKEY"'
alias xdebugoff 'unsetenv XDEBUG_CONFIG'

```

---
Tags: debugging, drush
---


title: Path to Images for Content Type

text:
# Question
Title: Path to Images for Content Type
In a custom module I'm trying to display results from mysql DB based on items users selected in a form. One of the fields in the content type I'd like to display is an image associated with the node. This image appears to be housed in the table 'file\_managed' in a field called 'filename' - or at least that's where the NAME of the file is located. I'm able to retrieve that field fine using SQL and joins and when I echo the result it shows the following (for example):

```
nameoffile.png

```

So I tried calling that with php using:

```
$icon = $row['filename'];
echo $icon; // works fine

$output .= '<img src="' . $icon . '" />';

```

And it just shows a blank image icon (not the image nameoffile.png).

So then I think well I must have the path wrong. So I dragged the image icon from the search results page (where it displays just fine) into a new tab and this is the URL I get:

```
http://pf.dev/sites/default/files/styles/thumbnail/public/PPP_CCYCL_CLP_ChrevonCycle_A_8Red.png

```

But of course I don't want to use an absolute path, esp. since this is on the dev. server.

So my question is this: how do I find the paths to my content type images so I can display them correctly in my custom module?

# Answer
There are a couple of things you can do. First, instead of grabbing the filename field from the {file\_managed} table, you'll want to grab the uri.

Then you can use file\_create\_url() to generate a url to the original file:

```
$icon = file_create_url($row['uri']);
$output .= '<img src="' . $icon . '" />';

```

Or if you want to run the image through an image style, you can use image\_style\_url() (you'll need to know the machine name of the image style)

```
$icon = image_style_url('image_style', $row['uri']);
$output .= '<img src="' . $icon . '" />';

```
> 1 votes

# Answer
You will get tid and nid from table taxonomy\_index and then using the nid you can able to fetch fid, uri from table `file_managed`.
> 0 votes

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


# Question
Title: Adding html subsites to Drupal 7 installation
Newbie here, and would appreciate any insight. I have a Drupal 7 site and am looking to create a few small HTML subsites (e.g., Drupal site www.mykittenmittons.com, html subsite cats.mykittenmittons.com).

After creating my Drupal site on BlueHost I used their "subsite" tool. The subsite folder is automatically generated in public\_html. I gave it a whirl and added my html files to the subsite folder and it seems to work. Are there any reasons to not handle html subsites in this way, or problems I could encounter? Thanks.

# Answer
I don't know anything about BlueHost or their tools, but the normal way to do that would be along the lines of:

1. Make a folder to house your HTML-only site
2. Put your site files in the folder
3. Set your webserver (Apache/Nginx/IIS) to direct requests for subsite.mysite.com to that new folder

Drupal is not involved in any way, shape or form.

So the answer is likely that there will be no problems, however I suggest asking this question of BlueHost as it really has nothing to do with Drupal.
> 1 votes

---
Tags: theming, subsites
---


# Question
Title: choosing image style during content creation
I am seeking for a method to enable users to:

* choose image style (thumbnail, medium, large, ...) during content creation
* change this style anytime during content update

Right now, with "Image" module on, the image field style can be decided only during content type creation.

I tried to use "Media" module 7.2, and there is possibility to choose image style during content creation, but no possibility to change it later.

# Answer
> 1 votes
The Formatter Field module looks like the right one. Here is a quote about it (from the module's project page):

> ... provides a mechanism for specifying a formatter and formatter settings to be used for displaying a field, on a per-entity basis. By default, Drupal provides formatters and settings per entity bundle, but in certain situations it is necessary to choose the formatter at the entity level.
>
> For example, say you have a page node with an image field. Normally, you would select an image style as the formatter, and all page nodes would use that same image style. With this module, you can add a formatter field to page nodes, which is hooked up to the image field. Then when the node is created or edited, the image style can be selected per-node.

# Answer
> 1 votes
I have the same issue. I couldn't get the formatter field module to work. However, this module looks like it's currently working for what I need it for: Image Style Selector

It looks like it only has an alpha branch and it has a relatively small install base. Still, not seeing any issues with it so far.

Edit: Looks like I can't use the colorbox module with this one though.

# Answer
> 0 votes
There is a simple way to do it. You can simply add a field radio buttons with all style that you would like to propose.

Then when you display your image, you can simply create the URL with the chosen style with this field.

This theme function then will help you to retrieve the image with the style.

---
Tags: 7, media
---


# Question
Title: Giving permissions to a node to multiple accounts without creating a new role
I've built a site where all of the content is essentially private. All the relevant content types are Unpublished and my users (role=Owner) only have permissions to view/edit/delete their own Content. This is working just fine.

However, requirements have changed and I'm trying to figure out what to do. The new requirement is that an Owner can give permission to another user (role=OwnerAssistant) to view/edit/delete their data. I'll refer to the group of users that all administer the same dataset as an OwnerGroup.

It will not be feasible to create a Role for each of these groups because each new customer would need a separate role and we're hopefully going to have 50,000+ customers.

How can I control the permissions on a node so that a specific list of users can view/edit/delete that content? I'm ok with maintaining my own DB table that tracks the mapping of OwnerAssistants to Owners so that I have a way of determine if an OwnerAssistant is allowed to access content created by the Owner. However, I don't know how to let drupal know that uids 234, 894, and 1029 have x,y,z permissions to node 24590.

I will likely be integrating this with the Field Permissions module because I want to hide certain fields from OwnerAssistants.

Any help is appreciated!

# Answer
How about using Entity Reference to designate non-owner users that may edit the node?

You could make your own module with a function to handle permission checks, i.e. "return TRUE if user is referenced on node".

Then use other hooks (`hook_form_alter()` for instance) to show/hide edit buttons and override edit privileges on nodes.

You can secure it by making the entity reference field only accessible by the content owner.
> 1 votes

# Answer
Try module Node access user reference

> Gives content access permissions to users for content that references the users with User reference or Entity reference.
>
> This is great if you want your content authors to be able to choose additional authors, or choose who can view their content, as well as being able to display the list of authors or viewers within your content, or in views displays.
> 1 votes

---
Tags: 7, users
---


# Question
Title: Getting an error while installing drupal 7 using xampp
Getting an error while installing drupal 7 using xampp

> An AJAX HTTP error occurred. HTTP Result Code: 200 Debugging information follows. Path: http://localhost/tes/install.php?profile=standard&locale=en&id=1&op=do StatusText: OK ResponseText: Fatal error: Maximum execution time of 30 seconds exceeded in C:\XAMPP\htdocs\tes\includes\database\database.inc on line 2171

I also tried reinstalling xampp but still didnt work out

# Answer
Try to compare & update these values in `php.ini`.

> max\_execution\_time = 300
>
> max\_input\_time = 180
>
> max\_input\_nesting\_level = 300
>
> memory\_limit = 512M

**Note** : After these changes, restart the server.
> 0 votes

---
Tags: ajax, database, installation
---


title: Allowed strings for the text field

text:
# Question
Title: Allowed strings for the text field
I have the form which is created through Webform module and now I need to add one more text field but its value has to be unique and can be only the value from some predefined list of allowed values.

It's not the problem that value of the field be unique (I can enable it in text field settings) but I don't have idea how to limit the value of the field on one from predefined list of values.

Those strings are voucher codes that are sent to the clients by email, also there are a 1500 different codes.

If the user enters the code that was already used or enters the code that doesn't exist in the list he should get the notification that the code is not valid right away (Ajax) or on the form submit.

Can anyone can help me with this or direct me? I'll appreciate any suggestion...

# Answer
> 0 votes
In your custom module implement hook\_form\_alter, this will let you add your custom validation handler to the form, something like

```
  my_module_name_form_alter(&$form, &$form_state, $form_id) {
    if($form_id == 'your_form_id') {
      // Add one more validation.
      $form['#validate'][] = '_my_module_name_custom_form_valition';
    }
  }

  function _my_module_name_custom_form_valition($form, $form_state) {
   // $form_state holds value for submitted fields.
   if(!in_array($allowed_values,$form_state['values']['your_form_field']) {
      form_set_error('your_form_field',t('Entered value is not allowed.'));
   }
  }

```

---
Tags: ajax, entities
---


# Question
Title: ajax http 500 error while editing panel in drupal 7
I am getting this error when I tried to edit my panel in drupal 7.

> An AJAX HTTP error occurred.
>
> HTTP Result Code: 500
>
> Debugging information follows.
>
> Path: /panels/ajax/editor/edit-pane/panel\_context%3Apage-contacts%3A%3Apage\_contacts\_panel\_context%3A%3A%3A%3A/8
>
> StatusText: Internal Server Error
>
> ResponseText: 500 - Internal server error.
>
> Server Error 500 - Internal server error.

Anyone with solution highly appreciated. Thanks

# Answer
> 1 votes
Please check below configuration & update :

**php.ini**

> max\_execution\_time = 30 --\> 60 ;
>
> memory\_limit = 32 --\> 128, or even 256M ;

**.htaccess**

Add the below lines :

> php\_value auto\_append\_file none
>
> php\_value memory\_limit 128M

**my.ini**

> max\_allowed\_packet = 4M --\> 64M

---
Tags: ajax, panels
---


# Question
Title: image in newsletter does not apply image style (defaults to original size)
I'm using a simplenews template (simplenews-newsletter-body.tpl.php) to output with mimemail in html.

Everything works as it should except that the image in my newsletter is always taken from the original size (/sites/default/files/blogs/blablabla.jpg) instead of the smaller "image style" that I created.

In my template, I use the token: \[node:field\_image\], as it's the only available choice I found.

Do you guys have an idea of what I should try?

Thanks

# Answer
Disclaimer: I've not personally tested this in detail...

To apply specific formatting to an image token (thus applying an image style to the URL) I think you'll have to define a "token" view mode for relevant node content type. Once this view mode is setup you should be able to configure display settings on your field\_image field (within this view mode) which should used when the token is rendered.

Some instructions on that are available here.

To get full field token support, and therefore this feature, I think you have enable the actual token module. It looks like core's token support does not fully cover field tokens in this way.

It may also be worth looking into the imagecache\_token module. If I'm not mistaken it would allow you to declare an image style on your token directly via chaining, something like \[node:field\_image:style\_name\]. However, that module is not available as a stable release yet, and it's compatibility with field tokens is not totally clear.
> 0 votes

---
Tags: theming, tokens, emails
---


# Question
Title: Redirect unauthorized user to login page
I need to show only home page and some inner pages (which i will create using a common content type) to the anonymous user. I need to redirect all other access to home page where i added a login box. Is there a way to do it.

# Answer
Rather than redirect to the homepage, I would suggest using this:

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

it will allow you to explain to users why they've been redirected here, and also gives the the login page.

if you MUST redirect to the homepage, you can set the 403 page location to be: website.com/node
> 1 votes

# Answer
In the permissions, make sure anonymous users don't have access. Then go to Configuration -\> System -\> Site information (admin/config/system/site-information). At the bottom, put your home page in 'Default 403 (access denied) page'.

All traffic going to an unaccessible page, will be redirected here.
> 3 votes

# Answer
This is sample for administrator.

```
global $user;

if($user->uid = 1){ //check user here

  drupal_goto('some_page'); //redirect to some page.

  }

```

it will redirect administrator to whatever page you want.

if you want anonymous user redirect.You can use user\_is\_anonymous().

Sample:

```
   if(user_is_anonymous()){ //check user here

      drupal_goto('some_page'); //redirect to some page.

      }

```

it will redirect anonymous to whatever page you want.
> 2 votes

# Answer
I strongly suggest the module "Anonymous Login"

https://www.drupal.org/project/anonymous\_login

> This is a very simple, lightweight module that will redirect anonymous users to the login page whenever they reach any admin-specified page paths, and will direct them back to the originally-requested page after successful login.

You can also specify which pages you do not want to be restricted. These pages can be viewed by anyone. I believe it can do exactly what you're asking. Hope this helps.
> 1 votes

---
Tags: users
---


title: Webform component permission

text:
# Question
Title: Webform component permission
I have webform in my site, so I need to do that there are 2 user approval field components in my webform so they both should be unique value, in my case its working like if my name is joy then I submit that form then it will display joy on both field's value.

I want to just display only one field joy and another field value get from another user. please let me know if anyone has solution for this.

# Answer
> 0 votes
You can do by using Field Permission module.

Or first you have to create a user role. And apply condition to fields as per role.

Or you can use User Role Field module.

---
Tags: webforms, tokens, users
---


title: Two JS files attached to one module

text:
# Question
Title: Two JS files attached to one module
Alright, so I have two files which should be added to a module. This is the way I do it:

```
$form['display']['#attached'] = array(
    'js' => array(
      array('data' => drupal_get_path('module', 'test_module') . '/js/test_module.js'),
      array('data' => drupal_get_path('module', 'test_module') . '/js/common.js'),
    ),
  );

```

Now my test\_module.js file looks like this:

```
(function ($) {
Drupal.behaviors.test_module = {
  attach: function(context) {
    console.log(Drupal.settings);
  }
}});

```

And js works fine because I get data from Drupal.settings object. However, the second one is totaly the same and console.log does not work. Here's how it looks:

```
(function ($) {
    Drupal.behaviors.test_module = {
      attach: function(context) {
        console.log("test data");
      }
    }});

```

Why the second file does not work?

# Answer
> 2 votes
Don't duplicate the attach function.

```
(function ($) {
Drupal.behaviors.test_module = {
  attach: function(context) {
    console.log(Drupal.settings);
  }
}})(jQuery);

```

If you have used this for 1st JS

```
(function ($) {
Drupal.behaviors.test_module_2 = {
  attach: function(context) {
    console.log("test data");
  }
}})(jQuery);

```

Then you can use this for 2nd JS as the attach function should be used only once

# Answer
> 1 votes
You are duplicating the attach function here.

```
(function ($) {
Drupal.behaviors.test_module = {
  attach: function(context) {
    console.log(Drupal.settings);
  }
}})(jQuery);

```

This should be used only once. I mean in Drupal.behaviors.test\_module only one function can be attached to be called at document.ready

---
Tags: 7, javascript
---


title: save node after paypal payment success

text:
# Question
Title: save node after paypal payment success
In my projects, Whenever Authenticated user create new content(page) they should redirect to paypal for done payment when they click save. Once Payment Success Node should be save otherwise its should not save.

Please help me for Fix this concept.

Thanks in Advance

# Answer
> 1 votes
Get the response from Pay-pal if the response code is 200 save the node otherwise don't save it.

**for example :**

```
if ($responseCode == 200){
  //node_save($node);
}
else {
  print "payment failed";
}

```

https://www.drupal.org/node/1207878 check this for more info only for condition to check the payment status.

---
Tags: nodes, commerce, ubercart, payment-gateways
---


title: Issues with workbench moderation

text:
# Question
Title: Issues with workbench moderation
I've installed workbench and tried to work with it. I followed the step-by-step instructions given in the video here and I was almost successful in creating the content and moderating it between the two kinds of user one is `Publisher` and the other is `content-creator`.

`Content-creator` creates the content and forwards it to `needs-review`, now the publishers gets the access to the content in the `needs-review` tab. And the moderation should be done between these two users.

Here, my issue is when the `content-creator` creates a content - he is unable to see his content in his profile (I mean either in '`MyContent`', '`MyDrafts`' and '`Needs review`'). And the same case with the other user (publisher)- the `Needs-review` tab looks empty even though there is some content created by '`content-creator`'.

To keep it short, `MyWorkbench` tab looks empty- the `Needs-review` tab, `MyContent` tab and `MyDrafts` tab are empty. The only way the content appears is in Content tab.

I'm not aware of `workbench` module, I've followed all the instructions given in the video. I'm missing any?? Please give your answers.

Thanks in advance.

# Answer
> 0 votes
Check your permissions in the Admin area for Workbench for each Role at `admin/config/workbench/moderation/check-permissions`

This is a module that has been at 1.0 for a very long time and is mature.

# Answer
> 1 votes
I faced the same issue where 'Needs Review' tab appeared empty after the workbench moderation state for conten type is set to 'Needs Review' or 'Draft'by the creator. I applied a patch from drupal.org and it worked. Please find the below patch and apply it in your Workbench Moderation module.

https://www.drupal.org/files/node\_revision-1363990-2.patch

Let me know if you still face an issue.

# Answer
> 0 votes
Have you modified the default View that Workbench Moderation creates? Make sure that no changes have been made that may alter what is displayed in the various Workbench tabs.

# Answer
> 0 votes
Home \> Administration\> Configuration \> Workbench \> Workbench Access

Select Require a Workbench Access Form Element

I was using Drupal 7.34 , I also followed the same tutorial link The tutorial link

---
Tags: workbench
---


title: Views Custom Field Handlers tokens

text:
# Question
Title: Views Custom Field Handlers tokens
I am using simple views custom field handler. And I would like to make list of custom tokens for this $data array I have. How could I do that?

```
class custom_views_handler_field_hostname extends views_handler_field {

  function render($value) {

     $location = get_some_data_from_outside;

     foreach ($location as $key => $value) {
      $data [] =  $key. ': ' . $value;
    }

    if (!is_array($value)) {
      return theme('item_list',
          array(
            'items' => $data,
            'title' => NULL,
            'type' => 'ul'
          ));
    }
  }

```

# Answer
The first hook, `hook_token_info()`, is used to declare any custom tokens.

```
    /**
 * Implements hook_token_info().
 */
function module_name_token_info() {
  $info = array();
  // Define a new token type.
  $info['types']['my_custom_tokens'] = array(
    'name' => t('My custom tokens'),
    'description' => t('A token type for my custom tokens.'),
  );
  // Define any new tokens.
  $info['tokens']['my_custom_tokens']['my_cool_token'] = array(
    'name' => t('My cool token'),
    'description' => t('A token I use to show that I am cool.'),
  );
  return $info;
}

```

We are creating our own custom token type here too but if you just want to put your token in an already existing type, you can get a list of the existing tokens and types by calling `token_get_info().`

Now that our new token is good and defined, we just need to give it some content with `hook_tokens().`

```
     /**
     * Implements hook_tokens().
     */
    function module_name_tokens($type, $tokens, array $data = array(), array $options = array()) {
      $replacements = array();

      if ($type == 'my_custom_tokens') {
        // Loop through the available tokens.
        foreach ($tokens as $name => $original) {
          // Find our custom tokens by name.
          switch ($name) {
            case 'my_cool_token':
              // Work out the value of our token.
              $value = 'Whatever we want the token to be';
              // Give our token it's value!
              $replacements[$original] = $value;
              break;
          }
        }
      }
   return $replacements;

}

```

That's it! Our token should now be available and appear in the list of tokens wherever tokens are available.
> 0 votes

---
Tags: tokens, views
---


# Question
Title: Problem embedding user_register_form in custom template
I need to embed the user\_register\_form inside a template.

In my module i do:

```
....
$form=drupal_get_form("user_register_form");
unset($form["field_nickname"]);
unset($form["locale"]);
$output=theme("agent_new",array("element"=>array("form"=>$form, "var1"=>$var1, "var2"=>$var2)));

```

I specify "agent\_new" in hook\_theme and in agent\_new.tpl.php:

```
<div>
   <?php print drupal_render($element["form"]["field_first_name"]); ?>
</div>
<div>
   <?php print drupal_render($element["form"]["field_surname"]); ?>
</div>
...
<?php print drupal_render_children($element["form"]); ?>

```

The problem is that the \<form\> tag is not rendered and i need to insert it manually, i think this is not a good thing.

Where is the mistake? Do i need to directly theme the user\_register\_form ? Is it not possible to embed it in my theme?

# Answer
> 0 votes
You can try something like this:

In your `.module` file:

```
<?php

/**
 * Implements hook_form_alter().
 */
function YOURMODULE_form_alter(&$form, &$form_state, $form_id) {
  // User Register
  if ($form_id == 'user_register_form') {
    unset($form["field_nickname"]);
    unset($form["locale"]);
  }
}

```

In your `.tpl.php` file:

```
<?php
if (!$logged_in):
  $elements = drupal_get_form('user_login_block');
  $rendered = drupal_render($elements);
  $output  = '<form action="' . $elements['#action'] . '" method="' . $elements['#method'] . '" id="' . $elements['#id'] . '" accept-charset="UTF-8">';
  // Your required fields here!
  $output .= $elements['name']['#children'];
  $output .= $elements['pass']['#children'];
  $output .= $elements['form_build_id']['#children'];
  $output .= $elements['form_id']['#children'];
  $output .= $elements['actions']['#children'];
  $output .= $elements['links']['#children'];
  $output .= '</form>';
  print $output;
endif;
?>

```

---
Tags: 7, forms, users
---


# Question
Title: Flexslider view with pictures from nodes tagged with a taxonomy term
I need to group 10 images (random choice) of nodes belonging to a content type, and belonging to taxonomy *foo* with the term bar, **in a Flexslider**. How can I setup that content pane view ?

Precision : each node can have one up to ten images.

I created a content view,

* with that image field
* Filtered by content type
* Sort criteria : Global Random
* Contextual filter : Content : taxonomy foo(provide default value : taxonomy term ID from URL)

If I use format unformatted list / display all items, it gives me a list of expected images. But if I use Flexslider format, **it groups all the images of a single node in each slide !** I understand that the query result is grouped by nodes, when I just need its images ...

## View preview

# Answer
> 0 votes
I suspect the "Multiple field settings" in the view image field configuration. Try to uncheck "Display all values in the same row".

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


# Question
Title: Drupal 7 change default user login functionality
I want to change the default login functionality to look at a web service and if true log in else do not log in.

I have tried to use in `hook_form_alter`

```
 $form['#submit'] = 'user_change_login_submit';
  $form['actions']['submit']['#submit'][]= 'user_change_login_submit';

```

But it doesn't call this function.

# Answer
> 1 votes
I had a similar functionality in a project a while ago and I solved it by adding a validation handler and doing the check in that.

```
function mymodule_form_alter(&$form, &$form_state, $form_id) {
  // Replace the drupal authenticate function is it's used as validation.
  if (isset($form['#validate']) && is_array($form['#validate']) && ($key = array_search('user_login_authenticate_validate', $form['#validate']))) {
    $form['#validate'][$key] = 'mymodule_login_authenticate_validate';
  }
}

function mymodule_login_authenticate_validate($form, &$form_state) {
  // Set
  $account = mymodule_authenticate($form_state);
  if ($account) {
    $form_state['uid'] = $account->uid;
  }
}

function mymodule_authenticate($form_state) {
  // Your magic code here
  // In my project I either created a new user or updated an existing user and set $account as that.

  // And if everything went well in your code, finalize login and return account
  user_login_finalize($form_state['values']);
  return $account;
}

```

---
Tags: forms
---


# Question
Title: Drupal 7 CKEditor while replacing from textarea media files are not rendering
I'm working with Drupal 7 + WYSIWYG module + CKEditor + Field Collection.

My issue is, CKEditor is not rendering the media files which is included through media browser.

Steps to reproduce:

1. Create field collection field with unlimited occurrence.
2. Add some text and audio/video/document file using media browser with media teaser setting.
3. Now click "Add another item" button.

That's it now new field will be added, but the previous field will only have the text you entered, the media will be gone.

When I debugged the field, I found the values in hidden textarea. When CKEditor tries to render the values, media elements are not rendering.

# Answer
After a long research I found one solution from here.

The patch they provided works for me.

https://www.drupal.org/files/issues/interdiff\_8413.txt

I will leave this question open, so that others can get some help from this.
> 0 votes

---
Tags: 7, wysiwyg, entities, media
---


title: Empty taxonomy pages

text:
# Question
Title: Empty taxonomy pages
I am having a taxonomy problem that I can't figure out and my searches haven't helped. Basically, I have created a taxonomy to tag my pages and I can use this field with views etc without any problem. However, when I have created links to those taxonomy terms, the page is coming up as empty (except the term is listed at the top).

If I use /all, then it seems to be working without problem.

So, this works: /taxonomy/term/all

this doesn't: /taxonomy/term/17 (though that term does exist)

this doesn't /taxonomy/term/17/all

In addition, I am using the taxonomy menu module. If I add a new term, it shows up in the menu, but if the counter is enabled, they all show up as "0."

(Drupal 6)

slowly going crazy....

Thanks

# Answer
I believe this question is too broad to have a correct answer. As noted in the comments, there are a few ways that this symptom could occur (i.e. modules that intervene), and tools to diagnose further (e.g. the sql query tool).

For my money, your best bet is to first figure out what code is actually handling the url - you might be able to do that with some debug code, or else by inspecting the menu tables (which are also routing tables in Drupal 6).
> 2 votes

---
Tags: 6, taxonomy-terms
---


# Question
Title: How to remove "Main Menu" title from Stark Theme
I want to have just the main menu list elements displayed through only the stark theme and I can't seem to figure out where I should go to delete the title "Main Menu" that is above the main menu elements.

# Answer
> 2 votes
Go to `admin/structure/blocks`, find out the `Main menu`, click `configure`, and set title to `<none>`. This should resolve it.

# Answer
> 0 votes
Use CSS to hide it. Based on Stark's documentation, there isn't styling at all, so you would have to add a class to it. I assume you have a custom theme based on Stark. If not, check the documentation on how to do it.

# Answer
> 0 votes
Go to Appearance/Stark/Options and uncheck Main menu in the Toggle Display section

---
Tags: routes, theming
---


title: Editing Drupal Search SQL

text:
# Question
Title: Editing Drupal Search SQL
I'm using the basic Drupal Search module (search.module) and I want to customize the SQL of the search. I don't know how to go about doing this.

There are two things I want to edit in the SQL:

1) Have the search return ONLY nodes with start dates (event\_start\_date) AFTER now.

And

2) Return results in ascending order.

Pretty basic stuff.

Perhaps I need to use another search module entirely. I don't know.

Any thoughts or suggestions?

# Answer
I've had to do an alteration to a specific search query before, here's my general code:

```
/**
 * Implements hook_query_alter()
 */
function MYMODULE_query_alter(QueryAlterableInterface $query) {

  if (get_class($query) == 'PagerDefault') {
    foreach ($query->getTables() as $table) {
      if ($table['table'] == 'search_index') {
        $query->join('field_data_field_event_start_date', 'sd', 'n.nid = sd.entity_id');
        $query->where('sd.field_event_start_date_value >= CURRENT_DATE')
          ->orderBy('sd.field_event_start_date_value');

        break;
      }
    }
  }
}

```

I didn't want to alter other queries so I used a couple of checks to narrow down that I was altering a search query.

You may need to adjust your table/field names as appropriate, and if you wanted to order by title ASC rather than date just change the orderBy to 'n.title'
> 1 votes

# Answer
The Views module provides a `Search` view out-of-the-box (it's disabled). I would:

1. Turn off the default `Search` module.
2. Install Views.
3. Clone the default `Search` view in the Views administration page and call it `My SITENAME Custom Search`.
4. Add whatever filters you want to this View like the date criteria you list and adjust the deafult sorting if needed.

**tip:** you can easily search all the text in say the `title` **and** `body` field(s) of your Nodes with 1 text search box by adding a `Filter` of type `Global: Combine Filter` which uses the `title` and `body` fields in your `Views: Fields` section.

note for really really really massive sites you'll want to actually use a robust search engine. But as a proof of concept or small site (less than says tens of thousands of nodes) this should work Ok.

**EDIT**

To use the existing site search mechanism you would use `hook_query_alter` to change the query array to add `SQL` conditions to the `Where` clause of the query statement with whatever conditions you want. Note, that *perhaps* you may not have the sql fields needed for the query logic (you might thought). And if thats the case you would then need to use sql `Joins` to be able to reference the fields in SQL you want to do business logic on. Then add/modify a `sort by` sql clause, the same caveats about fields applies here again.

My Views solution above is 5 minutes worth of simple configuration and then adjusting some CSS. This solution could be 5 minutes if all the fields are in the SQL query already -- or much longer to figure out the necessary joins and syntax. The Devel module can help you inspect the raw search query. Good luck.
> 2 votes

---
Tags: search
---


title: Multisite setup with drush

text:
# Question
Title: Multisite setup with drush
Is it possible to set up multisite with drush including folder creation and database setup?

# Answer
For the first site:

`drush qd --sites-subdir=<directory name>`

For each successive site:

`cd DRUPAL_ROOT_CREATED_ABOVE
drush qd --use-existing --sites-subdir=<directory name>`

These will create sqlite databases. Add --db-url with valid database credentials to use a pre-existing database. Also add --db-su and --db-su-pw to make Drush create the database for you.

Haven't tried some of the steps in this workflow in a while; report any problems back in the Drush issue queue. Also, you might want to use drush master instead of 6.x. There's a issue in the queue that hasn't landed yet that makes drush qd better.

**UPDATE:** Drush quick-drupal does not appear to be well suited for multisite usage. For subsiquent sites, call `drush site-install` with `--sites-subdir` and `--db-url` options. See `drush help si` for more information on options that may be useful here.

For example

```
drush si --sites-subdir=<folder> --db-url=mysql://db_user:str0n6passw0rd@localhost/db_name

```
> 1 votes

---
Tags: drush, multi-sites
---


# Question
Title: How to make a block showing the content entity the author of the node is linked to?
I have a 'business' content type and an 'information' content type on my page. The author of the business is the webmaster and from the information the authors are the users of the site. The contenttype 'business' has an entity reference field targeting the users linked to that business

On the 'business' pages there is a block showing the 'information'articles published by the users linked to that specific business. So far no problem.

I would like to have a block on the 'information' pages showing the business the author of that node/article is linked to. The author of the contenttype business is always the webmaster and the author of the article is the user. I think that I don't understand the relationship that I must make to get this correct. The block has to look at the author of the node where the block is displayed and see the business where that user is linked to.

I'm completely blocked getting that done. I'm new to Drupal, there were no serious problems so far. But this I can't get done.I'm missing something in the contextual filters and relationships.

# Answer
You've stumbled into the issue of Context. Blocks can be placed anywhere, and has a very limited concept of context (the only context that Blocks know of are logged in user, and parameters taken from the url).

Normally one will use CTools (the Context specialist) and Panels to solve this type of problem. You are lucky in that Views has a relationship that can solve it for you.

**Construct your block as follow:**

Type Content, filtered by content type Information.

**Contextual filter:**

Content: Nid (The node ID.), no relationship, and for WHEN THE FILTER VALUE IS NOT AVAILABLE you add Content ID from URL

**Relationships:**

1. Content: Author (Relate content to the user who created it.), and Require this relationship
2. Entity Reference: Referencing entity (A bridge to the Content entity that is referencing User via field\_users - Your field will be differently named, mine is field\_users). Set the relationship to 'author' (the first relationship added), and Require this relationship.

**Fields:**

I assume you are adding the node title. Make sure to set the relationship to: Content referencing Users from field\_users (the 2nd relationship you added - yours will be named slightly different)

If you add any other fields make sure to set the relationship as well.

If you find that it lists any duplicates, just go to OTHER in views, and under Query Settings, set it to Distinct (I'm sure this won't be necessary though).
> 1 votes

# Answer
Thanks very much for your quick reply! Really appreciate it.

The setting u describe is the way i have the blocks working on the nodes with the 'business' content. The blocks show the articles written by the users that are linked to that business.

I cant get it working the other way around. On the 'article' nodes i would like to have a block that shows the business that the author of that particular node is linked to. I was thinking that the problem is maybe in the relationship author. The contenttype business has as author the webmaster and not the users of the site who are writing the articles.

Could that be? English is not my mothertongue.. so maybe i completly misunderstand?
> 0 votes

---
Tags: entities, views
---