# Question
Title: User Import: Possible to use other variables in the user notification email?
We are using the User Import module to populate the User list, and having it send out a notification email with a temporary login URL. In the notification email section of User Import configuration, it is stated:

*Customize the body of the welcome e-mail, which is sent to imported members. Available variables are: !username, !site, !password, !uri, !uri\_brief, !mailto, !login\_uri, !edit\_uri, !login\_url.*

In this site we have some custom fields added to User which are being populated via User Import of .csv files. We would like to include a variable in the message body that picks up a numerical value from those fields. There is a set of fields of the name pattern "field\_schools\_owned\_zone\_1" which goes from 1 to 6; then in a View we have a math field that sums up those 6 field values for each user. It is that sum that we want to use.

Can this email form accept variables other than those listed? If so, how can we determine the replacement string for that math field value so it can work in the email message?

--Thanks--

# Answer
> 0 votes
Probably not easily an existing request in the issue queues shows people want to add fields from the Content Profile module on the 6.x branch of this module: https://www.drupal.org/node/1060394

There is a small patch in that issue that adds custom profile fields into the allowed list. The tokens would be in the same format as the given `!username` examples, eg `!field_schools_owned_zone_1` for 1 of your fields.

Until that patch is added to the version of the module you're using you'd have to apply or adapt that patch to your site.

---
Tags: users, tokens
---


# Question
Title: How can I include a custom JavaScript file such that it can access and bind events to DOM elements?
This is my first time writing custom JavaScript for Drupal, and at the moment I am attempting to bind onClick events to buttons within a block generated by a view, but I suspect I am approaching this from the wrong angle by doing what I'm familiar with in other frameworks. I believe I could, and likely will, use views to achieve the desired effect in this case, but I will need the ability to apply jQuery to different ends later on and would like to learn using this example.

At the moment I have a .js file with only basic alert bindings using the jQuery .click function and the buttons' ID selectors wrapped in a function to allow the use of the $ shortcut for jQuery:

```
(function ($) {

    $('#previous-arrow').click(function () {
        alert('previous clicked');
    });

    $('#next-arrow').click(function () {
        alert('next clicked');
    });

}(jQuery));

```

I have included this file both in the theme .info file and by calling drupal\_js\_add() in several locations throughout the site, and I have verified both that the file is being included and jQuery is correctly functioning within this function each time.

The issue I am hitting is that at the time this file is included and the function executed, the DOM does not appear to be completely built, and the elements I am attempting to target do not yet exist - only the calls to include the needed files. Attempting to retrieve the HTML of elements such as the body return a null value, while displaying the output of $('\*').html() at the beginning of my file shows the following:

```
<!--<![endif]--><head>
      <meta charset="utf-8">
<meta about="/home" property="sioc:num_replies" content="0" datatype="xsd:integer">
<link rel="shortcut icon" href="http://mysite.localhost/sites/all/themes/my_theme/favicon.ico" type="image/vnd.microsoft.icon">
<meta content="Home Page" about="/home" property="dc:title">
<link rel="shortlink" href="/node/10">
<meta name="Generator" content="Drupal 7 (http://drupal.org)">
<link rel="canonical" href="/home">
  <title>Home Page | mysite.localhost</title>

      <meta name="MobileOptimized" content="width">
    <meta name="HandheldFriendly" content="true">
    <meta name="viewport" content="width=device-width">
    <meta http-equiv="cleartype" content="on">

  <style>@import url("http://mysite.localhost/modules/system/system.base.css?nd8mqy");</style>
<style>@import url("http://mysite.localhost/misc/ui/jquery.ui.core.css?nd8mqy");
@import url("http://mysite.localhost/misc/ui/jquery.ui.theme.css?nd8mqy");
@import url("http://mysite.localhost/modules/overlay/overlay-parent.css?nd8mqy");
@import url("http://mysite.localhost/modules/contextual/contextual.css?nd8mqy");</style>
<style>@import url("http://mysite.localhost/modules/comment/comment.css?nd8mqy");
@import url("http://mysite.localhost/modules/field/theme/field.css?nd8mqy");
@import url("http://mysite.localhost/modules/node/node.css?nd8mqy");
@import url("http://mysite.localhost/modules/search/search.css?nd8mqy");
@import url("http://mysite.localhost/modules/user/user.css?nd8mqy");
@import url("http://mysite.localhost/sites/all/modules/views-7.x-3.8/views/css/views.css?nd8mqy");</style>
<style>@import url("http://mysite.localhost/sites/all/modules/ctools-7.x-1.4/ctools/css/ctools.css?nd8mqy");
@import url("http://mysite.localhost/modules/shortcut/shortcut.css?nd8mqy");
@import url("http://mysite.localhost/modules/toolbar/toolbar.css?nd8mqy");
@import url("http://mysite.localhost/sites/all/libraries/superfish/css/superfish.css?nd8mqy");
@import url("http://mysite.localhost/sites/all/libraries/superfish/style/default.css?nd8mqy");</style>
<style>@import url("http://mysite.localhost/sites/all/themes/my_theme/css/styles.css?nd8mqy");</style>
  <script src="http://mysite.localhost/misc/jquery.js?v=1.4.4"></script>
<script src="http://mysite.localhost/misc/jquery.once.js?v=1.2"></script>
<script src="http://mysite.localhost/misc/drupal.js?nd8mqy"></script>
<script src="http://mysite.localhost/misc/ui/jquery.ui.core.min.js?v=1.8.7"></script>
<script src="http://mysite.localhost/misc/jquery.ba-bbq.js?v=1.2.1"></script>
<script src="http://mysite.localhost/modules/overlay/overlay-parent.js?v=1.0"></script>
<script src="http://mysite.localhost/modules/contextual/contextual.js?v=1.0"></script>
<script src="http://mysite.localhost/misc/jquery.cookie.js?v=1.0"></script>
<script>var switchTo5x = true;</script>
<script src="http://w.sharethis.com/button/buttons.js"></script>
<script>if (stLight !== undefined) { stLight.options({"publisher":"dr-e13af4e9-811b-621c-becb-9db3833a59fd","version":"5x"}); }</script>
<script src="http://mysite.localhost/modules/toolbar/toolbar.js?nd8mqy"></script>
<script src="http://mysite.localhost/sites/all/libraries/superfish/jquery.hoverIntent.minified.js?nd8mqy"></script>
<script src="http://mysite.localhost/sites/all/libraries/superfish/sfsmallscreen.js?nd8mqy"></script>
<script src="http://mysite.localhost/sites/all/libraries/superfish/supposition.js?nd8mqy"></script>
<script src="http://mysite.localhost/sites/all/libraries/superfish/superfish.js?nd8mqy"></script>
<script src="http://mysite.localhost/sites/all/libraries/superfish/supersubs.js?nd8mqy"></script>
<script src="http://mysite.localhost/sites/all/modules/superfish-7.x-1.9/superfish/superfish.js?nd8mqy"></script>
<script src="http://mysite.localhost/sites/all/themes/my_theme/js/ui-scripts.js?nd8mqy"></script></head>

```

(If there any paths that don't make sense here, they have been \[hastily\] anonymized)

My guess is that there is a correct way in Drupal to do what I'm attempting that I am not aware of, and stand to waste a lot of time trying to shoehorn my approach into the framework. What is the way to accomplish event bindings in an included custom JavaScript file?

# Answer
> -1 votes
If you are getting alert message while loading the page then your Drupal and Javascript are working properly together.

That said, the problem you are facing with DOM elements, in your case #previous-arrow and #next-arrow, not loading when Jquery function executes is true. To overcome that you have to execute your Jquery inside $(document).ready() condition so your code will execute only when everything on the page is loaded.

So try with this:

```
(function ($) {

  $(document).ready(function() {

    $('#previous-arrow').click(function () {
      alert('previous clicked');
    });

    $('#next-arrow').click(function () {
      alert('next clicked');
    });

  });

}(jQuery));

```

---
Tags: javascript
---


# Question
Title: flex slider with unique links and no links
I have a flex banner that displays images from a content type I have created for the banner. In my banner view I can only link the image to the original image, the banner page or nothing. My goal is to be able to assign links to some of the banners. For example link slide 1 to a basic page, slide 2 to an article and slide 3 to another custom type page. My googling skills seem to let me down here.

I know that you can meet these requirements on different platforms for example on magento you can use 'Magestore\_BannerSlider' where for each banner you upload an image, set up the dates to display from X to Y, add a unique link to each banner or if left empty it is not linked.

I am interested if I can get similar functionality using Drupal.

# Answer
To do that you can simply:

1. Add new text field to your content type and name it Link for example.
2. Add this field into your view, hide it by check *'Exclude from display'* in views field settings and move it above your banner image field.
3. Open views settings for the banner image field, under *'Rewrite results '* section check *'Output this field as a link'* and put replacement pattern for your link text field in *'Link path'* input, e.g. \[field\_link\].
4. Save your view and now each banner is linked to any path you specify in the Link text field or is not if you leave this field empty.
> 1 votes

---
Tags: navigation, javascript
---


title: How to use panels_bootstrap_layouts?

text:
# Question
Title: How to use panels_bootstrap_layouts?
I am using the bootstrap theme together with panels\_bootstrap\_layouts. The bootstrap layouts option does show up and I can successfully add my content (2 views) to my panel with boostrap layout (2 colums stacked): one view in the left column and one view in the right column.

My problem is that when I save and view the page, the views are displayed one on top and one on the bottom but never left and right as they are suppose to be even when the browser is at full screen size. The theme seems to correctly be informed of the viewport size because when I resize the browser window to smaller width, then the main menu changes aspect as it is supposed to for smaller screens. My panel however does not change aspect, my views are always top/bottom and never change to left/right.

Is there a setting somewhere I should change in order for panels\_bootstrap\_layouts to correctly follow the fluid design and rearrange panels according to viewport width?

# Answer
> 1 votes
turns out that for some reason the bootstrap layouts .php files did NOT use bootstrap "spanX" classes. So I implemented them like this:

```
 <div class="row-fluid">
    <div class="span6" >
     <?php print $content['left']; ?>
    </div>

    <div class = "span6">
     <?php print $content['right']; ?>
    </div>
 </div>

```

instead of the original:

```
<div class="row-fluid">
     <?php print $content['left']; ?>
     <?php print $content['right']; ?>
</div>

```

in the file modules/contrib/panels\_bootstrap\_layouts/plugins/layouts/bootstrap\_twocol\_stacked/bootstrap-twocol-stacked.tpl.php

# Answer
> 3 votes
There a few reason this might be happening

1st is your using a bootstrap 3 theme with bootstrap 2 panel layouts.

The 2nd is your not setting panels with the bootstrap grids width.

After you have choosen the bootstrap stack layout.

1.Click on "Save and update"

2.Then click on the little gear you will see a drop down menu

3.then click on option that say's "Change"

4.Then select the bootstrap layout option

5.Then you will be able to select the column width of the layout

6.Then save.

Then do the same for the other right or left column and now your column will be right or left. You can see example how to do this here

If you want to hide some panels from on a mobile or desktop display, then you need to use bootstrap hide and show classes which you can find here

1.goto panels gear 2.Select css 3.add the "hidden-lg" class to panels on desktop you want to hide or "hidden-sm hidden-xs" to panels you want to hide on mobile or tablet

I hope that helps

---
Tags: panels
---


# Question
Title: How to include multiple Views in an already existing feature?
I have to work with an old Drupal 7 site. It's using features. I created some new views, now I have to include these 2 new views into a feature which already has 1 view. How can I do it and which steps or hooks I should follow? Thank you

# Answer
Feature module provides admin interface for each feature you create.

1. Just go to this page: admin\>structure\>feature
2. Find your feature
3. Edit it and check which Views to add.
4. Rebuild your custom feature module which your edited.
5. Open the code, delete old custom\_feature module and add new custom\_feature module which you just created.

You are done!
> 1 votes

---
Tags: views, 7, features
---


title: Frontpage grid - Rowsize to big

text:
# Question
Title: Frontpage grid - Rowsize to big
Following configuration: Drupal 7.31 / Theme: Tb Corpal (based on nucleus 7.x-1.5)

I am using views to configurate what is shown on the frontpage. Format is "Grid".

Please have a look at the page: www.reatch.ch

You will notice, that the first three teasers are shown right below the slideshow. Then there is a huge vertical gap to the fourth teaser. After the fourth teaser there is another huge vertical gap to the footer.

I am not sure why this happens. Did not find an option in views which enabled to change that... Please let me know what other information you need to answer this!

# Answer
Wow.. that min-height is a doozy. The only place I can find where it is located is inside one of the theme's javascript files **jquery.matchHeights.min.js**.

I did not buy that theme so I do not know the configuration files, however, see if there is a place in admin where you can disable the **Match Heights Plugin** file.
> 1 votes

# Answer
Looks like the system is tossing in an unusual min-height value for each div. Can you locate this in your code: div class="grid-inner col-inner clearfix" style="min-height: 2694px;" You might have to work your CSS to get it all formatted properly. If you remove that min-height variable, it formats correctly (in FireFox)
> 1 votes

---
Tags: views
---


# Question
Title: on submission of form respective form should open
in my form i have to show two radio button and one submit button, for example

candidate(radio)

organization(radio)

submit button.

my requirement is that

if user click/check on candidate and submit then candidate form should be open.

or

if user click/check on organization and submit then organization form should be open.

my code:

```
<?php
/**@file
*donation.module*/
/**
*Implements hook_menu()*/
function donation_menu(){
$items['donate'] = array(
'title' => 'Donate',
'page callback' => 'drupal_get_form',
'page arguments' => array('donation_donate_form'),
'access arguments' => array('access content'),
'access callback' => TRUE,
);
return $items;
}
/**
*Implements hook_form().
*/
function donation_donate_form($form, &$form_submit){
/*the options to display in our form radio buttons*/
$options = array
'candidate' => t('Candidate'),
'organization' => t('Organization'),
);
$form['officials'] = array(
'#title' => t('OFFICIALS'),
'#type' => 'radios',
'#options' => $options,
'#default_value' => $options['candidate'],
);
$form['name'] = array(
'#title' => t('NAME'),
'#type' => 'textfield',
);
$form['submit'] = array(
'#value' => t('PROCEED'),
'#type' => 'submit',
);
return $form;
}

```

# Answer
I'd do something like

```
function donation_donate_form_submit($form, &$form_state) {
  switch ($form_state['values']['donate']) {
    case 'candidate':
      $form_state['redirect'] = 'donate/candidate';
      break;

    case 'organization':
      $form_state['redirect'] = 'donate/organization';
      break;
  }
}

```

and from this point I can do two things

# Solution 1

Create other two menu items with different form for each

# Solution 2

your original form would be called if you don't create any extra menu items (drupal falls back to the longest menu item that match the current URL), then change the existing form depending on the argument like this

```
function donation_donate_form($form, &$form_submit) {
  $form = array();
enter code here
  // No argument ? we must be in the selection phase.
  if (arg(1) == NULL) {
    $form['officials'] = array(
      '#title' => t('OFFICIALS'),
      '#type' => 'radios',
      '#options' => array(
        'candidate' => t('Candidate'),
        'organization' => t('Organization'),
      ),
      '#default_value' => 'candidate',
    );

    $form['name'] = array(
      '#title' => t('NAME'),
      '#type' => 'textfield',
    );

    $form['submit'] = array(
      '#value' => t('PROCEED'),
      '#type' => 'submit',
    );
  }
  elseif (arg(1) == 'organization') {
    // Candidate form stuff.
  }
  elseif (arg(1) == 'candidate') {
    // Organization form stuff.
  }
  return $form;
}

```

It depends on how you like your code, and what you are trying to do.
> 0 votes

# Answer
I'm not too clear on what you mean by "candidate form should open". You did say after they press submit so can I assume you mean they go to the next page in some process? OR do you mean you want some other dynamic content to load on the same page?

IF you simply want to change the action of the form based on which radio is selected then something like this would do the trick,

```
<script type="text/javascript">

function chooseAction(form,radioname){

    var radios = document.getElementsByName(radioname);

    for(var i = 0; i < radios.length; i++){

        if (radios[i].checked){

            if (radios[i].value == 'candidate'){
                form.action = "can.php";
                return true;
            }
            if (radios[i].value == 'organization'){
                form.action = "org.php";
                return true;
            }

        }

    }

    return false;

}

</script>

<form id="myform" name="myform" method="get" action="" onSubmit="return chooseAction(this, 'officials')">
Candidate:<input type="radio" name="officials" value="candidate"><br>
Organization:<input type="radio" name="officials" value="organization"><br>
<input type="submit" value="go">
</form>

```

i suppose this might not be what youre looking for if you're looking for how to lay all this out automatically somehow in drupal
> -1 votes

---
Tags: forms
---


# Question
Title: Are there any modules where you can import H2Database data into drupal 7 as nodes?
I'm working with the java h2 database engine and there is data that i want to query/import everyday. Is there a module or how would I go about importing such data into drupal 7 as nodes?

# Answer
Your best bet is likely to use the Migrate module and a custom php H2 database driver.

This is not easy.

You can follow this to get php working with PDO and Java H2. http://www.webdevelopersdiary.com/1/post/2012/07/jamp-an-ultra-portable-php-web-server-and-database-stack-in-java.html

From there you will need to write a class for the migrate module that extends the migrate source class
> 0 votes

---
Tags: migrations, importing-exporting
---


# Question
Title: what is the strongarm variable addititonal_settings_active_tab_*
I am using the Features and Strongarm module to move my work between sites. I am using them as a way of version controlling changes made in the database (as Configuration Management module has many issues.)

I am trying to understand what the following settings are, which module (or core) creates them, and should they be passed from site to site:

```
 additional_settings__active_tab_chapter
 additional_settings__active_tab_committee
 additional_settings__active_tab_document
 additional_settings__active_tab_event
 additional_settings__active_tab_jcr_article
 additional_settings__active_tab_jcr_issue
 additional_settings__active_tab_news
 additional_settings__active_tab_page
 additional_settings__active_tab_success_stories

```

The last piece of these settings ie: 'chapter' are the names of the content types on the site. Should I be passing these variables?

# Answer
> 1 votes
It is the vertical tab that is "active" when the node edit form loads. Export as needed (I usually don't).

FWIW, i used 'drush vget' to take a look at the variables value and that made it pretty easy to figure out its purpose. (Drush)

---
Tags: features, strongarm
---


# Question
Title: Don't Allow User To Log Back In After Logging Out Of Drupal Site
This might be a simple fix, but I cannot figure out how to do it or find a module that accomplishes this. I simply need to dis-allow a user to log back into a site after they have logged out. They need to be allowed one login only. After they log out, they are locked out.

Another thing that would accomplish my goal would be to hide ALL webforms once user has submitted ONE of the webforms. Upon submission, they are not allowed to submit any of the other forms.

So, either logging them out without ability to log back in, or hiding all webforms after ONE has been submitted. Either will accomplish my goal.

Any suggestions?

# Answer
You can use workflow rules to accomplish this. Create a new rule to react on "User has logged out" , then add an action to "Block user".
> 2 votes

# Answer
Hope I can point you in right direction to get you started.

For reference Drupal user api

1. Create role 'One time login'
2. User this module node privacy by role to give access to webforms only user who belongs to role 'One time login'
3. Write custom module which,

3.1 Create custom table to store user one time login flag status

3.2 Use hook\_user\_login() to see if your user has logged in before reading one time log in status flag and access to webform according to node privacy by role

3.3 If above condition fails force logout.
> 0 votes

---
Tags: webforms, forms, database, users
---


# Question
Title: A view to display only nodes related from user field
So I have user accounts and have added some custom fields to the user accounts. One of the fields is 'field\_procedures' which is a entity reference to a content type called procedures.

Inside a view now, which is a calendar view, I want to display ONLY the procedure nodes that have been selected in the 'field\_procedures' field that match that user. So that I am able to set which procedure nodes that are related to this user and want him to only see the calendar with of that node type he has been selected for.

I can't figure out how to set this up.

# Answer
> 1 votes
In Views add a relationship to the "Entity Reference: Referenced Entity", then add a contextual filter for UID with a default value taken from the URL.

See also http://codekarate.com/daily-dose-of-drupal/using-views-entity-reference-module-drupal-7

---
Tags: 7, views
---


# Question
Title: How do I get rid of <p> tag in manually created block?
I'm trying to remove a `<p>` tag from a manually created block. This block only contains an image and nothing else. I have `kpr()` function outputting block variables but am not seeing where, or how the unnecessary `<p>` tag is being generated.

Would the modification occur in `theme_preprocess_block` function? It seems it's not possible to get rid of within the block template file.

Another thing is that my tried was getting turning on `themes info`, clicking the element in hopes of finding some override function, but `themer_info` only shows me block info instead of some function info.

Any help would be greatly appreciated, thank you.

# Answer
It's in fact because of the text input format. Going to admin/config/content/formats and removing the checkbox for

```
Convert line breaks into HTML (i.e. <br> and <p>)

```

for the input format you're using should do the trick (re-save the block, of course). Also, if you use WYSIWYG editor, it could do some formatting for you and put the image in `<p>` tag.
> 0 votes

---
Tags: theming, blocks
---


# Question
Title: How to capture git's output in drush make?
We use drush to clone a number of git-repositories during build. Most of the time this "just works", but on (a rare) occasion, a cloning fails.

Unfortunately, all that we get from drush in such cases is:

> Unable to clone *repository* \[error\]

The `DRUSH_BACKEND` piece of JSON is shown, but claims no error (`"error":null`):

```
DRUSH_BACKEND:{"type":"notice","message":"Command dispatch complete","timestamp":1411582254.5773,"memory":10891736,"error":null,"packet":"log"}

```

The actual error message generated by the git-executable is not shown. Is there a way to change that? Simply adding `--debug` to drush's command line does not do it...

This question may not even be drush-make specific -- the spawning of external programs and capturing their stdout/stderr may be a generic drush thing...

Thank you!

# Answer
> 1 votes
Ok, the short answer is: it is not possible. Not at the moment. Although the code in `includes/exec.inc` is prepared to output the captured `stdout` and `stderr` of the command, it will only do so, if `DRUSH_DEBUG` is set:

```
  exec($command . ' 2>&1', $output, $result);
  _drush_shell_exec_output_set($output);

  if (drush_get_context('DRUSH_DEBUG')) {
    foreach ($output as $line) {
      drush_print($line, 2);
    }
  }

```

The only way to set `DRUSH_DEBUG` is by giving the `--debug` flag on drush command-line (it can not be set from `drushrc.php`). Sadly, in a number of cases -- including git-invocations -- the top-level drush invokes a child drush to do the actual work. It is doing so *without passing the `--debug` flag to it*...

I filed a ticket with drush-maintainers and implemented a work-around. We replaced the real `git` executable with a shell-wrapper, which captures `stderr` of the real git (and some other info, like environment veriables) into a log-file, then feeds the captured stderr to its own descriptor 2 -- just in case the caller cares. Then, if the real git's exit-code is 0, the log is deleted, otherwise it is retained for investigation.

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


# Question
Title: Actual output in view is different than preview
I have set up a view to display all nodes for 1 taxonomy term. Something got messed up and now the final view drops one node (which is also a different content type).

I cannot find rhyme or reason why the content type with images is being left out.

I have deleted the old view and copied a working one that has been set up for a different model again, changed taxonomy term, path and link and BANG the gallery node missing again.

The preview of the view shows it as it should be.

The page affected is this one: http://www.riverlakesea.com/smartwave/skippa

A pointer where I must check would be much appropriated since I have been through node/content type/view gazillion times and cannot spot the problem.

Many thanks, Susanne

# Answer
Change your filter to include content of that particular content type. Does it pull just that gallery?

Also, screen shot of your view admin panel would be helpful.
> -1 votes

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


title: Uninstalling the module from drupal-7

text:
# Question
Title: Uninstalling the module from drupal-7
I had installed module **Commerce** and it was giving me error whenever I try to display product.Then I went through forums to find out solution. And reason mentioned in forum was `commerce` module might not installed properly due to maximum execution time.So I decide to uninstall **commerce** module and I have done. Also removed it from the `sites\all\modules`. I have cleared all the caches.

But question is that after removing the module, `product`(which is part of the commerce module) is still showing up in admin navigation bar at top.

I know it is not coding related question but still any help would be appreciated.

# Answer
> 0 votes
Follow these steps. From these steps I think your query may solved.

1. Clear caching from the drupal.
2. Clear caching from the database.
3. Clear browser caching.

& check. If the menu again shows then **Goto**

```
Admin -> Structure -> Menu -> Management -> list links

```

& check

**Clear Caching from the database (local server)**

```
TRUNCATE TABLE cache;
TRUNCATE TABLE cache_advagg_aggregates;
TRUNCATE TABLE cache_advagg_info;
TRUNCATE TABLE cache_block;
TRUNCATE TABLE cache_bootstrap;
TRUNCATE TABLE cache_field;
TRUNCATE TABLE cache_filter;
TRUNCATE TABLE cache_form;
TRUNCATE TABLE cache_image;
TRUNCATE TABLE cache_menu;
TRUNCATE TABLE cache_page;
TRUNCATE TABLE cache_path;
TRUNCATE TABLE cache_update;
TRUNCATE TABLE cache_views;
TRUNCATE TABLE cache_views_data;

```

# Answer
> 0 votes
Visit admin/modules/uninstall, check if its uninstalled.

Check once again DRUPAL\_ROOT/sites/all/modules for commerce module, if exist delete the folder. and still not solved

Clear the cache twice thrice still not solved

If you have ssh access to your project clear cache via drush still not solved

Restart mysql and apache2 still not solved

put site in maintenance mode and reboot the live server.

For further help visit How to fix error found in Drupal Commerce after installation

---
Tags: 7, commerce
---


# Question
Title: How can I suppress "CSS file not found" errors on production?
"One or more CSS files were not found or does not exist" errors are being displayed to users on production. Of course I should fix the source of these errors, but in the meantime, I would like to suppress this error message.

On `admin/config/development/logging`, I have set **Error messages to display** to *None*. Is there some other step I need to take to suppress these errors?

I have also cleared all caches (Drupal, Redis, Varnish) but the error (only present on some pages) is still being displayed to authenticated (non-admin) users.

# Answer
I would first ask, are you logged in as super admin? I believe if you are logged in as super admin the message will display regardless of the setting in development/logging.

If you are not logged in as admin and are viewing the page anonymously did you clear your browser cache. If the messages are still being displayed, is your site being cached via varnish? You may need to clear the varnish cache or simply add an extra query parameter to the end of the url to make certain you are viewing an unvarnished page. Ex: www.example.com/homepage?extraquery

This is generally unadvisable but when push comes to shove and you need to hide something quickly on the production site, you can alway hide the error message box with css until you actually fix the error. AGAIN, i would only use this as a last resort and if deadlines are rapidly approaching and there just is no other option.

You could do something like .error {display:none;} in your global.css file or wherever seems more suitable.

Good luck
> 2 votes

---
Tags: theming
---


# Question
Title: how to create a node slideshow with customized fields?
I have created a view displaying an image with two other fields, i have created a lightbox slideshow of that image, now i want that the slide show should display other required fields of the content type along with the image. How to achieve this?

thanks in advance

# Answer
Use Views Slideshow module.

**steps :**

> Enable view slideshow module.
>
> Create a view using existing content type(ex-product).
>
> View format: Slideshow
>
> Add item for slideshow (such as the title, image etc).

Or you can use jCarousel module.
> 0 votes

---
Tags: javascript, views
---


title: Remove link from active page in menu

text:
# Question
Title: Remove link from active page in menu
I need the active page in my menu not to be a link.

So let's say I'm on the services page, I need my menu structure to look like this:

```
<ul class="menu">
    <li class="first leaf"><a href="/mysite/">home</a></li>
    <li class="leaf">services</li>
    <li class="leaf"><a href="/mysite/portfolio">portfolio</a></li>
    <li class="leaf"><a href="/mysite/contact">contact</a></li>
</ul>

```

How can I do that?

# Answer
You need to override the theme\_link function.
In your template.php file add this. (changing THEME to the name of your theme).

```
function THEME_link($variables) {
  if ((isset($variables['path']) && ($variables['path'] == $_GET['q'] || ($variables['path'] == '<front>' && drupal_is_front_page())))) {
    // Return text instead of link if current menu item active
    return ($variables['options']['html'] ? $variables['text'] : check_plain($variables['text']));
  } else {
    return '<a href="' . check_plain(url($variables['path'], $variables['options'])) . '"' . drupal_attributes($variables['options']['attributes']) . '>' . ($variables['options']['html'] ? $variables['text'] : check_plain($variables['text'])) . '</a>';
  }
}

```
> 2 votes

---
Tags: 7, routes, navigation
---


# Question
Title: How to create a user after ldap authenticaion?
I am using ldap for Drupal 7. After successfully authenticating, how do I create a Drupal user.

# Answer
The LDAP module will also allow you to automatically create a user after authentication.

* Once you configure your server, look at the third tab LDAP authorization Choose edit to configure that server
* Under basic, enable and Only apply the following LDAP to drupal role configuration to users authenticated via LDAP.
* You can set the role of the new user by checking drupal roles are specified by LDAP attributes under IIB. Also name the field that will be use to determine role
* Configure part III. LDAP to drupal role mapping and filtering For example, if the title field is Staff you may want to give a staff role Staff|staff
* Part 4 IV.B. When should drupal roles be granted/revoked from user? Check "When a user logs on"
* IV.C. What actions would you like performed when drupal roles are granted/revoked from user? Check Revoke drupal roles previously granted by LDAP Authorization but no longer valid.

There are other settings that you can configure but this should get you started.
> 1 votes

# Answer
the Ldap and Simple LDAP modules both can create Drupal user accounts for you after authentication. Read the project documentation and readme files.

For example from the Simple Ldap project page:

> Simple LDAP User
>
> This module allows authentication to the LDAP directory configured in the Simple LDAP module. It also provides synchronization services both to and from LDAP and Drupal. It supports mapping LDAP attributes to Drupal user object fields (both native, and using Field API).
> 0 votes

---
Tags: authentication-authorization
---


# Question
Title: Drupal Services 3.x - Custom error output
Is there a way to control the output in the drupal services? Example, if a argument that is required, it not provided in the call, I get the following output as a JSON array.

```
Missing required argument title

```

I'd like to either override this output, or instead of returning a json object, just return plain text.

Is this possible to do?

# Answer
> 3 votes
You most certainly can.

If you open up the docs folder in the services module you can see the function `hook_rest_server_execute_errors_alter(&$error_alter_array, $controller, $arguments)` in the file `services.alter.api.php`

```
<?php
/**
 * Allows alteration of error data before the status code or message are returned.
 *
 * @param array $error_alter_array
 *   An associative array with the following keys:
 *     - 'code': the HTTP status code.
 *     - 'header_message': the message returned as part of the error response
 *       (for instance, "404 Not found").
 *     - 'body_data': data that was passed to the thrown exception.
 * @param array $controller
 *   The current controller definition.
 * @param array $arguments
 *   Arguments passed to the current controller.
 *
 * @see RESTServer->handleException()
*/
function hook_rest_server_execute_errors_alter(&$error_alter_array, $controller, $arguments) {

}

```

Example output would be:

```
Array (
  [code] => 401
  [header_message] => 401 Unauthorized : Missing required argument username
  [body_data] => Missing required argument username
)

```

So you could alter it like,

```
function MYMODULENAME_rest_server_execute_errors_alter(&$error_alter_array, $controller, $arguments) {
 $error_alter_array['code'] = 500;
 $error_alter_array['header_message'] = '500 Come on man, send that username';
 $error_alter_array['body_data'] = 'Come on man, send that username';
}

```

Note: You do not need to return anything because it is alter by reference and two, make sure you clear cache after adding this function to a module.

---
Tags: services
---


# Question
Title: How to share menus and blocks across domains, but not users and content data?
I'm trying to create multiple sites(maybe over 20 sites) using the same menu and some blocks, but not others.

I found these modules that have very similar features/functions: \- Domain Access. \- Domain Menu Access. \- Domain Blocks.

However, I don't want to share the users, content and other data.

Also, for each of the domain, I would like to have their own Drupal backend.

What is the easiest and effective solution?

# Answer
There really is not "Easy" way but you are on the right track. From your description it sounds like you need to be using Domain Access. In order to share content all sites need to be using the same shared database. As for content/users, you will have to configure your data and users to not be shared across all domains. These are all permission settings that can be set from Domain Access. Set each user to only have access to a specific domain. And set each content type to be visible for the domain it was created under.

With domain access you can have a different theme set up for each domain, so that will help you have a different "backend" experience for your authenticated users. So to answer your question, Domain access is the most effective apporach for this type of scenario. Its all just a matter of configurations and permission settings.
> 1 votes

---
Tags: routes, blocks, domain-access
---


# Question
Title: Changing to date field based on from date using javascript
I have a form written using Drupal's FAPI (Drupal v7.15). The form includes two date fields - a from date and a to date. I've installed the Date module and both fields are both set-up to use the 'date\_popup' widget.

Now I want to make the to date automatically change when the from date is updated by the user. Eg if the user sets the from date to 1st Nov 2012, I want the to date to automatically change to match the from date. Ideally I would also like the date picker to disable all options earlier than this date. This is the same behaviour you see on many travel sites, such as expedia.com.

I can't find a good example of how to add the Javascript to do this. I can only see AJAX examples, and it seems unnecessary to make a round trip to the server to do this - the browser has all the info it needs to do so client side.

# Answer
> 2 votes
If I understand you right it should be as simple as dropping something like this into a JS file included in the page:

```
(function($) {
  Drupal.behaviors.myModule = {
    attach: function(context, settings) {
      $('#edit-from-date', context).change(function() {
        $('#edit-to-date', context).val($(this).val());
      });
    }
  }
})(jQuery);

```

Disabling certain dates is a bit more complicated but there's an example here that should point you in the right direction.

# Answer
> 1 votes
Here's the complete solution. The 'to date' is updated to the 'from date' plus one week and dates in its datepicker are disabled for dates equal to or earlier to the 'from date'. The form fields are created with Drupal's Forms API.

**First the PHP code**

```
$default_from = date('Y-m-d 00:00:00', strtotime(date('Y-m-d')." +1 month"));
$form['dates']['from_date'] = array(
    '#type' => 'date',
    '#title' => t('Ingreso'),
    '#type' => 'date_popup',
    '#date_year_range' => '-0:+2',
    '#date_format' => 'd/m/Y',
    '#default_value' => $default_from,
    '#datepicker_options' => array('minDate' => 'today'),
    '#required' => TRUE,
);

$form['dates']['to_date'] = array(
    '#type' => 'date',
    '#title' => t('Salida'),
    '#type' => 'date_popup',
    '#date_year_range' => '-0:+2',
    '#date_format' => 'd/m/Y',
    '#default_value' => date('Y-m-d 00:00:00', strtotime($default_from." +1 week")),
    '#datepicker_options' => array('minDate' => date('d/m/Y', strtotime($default_from." +1 day"))),
    '#required' => TRUE,
);

```

**Then the Javascript**

```
(function($) {
Drupal.behaviors.viajes = {
    attach: function(context, settings) {
        $('#edit-from-date-datepicker-popup-0', context).change(function() {

            //change min to-date to from-date plus one day
            if ($("#edit-to-date-datepicker-popup-0" ).hasClass('hasDatepicker')) {
                $("#edit-to-date-datepicker-popup-0" ).datepicker( "option", "minDate", addDays($(this).val(),1) ); //this method if to datepicker already initialised
            } else {
                Drupal.settings.datePopup['edit-to-date-datepicker-popup-0']['settings']['minDate'] = addDays($(this).val(),1); //this method if to datepicker has never been used
            }

            //change to-date to from-date plus one week
            $('#edit-to-date-datepicker-popup-0', context).val( addDays($(this).val(),7) );

        });

        //takes date string in format dd/mm/yyyy and returns date plus 'days' in the same format
        function addDays(dateStr, days) {
            //convert to date obejct
            var dateArray = dateStr.split('/');
            var date = new Date(dateArray[2], dateArray[1]-1, dateArray[0]);

            //add days
            date.setDate(date.getDate() + days);

            //convert back to correct string format and return
            return addZero(date.getDate()) + '/' + addZero(date.getMonth()+1) + '/' + date.getFullYear();
        }

        //add leading zero if number is 9 or less
        function addZero(number) {
            if (number <= 9) {
                return '0'+number;
            } else {
                return number;
            }
        }
    }
}
})(jQuery);

```

# Answer
> 0 votes
This is a modified version of adamf321's script. The differences are:

* Format independent, uses the format set in Drupal instead of mm/dd/yy
* Preserves the time difference to 'to date' when changing the 'from date'

You can change the `fromDateId` and `toDateId` to match your input field id's.

```
(function($) {
  Drupal.behaviors.myModule = {
    attach: function(context, settings) {
      var fromDateId = 'edit-from-date-datepicker-popup-0';
      var toDateId = 'edit-to-date-datepicker-popup-0';
      var $fromDate = $('#'+fromDateId, context);
      var $toDate = $('#'+toDateId, context);
      var currentfromDate = $fromDate.val();
      $fromDate.change(function() {
        var dateFormat = $fromDate.datepicker('option','dateFormat');

        //change min to-date to from-date plus one day
        if ($toDate.hasClass('hasDatepicker')) {
          $toDate.datepicker( "option", "minDate", addDays(dateFormat,$(this).val(),1)); //this method if to datepicker already initialised
        } else {
          Drupal.settings.datePopup[toDateId]['settings']['minDate'] = addDays(dateFormat,$(this).val(),1); //this method if to datepicker has never been used
        }

        //move toDate the same amount as fromDate has moved
        var daysShifted = dateStrDiff(dateFormat, currentfromDate, $(this).val());
        $toDate.val(addDays(dateFormat,$toDate.val(), daysShifted));
        currentfromDate = $fromDate.val();
      });

      //takes date string in given format (e.g. 'dd-mm-yy') and returns date plus 'days' in the same format
      function addDays(format, dateStr, days) {
        //convert to date object
        var date = getDate(format, dateStr);

        //add days
        date.setDate(date.getDate() + days);

        //convert back to correct string format and return
        return jQuery.datepicker.formatDate(format, date);
      }

      function getDate(format, dateStr) {
        return $.datepicker.parseDate(format, dateStr);
      }

      function dateStrDiff(format, dateStr1, dateStr2) {
        var date1 = getDate(format, dateStr1);
        var date2 = getDate(format, dateStr2);
        return dateDiffInDays(date1, date2);
      }

      // See http://stackoverflow.com/questions/3224834/get-difference-between-2-dates-in-javascript
      // a and b are javascript Date objects
      function dateDiffInDays(a, b) {
        var _MS_PER_DAY = 1000 * 60 * 60 * 24;
        // Discard the time and time-zone information.
        var utc1 = Date.UTC(a.getFullYear(), a.getMonth(), a.getDate());
        var utc2 = Date.UTC(b.getFullYear(), b.getMonth(), b.getDate());

        return Math.floor((utc2 - utc1) / _MS_PER_DAY);
      }

    }
  }
})(jQuery);

```

---
Tags: forms, javascript
---


title: Services, OAuth and a mobile app

text:
# Question
Title: Services, OAuth and a mobile app
I'm struggling with Drupal, OAuth and a (Cordova) mobile app I'm developing. I've made a custom module and it exposes data to the Services module. What I want to do now is get that data into my mobile app.

I've set up my endpoint, but I need authentication of course.

I've read the tutorials on 3-legged and 2-legged authentication, but from what I've read, I (think I) want the Client-flow. This is the flow where the user enters his/her username and password in the app.

Can anyone get me started on this flow? Is it even possible with Services and OAuth?

Tell me if you need any more info. I'm a developer, but mainly in the .NET space. I've managed with Drupal modules so far, but I find OAuth quite complicated.

# Answer
First, this is a poorly worded question, so I'm answering the questions you asked, probably not what you really want though..

Both 3-legged and 2 legged work in Services with the OAuth module and the Services\_oauth module enabled. I wrote a lengthy article on how to set this up here, and documentation here

But that doesn't really answer your question in terms of If I can help you get started with your flow. I suggest you ask a new question with the problems you're currently having rather than asking if we can help you get started on a solution we know nothing about.

This may help you understand why this is an extremely tough question to answer. Asking smart questions
> 1 votes

---
Tags: services, authentication-authorization
---


title: Private Files on drupal

text:
# Question
Title: Private Files on drupal
I am using drupal 7.

I have uploaded pdf files into

**files/private**

Now I want that when I try to access

```
www.site.com/sites/default/files/private/q1-2014-fs.pdf

```

It will open. Only if user is activate then he can able to see file

I have created a `.htaccess` file too

in that

```
Deny from all

# Turn off all options we don't need.
Options None
Options +FollowSymLinks

# Set the catch-all handler to prevent scripts from being executed.
SetHandler Drupal_Security_Do_Not_Remove_See_SA_2006_006
<Files *>
  # Override the handler again if we're run later in the evaluation list.
  SetHandler Drupal_Security_Do_Not_Remove_See_SA_2013_003
</Files>

# If we know how to do it safely, disable the PHP engine entirely.
<IfModule mod_php5.c>
  php_flag engine off
</IfModule>

```

Can anybody tell me, where am I doing wrong.

# Answer
Use Private Files download permission module to set permission to download to certain users.

Also you can go for Field Permission Module
> 2 votes

# Answer
If the file is directly accessible by path or URL, then something is wrong.

It is not clear if you've set up Drupal to use the private access method for File Access Control, or just created the `files/private` path and hope that this will do it (it won't).

You need to set up the private file access method in Drupal. Read through "Working with files in Drupal 7", and pay attention to the section "Managing file locations and access".

Please note that you should *not* create a `.htaccess` file yourself. Drupal will do that for you when you set this up correctly through Drupal. If you create this file yourself, you prevent Drupal from creating it.
> 0 votes

# Answer
Your private files folder should be outside of drupal's structure as its public.

For example you'd want to structure it so that on your server you have a public\_html directory with the drupal files in and then say private\_files directory containing your private files, then in admin/config/media/file-system you should change the directory to point towards your new private folder.
> 0 votes

---
Tags: views, 7
---


title: Show all child terms in user page

text:
# Question
Title: Show all child terms in user page
I have field in taxonomy term field\_user which references to User.

At user own page (for example: user/1) I need to show taxonomy tree like this:
-user1 (this is the user whose page we are)
--user2
--user3
---user4
----user5
----user6
--etc

And if we are for example user4 page then:
-user4
--user5
--user6
--etc

It is not necessary to show current user at the tree, but it should show all terms under that user.

I'm using Views to trying to achieve this, but could not figure out proper settings for it. How to do this?

# Answer
> 0 votes
First, create a new term view using the fields row style / unformatted list of fields (it is important that the tree style not be chosen now). Then:

```
Add relationship for taxonomy term: parent term
Add field term id (do not use relationship) and exclude it from display
Add field term id with relationship, exclude from display
Add any fields you want to display, like term name, term description, etc...
Change style / format plugin to Tree (Adjacency model)
Set Main field to Term ID
Set Parent field to Term ID with parent relationship

```

For details refer https://www.drupal.org/node/1493366

https://www.drupal.org/project/views\_tree (Compatibility and Usage)

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


title: Get the name of the uploaded file

text:
# Question
Title: Get the name of the uploaded file
I'm completely new in using drupal 6. I was wondering if there is a way to print the name of an uploaded file in a node. Thanks for the help

Cheers

# Answer
> 0 votes
@blankturd

You can add Custom field in the content type for uploading image to your node.

For that perform the below mentioned steps:

1) Go to the content type to which you want to have image upload field.

2) Click on the "Manage fields" tab

3) Then Add Label of the field name Ex, "Image" And machine Readable name like "field\_image" then from the Dropdown select "File" as a controll type and last select "File Upload" widget.

By this way you can have an image upload field in your content type.

Now For displaying the image name which is uploaded there is many ways.

1) You can create new template file for the specific content type. Ex, page-CONTENT TYPE NAME.tpl.php and print the field directly.

2) You can create view for this purpose.

Hope this answer helps you.

# Answer
> 0 votes
If you want to get any node data (it loads all fields image or text), you can use **node\_load** function

**function node\_load**

```
Load a node object from the database

```

try from devel/php by loading any node by calling `print_r( node_load(1) );`

now you able to fetch your uploaded image data from node object.

**or**

if you want to fetch any node related data while creating node, use form alters & do custom submitting handler please refer this link

---
Tags: 6
---


# Question
Title: better exposed filters and bootstrap 3. Problems with alignment
I have Drupal 7 and the BEF to filter a view. My site is running the Drupal Bootstrap framework V3. The regular 'basic' theming for the exposed filters works, but I would like to use checkboxes and the JQuery slider.

I have a problem with the formatting on check-boxes and sliders.

I've googled it, but didn't find anything relevant.

Thanks in advance

# Answer
> 1 votes
https://www.drupal.org/node/2121203 gives some answers...

> Look at bootstrap/theme/process.inc at function \_bootstrap\_process\_input and comment out or remove the 'select' in there.

Still looking for the "ultimate solution" myself as well.

---
Tags: bootstrapping, views
---


# Question
Title: Views 3.8 hook_views_default_views() stopped working
I have a default view made using the views hook hook\_views\_default\_views().

It was working right and when I updated to Views 7.x-3.8 it stopped working.

It is not shown in structure -\> views, the routes don't work too (site\_url/calendar)

Seems the hook is not launching, or if it is, it does not load the view.

Updated drupal to 7.31 version, and CTools to 7.x-1.4.

Erased all the caches, drupal, views, memcached.

And it is not working.

The code looks like this:

```
// code included in my_module.views_default.inc
function my_module_views_default_views()
{
  export = array();
  $view = new view();
  $view->name = 'planning_calendar';
  $view->description = 'Calendar with planning dates';
  $view->tag = 'Calendar';
  $view->base_table = 'node_revision';
  $view->human_name = 'Planning Calendar';
  $view->core = 7;
  $view->api_version = '3.8';
  $view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */

  // view code ......

  $export[$view->name] = $view;
  return $export;
}

```

There is also this hook on the module:

```
// code included in my_module.module
function my_module_views_api() {
  return array("api" => "3.8");
}

```

# Answer
> 5 votes
See the API documentation: The correct way to declare the version is by the major number only (i.e. an integer) not the entire version as a string.

```
// code included in my_module.module
function my_module_views_api() {
  return array('api' => 3);
}

```

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


# Question
Title: Apache solr is not accessible by my server but accessible by my localhost
I have a solr installed in my server(centos 6.5).and everything works fine and my conf files exist where they should be. I try to connect to solr by help of search\_api\_solr module in drupal. Everything works fine on my localhost and one other host I try my website on,but when I try to connect to this solr using a website on the same server as the solr I'm get error

> The Solr server could not be reached

where should I start looking for something that went wrong?

# Answer
> 0 votes
problem was caused by selinux on my server.

by disabling selinux and rebooting centOs I could connect to my solr apache.

I found the answer **here**

---
Tags: search
---


# Question
Title: How to change label pass field on registration form
I need to change the password field label on the registration form. Name and Email I changed through hook\_form\_alter and password does not work. Help me!

```
$form['account']['name']['#title'] = 'Имя пользователя/Login';
$form['account']['mail']['#title'] = 'E-mail адрес/E-mail';

```

# Answer
Here is the soluition (need to clear the caches):

```
function MYMODULE_element_info_alter(&$type)
{
    // dpm($type);
    // assuming it's a password_confirm type
    $type['password_confirm']['#process'][] = 'custom_pass';
}

function custom_pass($element)
{
    $element['pass1']['#title'] = 'Пароль / Password';
    ...

    return $element;
}

```
> 1 votes

---
Tags: forms
---


title: client side validation

text:
# Question
Title: client side validation
I am trying to enable client side validation on my web forms. I installed & enabled the modules as per the Drupal.org link: https://www.drupal.org/node/1324924 & then went into the Configuration \> Client Side Validation & inserted the form ids I had in my HTML code.

However, I am unable to get the client side validation to work (errors are not recognised in the input fields), the attached screenshot shows the modules view.

The only module that seems to be missing is the 'IFE' module which I cannot find / install.

# Answer
> 1 votes
You need to download, install and enable the **IFE** (aka. "Inline Form Errors") module.

Like all Drupal modules, its project page is immediately below `https://www.drupal.org/project/`.

Here is a link to the project page where you can download it: IFE project page.

# Answer
> 0 votes
You Can use Field Validation module in case of content type. If you are using webform module then use Webform validation

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


# Question
Title: taxonomy tokens throwing invalid token error
I have a drupal 7 site, any time I use a token with taxonomy term in it, I am getting the error,

The Default path pattern for Product (applies to all Product content types with blank patterns below) is using the following invalid tokens: \[term:name\].

for example \[term:name\] or \[term:description\]

# Answer
Look at http://drupalcontrib.org/api/drupal/contributions!token!token.module/function/token\_element\_validate/7. Implement hook\_form\_alter() of form you are trying to submit and look for #element\_validate array key, in field you get an error should be

```
  '#element_validate' => array('token_element_validate'),

```

Then you should check #token\_types key value. It can have any value, as examples:

```
 '#token_types' => array('node'),

```

OR

```
 '#token_types' => array('all'),

```

In my case I got similar error in metatag\_context module when I was trying to save taxonomy token into metatags context field. Problem was in '#token\_types', they was empty, I added array('all') value and form works fine.
> 1 votes

---
Tags: taxonomy-terms, tokens
---


# Question
Title: How to implement user hierarchy with different levels of roles under different branches, groups etc
I have to create a web portal, that should have a number of users from super administrator to employee. Users have single or multilevel access (either to data of one branch or to multiple) on the system.

Some can add/edit data and some can only view some data. The system has different branches, different departments etc.. How can I implement such a system using Drupal?

I had created multiple roles and given permissions to them. But how can I achieve those multi branch multi groups kind of user hierarchy?

**Update**: Can I achieve it by using TAC : https://www.drupal.org/node/31601 ?

# Answer
> 2 votes
Have you looked at Organic Groups.

Im using it for a similar use-case. I would allow you to create content types that can act as 'Departments' and add different roles within those.

You can have for example:

* 'department' content types with following roles: admin, supervisor
* 'branch' content type with completely different roles: it programmer, temp

It is very flexible and access control works with views as well. Nice tutorial can be found here.

If you opt to however to write your custom access control module, make sure that you read up on that here

Hope that helps.

# Answer
> 1 votes
It would really depend on what your data is and how it's stored/ displayed. You could use TAC or maybe something like Organic Groups and if the provided access control isn't enough, you could use Organic Groups Access Roles.

You have plenty of options, maybe you could describe your portal a little more?

---
Tags: 7, users
---


# Question
Title: How to get different languages of the site to appear in that language's Google search results
I would like,when a user searches english terms the english version of the site to appear in google search results. When a user searches the same terms but in a different language e.g. german ,the german version of my site to appear in google search results. How can I do this?Which modules can I use?thanks

# Answer
The i18n module, which can be used for various localization tasks, includes a redirect submodule specifically for SEO. If you read the i18n documentation and set up your site carefully, you can create a site in which the English versions show up in English Google search, and the German version in German Google search.

One way to speed this process up is to use the XML Sitemap module and create a sitemap for each language; this will help Google learn which pages of your site belong to which language (although Google certainly doesn't need this, and can determine it automatically; it will just take longer to index your site).
> 4 votes

---
Tags: i18n-l10n
---


# Question
Title: how to develop multiple pages registration form
I want to develop a registration form employees based on different steps like company,salary,interview,pors and crons etc. they are pages for the registration process. Can anyone tell me how to develop this kind of functionality?

# Answer
> 1 votes
Try the Multi-Step Registration module

> With Multi-Step Registration you can create multi-step (wizard) user account registration forms. Each step of the wizard can be configured to, optionally, expose one ore more Profile2 types.

You can also achieve that by creating a custom module. Checkout this post and

Altering User Registration Form to Multi-Step Drupal 7

---
Tags: 7
---


title: Error connecting to smtp server

text:
# Question
Title: Error connecting to smtp server
I have a Drupal 7.30 installation that I'm trying to develop on webenabled ( I also had it on network solutions shared hosting), and every time I attempt to send an email, I get the error unable to connect to the smtp server, and unable to send email, contact the system admin if this persists. I have read numerous articles and check the drupal forum, but I have had no luck. None of the solutins work for me. I'm wondering if it is the configuration on the shared hosting. That is why I left network solutions. They culd not help, and were rather rude about my attempts. Thank you ahead of time for anyone that can provide an answer. SimmonsOne (Drupal username)

# Answer
If there is a mail system installed on your server, Drupal will use it to send mail.

Things to check:

1. Can you send mail using a CLI mail program (e.g. "mail")?
2. Can PHP send mail? (Create a small PHP program outside of Drupal that uses this PHP-function to send mail.)

Usually, this is not a Drupal problem. If you're able to send mail *outside* of Drupal, then Drupal will also send mail without any special configuration on your part.

Most shared hosting plans I've used (never used *Network Solutions*) is set up to send mail by default.

Also read this about debugging email problems.
> 1 votes

---
Tags: nodes, emails
---


# Question
Title: can any one tell me steps to use ajax-register module
can any one please tell me the steps to use ajax-register module for user login, user registration and change password in drupal 7. which display user registration, user login, forget password forms in i-box.

# Answer
1. Download & install Ajax Register.
2. Goto

Admin -\> Module -\> Enable \[Ajax Register\]
3. Goto

Admin -\> Configuration -\> Ajax Register

Update configuration setting as per you want.
> 0 votes

---
Tags: users
---


# Question
Title: Programmatically add node translation drupal 7 ( Entity translation )
I need to create multilingual node programmatically in Drupal with entity\_translation.

No problem to create the node, but I have no idea how can I create the translation ( + field translated).

I don't want to create another node, just translate it (same nid).

My language is FR , I need translation in EN and DE.

# Answer
> 2 votes
Found the answer ! Thanks to my co worker.

In order to add translation to a node you need to add every translatable field like this in your creation node code :

```
 $node->field_trailer['fr'][0]['value'] = $movie['link'];
 $node->field_trailer['de'][0]['value'] = $movie['link'];
 $node->field_trailer['en'][0]['value'] = $movie['link'];

```

And after `node_save($node);` add

```
  node->translations->data['de']['entity_type'] = 'node';
  $node->translations->data['de']['entity_id'] = $node->nid;
  $node->translations->data['de']['language'] = 'de';
  $node->translations->data['de']['source'] = 'fr';
  $node->translations->data['de']['uid'] = $node->uid;
  $node->translations->data['de']['status'] = $node->status;
  $node->translations->data['de']['translate'] = 0;
  $node->translations->data['de']['created'] = $node->created;
  $node->translations->data['de']['changed'] = $node->changed;

```

For each language and the `node_save($node)` again.

# Answer
> 2 votes
Here is other solution. Perhaps you already have $node object (from node\_load or menu\_get\_object etc), and $lang - langcode to translate:

```
$handler  = entity_translation_get_handler('node', $node);
$translations = $handler->getTranslations();
if ($lang !== $node->language && !isset($translations->data[$lang])) {
  $translation_node = $node;
  $values = array();
  // Change translatable fields languages to trasnlation language.
  foreach(field_info_instances('node', $node->type) as $instance) {
    $field_name = $instance['field_name'];
    $field = field_info_field($field_name);
    if ($field['translatable'] && isset($translation_node->$field_name)) {
      foreach ($translation_node->$field_name as $lang_key => $field) {
        if ($lang_key == $node->language) {
          $values[$field_name][$lang] = $field;
        }
      }
    }
  }
  // Create a translation.
  $translation = array(
    'translate' => 0,
    'status' => 1,
    'language' => $lang,
    'source' => $node->language,
  );
  $handler->setTranslation($translation, $values);
  node_save($translation_node);
}

```

---
Tags: i18n-l10n
---


# Question
Title: What would the snippet(s) look like for multiple google analytics tracking IDs?
I'd like to include 3 tracking IDs on all pages. I'm using the Google Analytics module and there are three fields in the custom javascript code under advanced settings.

# Answer
> 1 votes
Using Universal Google Analytics, in the Google Analytics Module 7.x-2.0 @ /admin/config/system/googleanalytics \> ADVANCED SETTINGS \> CUSTOM JAVASCRIPT CODE \> Code snippet (after)

```
ga('create', 'UA-XXXXXXXX-Y', 'auto', {'name': 'foo'});
ga(function(foo) {
  foo.send('pageview');
});
ga('create', 'UA-XXXXXXXX-Y', 'auto', {'name': 'bar'});
ga(function(bar) {
  bar.send('pageview');
});

```

# Answer
> 0 votes
If you want more than one person to have access to the google analytics property, the easiest way would eb to invite them to the property (within analytics you can add new users).

If you really need more than one trackingcode within the site add in the field *Code snippet (before)*:

```
ga('create', 'UA-12345-6', 'auto', {'name': 'newTracker'});

```

and in the field *Code snippet (after)*:

```
ga('newTracker.send', 'pageview');

```

But again, that only makes sense, when you restict each property to certain portion of the site.

---
Tags: google-analytics
---


# Question
Title: Drupal commerce: product field based in calculation of other fields
The commerce product has the field: **Price**

Then I added two more field: **Quantity** and **Price per Unit**

I need the field **Price per Unit** to take the calculated value from this:

```
Price per Unit = Price/Quantity

```

How I get this?

# Answer
> 1 votes
Commerce out of the box has a quantity field and does by default a 'price-per-unit'. Watch this tutorial to give you an idea of how it works without any customizations.

https://www.youtube.com/watch?v=3KEJcieG4jI

---
Tags: entities, commerce
---


# Question
Title: Do I need to use drupal_mail after the hook_form_contact_site_form_alter?
I have added on field in my site wide contact form through this code :

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

    // Add a phone number field to the contact form.
    $form['phone'] = array(
    '#type' => 'textfield',
    '#maxlength' => 20,
    '#title' => t('Your phone'),
    );

    // Define the order of the top level elements on the form (include those from contact_site_form().
    $order = array('name', 'mail', 'phone', 'subject', 'cid', 'message', 'copy', 'actions');

    // Order the elements by changing their #weight property.
    foreach($order as $key => $field) {
    $form[$field]['#weight'] = $key;
    }
    }

```

Now Do I need to add `drupal_mail` with phone number into it or **Drupal** will consider it automatically ? As I am new to drupal I don't know much about it.

# Answer
> 0 votes
You should use `hook_mail_alter()`.

`hook_mail_alter()` allows you to modify the email cleanly before it is sent. The Contact module passes the entire form state to `drupal_mail()`, so you have access to it in this alter hook via the `params` key.

A quick example. I haven't tested it:

```
function my_module_mail_alter(&$message) {
  if ($message['id'] == 'contact_page_mail') {
    $phone = $message['params']['phone'];

    $message['body'][] = "Phone number: " . check_plain($phone);
  }
}

```

Let me know if that works.

# Answer
> 0 votes
I think what you are looking for is already answered here

Also if you are looking for basic tutorial you can check below links

http://www.blog.yamandi.com/how-use-drupalmail-function-tutorial

http://www.chrisfree.me/2010/01/override-drupal-contact-form

http://www.panda-os.com/2013/02/drupal-email-system/#.VD5-TPmSxws

And If you want to theme the outgoing mails with the help of custom templates, you should use the HTML Mail module.

> Lets you theme your messages the same way you theme the rest of your website.

It works well with other modules, like Print, Mail mime, etc.

You have to install the Mail System module in order to use HTML mail.

---
Tags: 7, emails
---


# Question
Title: Autopublish content from drupal to wordpress
My question is that i am having a drupal blog and wordpress on different different domains. I am looking for a module so that whenever i publish some content in drupal it should also published in wordpress.

# Answer
> 2 votes
This is more of a Wordpress question, but on drupal side you could expose the new content with a feed or JSON View and after that use some WP module to import the data.

**Edit** And here's something that you can use on WP side to autopost from a feed: https://wordpress.org/plugins/wp-rss-multi-importer/

---
Tags: nodes
---


# Question
Title: Drupal 7 Multiple Display Types Different Options?
I have one view with two display types (two blocks), for one of them I want to limit it to 1 result, for the other I want it to show all the results.

How can I do this? I can't seem to figure out how to allow one display type to override the other. They keep to copy eachother.

# Answer
With the Panels module, you can build pages using views blocks. When you select a block you are looking for to include, you can alter on the fly the paging mecanism. So for the first one : only 1 row, and for the second one : all rows ...

---

Alternatively setting the paging parameter for a specific block is done into a popin in the Views backoffice. On left top corner of this popin you have a select box which allow you to select "This block (override)". Doing this, will setup different parameters for only this block. All parameters in views can be setup like this : global or override.
> 0 votes

# Answer
You can have two blocks of the same view with different output.

On Block one, go to the section where you choose the output. Make sure you select overide this block/view at the top left corner. Save your changes. Do the same thing on your second block. This was you will leave your Master set up intact, and over ide the individual blocks. It sounds like you are overwriting the master each time you save.
> 0 votes

---
Tags: 7, views
---


# Question
Title: Relationships between content types and views
I am new to drupal, but have decent knowledge of WordPress & PHP. I am currently building a drupal site where I need to link two content types together and display them on the front end accordingly.

I have one content type called `Vehicle Range`, which contains a list of Vehicle ranged `(e.g. BMW 1 Series, BMW 3 Series)`

I have another content type called `Vehicle Models`, which lists the vehicle models `(e.g. 1 Series 118i, 1 Series 118d, 3 Series 335d).`

What I want to achieve is a menu that lists all of the Vehicle Ranges with the relevant models as dropdowns.

Example:

1 Series 3 Series

118i 335d

118d

I have created a reference between the two content types using the Entity Reference Module. The reference field is attached to the Range content type so that you tick all of the relevant models that belong to that range.

I am trying to create a view using this relationship, but my lack of experience with Drupal and views is causing me to fail. Whilst creating a view, the closest I can get is either a list of all of the models, displaying all of their fields, but they are not 'categorised' under the relevant range, or a list of the ranges with the model labels, which is close, but I need the full content / all of the fields attached to each model rather than just the label.

How can I make a view that will give me the output I need as shown in the example above using the two content types and reference field? Any help would be massively appreciated as I'm brand new to Drupal!

# Answer
> 0 votes
Resolved. Incase anybody want's to know, I set up a 'Referenced Entity' type relationship and took the following steps:

Under format, I selected 'HTML List' and under format settings, I set 'Grouping field Nr.1' to content:title and ticked the box that say's 'Use rendered output to group rows'.

Under show, i selected Fields, and added the fields from my model content type, and it worked perfectly.

# Answer
> 1 votes
I don't think you need to create content types to do what you need.

You have a content type of car and then I would use taxonomy to select the series and models. You can add fields/images etc to taxonomy and pull those into your view if you need to.

# Answer
> 0 votes
To do a such thing you should change elements in the "Format" section of you view like this : \- Format : Unformatted list (this will display each element into a DIV) \- Show : Rendered entity +

Doing this will display each result as a node based on view\_mode. In the "Content Type \> Manage Display" you should enable a new view\_mode or use "Teaser" which is usually enabled. Like this you'll be able to select each field + formatted you want to display.

---
Tags: entities, views
---


# Question
Title: Is there a way to call "access callback" with parameters?
I have:

```
function hook_menu()  {
    $items = array();
    $items['experiment-2'] = array(
        'title' => 'Experiment 2',
        'page callback' => 'drupal_get_form',
        'page arguments' => array('experiment_form'),
        'access callback' => 'user_can_access_experiment',
        'file' => 'includes/experiment-2.form.inc',
        'type' => MENU_NORMAL_ITEM,
      );

    ...

```

This will call:

```
function user_can_access_experiment() { }

```

But I want to be able to call it something like:

```
function user_can_access_experiment($experimentID) { }

```

And then somehow let `hook_menu` call the function as `user_can_access_experiment(1)` or `user_can_access_experiment(2)` or whatever.

Is this possible?

# Answer
> 5 votes
If I understand your query right the `access callback` needs to accept a parameter based on which it decides whether or not to return TRUE for the menu path. This should be achievable using `access arguments`, like

`'access arguments' => array($experimentID),`

quoting from the hook\_menu API documentation

> "access arguments": An array of arguments to pass to the access callback function, with path component substitution as described above. If the access callback is inherited (see above), the access arguments will be inherited with it, unless overridden in the child menu item.

The passed argument, in your case the `$experimentID` could be either from any custom computation like a value from the user object or even a part of your query parameters.

# Answer
> 1 votes
You should use "access arguments" to indicate it. This array key is waiting for an array.

cf : https://api.drupal.org/api/drupal/modules%21system%21system.api.php/function/hook\_menu/7

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

This example may helps you:

```
function hook_menu()  {
    $items = array();
    $items['experiment-2'] = array(
        'title' => 'Experiment 2',
        'page callback' => 'drupal_get_form',
        'page arguments' => array('experiment_form'),
        'access callback' => 'user_has_role',
        'access arguments' => array(array('Role 1', 'Role 2')),
        'file' => 'includes/experiment-2.form.inc',
        'type' => MENU_NORMAL_ITEM,
      );

    return $items;
}

function user_has_role($roles) {
    if (user_is_logged_in()) {
        global $user;
        if (in_array('administrator', $user->roles)) {
            return TRUE;
        }
        foreach ($roles as $role) {
            if (in_array($role, $user->roles)) {
                return TRUE;
            }
        }
    }
    else {
        return FALSE;
    }
}

```

---
Tags: routes
---


# Question
Title: Save language preference for future visit
I would like to achieve this:When a user selects a language in a multilingual site,when he visits this site into future,the site remembers its language previous selection and shows this language for the user. Is there a module for this or I need to write something with cookies? thanks

# Answer
> 1 votes
Actually there are two modules, Language Cookie and Locale Cookie. Both work about the same, but both have problems if you are using Varnish as a cache. There was some work on Language Cookie done to fix this, but I haven't been able to get it working with Varnish yet. If you're not working with Varnish, though, it works great.

---
Tags: i18n-l10n
---


# Question
Title: How to skip "Checked available update data for" all modules when I just want to update core or a specific module?
I'm upgrading a lot of my Drupal sites to 7.32. Unfortunately it takes a lot of time for each site because of some update check that I don't need.

On How to upgrade only core with drush? I learned I can use `drush up drupal` to only upgrade core. But unfortunately `drush` is still checking a lot of statuses, which takes a long time for every site:

```
Checking available update data ...
Checked available update data for Administration menu.
Checked available update data for Admin VBO Views.
Checked available update data for Advanced CSS/JS Aggregation.
Checked available update data for Block.
...

```

How can I skip this? I just want drush to fetch 7.32, check if the site is still functional and head to the next site.

# Answer
> 0 votes
Drush calls Drupal code to update the list of available releases, so regrettably there is no way to update the release info for just some subset of available projects.

---
Tags: drush, upgrading, security
---


title: All taxonomy terms of a specific depth

text:
# Question
Title: All taxonomy terms of a specific depth
On a Drupal 7 site I have a view with a bunch of exposed filters (using Views + BEF) for taxonomies. Some of these taxonomies have terms with different depths. Is there a way I can dynamically show only the values of a specific depth? For example, one filter would have the depth 0 terms, another would have just the depth 1 terms.

I know that I can use "Limit list to selected items" and manually do it, but that feels clunky and requires more maintenance as terms are added. I also tried playing around with simple hierarchical select without success.

Is there some way of achieving this without manually adding terms to the exposed filter option list?

# Answer
In the Views filters, there are 2 default filters for taxonomy. You want to use *Content: Has taxonomy terms (with depth)*, then select the vocabulary and depth of the terms to include.
> 1 votes

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


# Question
Title: Modal Popup for Vimeo when clicking on Vimeo Thumbnail Link
I have a basic link field and in this link field I just have a vimeo/youtube link. What are some of the available modules that can give the functionality of:

* Render the display of the video link with a thumbnail of the video on teaser/full display
* When clicking on the video link, a modal popup overlay will show with the video.
* The popup can also be responsive. (i guess this can be done manually via css)

# Answer
You want to have a look at the video\_embed\_field module and the colorbox module. They combine well to achieve what you want.

Create a contenttype with the new field provided by video\_embed\_field. Then for the thumbs you could make a view and select the video\_embed\_field. Go into settings of this video field and in the selectbox labeled Formatting tool, select thumbnails/w colorbox This should give you a nice grid with thumbnails all linking to a colorbox overlay with player embedded.
> 1 votes

---
Tags: 7, files, javascript
---


# Question
Title: Rules token one-time-login-url is showing up empty
I have a rule that, after submitting a webform, a user gets created and then sends two emails to that user. One saying their form data is being looked at by someone for review before they get a certain role, and another that gives them the one-time login url. The problem is the that, while the rule works and both emails get sent, the login url is not displayed in the second email.

```
{ "rules_application_submission_affiliate" : {
    "LABEL" : "Application submission: Affiliate",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "webform_rules", "php" ],
    "ON" : { "webform_rules_submit" : [] },
    "IF" : [
      { "webform_has_id" : {
          "form_id" : "[form-id:value]",
          "selected_webform" : { "value" : { "webform-client-form-101" : "webform-client-form-101" } }
        }
      }
    ],
    "DO" : [
      { "entity_create" : {
          "USING" : {
            "type" : "user",
            "param_name" : "\u003C?php echo $data[\u0027components\u0027][\u0027your_username\u0027][\u0027value\u0027][0]; ?\u003E",
            "param_mail" : "\u003C?php echo $data[\u0027components\u0027][\u0027your_e_mail\u0027][\u0027value\u0027][0]; ?\u003E"
          },
          "PROVIDE" : { "entity_created" : { "new_user" : "New user" } }
        }
      },
      { "entity_save" : { "data" : [ "new-user" ] } },
      { "user_unblock" : { "account" : [ "new-user" ] } },
      { "mail" : {
          "to" : "[data:your_e_mail-value]",
          "subject" : "Thank you for your application!",
          "message" : "Your application is being processed.  You will receive another email when your account is ready for activation.",
          "language" : [ "" ]
        }
      },
      { "mail" : {
          "to" : "[new-user:mail]",
          "subject" : "Your account is ready!",
          "message" : "You may activate your account by going to this link to set your password:\r\n[new-user:one-time-login-url]",
          "language" : [ "" ]
        }
      }
    ]
  }
}

```

# Answer
> 0 votes
The problem was on the "save entity" action, I had to force it to save by checking "force" on the action, because the entity would only get saved after the other actions had been applied.

---
Tags: 7, rules, tokens, actions
---


# Question
Title: Updating all existing user's custom field
I am fairly new to Drupal development and ran into a problem when trying to create a cron to update the value on a custom field for all the existing users.

Here is the code, when I click run cron it does nothing. I do no see my value in the custom field I created on any of the users.

```
/**
* Implementation of hook_cron().
*/
function testingdev_cron()
{
  $users = entity_load('user');
  foreach ($users as $user)
  {
    $user->field_my_field = 'test';
    user_save($user);
  }
}

```

# Answer
> 2 votes
Found out why it was not working (Which also explains why none of my debugging was displaying.) I had to skip over the the user with UID of 0 and modify how I set the field value or else the user\_save function would break the code (For anyone that is interested.)

```
/**
* Implementation of hook_cron().
*/
function testingdev_cron()
{
  $users = entity_load('user');
  foreach ($users as $user)
  {
    if($user->uid == 0)
    {
      continue;
    }

    $edit = array(
      'field_my_field' => array(
        'und' => array(
          0 => array(
            'value' => 'test'
            )
          )
        )
      );
    user_save($user, $edit);
  }
}

```

---
Tags: cron
---


# Question
Title: How to push form values to database in Drupal
I am building a drupal site in which I would like the admin to have the ability to input goals into a table on the drupal database that can then be output to other users to be completed.

The form for the input and the table get created, however the values are not added into the table when submit is pressed and I'm not sure why.

I have the following code from the module that I am hooking into my site. I think the problem occurs at the top where I am creating the fields, or at the bottom when I submit the values. I'm really not sure.

Can anyone tell me where I went wrong and how to fix it?

```
function achievementList_init() {
if(!(db_table_exists('achievements'))) {
    $achvmnt_list_schema = array(
        'description' => 'Achievement Fields',
        'fields' => array (
            'achvmntID' => array('type' => 'int', 'unsigned' => TRUE, 'AUTO_INCREMENT' => TRUE, 'not null' => TRUE),

            'achvmntName' => array('type' => 'varchar', 'length' => 256, 'not null' => TRUE, 'default' => ''),

            'achvmntDesc' => array('type' => 'varchar', 'length' => 256, 'not null' => TRUE, 'default' => ''),

            'achvmntPts' => array('type' => 'int', 'unsigned' => TRUE, 'not null' => TRUE),

    ));
    db_create_table('achievements', $achvmnt_list_schema);
}
}

function achievementList_menu($form, &$form_state) {
$items = array();
$items['achievementList/addAchievement'] = array(
    'title' => 'Achievement Input',
    'description' => 'Input Achievement info to add achievement to database',
    'page callback' =>'drupal_get_form',
    'page arguments' => array('achievementList_form'),
    'access callback' => TRUE
);
return $items;
}

function achievementList_form($form, &$form_state) {
$form['name'] = array (
    '#type' => 'textfield',
    '#title' => 'Achievement Name',
    '#size' => '20',
    '#maxlength' => '20',
    '#required' => TRUE
);
$form['description'] = array(
    '#type' => 'textfield',
    '#title' => 'Achievement Description',
    '#size' => 50,
    '#maxLength' => 400,
    '#required' => TRUE

);
$form['points'] = array(
    '#type' => 'textfield',
    '#title' => 'Point Award',
    '#size' => '20',
    '#maxlength' => '20',
    '#required' => TRUE
);
$form['add_button'] = array(
    '#type' => 'submit',
    '#value' => t('Add Achievement')
);
return $form;
    }

function achievementList_validate($form, &$form_state) {
$name = $form_state['values']['name'];

if($form_state['values']['name'] = '') {
    form_set_error('name', t('Achievement must have a name!'));
}
if($form_state['values']['description'] = '') {
    form_set_error('name', t('Please describe the achievement!'));
}
if(!($form_state['values']['points'] > 0)) {
    form_set_error('name', t('Achievement must be worth points!'));
}
}

function achievementList_submit($form, &$form_state) {
db_insert('achievements')
->fields(array(
'achvmntName' => $form_state['values']['name'],
'achvmntDesc' => $form_state['values']['description'],
'achvmntPts' => $form_state['values']['points'],
))
->execute();
}

```

# Answer
You're not far off, a couple of things:

* Creating a table like that in an init hook is definitely not recommended; Drupal provides `hook_schema()` so you can describe tables to the system. Uninstall and install your module again after implementing it and you'll see the table appear.
* The reason your insert is failing is because you have a `NOT NULL` integer field which you're not providing (`achvmntID`). Drupal has the `serial` field type rather than an `AUTO_INCREMENT` key to get a serial field:

```
'achvmntID' => array(
  'type' => 'serial',
  'unsigned' => TRUE,
  'not null' => TRUE,
),

```
> 3 votes

# Answer
You need to make some changes like

It is better to create hook\_schema as @Clive mention above.

For this recommended to create achievementList.install file in module

```
 <?php
/**
 * Implementation of hook_install().
 */
function achievementList_install() {
    //drupal_install_schema('achievementList');
    //for d6 uncomment above line
}

/**
 * Implementation of hook_uninstall().
 */
function achievementList_uninstall() {
    //drupal_uninstall_schema('achievementList');
    //for d6 uncomment above line
}

function achievementList_schema() {
    $schema['achievements'] = array(
    'description' => t('Achievement Fields'),
        'fields' => array(
                'achvmntID' => array(
                    'type' => 'serial',
                    'unsigned' => TRUE,
                    'not null' => TRUE
                ),
                'achvmntName' => array(
                    'type' => 'varchar',
                    'length' => '256',
                    'not null' => TRUE,
                    'default' => ''
                ),
                'achvmntDesc' => array(
                    'type' => 'varchar',
                    'length' => '256',
                    'not null' => TRUE,
                    'default' => ''
                ),
                'achvmntPts' => array(
                    'type' => 'int',
                    'not null' => TRUE,
                    'size' => 'normal',
                    'auto increment' => TRUE,
                ),
            ),
            'primary key' => array('achvmntID'),
        );
    return $schema;
}

```

function achievementList\_menu($form, &$form\_state) does not contain parameter.

Use function achievementList\_menu()

function achievementList\_validate($form, &$form\_state) here "form" missing

use function achievementList\_form\_validate()

function achievementList\_submit($form, &$form\_state) here "form" missing

use function achievementList\_form\_form()

.module file

```
<?php
function achievementList_menu() {
$items = array();
$items['achievementList/addAchievement'] = array(
    'title' => 'Achievement Input',
    'description' => 'Input Achievement info to add achievement to database',
    'page callback' =>'drupal_get_form',
    'page arguments' => array('achievementList_form'),
    'access callback' => TRUE
);
return $items;
}

function achievementList_form($form, &$form_state) {
$form['name'] = array (
    '#type' => 'textfield',
    '#title' => 'Achievement Name',
    '#size' => '20',
    '#maxlength' => '20',
    '#required' => TRUE
);
$form['description'] = array(
    '#type' => 'textfield',
    '#title' => 'Achievement Description',
    '#size' => 50,
    '#maxLength' => 400,
    '#required' => TRUE

);
$form['points'] = array(
    '#type' => 'textfield',
    '#title' => 'Point Award',
    '#size' => '20',
    '#maxlength' => '20',
    '#required' => TRUE
);
$form['add_button'] = array(
    '#type' => 'submit',
    '#value' => t('Add Achievement')
);
return $form;
    }

function achievementList_form_validate($form, &$form_state) {
$name = $form_state['values']['name'];

if($form_state['values']['name'] = '') {
    form_set_error('name', t('Achievement must have a name!'));
}
if($form_state['values']['description'] = '') {
    form_set_error('name', t('Please describe the achievement!'));
}
if(!($form_state['values']['points'] > 0)) {
    form_set_error('name', t('Achievement must be worth points!'));
}
}

function achievementList_form_submit($form, &$form_state) {
//print_r($form_state);
//die();
db_insert('achievements')
->fields(array(
'achvmntName' => $form_state['values']['name'],
'achvmntDesc' => $form_state['values']['description'],
'achvmntPts' => $form_state['values']['points'],
))
->execute();
}

```
> 1 votes

---
Tags: 7, database
---


title: Mb Mini Player for drupal7

text:
# Question
Title: Mb Mini Player for drupal7
Is there is any modle avaibale for mini player like

```
http://pupunzi.open-lab.com/mb-jquery-components/jquery-mb-miniaudioplayer/

```

I want to implement same player on my website

# Answer
These are the players :

1. MP3 Player
2. AudioField
3. jPlayer \- I think this is a player that you want.
> 0 votes

---
Tags: 7
---


# Question
Title: How to navigate in a view result from node full view
I have a view which displays a list of nodes. When I click a node link from the view to see node's full view, I want in this node full view to add "back to list", "previous" and "next" links to let user navigate in view results.

I think to add view name and exposed filters selected values as parameters to node links in the view, so I can compute navigation links in node full view. First question : isn't it an easier, cleaner, or more drupal compliant way to achieve this ?

If not : is there a better way to modify the links that in node teaser tlp.php ? I guess I could use hook\_node\_view\_alter (I'm D7), but wouldn't it cause potential performance issue (I mean it need to test if I'm in my particular view for every node everywhere in the site, though it's a very specific feature)

Thanks for your help,

Philip

# Answer
> 1 votes
Check out Views Navigation module. This seems to be a good fit for your requirement.

> This module adds next and previous links on content pages when accessed from a view. It is intended for dynamic and/or paged view results, where the result set changes according to exposed filters, current user access rights,...

Also here is the link to the comparison other node based navigation modules.

---
Tags: views
---


# Question
Title: Email not to admin, When user create an account
I want to send an email to another email, rather than admin Email, When user create an account

Can Anybody tell me how to do that . I am using drupal 7

Thanks

# Answer
> 0 votes
1. Download, install & Enable Rules module.
2. Goto

Admin -\> Configuration -\> Rules

-\> Click on **Component** tab -\> Add Component

-\> Select **Action set** -\> In **Component Plugin** -\>

Name: Send email to inactive user

Datatype: User,

Label:active\_user,

Machine\_name: active\_user

Usage: Parameter

-\> Add action -\> data selector: active\_user

-\> Enter the subject & body & save

-\> Go back & Add new rule

-\> React on Event : **After Saving a new new user a/c**

-\> **Add Action** -\> Select **Schedule Component Evaluation**

-\> **Value** : Choose your component

-\> Identifier : \[account:uid\]

-\> Data selector : account

If you have any doubt then you may **CLICK**

---
Tags: 7
---


# Question
Title: How to apply a function to the title of a teaser made with display suite?
I'm pretty new to functions and PHP (so please forgive my terminology) but here's what I would like to do:

**Background**

My homepage contains a view displaying various content type teasers. I would like to truncate the title of an article teaser (a custom teaser created with display suite) to 48 characters.

**Action taken so far**

If I add the following code to my subtheme's template.php file, nothing happens:

```
function THEMENAME_preprocess_node(&$variables) {
     if ($variables['type'] == 'article' && $variables['view_mode'] == 'teaser') {
     $variables['title'] = truncate_utf8($variables['title'], 48, TRUE, TRUE);
   }
}

```

However, if I add this other variation of the code (i.e. applying to all teasers, not just article teasers) the titles of some teasers are indeed shortened:

```
function eunic_global_preprocess_node(&$variables) {
if ($variables['teaser']) {
    $variables['title'] = truncate_utf8($variables['title'], 48, TRUE, TRUE);
   }
}

```

**Conclusion & Question**

I think the problem is to do with the fact that some teasers have been created using the Display Suite module while others use more or less the default teaser.

So my question is - how do I 'refer' to the title of a teaser made with display suite in order to apply the truncate\_utf8 function? Fingers crossed there's a way to do it...

Thanks A~

# Answer
If you added the title as a field in Display Suite, I'd recommend you look at the field functions of Display Suite.

You may use a Code field, but I'd discourage that.

Rather remove the title from the display, then add the truncated title as a new field in the preprocess function, ie:

```
$variables['new_title'] = truncate_utf8($variables['title'], 48, TRUE, TRUE);

```

Then add a new preprocess field to display suite, using the exact same name as the new field, ie:

```
new_title

```

You can then place this new field in Display Suite.
> 0 votes

---
Tags: theming, display-suite
---


# Question
Title: Error in simplenews when send the node more than one
I am using module simplenews and when I send node more than one. Its show me this:-

> This newsletter has been sent.

Why and how can I solve this and don't want to show me again.

# Answer
> 0 votes
This is by design. Why would you want to send the *same* newsletter twice? If you want to test your newsletter, choose the option "Send test newsletter". This can be done multiple times before sending out the newsletter to all subscribers.

EDIT: I just saw your other question (you should maybe combine both) and if you want to send a newsletter containing a View on a regular basis, see my answer to the other question or my documentation on drupal.org.

---
Tags: emails
---