# Question
Title: Manage Display page not displaying anymore
I set (or at least tried to) my user display page (admin/config/people/accounts/display) to use DS 1col on friday and part way through the request my computer crashed out (the server is running on the local machine too) and now I can't seem to access that page if I let it run forever I get:

> Fatal error: Maximum execution time of 120 seconds exceeded in /Applications/MAMP/htdocs/modules/field\_ui/field\_ui.admin.inc on line 145

I've tried to:

* Clear caches
* Run cron
* Disable and re-enable DS

Although I'm continuing to play with DS, I'm assuming whatever got corrupted is related to the field\_ui module because of the error and it only seems to be affecting the manage display for the user account page; no other user account pages or manage display pages are affected.

Does anyone know if there is a simple way to reset that page to the default?

# Answer
> 0 votes
after playing around in the database for awhile and trying things (I backed it up first) I found the problem in the field\_group table by deleting all the default user groups I can now see and edit the manage display page for the account

---
Tags: entities, users, display-suite
---


title: Remove forum comment title

text:
# Question
Title: Remove forum comment title
I'm having problems with removing the title of comments on my forum. I'm using the advanced forum module and the 'comment title' option is disabled. Anyone knows how to remove it? Thanks!

# Answer
First install the devel module and then check the theme registry to see if the forum form is in the theme registry or not. for more information about registering a form visit this page. as an example to register the comment form you must use this code:

```
function YOUR-THEME-NAME_theme($existing, $type, $theme, $path) {
    return array(
           'comment_form' => array(
               'render element' => 'form',
            ),
       );
};

```

**When checking the existence the form theme in theme registry make sure that you use the *YOUR-THEME-NAME* as administrator theme.**

Now use the hook\_form\_id\_alter to customize the form.to see the form elements write:

```
kpr($form);

```

now you can hide or change the order of form elements.

Here is the video tutorial
> 0 votes

---
Tags: nodes
---


# Question
Title: Programatically created node type does not display title field
I have created a new node type within a module (for Drupal 7). I have created fields for it programatically as well and they all display. The one problem I am experiencing is that the title field does not display. I am not sure how or where to look to fix this. The title field does display in the node type's manage fields display.

Here is the code for creating the node type in hook\_install():

```
// define the node type
  $type = array(
    'type' => $machine_name,
    'name' => $t($parameters['name']),
    'base' => 'room_reservations',
    'module' => 'room_reservations',
    'description' => $t($parameters['description']),
    'has_title' => TRUE,
    'title_label' => $t($parameters['title_label']),
    'custom' => FALSE,
    'locked' => TRUE,
    'disabled' => FALSE,
  );

// set other node defaults not declared above
  $content_type = node_type_set_defaults($type);

// add the body field
  node_add_body_field($content_type, $t($parameters['body_label']));

// save the content type
  node_type_save($content_type);

```

# Answer
> 0 votes
Drupal does not display the title field in the manage display page by default.

You would have to use Display Suite Module and enable a layout for the page to get the title and other fields to display in the Manage Display page.

# Answer
> 0 votes
To automatically have the node title you need to define "node\_content" as base for the node type. Else I think you have to implement the title form field display/store for your node add/edit form

---
Tags: 7, installation
---


# Question
Title: Theming / modifying the markup of default search block form
I'm trying to modify the basic search block form that comes with Drupal 7 core. I have a custom theme and inside my templates folder I copied the search-block-form.tpl.php and modified it like so

```
<form action="/fi" method="post" accept-charset="UTF-8" class="ng-pristine ng-valid form-inline" novalidate role="form">
<div class="form-group">
    <div class="input-group">
        <input
            title="<?php print t('Type in your search terms'); ?>"
            type="text"
            name="search_block_form"
            value=""
            maxlength="128"
            class="form-text" />
    </div>
    <?php print $search['hidden']; ?>
</div>
<button
    type="submit"
    name="op"
    class="btn btn-default">
    <span class="glyphicon glyphicon-search"></span>
</button>

```

But when I look my rendered markup on page it is totally different.

```
<form action="/fi" method="post" id="search-block-form" accept-charset="UTF-8" class="ng-pristine ng-valid">
<div>
    <div class="form-group">
        <div class="input-group">
            <input title="Type in your search terms" type="text" name="search_block_form" value="" maxlength="128" class="form-text">
    </div>
    <input type="hidden" name="form_build_id" value="">
    <input type="hidden" name="form_id" value="search_block_form">
</div>
<button type="submit" name="op" class="btn btn-default">
    <span class="glyphicon glyphicon-search"></span>
</button>
</div>
</form>

```

Why is there an extra div inside the form and where is my form-inline class and who put that id on my form? Why isn't my markup rendered as I wrote it? I also tried to remove all unnecessary preprocessing by overriding xxx\_preprocess\_search\_block\_form and xxx\_form\_alter but nothing seems to work.

And yes I have tried to clear theme cache many times.

This is driving me insane about Drupal. All this "magical" stuff that keeps happening when I'm trying to accomplish even the most simplest templating tasks. Could someone please explain what is going on? Thanks!

# Answer
First of all nothing is "magical" and if you are new to drupal then you have not looked into the Form API or ignored it.

What you are trying to do resides on hooking into the form api using the hook\_form\_alter or hook\_form\_FORM\_ID\_alter functions. The "magical" inline elements on your form are being handled by the form API I spoke of. You are trying to enter form elements and a button into a template file which is not only a security issue but is not the way that drupal handles forms.

You will need to create a custom module and add your hook\_form into there and use the form api I spoke of to handle what you are trying to do.
> 3 votes

---
Tags: 7, theming, forms, blocks, search
---


title: Display taxonomy field in node display

text:
# Question
Title: Display taxonomy field in node display
I created a vocabulary where terms have an image as additional field.
I want to show the image instead of the term name in the node page. How can I do this?
In Drupal 6.x, I would load the term and display it, but I guess in Drupal 7 with field API there must be a better way to do this.

# Answer
You could define your own formatter with hook\_field\_formatter\_info() and then select that in the Manage display screen of the content type/view mode you want to be displayed like that.

For reference, have a look at what taxonomy.module is doing: taxonomy\_field\_formatter\_info(), taxonomy\_field\_formatter\_prepare\_view() and finally taxonomy\_field\_formatter\_view().
> 3 votes

# Answer
You can do it without custom code by using an Entity Reference field (with a target type of "taxonomy term") to link to the taxonomy instead of a Term Reference field. Set the display mode of the field to "Rendered Entity" and make sure the Display for the taxonomy vocabulary includes all of the fields you want.

If your vocabulary is large, or if content creators need to see the additional fields when choosing to associate the terms with content, you may also want to add the Entity Reference View Widget or Entity Reference Browser. Both of these allow you to use a view to build the UI that content creators use to select a term.

(That Entity Reference Browser is a sandbox project, but it's a great module and I've been using it happily for the past two years. I mention it specifically because the OP mentions having an image as an additional field in the taxonomy vocabulary; I really like the ERB for this use case).
> 2 votes

# Answer
Here's how to do it with the Views Module:
Are taxonomy fields exposed to views?
> 1 votes

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


# Question
Title: There's something terribly wrong with the CKEditor, and I can't remove it
Although I have advanced knowledge in HTML, JS, and CSS, I have some co-workers who do not. For that reason, I have installed the CKEditor module, which they love.

I, on the other hand, have had nothing but grief with this module. . . Let me explain.

I have been making and editing "templates" in Notepad++, copying them, and pasting them into the CKEditor through the "plain text" option.

This usually works, kinda... At least it only screws things up in a way I can work around, usually.

Right now, it is screwing things up in a way that I cannot work around.

So, lets say I enter a block like this one:

```
<p>
    <a href="facebook.com" >
        <div class="facebook" ></div>
    </a>
    <a href="twitter.com" >
        <div class="twitter" ></div>
    </a>
    <a href="linkedin.com" >
        <div class="linkedin" ></div>
    </a>
</p>

```

*This is almost exactly what I am entering*

And what I get instead is this:

```
<p>
    <a href="facebook.com" >
</p>
<div class="facebook" ></div>
<a href="facebook.com" ></a>
<a href="twitter.com" >
    <div class="twitter" ></div>
</a>
<a href="linkedin.com" >
    <div class="linkedin" ></div>
</a>
<p></p>

```

I've tested this in multple different browsers and I am getting the same result. What am I doing wrong? Is this a known issue? Is there a different Wysiwyg editor I can use that doesn't have this issue? Thanks everyone!

# Answer
I found the answer I needed (not quite the one I was looking for) thanks to @Trey for pointing me in the right direction. My issue was with the CKEditor DTD.

I simply had to remove the `<p>` element for my block to work:

```
<a href="facebook.com" >
    <div class="facebook" ></div>
</a>
<a href="twitter.com" >
    <div class="twitter" ></div>
</a>
<a href="linkedin.com" >
    <div class="linkedin" ></div>
</a>

```
> 0 votes

# Answer
CKEditor does this intentionally because your inline tags should not contain block level tags.... an easy work around is to change your divs to spans and add a class that makes the span display block.

If it is your preference to use invalid html (I have needed to before) another option is to add this line:

`CKEDITOR.dtd.a.div = 1;`

I wouldn't recommend this unless absolutely necessary since changing the dtd can have unexpected results.
> 1 votes

# Answer
So drupal allows admins to create text formats (see at /admin/config/content/formats). There you can create multiple different text formats (like an html format, plain text, etc, etc.)

You could duplicate the Full Html, name it something like "Full HTML (No Wysiwyg)." If you download the WYSIWYG module, I think you should be able to use that to tell ckeditor what text formats to be used on. So if you download and install that module, you should be able to control what text formats ckeditor shows up on at /admin/config/content/wysiwyg.
> 1 votes

---
Tags: 7, wysiwyg
---


# Question
Title: How install a module without break the installation if error
When I install my module, I get the following error:

> Declaration of Drupal\media\_gallery\Form\GalleryForm::create() must be compatible with Drupal\Core\DependencyInjection\ContainerInjectionInterface::create(Symfony\Component\DependencyInjection\ContainerInterface $container) in

I can't uninstall my module and I need to re-install all Drupal 8, since my module is not displayed in the uninstall tab.

How can I fix this without re-installing Drupal 8?

# Answer
> 1 votes
I'm not sure what exactly you are asking?

Yes, I've seen it as well that when a module installation fails, then it is neither installed nor uninstalled properly. That seems like a core bug, not something that can be "answered away", so you should open a bug report instead.

For the actual error you have, the only thing that is not already in the message is that you might be missing the user for ContainerInterface or have the wrong use.

# Answer
> 0 votes
I believe that Drush has the ability to uninstall modules.

---
Tags: 8, installation
---


# Question
Title: How can I undo the changes made by setting a private file system path?
I was installing the demo module on D7. I wanted to create a snapshot to use the demo reset part of the module. It told me to set the private file system path. So I entered the directory where all my websites live. /var/www/vhosts/domainname.com/ . Inside that folder there is a folder by domain name for each domain in the subscription. Including the folder for the site where i changed the path.

Now all the websites that are contained on the subscription are broken. As you can imagine, I'm desperate to know how to undo whatever I did. I'm so confused as yto how it has effected the other websites. I thought it was just going to be used to store the snapshot.

# Answer
When I set the path to the directory that contained my actual site/s, it placed a .htaccess file restricting access. Being as that folder contained many Drupal sites, all sites seemed broken.

Deleting that .htaccess file in the folder I entered resolved the issue.
> 0 votes

---
Tags: 7, files
---


title: Chrome makes images in Views smaller

text:
# Question
Title: Chrome makes images in Views smaller
I made Views page in table format. 2 columns. In the left - image in format 220x220 (resizing by Drupal). Right column consists from text. When I see page from Chrome, I noticed that images in first comn are extremely small.

What can be the problem?

# Answer
> 0 votes
Try setting width:220px to the left td elements in the table.

In css: table tr td:first-child {width: 220px;}

---
Tags: views
---


# Question
Title: Can a Drupal view show some fields for one role and other fields for another role without having two page views?
I need to create a view showing the history of the users events. I need the authenticated users to be able to see part of the view, certain fields, and the admin to see all fields in the view. The fields are user\_id, activity\_id, title, status. I need the user\_id and activity\_id to be hidden from the authenticated user but not the admin. I know how to control the whole view but not fields in that way.

Has anyone tried to manage that? Is there a way to do this?

# Answer
> 0 votes
You can add all the fields to the view and than hide some of them in either a hook, a preprocess function or a template file.

There views module provide many hooks for you to use i suggest the views view pre render hook.

If you choose the preprocess route than you will need to find the correct template first. Go to the view configuration page and look for a link called theme info. That link will be placed in the advanced column at the very bottom.

After you know which template you need add the corresponding preprocess function to your THEME.theme file.

Fit the views-view-unformatted.tpl.php a function called THEME\_views\_view\_unformatted\_preprocess will work.

---
Tags: views
---


# Question
Title: Why does dpm() sometimes fail and krumo() works
They both dump variables in the same format & style. From some articles or documentation that I'd read, it seems `krumo()` calls `dpm()`.

The problem is that sometimes I call `dpm($var)` and nothing happens, but `krumo($var)` on the same script works fine. I think I'd had the same problem in the reverse circumstance(ie: `krumo($var)` does not work, `dpm($var)` works). Why is this so? Is there some structure that needs to be available on the particular page or script that either of these functions uses for it's display? Maybe some region or block?

# Answer
typically `inline php code` such as a `views php` field value, or a Display Suite code field for example ... doesn't always run in a page's context.

When you have a field expecting `<?php /* some code here */ ?>` this is run an Anonymous php function and `returns` a value.

In my experience `dpm()` doesnt always work in these cases.

Another example is trying to `dpm` within a `Cron` or `Queue` task. These dont run in a page context either so using something like Devel's `dd` function can be useful.
> 0 votes

# Answer
Another problem with dpm is that if you call if from a theme function a preprocess or a template it will only work after a refresh. That is because the place the date gets printed is already processed when calling the dpm function
> 0 votes

---
Tags: debugging
---


# Question
Title: How to return boolean with math expression comparison in Views
I want to output a boolean value like this:

*if some field value (e.g. \[comment\_count\]) \> x (my constant, e.g. 5) = 1, else 0*

without installing Views PHP (or other modules) or having to create a field.

I tried with the Views field "Global: math expression" but that won't support comparisons.

Is there a math expression or another simple way to do this within my view?

PS: I thought I could use **floor(logX(\[comment\_count\])** but logX() seems not supported: it always returns 0. Custom base logarithm is among PHP math functions but not present in Views? :(

# Answer
Easiest method is to either use hook views view pre render out a preprocess function.
> 0 votes

---
Tags: views
---


# Question
Title: How do I store URL parameter in user registration field?
I'm trying to store a url variable into a field on the user registration page.

Can I use javascript to pull that variable and store it in one of the input fields?

# Answer
> -1 votes
Using hook\_form\_alter you can set the default value of your field to be this query parameter.

```
function MY_MODULE_form_alter(&$form) {
  $q = drupal_get_query_parameters();
  $form['parameter_field']['default value'] = check_plain($q['aid']);
}

```

---
Tags: users
---


# Question
Title: how to add a class to the widget pager of views slideshow
I want to add a class to the widget pager of views slideshow. I found the function in the file /theme/views\_slideshow.theme.inc wich theme the wrapper of the widget

```
function theme_views_slideshow_pager_widget_render($vars) {
  // Add javascript settings for the pager type.
  $js_vars = array(
    'viewsSlideshowPager' => array(
      $vars['vss_id'] => array(
        $vars['location'] => array(
          'type' => preg_replace('/_(.?)/e', "strtoupper('$1')", $vars['settings']['type']),
        ),
      ),
    ),
  );

  drupal_add_js($js_vars, 'setting');

  // Create some attributes
  $attributes['class'] = 'widget_pager widget_pager_' . $vars['location'];
  $attributes['id'] = 'widget_pager_' . $vars['location'] . '_' . $vars['vss_id'];
  return theme($vars['settings']['type'], array('vss_id' => $vars['vss_id'], 'view' => $vars['view'], 'settings' => $vars['settings'], 'location' => $vars['location'], 'attributes' => $attributes));
}

```

I just want to modify the line to add my own class (as grid-6 for example)

```
$attributes['class'] = 'widget_pager widget_pager_' . $vars['location'];

```

I try to use this function in my file template.php without success.

the classes of the wigdet pager in my html code are :

```
views-slideshow-pager-fields widget_pager widget_pager_bottom views_slideshow_pager_field views-slideshow-pager-field-processed

```

So i imagine that an other function add the classes. But wich ?

How can i do this ? May i write a module or simply use a preprocess function in my template.php

Thanks

# Answer
> 1 votes
In fact, after looking at the HTML code generated by views slideshow, pager widget is contained in a div on the same level that the content of the slideshow. So even if I could add a class, it would not be useful because I already positioned text to the right of my image. So the div content of the slideshow is already 100% of the width (and the sub-content have already custom classes to position them in line) .

So I have to use position: absolute to position the pager widget, so I can just add my classes on the container of all global gadgets (positioned at the bottom) by overriding the template views-slideshow.tpl.php as below, and then use the default classes of the widget in my css.

```
views-slideshow--MY-BANNER.tpl.php

<div class="skin-<?php print $skin; ?>">
  <?php if (!empty($top_widget_rendered)): ?>
    <div class="views-slideshow-controls-top clearfix">
      <?php print $top_widget_rendered; ?>
    </div>
  <?php endif; ?>

  <?php print $slideshow; ?>

  <?php if (!empty($bottom_widget_rendered)): ?>
    <div class="views-slideshow-controls-bottom MY-CLASSSES clearfix">
      <?php print $bottom_widget_rendered; ?>
    </div>
  <?php endif; ?>
</div>

```

But I'd like to know if this is possible and with wich function.

# Answer
> 0 votes
Here is a `hook_preprocess_HOOK()` solution.

I couldn't find a way to add a class to `theme_pager()`, so I decided to take a closer look at the source and found that views pagers are also run through `theme_item_list()` which does allow you to add classes.

```
function MYTHEME_preprocess_item_list(&$vars) {
  $vars['attributes']['class'][] = 'my-class';
}

```

You can/should add an if condition check to see that the list really is going to be a pager, e.g. use `if ($vars['attributes']['class'][0] == 'pager')` or some other identifier to confirm that you're adding the class to a pager ul.

---
Tags: paging, entities, javascript
---


title: How to change pager class to view

text:
# Question
Title: How to change pager class to view
I have HTML desing of pagger ,How to I assign my own class to pager in side view ?I dont have any idea about it so will you plese tell how can I ?

# Answer
> 0 votes
I believe there are two ways you can do it:-

1. In template.php , you can use theme\_pager. Then overrite it.
2. You can make a views template and overrite it. For this just goto advance option in views and search for template suggestion.

# Answer
> -1 votes
I could not find a way to add a class to `theme_pager()` using the `hook_preprocess_HOOK` system, so here is a slightly different `template.php` solution that won't involve having to override a core function.

I noticed that views pagers are also run through `theme_item_list()` which does allow you to add classes.

```
function MYTHEME_preprocess_item_list(&$vars) {
  $vars['attributes']['class'][] = 'my-class';
}

```

You can/should add an if condition check to see that the list really is going to be a pager, e.g. use `if ($vars['attributes']['class'][0] == 'pager')` or some other identifier to confirm that you're adding the class to a pager ul.

---
Tags: paging
---


title: Node translate tab access

text:
# Question
Title: Node translate tab access
Why translate tab only available for super Admin in node & taxonomy form. how can i view this tab & also button of save & translate for both Node & Taxonomy to another roles (Editors & Translators), what is the proper permission access should be given to show the translation tab ?

Forget to mention, this happen only when the node or content is unpublished, but if its published the tabs appear normally.

# Answer
I think it's because the not-super-admin users don't have permission to edit unpublished content that they didn't create.

If you want to alter this behavior you can add a new permission "edit any unpublished content" and use hook\_node\_access to allow editing unpublished nodes (if they have that permission)
> 0 votes

---
Tags: i18n-l10n
---


title: Taxonomy term count per vocabulary

text:
# Question
Title: Taxonomy term count per vocabulary
I want to count taxonomy terms for one (or per) vocabulary. I know, it can be done via views with aggregation but I wonder if there is another way to do this without using views.

There is a taxonomy vocabulary. There are terms in this vocabulary. **I want to learn how many terms are there in this vocabulary.**

Is there a method to show term counts as node count below?

```
<?php $counter = db_query("SELECT count(nid) FROM {node} WHERE node.type='page' AND node.status=1")->fetchField(); ?>

```

# Answer
For count the number of term in a vocabulary you can use this method : taxonomy\_get\_tree($vocabulary\_id). It will returns all the terms of the vocabulary in an array. After that, you only have to get the size of the array.

Example :

```
$terms_array = taxonomy_get_tree(9); //9 is the vocabulary ID.
$terms_nb = sizeof($terms_array); // $terms_nb = your number of terms.

```
> 4 votes

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


# Question
Title: Can't access global user object after drupal_bootstrap
I have a stand-alone php script with the following lines at the beginning:

```
define('DRUPAL_ROOT', '../../../../../');

require_once DRUPAL_ROOT . '/includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);

```

And this is giving me access to all of Drupal's functions just fine, however, when I try to access the global user object, it's as if the user is not logged in (IE the user object says the user is anonymous and has a UID of 0), even though I know they are because when I browse the site normally, the user is logged in.

Why does it not pick up the user's session in my script?

# Answer
> 3 votes
The solution was a one line fix:

```
define('DRUPAL_ROOT', '../../../../../');
$base_url = 'http://' . $_SERVER['HTTP_HOST'];
require_once DRUPAL_ROOT . '/includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);

```

Note the addition of $base\_url

# Answer
> 0 votes
Add `global $user` after `drupal_bootstrap`, that makes user's `$user` object available in your script.

Example:

> ```
> require_once './includes/bootstrap.inc';
> drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);
> global $user;
> print $user->name;
>
> ```

# Answer
> 0 votes
You need to set $base\_url to $\_SERVER\['HTTP\_HOST'\] with 'http://' prepended and then it will work from a subdirectory.

# Answer
> 0 votes
This is my boilerplate for stand alone php. I mainly use it for debugging so adjust accordingly.

```
if (isset($_SERVER['argc']) || isset($_SERVER['argv'])) {
  // Set server variables if cli.
  $_SERVER['REMOTE_ADDR']     = '127.0.0.1';
  $_SERVER['SERVER_SOFTWARE'] = NULL;
  $_SERVER['REQUEST_METHOD']  = 'GET';
  $_SERVER['QUERY_STRING']    = '';
  $_SERVER['HTTP_USER_AGENT'] = 'console';
}

// Find index.php
$webroot = str_replace('\\', '/', dirname(__FILE__));
$webroot = str_replace('\\', '/', realpath(dirname($_SERVER['SCRIPT_FILENAME'])));
while (!empty($webroot)) {
  if (file_exists($webroot . '/index.php') && strpos(file_get_contents($webroot . '/index.php'), 'menu_execute_active_handler();') !== FALSE) {
    break;
  }
  $new_webroot = str_replace('\\', '/', dirname($webroot));
  if ($new_webroot == $webroot) {
    $webroot = str_replace('\\', '/', getcwd());
    break;
  }
  $webroot = $new_webroot;
}
chdir($webroot);
/**
  * Root directory of Drupal installation.
  */
define('DRUPAL_ROOT', getcwd());
require_once DRUPAL_ROOT . '/includes/bootstrap.inc';

// Set the base URL.
$base_url = 'http://' . $_SERVER['HTTP_HOST'];
// Set https to on if it should be.
if ( (isset($_SERVER["HTTPS"]) && strtolower($_SERVER["HTTPS"]) == "on")
  || (isset($_SERVER["HTTP_X_FORWARDED_PROTO"]) && $_SERVER["HTTP_X_FORWARDED_PROTO"] == "https")
  || (isset($_SERVER["HTTP_HTTPS"]) && $_SERVER["HTTP_HTTPS"] == "on")
    ) {
  $_SERVER["HTTPS"] = "on";
}
// Fix base URL if HTTPS.
if (isset($_SERVER["HTTPS"]) && strtolower($_SERVER["HTTPS"]) == "on" && isset($base_url)) {
  $base_url = str_replace("http://", "https://", $base_url);
}

try {
  drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);
  ini_set('memory_limit', '8000M');
  $output = array();
  $time_start = microtime(true);
  set_time_limit(0);
  // header('Content-Type: text/plain');

  // Run code here.

  $time_end = microtime(true);
  $time = round($time_end - $time_start, 4);
  echo "took $time seconds<br>\n";
}
catch (Exception $e) {
  echo 'Caught exception: ',  $e->getMessage(), "\n";
}

```

---
Tags: 7, users, sessions, bootstrapping
---


# Question
Title: Can't get jQuery UI autocomplete working
The text field that is created seems to just act like a normal textfield, no autocomplete function or any indication that it works at all.

There's no errors in the console. I've run checks to see if jQuery UI is loading, it is. I'm using jQuery Update module, so both libraries are at version 1.10.

I'm using the Bootstrap theme, but I've tried disabling that and using Bartik, it makes no difference.

Any ideas?

Here's the form alter function I'm using in my module. It fires just fine.

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

    $form['business_category'] = array(
        '#title' => t('Business Category'),
        '#description' => t('Category' ),
        '#type' => 'textfield',
        '#id' => 'business_category',
        '#attached' => array(
            'library' => array(
                array('system', 'ui.autocomplete'),
            ),
            'js' => array(
                drupal_get_path('module', 'mymodule') . "/custom.js",
            ),
        ),
    );

}

```

Here's custom.js

```
(function ($) {

        $( "#business_category" ).autocomplete({
            source: [ "cat1", "cat2", "cat3" ]
        });

})(jQuery);

```

# Answer
Adding drupal behaviours, as suggested by @2pha, did the trick:

```
(function ($) {
    Drupal.behaviors.infiniteScrollAddClass = {
        attach: function (context, settings) {

            $( "#business_category" ).autocomplete({
                source: [ "cat1", "cat2", "cat3" ]
            });
        }
    }

})(jQuery);

```
> 0 votes

---
Tags: forms, javascript
---


# Question
Title: Acquia Dev Desktop Redirects to Live Site
I have a weird thing happening - I took a copy of my live site, and a dump of my database, and imported it into the Acquia Dev Desktop application to run a dev site locally. This site has worked in this manner in the past. However, when I do this now, visiting the local path (ex. localhost:8082) redirects to my live site out on the web. I believe it's something in the database, as running the code with a standard Acquia database works, but as soon as I swap in the database from my live site the redirect occurs.

Any ideas what could be causing this?? I don't have anything in rules or actions to redirect anything, and I don't know what else it would be.

# Answer
> 1 votes
I encountered this problem tody, and it turns out that the securepages module causes it. After disable that module, everythin works.

Though, don't forget to enable the module before going online.

---
Tags: 7, acquia-dev-desktop
---


title: Theme table with html

text:
# Question
Title: Theme table with html
I am using custom module to insert and rendering data from Drupal Database.Is it possible rendering data using theme table in my custom div block

# Answer
You could render content as table using **Theme Table**

```
<?php
$table_element = array(
    '#theme' => 'table',
    '#header' => $header,
    '#rows' => $rows,
    '#empty' =>t('Your table is empty'),
);
drupal_render($table_element);
?>

```

Here are some Examples for it:
> 2 votes

---
Tags: theming
---


title: Generate a new form

text:
# Question
Title: Generate a new form
I want to insert a form element (`type = 'select'`) into an EXISTING page.

Normally we would use define a new page with a page callback, the page callback would then call `drupal_get_form`.

In this case, the page is being generated by views and I want to simply insert a form field within `hook_views_pre_view` .

Not having success so far with `drupal_get_form` or `drupal_build_form`.

`drupal_build_form` is advertised as returning a rendered form. But doesn't seem to work.

# Answer
In Drupal 7 you can achieve by the following steps

* You can embed a **node creation form** inside a VIEW

+ Either in **VIEW Header** or you can created a **new VIEW and attach it to your VIEW**
* For this example I am embedding inside **Views Header**. Embedding inside **Views Header** will be the better options. Click to **Add Views Header**
* Select Global: Text area
* Add the PHP code and don't forget to change the **Text Format to PHP**
* PHP code

```
<?php
    module_load_include('inc', 'node', 'node.pages');
    $node_form = node_add('node_type');
    print drupal_render($node_form);
?>

```

Note :

* Don't forget to replace **node\_type** in the PHP code.
* Use **hook\_form\_alter** for node form redirection, as after the node creation the form will redirect to node detail page. If you want to redirect to your page then use `$form_state['redirect'] = 'mycustompage';` reference
* Enable **PHP Filter** module using **admin/modules**

* Set the **Permissions** for this module by enabling "Administrator" for **Execute PHP Code** as follows:
> 0 votes

---
Tags: forms
---


# Question
Title: "Entity Content" not available in views UI
I have installed Eva module (7.x-1.2). I can't see Entity Views attachemet section on my views screen.

I want a replicate what is described in this video for creating galleries. Its 2:30 mins in https://www.youtube.com/watch?v=XPlY8MUl0XQ

Please help.

# Answer
Finally, I found the alternate solution to the problem. If the Entity content is not showing up, add EVA view display, show do (admin/structure/views/add new views/add/EVA filed)
> 0 votes

---
Tags: views, entities
---


# Question
Title: Views Bulk Operations Checkboxes check on click
I do search for a specific option in bulk operations. For now, when I click somewhere in my row, the checkbox for the bulk operation gets selected, but I want a user to directly click on the checkbox. If he clicks somewhere in the row, it shouldn't select the row for bulk-operations. Any chance to do that without hacking the core?

In short: only a direct click on the checkbox should select the row for bulk operations.

# Answer
This is due to the **JQuery** in `views_bulk_operation.js` :

```
    // Set up the ability to click anywhere on the row to select it.
$('.views-table tbody tr', form).click(function(event) {
  if (event.target.tagName.toLowerCase() != 'input' && event.target.tagName.toLowerCase() != 'a') {
    $('input[id^="edit-views-bulk-operations"]:not(:disabled)', this).each(function() {
      var checked = this.checked;
      // trigger() toggles the checkmark *after* the event is set,
      // whereas manually clicking the checkbox toggles it *beforehand*.
      // that's why we manually set the checkmark first, then trigger the
      // event (so that listeners get notified), then re-set the checkmark
      // which the trigger will have toggled. yuck!
      this.checked = !checked;
      $(this).trigger('click');
      this.checked = !checked;
    });
  }
});

```
* Commenting them will solve it but instead of hacking the core. In your custom js file add something like:

> ```
> $('.views-table tbody tr').off();
>
> ```

* This will disable all event handlers!!
> 0 votes

---
Tags: 7, views
---


# Question
Title: Difference between #type and #theme in Render API
I am reading this theming article http://themery.com/dgd7/advanced-theming/render/manipulate and I have a question.

This article has the following code:

```
$page['highlighted']['new_stuff'] = array(
'#type' => 'container',
'#attributes' => array('class' => 'my-container'),
);
$page['highlighted']['new_stuff']['heading'] = array(
'#type' => 'html_tag',
'#tag' => 'h2',
'#value' => t('Heading'),
'#attributes' => array('id' => 'my-heading'),
);
$page['highlighted']['new_stuff']['list'] = array(
'#theme' => 'item_list',
'#items' => array(
  'First item',
  'Second item',
  'Third item',
),
);

```

I see that when you provide the #theme property you are telling the Render API to use the theme\_item\_list, and you pass it the #items variable. But isn't that exactly what you are doing when you set type to #html\_tag, you're using the theme\_html\_tag and passing it variables?

# Answer
> 5 votes
The purpose is a little different:

* `'#type'` is telling to the render API to merge what returned from `hook_element_info()`
* `'#theme'` is saying to the render API which theme function to use

In the example you are making, the theme function used is `theme_html_tag()` because `system_element_info()` returns the following data.

```
  $types['html_tag'] = array(
    '#theme' => 'html_tag',
    '#pre_render' => array('drupal_pre_render_conditional_comments'),
    '#attributes' => array(),
    '#value' => NULL,
  );

```

If `'#theme'` were set to `'tag_html'`, `theme_tag_html()` would be the theme used by the render API.

---
Tags: theming
---


# Question
Title: One exposed filter for many views/views blocks
I want to have one exposed filter and 2 blocks displaying different content types. They both have 'date' field and I want to show same-day content with one date exposed filter.

Anyone knows how to achieve this? Do I have to create one or two different views? How to share exposed filter (ie. field\_content\_type\_1\_date) with another content type (which has field\_content\_type\_2\_date field)?

# Answer
> 0 votes
If the two content types are using the same date\_field and the blocks are shown on the same url, you can use the exposed filter of one view display to filter both views blocks. You just have to configure the exposed filter on the same field in both views/displays

# Answer
> 0 votes
You need *Views Global Filter* module, it can be found here:

https://www.drupal.org/project/global\_filter

---
Tags: views
---


title: Redirect with www on without www

text:
# Question
Title: Redirect with www on without www
I need to do a redirect to the transition from www passed on without www. I uncomment this part in `.htaccess`. But when I go to the website link `www.site.com` I get an error: `This webpage is not available`

```
# To redirect all users to access the site WITHOUT the 'www.' prefix,
# (http://www.example.com/... will be redirected to http://example.com/...)
# uncomment the following:
RewriteCond %{HTTP_HOST} ^www\.(.+)$ [NC]
RewriteRule ^ http%{ENV:protossl}://%1%{REQUEST_URI} [L,R=301]

```

Without www site works. Server version: Apache/2.2.22 (Debian)

In the firebug displays 3 error:

```
Failed to load resource: net::ERR_NAME_NOT_RESOLVED
Failed to load resource: net::ERR_CACHE_MISS
GET _http://www.example.com/ net::ERR_NAME_NOT_RESOLVED

```

# Answer
> 0 votes
Use the following .htaccess rule when user enter in browser `sitename.com` then it will run as www.sitename.com.

Here we write the rewrite rule condition. For more details please visit following the website: http://httpd.apache.org/docs/2.0/misc/rewriteguide.html

```
**RewriteCond %{HTTP_HOST} ^sitename.com$
RewriteRule (.*) http://www.sitename.com/$1 [R=301,L]**

```

---
Tags: 7, redirection, .htaccess
---


# Question
Title: Add extra obligatory fields when editing a node as anonymous user
I need a way to either add extra fields or make two fields obligatory when an anonymous user is editing a node. I'll explain:
There is a node type in my site that can be freely edited, modifications are saved as new revisions. To know who edited a node i want to add a mail field and other extra fields that require other info from the anonymous user but these fields don't need to be obgligatory when the nodes are edited by registered users.

I was thinking about using the module suggested in this discussion: How can anonymous users be allowed to post while still maintaining content integrity?
but i require that the mail entered from the user is saved inside the node and also i require an extra field other than the mail.

Is there any way to achieve that?

# Answer
> 3 votes
You could use a the hook\_form\_alter to get the desired function:

```
function mymodule_form_alter(&$form, &$form_state) {
  if($form['type']['#value'] == 'DESIRED_CONTENT_TYPE') {
    if( user_is_anonymous() ){
      //Fields are required for anonymous users
      $form['field_ABC'][LANGUAGE_NONE]['0']['value']['#required'] = TRUE;
      $form['field_DEF'][LANGUAGE_NONE]['0']['value']['#required'] = TRUE;
    }
    else{
      //Hide fields for logged in users
      $form['field_ABC']['#access'] = FALSE;
      $form['field_DEF']['#access'] = FALSE;
    }
  }
}

```

---
Tags: entities, nodes, users
---


# Question
Title: How to direct user to a custom path after executing a Views Bulk Operations action?
I have created a custom action as described at https://www.drupal.org/node/2052067. My question is how to direct the user to a custom path after executing the action?

# Answer
Its like altering normal form using `hook_form_alter`:

```
function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'views_form_MYVIEW_page') {
    $form['#action'] = '/my/target'; // the url that is displayed when in VBO multistep

    if (!empty($form['actions']['submit']['#submit'])) {

      if (in_array('views_bulk_operations_form_submit', $form['actions']['submit']['#submit'])) {
        $form['actions']['submit']['#submit'][] = 'MYMODULE_vbo_redirect';
        $form['actions']['cancel']['#href'] = 'my/target';
        $form['actions']['cancel']['#options']['path'] = 'my/target';
        dpm($form);
      }
    }
  }
}

function MYMODULE_vbo_redirect($form, &$form_state) {
  $form_state['redirect'] = array('my/target');
}

```
> 0 votes

---
Tags: views
---


# Question
Title: How can I edit the way the images are displayed?
For a course in university , we have to make a website in Drupal. The problem is, we don't know a lot of HTML and CSS (except for the information we can find on internet). So I don't really know how to solve my problem.

Have a look at this image:

You can see all the images are shown underneath each other. I want them in a horizontal line, like some kind of grid (4 images next to each other and then a new row with another 4 images ).

How can I solve this?

# Answer
It's not about Drupal itself. You need some css knowledge.

Install firebug (for firefox) first and then check your images' class via firebug.

Then add something like that to your css file:

```
.my-image { float: left; width: 25% }

```

If you don't know how to do these, learn a little css and html to survive.
> 2 votes

---
Tags: media
---


# Question
Title: How to limit entity reference for new nodes only?
In an institutional website, there's an archive section listing all events (content type: Event). Each event is coordinated by an event manager (content type: Event Manager). CT Event has an entityreference field to select an Event Manager. The available options are defined by an entityreference view. This process works well so far.

Next, I needed to limit the available managers depending on their status. The status is a simple boolean field in the CT Event Manager defining if that manager is still active or retired. This limitation also works such as new events can't be assigned to retired managers.

However, if I want to edit an (old) event which was managed by a now retired manager, I can't save the node since the reference is not valid anymore.

My question is, how can I restrict the number of available managers for new events but still maintain the relations between old events and retired managers?

# Answer
It can be done with a few short lines of code if you are prepared to write a custom module for it.

First, you need to alter your Entity Reference View. Add a Contextual filter of your boolean field that indicates whether the manager is active or not. Set it to 'Display all results for the specified field' WHEN THE FILTER VALUE IS NOT AVAILABLE.

Now note the machine name and display\_id of your view, then create a custom module, and add these lines to it:

```
function MODULE_views_pre_view(&$view, &$display_id, &$args) {
  if ($view->name == "VIEW_MACHINE_NAME" && $display_id == "DISPLAY_ID") {
    $node = menu_get_object();
    if (!$node) {
      $args[] = 1;
    }
  }
}

```

What happens here is that we are checking if we are on a node page and have an existing node object. If we do, we assign an argument of '1' to the view, which is boolean yes, and the view subsequently only displays active managers. If we do not have a node object, then we are in the process of creating a new node, so we leave the argument empty, and the view has been set to then display all nodes.
> 1 votes

# Answer
You need to render views in the Entity Reference field.

1. Add a reference type display in a view.
2. Add a nid and title field in the view.
3. A list of views will be displayed in the field configuration. Select specific view in field's configuration.

**Edit:**

May be adding `hook_form_alter` to form can do the trick for you.

```
function hook_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'your_node_form') {
    // $form['#node'] if it is node edit form.
    // $form['reference_field']['#options'] = $altered_list
  }
}

```
> 3 votes

---
Tags: views, entities
---


# Question
Title: View, Nodes categorized by field with counter just right to Category name
I would like to split my 100 nodes by category field and display amount of nodes (from 1 category) near Category name.

Here is a screenshot of what I want to get at the end.

> (X documents)

Could you please give me a hint/direction how can I do that?

* "X" - number of documents in category
* "documents" - word that could be translated in other languages.

# Answer
Amend your view as follows:

Add the category term as a field to the view, either straight as a field from the node, or as a relationship. Make sure to exclude this category field from display.

Choose your format for the view, and for the format settings, select the hidden category field you just added as 'Grouping Field Nr. 1'.

Your view should now categorise the content with the category as the headings for each group.

Now to add the count.

In the Advanced part of the view, click on Theme: Information.

This open this window:

Now copy the name of a view override from the row 'Style Output' (underlined in red in screenshot'. The names to the left are to override the view in a very general way, and more the right it will target the view more specifically. Make it specific so that only this view is targeted.

Create a new file in your theme's `templates` folder with the name you just copied.

Paste this code in your file (it comes from clicking on the blue 'Style output' link in the view's theme information window, with a slight adaption).

```
<?php

/**
 * @file
 * Default simple view template to display a list of rows.
 *
 * @ingroup views_templates
 */
?>
<?php if (!empty($title)): ?>
  <h3><?php print $title . ' (' . count($rows) . ' ' . format_plural(count($rows), 'document', 'documents') . ')'; ?></h3>
<?php endif; ?>
<?php foreach ($rows as $id => $row): ?>
  <div<?php if ($classes_array[$id]) { print ' class="' . $classes_array[$id] .'"';  } ?>>
    <?php print $row; ?>
  </div>
<?php endforeach; ?>

```

The last thing to do is to clear your cache.
> 2 votes

---
Tags: views
---


title: Taxonomy field in code

text:
# Question
Title: Taxonomy field in code
I am working on a module that has an install file that creates a taxonomy with postal codes. And then imports all contacts from a csv file.

Now i would like to add a field to my taxonomy (boolean).

How would i approach this?

Thanks in advance!

# Answer
Create a vocabulary with fields

```
taxonomy_vocabulary_save((object) array(
      'name' => 'Vocabulary Name',
      'machine_name' => 'vocabulary_machine_name',
    ));

// Create a field
 $field = array(
    'field_name' => 'field_your_field',
    'type' => 'text',
    'label' => 'your label'
  );
  field_create_field($field);

  // Attach the field to our taxonomy entity
  $instance = array(
      'field_name' => 'field_your_field',
      'entity_type' => 'taxonomy_term',
      'bundle' => 'vocabulary_machine_name',
      'label' => 'Label',
      'description' => 'Description',
      'required' => true,
      'widget' => array(
        'type' => 'text_textfield',

      )
  );
  field_create_instance($instance);

```

You can create terms like below :

```
 $term = new stdClass();
    $term->name = ‘Your Term name’;
    $term->vid = 'vocabulary id';
    $term->field_your_field[LANGUAGE_NONE][0]['value'] = ‘data’;
    taxonomy_term_save($term);

```
> 0 votes

---
Tags: taxonomy-terms, installation
---


title: EntityFieldQuery fieldCondition

text:
# Question
Title: EntityFieldQuery fieldCondition
I have the following code:

```
$query = new EntityFieldQuery();

$result = $query
    ->entityCondition('entity_type', 'field_collection_item', '=')
    ->propertyCondition('field_name', 'field_version', '=')
    ->fieldCondition('field_version', 'entity_id', '105', '=')
    ->execute()
;

```

The first two conditions are fine, but the fieldCondition() is causing the following SQL exception:

> PDOException: SQLSTATE\[42S22\]: Column not found: 1054 Unknown column 'field\_data\_field\_version0.field\_version\_entity\_id' in 'where clause'...

The problem seems to be that 'field\_version' is prepended to the column 'entity\_id'. I have looked inside `_field_sql_storage_query_field_conditions()` and there appears to be no way to stop it from prepending this. This is the table I am trying to perform the fieldCondition on:

```
+-------------+---------------+---------+-----------+-------------+----------+-------+---------------------+
| entity_type | bundle        | deleted | entity_id | revision_id | language | delta | field_version_value |
+-------------+---------------+---------+-----------+-------------+----------+-------+---------------------+
| node        | shopping_cart |       0 |       105 |         123 | und      | 0     |                   5 |
| node        | shopping_cart |       0 |       108 |         126 | und      | 0     |                   8 |
+-------------+---------------+---------+-----------+-------------+----------+-------+---------------------+

```

How may I perform this query correctly?

# Answer
I managed to solve this a different way.

I was trying to retrieve the entity ID in order to retrieve the information from the node that the field collection was attached to. Instead, however, I used `node_load()` to load the relevant nodes. I then was able to retrieve the entity ID of the field collection object and load it using `entity_load()`.
> 1 votes

# Answer
`entity_id` is the entity ID of the entity the field is attached to; in this case, the ID of your field collection item. To add a condition on that, you need to use a `propertyCondition()` on the "field\_collection\_item" primary key.
> 2 votes

# Answer
For anyone still intrested in this one, it can be done via:

`->entityCondition('entity_id', '68', '!=')`
> 1 votes

---
Tags: 7, entities, database
---


# Question
Title: How Do I Disable CiviCRM locally if I don't need it?
I'm working on a Drupal 7 site build and I have a local development environment. The site has CiviCRM working with it, but I'm not doing any work related to CiviCRM so I'd like to just have it disabled in my local environment.

Can I somehow set my civicrm.settings.php or other file to just have CiviCRM disabled (or pointing to a dummy civi install) when working locally?

I could disable the module, obviously, but this throws a bunch of errors on various places, so I guess ideally I want to 'fake out' CiviCRM with fake database or other information in settings.php, making everything just fail silently.

# Answer
I use a "fake" database and a local civicrm.settings.php. you can encrypt the data if necessary. That way any references are maintained. Another approach is to use a multisite configuration and share some of the tables. If you disable the civicrm module, and you are getting errors, then it will depend on the nature of the errors (ie. view references to civicrm entities?) If you go that route, refer to this or this
> 1 votes

# Answer
In a clean Drupal and CiviCRM install, the CiviCRM module can be disabled without generating any errors.

Getting CiviCRM working in a local development environment that doesn't mirror the configuration of the actual site can be a pain and CiviCRM adds a lot of overhead to page loads and increases the memory required for many tasks, but the steps for resetting the paths and deleting temp files are well documented at http://wiki.civicrm.org/confluence/display/CRMDOC/Moving+an+Existing+Installation+to+a+New+Server+or+Location

CiviCRM includes handful of Drupal modules that give Drupal access to the CiviCRM data in modules like Views and Rules as well modules that do things like add or remove users from roles based on having paid their membership, but CiviCRM is much more than just those modules. CiviCRM is a large PHP project (much larger than Drupal core) that runs within Drupal, WordPress, or Joomla's menu and authentication and includes APIs and hooks that allow custom development to tap into CiviCRM at many levels with any of those CMSes.

You could probably get away with a "dummy" CiviCRM install if the site hasn't done much customization to CiviCRM or written any custom code that leverages it, but if disabling CiviCRM "throws a bunch of errors on various places" my guess is you are working with an instance of CiviCRM that has already been customized and integrated. You'd have to share the specific errors for anyone to confirm that. As soon as anyone added a custom field to one of the CiviCRM data types (profiles, contributions, events, etc), that fields could be used in a View. If a custom field is already used in a View, you have to get the client's copy of CiviCRM running or risk deleting a CiviCRM reference when updating a View.

While CiviCRM isn't Drupal, it isn't rocket science either. If you aren't sure what customizations and integration have been done, it is much safer to get CiviCRM working than trying to disable it.
> 2 votes

---
Tags: civicrm
---


# Question
Title: Retrieve select option value in webform-mail.tpl.php (7.x-4.x-dev)
I have a custom mail template in Webform so values can be in a table for copying/pasting into Excel.

I want the value of the select option fields instead of the key (doing manual entry for webform creators would be too tedious). I can't seem to get to those values.

Any help would be appreciated.

Here's my current code for webform-mail.tpl.php:

```
<h2>
<?php
    print $node->title;
?>
</h2>

<?php print ($email['html'] ? '<p>' : '') . t('Submitted on [submission:date:long]'). ($email['html'] ? '</p>' : ''); ?>

<table style="border: 1px solid black; border-collapse: collapse;">
<?php
foreach ($node->webform['components'] as $key => $component) {
    if (isset($submission->data[$key][0])) {
   $key_converted = ucwords(str_replace('_',' ', $node->webform['components'][$key]['form_key']));
    print '<tr><td style="border: 1px solid black;">'. $key_converted .'<td style="border: 1px solid black;">' . ($submission->data[$key][0]) . "</td></tr>";
}
}
?>
</table>

```

# Answer
For anyone else that runs across this:

```
<h2>
<?php
print $node->title;
?>
</h2>

<?php print ($email['html'] ? '<p>' : '') . t('Submitted on [submission:date:long]'). ($email['html'] ? '</p>' : ''); ?>

<table style="border: 1px solid black; border-collapse: collapse;">
<?php
foreach ($node->webform['components'] as $key => $component) {
   if (isset($submission->data[$key][0])) {
     $key_converted = ucwords(str_replace('_',' ', $node->webform['components'][$key]['form_key']));
     $submittedvalue = $submission->data[$key][0];

     if (isset($submittedvalue)) {
       print '<tr><td style="border: 1px solid black;">'. $key_converted .'</td><td style="border: 1px solid black;">';
       if ($node->webform['components'][$key]['type'] != "select") {
           print $submittedvalue;
       }
       else {
        $selectlistitems = explode("|", $node->webform['components'][$key]['extra']['items']);
        if (is_numeric($submittedvalue)) {
                print $selectlistitems[$submittedvalue];
        }
        else {
                 print $submittedvalue;
        }
       }
       print '</td></tr>';
       }
  }
}
?>
</table>

```
> 0 votes

---
Tags: theming, webforms
---


# Question
Title: Division by zero in theme_image_style_preview after moving to production server
> Warning: Division by zero in theme\_image\_style\_preview() (line 804 of /var/www/html/modules/image/image.admin.inc).
>
> Warning: array\_intersect\_key(): Argument #1 is not an array in theme\_image\_style\_preview() (line 806 of /var/www/html/modules/image/image.admin.inc).

I am receiving the above errors when I view several of the "stock" image styles on my site. I just moved my site from a development server to a production server, and the error does not occur on the development server version. I checked the directory permissions on the production server, and they appear to be consistent with the development server's permissions.

One really strange thing occurs when I view the source on the "preview image" in the admin back-end of one of those styles that has the issue. When I do, it shows the following path being called (which is, of course, not a valid path):

http://mysite.com/sites/default/files/styles/large/public/modules/image/sample.png?cache\_bypass=1399676683

The "sites/default/files/styles/large/public/" part seems to be part of the issue, but I am not sure how that got there. All of my custom image styles work fine.

Thanks!

# Answer
> 4 votes
I did:

`chmod 777 drupal/sites/example.com/files/styles`

and the error went away and my drupal 7 new image-style worked.

# Answer
> 10 votes
Apparently it is not safe to chmod files to 777.

A preferred way is to chmod files to 644, directories to 755 and set the ownership to the webserver, so the webserver can write files.

Here's a script for Ubuntu:

```
# Change directory permissions to 755.
find sites/default/files -type d -exec chmod 755 {} +
# Change folder permissions to 644.
find sites/default/files -type f -exec chmod 644 {} +
# Set ownership to webserver.
chown -R www-data:www-data sites/default/files

```

Learn more on - Recommended directory permissions.

---
Tags: 7, media
---


# Question
Title: Create description for taxonomy term view
I am after a description which is similar for all taxonomy terms based on a schools location.

So I've created a few views based on continents at http://www.explorefreediving.com/freediving-schools-in-africa and then just added a description for that view and will be doing the same for the other continents.

"Improve your snorkeling, spearfishing and freediving with one of the many schools and freediving training courses held by apnea instructors across Africa."

I am now after a similar description for every country taxonomy term which is what I use to categorise the freedive schools.

So if you click on Egypt to the right when you are looking at Africa http://www.explorefreediving.com/school-location/africa/egypt you get sent to a taxonomy term and the same with other locations too

I want to be able to insert a description for the hundreds of taxonomy term school locations (countries) without having to manually do it? The most I know I could do is set up a description in each header and use tokens but is this the right approach? If it is, how do I do that exactly? I usually have problems with tokens and using the right ones.

If it is the right approach, doesn't that mean I will have that description across all taxonomy terms because the same view is used?

# Answer
There are at least two ways to do this:

## 1. Views

In your views admin page, add a **Global: Text area** to header. Then check off **Use replacement tokens from the first row**. You can see the tokens (patterns) below under Replacement patterns. Your custom text my be like that:

"Improve your snorkeling, spearfishing and freediving with one of the many schools and freediving training courses held by apnea instructors across **%1**."

## 2. page--vocabulary--\[machine-name\].tpl.php

You could create a custom vocabulary tpl.php page and add your custom text. Details come from that answer:

* Copy (and past) the page.tpl.php into your theme folder.
* Rename it page--vocabulary--\[machine name\].tpl.php

(page--vocabulary--location.tpl.php etc.)

* Open the template.php file in the theme folder and add this function:

Don't forget to change the THEME to your theme name and if you have already had the preprocess\_page function in the template.php file and do not add the preprocess\_page function again.

```
function THEME_preprocess_page(&$vars) {
  if (arg(0) == 'taxonomy' && arg(1) == 'term' && is_numeric(arg(2))) {
    $term = taxonomy_term_load(arg(2));
    $vars['theme_hook_suggestions'][] = 'page__vocabulary__' . $term->vocabulary_machine_name;
  }
}

```
* Open the page--vocabulary--location.tpl.php file and find that line:

(Your theme's template.php file may be different but the main structure is the same.)

* Then add what you want:

(with your css class, spans etc.)

```
<div class="term_description"
"Improve your snorkeling, spearfishing and freediving with one of the many schools and freediving training courses held by apnea instructors across <?php print $title; ?>."
</div>

```

\- Clear all caches.
> 1 votes

# Answer
Herci I have added Taxonomy Views Intergrator https://www.drupal.org/project/tvi and it has worked like a charm now, so I can add a description to any taxonomy vocab I want now, use it across all of it's terms, with tokens too to mix it up and keep each one unique to the page it's on.

So this is a module solution and work around for your second way.

I still have two descriptions though...
> 0 votes

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


# Question
Title: Best way to delete all variables when uninstalling module
I'm writing a module that writes several variables (three, four variables for every content type, and other).

Which method should I use to delete them on hook\_uninstall?

Is it safe to perform a query, searching "mymodule\_\*" variables?

Or should I loop for content types and search variabels, so call many times variable\_del?

# Answer
Variables are cached, so deleting manually is fine so long as you invalidate that cache, e.g.

```
db_delete('variable')
  ->condition('name', 'mymodule_%', 'LIKE')
  ->execute();

cache_clear_all('variables', 'cache_bootstrap');

```
> 10 votes

# Answer
You also might look into the Variable module which allows your module to use a registry, configure default values and so forth.
> 1 votes

---
Tags: hooks, configuration, installation
---


# Question
Title: Simplenews newsletter producing undecoded base64 email
I have a client site that's running Simplenews with Mime Mail and SMTP Authentication Support. Everything works fine except when my client wants to include a link to a YouTube video (and just to be clear, this just a link to the video, not an attempt to embed a video in the newsletter). Here is an excerpt of the resulting newsletter email:

> PCFET0NUWVBFIGh0bWwgUFVCTElDICItLy9XM0MvL0RURCBIVE1MIDQuMCBUcmFuc2l0aW9uYWwvL0VOIiAiaHR0cDovL3d3dy53My5vcmcvVFIvUkVDLWh0bWw0MC9sb29zZS5kdGQiPgo8aHRtbD4KPGhlYWQ+PG1ldGEgaHR0cC1lcXVpdj0iQ29udGVudC1UeXBlIiBjb250ZW50PSJ0ZXh0L2h0bWw7nIGNoYXJzZXQ9dXRmLTgiPjwvaGVhZD4KPGJvZHkgaWQ9Im1pbWVtYWlsLWJvZHkiIHN0eWxlPSJi

. . . and so on. No other links cause this to occur. When I look at the email source, the plain text version is fine. This only happens to the HTML version. I am thoroughly stumped. Has anyone seen anything like this?

# Answer
> 0 votes
It turns out this was a bug in the SMTP Authentication Module. It uses uses 8bit encoding in the Content-Transfer-Encoding header for the base64 encoded body. I applied this patch with success:

https://www.drupal.org/node/1741082#comment-9121815

---
Tags: emails, files
---


# Question
Title: How to include a Google font not available in @font-your-face module?
I want to use a Google Font on my site. I saw the @font-your-face module and installed it. Unfortunately, it does not offer the version of the 'Pacifico' font I want.

Google suggests adding the following:

```
<link href='http://fonts.googleapis.com/css?family=Pacifico' rel='stylesheet' type='text/css'>

```

Is it possible to add it to all my Drupal page without fiddling with core code? Or is there are better way to add a font to my site?

# Answer
> 4 votes
Rather than using the @font-your-face module, try the Google Fonts module instead. It fetches the current font list from Google - and Pacifico is included. I've used the module in several projects - it works well and unobtrusively.

# Answer
> 4 votes
You can add it by using drupal\_add\_css() in your template.php file's template\_preprocess\_html() function:

```
function mytheme_preprocess_html(&$variables) {
  drupal_add_css('http://fonts.googleapis.com/css?family=Pacifico', array('type' => 'external'));
}

```

# Answer
> 2 votes
I would simply modify the html.tpl.php in your sub-theme, and add the `<link href='http://fonts.googleapis.com/css?family=Pacifico' rel='stylesheet' type='text/css'>` where you want.

I think it's clean, fast, and it won't pollute your hook\_preprocess\_html.

# Answer
> 2 votes
The simpliest and quickest method is to add

```
@import url(http://fonts.googleapis.com/css?family=Fontname:400,700|Fontname2:400,700);

```

in one of your drupal css files. You can find this ready-generated snippet everytime you select font to use.

# Answer
> 0 votes
If you're looking to add simply add a to the html head, you can use the drupal\_add\_html\_head() function in hook\_page\_alter(). I like this technique as it means one less module for a complex site. See this article for an example.

# Answer
> 0 votes
90% of all time, I add the following into my `page.tpl.php` file.

```
  drupal_add_css('http://fonts.googleapis.com/css?family=Lato:400', array('type' => 'external'));

```

For greater control, use

```
$element = array(
  '#tag' => 'link',
  '#attributes' => array(
    'href' => 'http://fonts.googleapis.com/css?family=Lato:400',
    'rel' => 'stylesheet',
    'type' => 'text/css',
  ),
);
drupal_add_html_head($element, 'lato'); // You can change the word lato.

```

---
Tags: 7, theming
---


title: How to list node parent's children

text:
# Question
Title: How to list node parent's children
Sorry if this is a repeated question, tried many suggested options but no result.

There is business model of 1 to N relationship "parent and children".

I am working on a project where i have a content type building as parent and apartment as child. within a building there could be N number of apartment and every apartment has it is own contents. something similar to attached screenshots

Parent :

Children :

-Building #1 --Apartment #1 --Apartment #1 --Apartment #1 --Apartment #1

I guess there are few modules which could help "Reference module, Entityreference, Views and Taxonomy"

# Answer
The 'Description' tab seems to be the normal 'View' tab for the node. So you first need to change that tab's title to 'Description' only for the building type. Look here to do this: Change name of a tab for a specific content type

As to you two content types: You can create an entity reference field on the building content type that references apartments. Look at the Inline Entity Form to help you with content editing in this regard. Or you can do it the other way round by putting the entity reference field on the apartment that references the building (more manageable), especially if you are going to have lots of apartments.

Then as to the Apartments tab. You need to use entity reference module and views. You will create a view page of nodes filtered by type apartment. You add the relationship to the building, and then add a contextual filter of nid that includes that relationship. You set the path of the page as `node/%/apartments`, and add a menu tab with the title 'Apartments'. For a tutorial refer to Drupal 7 tutorial - How To Create Tabs With Views or Taming the Beast: Learn Views with NodeOne episode 21 and 22.
> 0 votes

# Answer
# To list all nodes of the parent, i.e. siblings.

```
// Node ID to to search by
$nid = 1;

// Load Node
$node = node_load($nid);

// Get Node's Content Type
$type = $node->type;

// Search for siblings
$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'node')
  ->propertyCondition('type', $type)
  ->propertyCondition('status', TRUE); // Get only active nodes
$result = $query->execute();

// Load Sibling Nids
$nids = array();
if (isset($result['node'])) {
  foreach ($result['node'] as $node) {
    $nids[] = $node->nid;
  }
}

// Load Sibling Nodes
$nodes = node_load_multiple($nids);

```

# Building relationships

In regards to structuring a 3 tier relationship, I personally use Entity API and simply reference Nodes to Terms. In cases where I need to create a relationship between Nodes only, I've used an Entity Reference module, or now, I just create a module, which attaches a field with an option to enter a referencing node.

You may also want to check out a Relation module, which has a more complex use to it.
> 0 votes

---
Tags: views, nodes, entities
---


# Question
Title: How can i add a depth class to UL in a menu list?
I try this code, but i get only the same default depth for all UL tags.

```
function MYTHEME_preprocess_menu_tree_override(&$variables) {
  $variables['tree_raw'] = $variables['tree'];
}

function MYTHEME_menu_tree($variables) {
  $menu_level = isset($variables['tree_raw']['#depth']) ? $variables['tree_raw']['#depth'] : 1;
  $class = "menu menu-lvl-".$menu_level;
  return '<ul class="menu clearfix'.$class.'">' . $variables['tree'] . '</ul>';
}

```

# Answer
> 1 votes
For Drupal 7.

```
MYTHEME_menu_link(array $variables) {
  global $_current_menu_depth;
  $element = $variables['element'];
  $_current_menu_depth = $element['#original_link']['depth'];
  $sub_menu = '';

  if ($element['#below']) {
    $sub_menu = drupal_render($element['#below']);
  }
  $output = l($element['#title'], $element['#href'], $element['#localized_options']);
  return '<li' . drupal_attributes($element['#attributes']) . '>' . $output . $sub_menu . "</li>\n";
}

function MYTHEME_menu_tree($variables) {
  global $_current_menu_depth;
  return '<ul class="menu menu--'.$_current_menu_depth.'">' . $variables['tree'] . '</ul>';
}

```

NOTE! I noticed this breaks in some cases. I had a three levels deep menu and the second level menu was marked as third.

---
Tags: routes, theming
---


# Question
Title: How do we create a new product display for customeize product?
I have created a product called music now how to create a product display for the music product in drupal commerce?

# Answer
> 0 votes
To set this up manually, follow these steps:

1. Add a node type called *Product display*. Submit using the *Save and add fields* button.
2. Add a **Product Reference field** that uses an *Autocomplete text field* widget. Make the field required and allow an unlimited number of values (even if you only intend to use a single value for now).
3. Click over to the *Manage display* tab and ensure this field uses the ***Add to Cart form*** display formatter. You might also want to move around the product fields you see listed here.
4. Create a *Product display* referencing one of your products and examine the node's teaser and full page views. You may want to change the way product fields are displayed. To do this, you actually have to browse to your product type's *Manage display* page and update the display formatter settings there. You can only adjust the sort order and visibility of product fields through the content type edit pages, not the formatter settings.

---
Tags: commerce
---


# Question
Title: How do you allow users to create own menus?
The idea is that a user should be able to create a menu to structure his uploaded content. How would you go about making this possible without giving the user access to edit other users menus?

Cheers,

# Answer
> 1 votes
**Menu Admin Per Menu Module** comes to solve this purpose!!

> The Drupal 7 Menu Admin Per Menu module is a simple module that allows you to grant permissions for users to administer specific Drupal menus based on their role.
>
> This module for instance would allow you to allow one role to modify the Main menu, while not allowing the role to modify a separate menu on your Drupal 7 website.

Watch this Screencast to learn about it : How to allow a specific role to administer the user menu on a Drupal site without giving them access to modify the Main menu

---
Tags: routes, users
---


title: Interview available slot

text:
# Question
Title: Interview available slot
I'm currently doing recruitment system by using drupal 7..

In my system have 3 role.. 1) applicant 2) hr admin 3) interviewer

Applicant can apply the job and HR admin will shortlisted the applicant. The interviewer can evaluate the shortlisted candidate during the interview session..

My question is there any module that can show the availability of the interview session..the idea is same like confrence session where we can register for the confrence and we can set the limit of audience.. Because i want the candidate can choose the interview session..

I've tried the signup module but i seem not working for drupal 7.

Thank you very much.

# Answer
> 2 votes
If a simple sign up you are looking for, have you tried Entity Registration? https://www.drupal.org/project/registration. Works similar to Signup module

---
Tags: 7, views, nodes
---


# Question
Title: Progress bar advances, operations does nothing
I'm trying to create a batch to import users. I used this (http://pastebin.com/duTbxpgd) as an example, but somehow it's not working. I see the progress bar advancing and It's showing the right number of rows I'm processing. But what I'm trying to do in the operation function isn't executed.

Here's my code:

```
function form_submit($form, &$form_state) {
  batch_import_users();
}

function batch_import_users() {
  db_set_active('mysqldb');

  $result = db_query("SELECT * FROM {users}");

  db_set_active('default');

  $batch = array(
    'title' => t('Importing users ...'),
    'operations' => array(),
    'init_message' => t('Commencing'),
    'progress_message' => t('Processed @current out of @total.'),
    'error_message' => t('An error occurred during processing'),
    'finished' => 'batch_import_users_finished',
    'progressive' => FALSE,
    'file' => 'users.inc',
  );

  foreach ($result as $row) {
    $batch['operations'][] = array('batch_create_user', array($row));
  }

  batch_set($batch);

  batch_process();
}

function batch_create_user($row, &$context) {
  // Here I'm just trying to get some output so I know the operation is called, I'm not actually importing the users yet.

  drupal_set_message($row->uid . ' : ' . $row->login);
  dd($row->uid . ' : ' . $row->login);

  $context['results']['processed']++;
  $context['message'] = $row->login;
}

function batch_import_users_finished($success, $results, $operations) {
  if ($success) {
    drupal_set_message('Importing users has finished.');
  }
  else {
    drupal_set_message('Some error.');
  }
}

```

Am I missing something or doing something wrong? Any help is very much appreciated.

# Answer
> 0 votes
Try below code

```
$operations = array();
foreach ($result as $row) {
  $operations[] = array('batch_create_user', array($row));
}

$batch = array(
  'title' => t('Importing users ...'),
  'operations' => $operations,
  'init_message' => t('Commencing'),
  'progress_message' => t('Processed @current out of @total.'),
  'error_message' => t('An error occurred during processing'),
  'finished' => 'batch_import_users_finished',
  'file' => drupal_get_path('module', 'user') . '/' . 'user.inc',
);

```

Also add path to redirect after batch process

```
batch_process();

```

---
Tags: 7, batch-operations
---


# Question
Title: Drush site upgrade: Contributed extensions were not upgaraded
I am using Drush site upgrade module for D6 to D7 Upgrade.

In step 15, drush asks me to update only one module i.e. path\_access, and for all the modules it says "following contributed extensions were not upgaraded". Then in final step its says "there are no more modules to be upgraded". And my all contributed modules remained unupgraded. Should I need to upgrade them manually.

# Answer
I think you should Migrate d2d module for content migration and also should upgrade contributed modules manually as might be some modules aren't supported in drupal 7. So, this should be a manual task. But using Migrate d2d module, you should be able to migrate content :).

I guess this is helpful to you.
> 2 votes

---
Tags: 7, drush, upgrading
---


# Question
Title: Enabling HTML in MENU_LOCAL_TASK titles (primary tabs)
I would like to place a `<br />` tag in my `MENU_LOCAL_TASK` titles so that I can reduce the width of the primary tabs.

It seems that in theme\_menu\_local\_task the link title is run through `check_plain`, but when I remark this line out only the link title of the active tab responds. All the inactive tab link title are still being sanitized.

Basically, I want to have HTML in my `MENU_LOCAL_TASK` titles - without using any contrib modules.

Any ideas? Thanks.

# Answer
> 0 votes
The key is this `if` construct: `if (!empty($variables['element']['#active']))` with regard to getting the titles of the inactive tabs to respond. My solution was to customize: `theme_menu_local_task`. Perhaps there is a better solution?

```
/**
 * Alter theme_menu_local_task.
 */
function my_theme_menu_local_task($variables) {
  $link = $variables['element']['#link'];
  $link_text = $link['title'];

  if (!empty($variables['element']['#active'])) {
    // Add text to indicate active tab for non-visual users.
    $active = '<span class="element-invisible">' . t('(active tab)') . '</span>';

    // If the link does not contain HTML already, check_plain() it now.
    // After we set 'html'=TRUE the link will not be sanitized by l().
    if (empty($link['localized_options']['html'])) {
      if (arg(0) != 'my-page') { // ** ADDED **
        $link['title'] = check_plain($link['title']);
      } // ** ADDED **
    }
    $link['localized_options']['html'] = TRUE;
    $link_text = t('!local-task-title!active', array('!local-task-title' => $link['title'], '!active' => $active));
  }

  if (arg(0) == 'my-page') { // ** ADDED **
    $link['localized_options']['html'] = TRUE; // ** ADDED **
  } // ** ADDED **

  return '<li' . (!empty($variables['element']['#active']) ? ' class="active"' : '') . '>' . l($link_text, $link['href'], $link['localized_options']) . "</li>\n";
}

```

---
Tags: routes
---


# Question
Title: Returning HTML through an ajax-call in Drupal 8
I am trying to grasp the MVC/Symphony integraton of Drupal and am making use of the controllers. My controller has a function named "returnHTML" which is called by a normal XMLHttpRequest. Problem is I do not know how to generate the HTML. I could use a theme, but implementing a theme feels a little bit too complicated for this simple task. I want a HTML-fragment, ergo what you see is what you get, not a complete webpage.

Is there a way to return HTML just specifying where a twig is and have this twig-file injected with data in the "returnHTML"-function immediately? Also is there a recommended class (like Symphonys JsonResponse) which will help with the headers?

# Answer
> 4 votes
Since we are fairly new in the Drupal 8 jungle I'll give some feedback how I fixed this. Be aware this is probably not the best solution.

Using a controller I included this function:

```
    /**
     * Inspiration page action
     */
    function inspiration(){
        $twig = \Drupal::service('twig');
        $template = $twig->loadTemplate(drupal_get_path('module', 'experimental') . '/templates/inspiration.html.twig');
        echo $template->render([]);
        die;
    }

```

This works fine, allthough it is not very beautiful.

---
Tags: ajax, theming
---


# Question
Title: Remove choice for user delete from Roles which can adminster the Users
I have a **User Role** called **Supervisor** which can create new accounts of role **Supervisor**.

The **Supervisor** can also delete other users with **supervisor** role. While deleting Other users the Supervisor gets the 4 choices that Drupal comes standard with:-

However, I want to present the **Supervisor** only the first option:-
***Disable the account and keep its content***
and other options to be hidden or disabled by default.

I'd be very thankful for any hints how to achieve that... I'm already using **Role Delegation module** and have been trying different settings, looks like its not possible via that module.

# Answer
> 1 votes
I would start by creating a custom module and try using hook\_form\_alter.

```
function MYMODULE_form_alter(&$form, $form_state, $form_id)  {
  switch ($form_id)  {
    case 'user-multiple-cancel-confirm':
        // ALTER STUFF.. user dsm($form) to show available fields.
        break;
   }
}

```

Using

```
global $user;
$roles = $user->roles; // Array with user assigned roles

```

you can check the array for the Supervisor role.

---
Tags: 7, users
---


# Question
Title: What naming conventions should I follow?
I am a Drupal CMS beginner, studying this CMS for several days, also through the Drupal module development pages.

I still have no clue on the proper function names, database table names, and relationship between .module, .info and so on.

How are names mapped and what is the sequence of functions that are called?

# Answer
> 0 votes
I'm a bit surprised that you haven't found anything on the internet that could answer your questions. Here is an article about coding standards for Drupal.

Anyway, here are several things I always do with naming, functions and directories (that doesn't mean it's the best conventions):

* The only directory you should work in is **./sites** (please never ever edit something in the other directories).
* The contribute modules you download should be placed in **./sites/all/modules/contrib**
* The custom modules that you develop yourself should be placed in **./sites/all/modules/custom**
* When you create a custom module, chose a **simple and suitable name** of it, preceded by the name of your project (better), for example `myproject_blog`.
* The `.module` and `.info` files should have the **same name** as your module's, for example `myproject_blog.module` and `myproject_blog.info`. It will automatically make the relationship between them.
* All the **functions** that appear in your `.module` file should be named by your module's name, for example `myproject_blog_revision_publish()`.
* If your custom module needs a **table** in your database, the name of your module has to show up somewhere, for example `$schema['myproject_blog']`. If you need more than one table, keep the prefix and add some explicit suffix.
* Idem for the **custom themes** in **./sites/all/themes**.

If I forgot something, just ask ;)

# Answer
> 0 votes
From the sound of the question you are looking for a simple overview to help you get started. I would suggest that rather than initially tracing the way that the (labyrinthian) drupal core passes requests through functions, you should start with looking at how simple modules and themes connect to it to get an idea of the larger design pattern. Once you have an idea of the concepts and terminology used, the commented code examples are invaluable for this, giving examples of things you can do, and describing how to accomplish it.

Basically, as Djouuuuh points out, you can safely leave drupal core to do its thing. That is why you will work exclusively within the **sites** directory. Your interaction as a developer is to configure the installation to behave how you you would like (site building), create themes to customise display (theming) and create modules (development) to match very site-specific functionality. Always look to existing, supported modules first, it will save you a lot of time, even if must add to their functionality with your own module.

To understand the naming conventions for files and functions used in modules and themes, you will need to learn about the hook system and then look to the examples and the API(via google) to understand the uses of those hooks. More than likely you will rely heavily on just a few hooks to start with, for example hook\_menu, hook\_node\_load, hook\_form\_alter (forms are a big subject).

Drupal.org holds extensive documentation about development methods.

Also Jeff Eaton of lullabot looks to have created a good slideshow on the subject of drupal development, which might be worth a click through.

---
Tags: 7
---


title: Find all pdf links using a module

text:
# Question
Title: Find all pdf links using a module
Is there a way to find certain types of links and edit them from a custom module in Drupal 7? I want to add an attribute to all pdf links throughout my site. I tried the following:

```
function my_module_preprocess_link(&$link){
  if( substr($link['path'], 4) === '.php' ) {
    var_dump($link);
  }
}

```

But I suppose since the pdf links are contained in the node content of my pages, they aren't included here.

I'd like to add a custom class to all pdf links or maybe an inline onclick javascript event. Is there a way to do that?

# Answer
It depends how the links have been created.

If the links were added using a field, eg using the file module, then you could look to that module for it's theme functions, and create your own replacement theme function in your module or theme.

If (just reread your question) the links are included in the body (or other textarea field) of your site's nodes, then you would have to rely on an input filter to alter them before displaying the field. You could look to a module like ELF, for how this can be accomplished using an input filter, or 'External Links' for an example using javascript.
> 0 votes

---
Tags: 7, navigation
---


# Question
Title: Send an alternative email to an anonymous user who placed an order
I have 2 cases:

A registered and logged in user who gets an email after he placed an order. In that email he gets the token \[message:message-commerce-order:view-url\] where he can view his order.

An anonymous user gets the same email but: But I'd like to delete the token \[message:message-commerce-order:view-url\] because an anonymous user can't see that page because he needs to log in.

How do I send an alternative mail to anonymous users after they place an order?

# Answer
You could look to the Rules module to accomplish this, though a lot depends on how you are managing orders (Commerce module?).

If using Rules you could set **conditions** for user role to determine which email they get.
> 1 votes

---
Tags: emails, commerce, notifications
---


title: SQL Error on view

text:
# Question
Title: SQL Error on view
There is a Drupal view, replacing the normal page at /admin/content. It throws an error on the view page which goes away after you clear the cache, and then comes back.

```
SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'LEFT JOIN taxonomy_index taxonomy_index ON node.nid = taxonomy_index.nid LEFT JO' at line 2

```

Cant seem to figure out what the issue is.

# Answer
> 0 votes
I would need more information to help, but I would suggest updating both views and taxonomy modules to their most recent stable version first, to see if this resolves your issue. If this does not, then try the latest dev version of each module (as always, back up your db first).

---
Tags: views, database
---


# Question
Title: How to register a theme function from the theme
I want to introduce a custom theme function in my theme. Typically, I would register a theme in `hook_theme()` in a module, but I want to define this function from my theme (Omega 4). In whatever module I'm in, I'd like to just build my render array and let it be themed by the theme-side theme function.

Example:

```
$ra = array(
    '#theme' => 'my_theme_fx',
    '#somevar' => 'foo',
    '#anothervar' => 'bar'
);

```

# Answer
> 0 votes
The description of `hook_theme()` is:

> Register a module (or theme's) theme implementations.

So you can implement this hook in your theme.

---
Tags: 7, theming
---


# Question
Title: How to apply theme_menu_tree to only the top <ul> menu
I am using the following function in the template.php (drupal 7) to override the original menu output. However, the tags in all levels are also affected. I wonder how to only apply it to the top/first tag? Please advise. Thanks!

```
function THEMENAME_menu_tree__MAIN_MENU($variables) {
  return '<ul id="myid" class="menu myclass">' . $variables['tree'] . '</ul>';
}

```

# Answer
> 2 votes
In order to theme the top level `ul` tag only:

```
function THEMENAME_menu_tree__menu_top_menu(&$variables) {
 return '<ul class="menu myclass">' . $variables['tree'] . '</ul>';
}

```

You have to put this piece of code in your custom theme's `template.php` file and replace `THEMENAME` with your theme's name.

---
Tags: theming, routes
---


# Question
Title: drupal_set_breadcrumb() function doesn't work on "Add content" pages!
I have written a custom block and put it inside the panel of "Add Content" page, but it can not change the breadcrumb. Actually the code in module includes drupal\_set\_breadcrumb() function, which doesn't work on “Add content” pages. My code is working on the others pages!

I need your help to change only the breadcrumb of each "Add content" page without using the available modules for drupal breadcrumb. Because I have written my code and the customization level is so high which can not be obtained with those modules.

# Answer
Ok, I just solved it! It's too easy! Using the below function in template.php file:

```
function mytheme_breadcrumb($variables) {
  $sep = ' > ';
  if (count($variables['breadcrumb']) > 0) {
    return implode($sep, $variables['breadcrumb']) . $sep;
  }
  else {
    return t("Home");
  }
}

```

and using the `arg()` values and `$variables['breadcrumb']` values in above function can enable you to check every pages path. Such as adding the below piece of code the above function:

```
  $breadcrumb = $variables['breadcrumb'];

  $is_add_content=false;
  foreach($breadcrumb as $key=>$value){
    if(strpos($value,"node/add"))
      $is_add_content=true;
  }

```

References:

https://www.drupal.org/node/64067 https://api.drupal.org/api/drupal/includes%21theme.inc/function/theme\_breadcrumb/7
> 0 votes

---
Tags: 7, panels, breadcrumbs
---


# Question
Title: Contextual view -> entity reference target ID
I have the following situation:

I have 2 content types (session and preformance)

Performance has an entity reference to session

I want to create a view that shows me all performances for the session that is referenced by the performance i am looking at right now.

So this is a contextual view that filters on the nid of the performance, and has a relation to the session that is referenced by the viewed performance.

I cannot get the target\_id of the session (from field\_session on content type performance) to be passed in as a contextual filter.

I tried to use %node:field\_session, but that gives me the label of the session, and not the target\_id.

I also tried to change the display of the performance content type-\>field\_session to 'entity id', but no luck.

All suggestions are very welcome.

# Answer
> 0 votes
You need to add the proper Context to the variant.

Then you complete the setup.

And lastly you select it in the panel settings for the Contextual view:

---
Tags: views, entities, chaos-tool-suite
---


# Question
Title: How to send user password during registration?
How to send user password during registration. I have to send html email when user register in the site using rules module in drupal 7 and i have to send the username and user password in that mail. i used \[account:name\] and \[account:password\] or \[user:password\] but i did not get the user password on my mail.

# Answer
This doesn't answer the question, but it has to be said.

You should **not** e-mail users their password.

It's highly **irresponsible** to do so.

There are strong reasons for Drupals default behaviour.

People tend to re-use their passwords in lots of places, and e-mails are not a secure communications channel.

If your end user re-uses the password for their VPN tunnel, and login to their e-mail over an unencrypted channel, (no https for the e-mail, and no password on the local wifi for example), then **you** have just broadcasted that password for the world to see. And now you've facilitated the cyber attack on their workplace. There's probably a large number of both known and unknown ways to compromise the passwords as well. NSA are practically guaranteed to get it.

Don't do it.

Yes, it's the users fault for re-using their password and not requiring HTTPS to their mail and a strong password on the wifi, but you are the developer and need to know better.
> 2 votes

# Answer
This question may already have been answered:

Send user's password in mail

Email is not fully secure. It would seem problematic to send the user's password in this manner.
> 1 votes

---
Tags: users
---


title: hook_views_pre_execute not working

text:
# Question
Title: hook_views_pre_execute not working
I want to alter the view query before rendering the view, so I use the hook\_views\_pre\_execute. I want to add an 'WHERE' 'AND' condition clause to the query. So here is my code :

```
MYMODULE_views_pre_execute(&$view) {
    // some code here to get my node id to exclude
    $view->query->add_where('1', 'node.nid', $nid_exclude, '!=');
}

```

but it seems to me the hook not working, or I did mistake to the `add_where`function?

UPDATE : The hook is executed but the view is not modified.

# Answer
> 3 votes
To alter query you should use hook\_views\_query\_alter

Sample Code using `hook_views_query_alter` :

```
function MODULE_views_query_alter(&$view, &$query){
switch($view -> name){
    case 'products':
        if($view->current_display == 'block_1'){
            $nids = get_nid();
            $nids = !empty($nids) ? $nids : array(0);
            $query->where[1]['conditions'][2]['value'] = $nids;
            $query->where[1]['conditions'][2]['operator'] = 'IN';
        }
            break;
  }
}

```

---
Tags: views
---


# Question
Title: How to I add translations for Month and Day in a date field?
I am working on a Drupal 7 site that will be in English and Inuktitut. I have the i18n internationalization module installed. It does provide Inuktitut as a language option, but there are no available translations for Inuktitut.

I can see the options to localize the date format, but I need to be able to translate the months and days. How do I do this?

I'm looking for

Monday = naggajjau

Tuesday = aippiq

...

January = jaannuari

February = viivvuari

and so on.

Thank you

# Answer
You can translate everything in Administration » Configuration » Regional and language » Translate interface (admin/config/regional/translate/translate)

Concerning dates, you usually need to translate the following strings :

* `!month-name |January|February|March|April|May|June|July|August|September|October|November|December` : you must keep `!month-name` and `|` in the translated string
* every string starting by `!long-month-name`
* `!day-name Sunday|Monday|Tuesday|Wednesday|Thursday|Friday|Saturday`

And you should be good.

Even better, if you know several people interested in maintaining a language translation, you should go to https://www.drupal.org/node/807756 and reopen the issue. The goal is to have one place to improve and maintain the translation in https://localize.drupal.org/
> 1 votes

# Answer
You can download translation from http://localize.drupal.org. I think the chance is relatively high that month names and weekdays are already translated.

Otherwise, go to Intraface Translation on you Drupal Site (admin/config/regional/translate/translate) and search for the month names and weekdays.
> 0 votes

---
Tags: 7, i18n-l10n
---


# Question
Title: Views RSS channel properties added with hook_views_query_alter() disappear
I have applied this patch to the Views module so that it will add the channel properties of pubDate and lastBuildDate.

Then I ran Drupal "Clear all caches" within /admin/config/development/performance.

The added channel properties are only available for the first page requested each time after running another Drupal "Clear all caches".

For Drupal 7 how can I ensure that views RSS channel properties that are added with hook\_views\_query\_alter() remain?

=================================================================================

I have already tried the “Views RSS” module and after downloading and enabling this module along with its associated “views\_rss\_core” the “RSS Feed – Fields” radio button does not display and only the “RSS Feed” option is present which comes from the “Views” module.

# Answer
> 1 votes
You can do this with Views RSS 2 and `hook_views_rss_item_elements()`.

As we can see in the documentation for Views RSS API views\_rss\_get it can :

> Fetch item elements provided by other modules.

So to create your own item element do the following :

* First thing, revert your hack, it won't be needed.
* Download and install the module Views RSS (and Core Elements, DC Elements)
* Create a default view for content and fields
* Add a feed to it
* Style it as `RSS Feed - Fields`
* In the settings `pubDate` is avaible alerady so we don't have to worry about that.

Create a tiny module and enter the following

```
/**
 * Implements hook_views_rss_namespaces().
 */
function MY_MODULE_views_rss_item_elements() {
  $elements['dc:lastBuildDate'] = array(
    'description' => t('My custom lastBuildDate field.'),
    'help' => '',
  );
  return $elements;
}

```

Then install it and clear your cache.

Now, in the Views RSS field settings there should be a new field for your custom field (see image)

And when you view your feed it should be included (see image - last line)

Note: if you look at the snippet, it adds the field to the `dc` namespace. If you want to use another or provide your own namespaces have a look at the API and hooks.

# Answer
> -1 votes
It appears to me that you have custom patched the Views modules with an extra function which calls hook\_views\_query\_alter. There are at least two problems with doing it this way:

1. Altering a module with a patch that is not being considered for commit by the maintainers will lead to trouble when the module is updated - in a few years when somebody else is maintaining the site, will they remember to apply the same or an updated patch each time? Will you?
2. The views module may *already have a hook\_views\_query\_alter call* and you can't call a hook more than once in any one module. If it doesn't, maybe it will have one in later versions.

I suggest moving your code to a custom module.

---
Tags: views, feeds
---