# Question
Title: Why does "Read more" link not show up on view, but "Add new comment" does?
As said in the title, I'm having a problem with the "read more" link. I made my own view (wie-zijn-we-pagina) and content type (wie-zijn-we-) and am trying to add a custom "read more" and "add new comment" link to it. The code that I'm using gives me the correct custom "Add new comment" link but the "Read more" link doesn't work. At first it didnt even show up.

My code:

```
function ap_hogeschool_theme_preprocess_node(&$variables){
$variables['content']['links']['comment']['#links']['comment-comments'] = FALSE;
if($variables['view'] && $variables['type'] == 'wie_zijn_we_')
    {
    $variables['content']['links']['node']['#links']['node-readmore']['title'] ='<div class="custom-add-read-more"> </div>';
    $variables['content']['links']['comment']['#links']['node-readmore']['html'] = TRUE;
    $variables['content']['links']['comment']['#links']['comment-add']['title'] = '<div class="custom-add-comment"> </div>';
    $variables['content']['links']['comment']['#links']['comment-add']['html'] = TRUE;

}
}

```

I don't know if the part where i call the view and content type is correct... I'm still a new drupal user.

An image of what i have:

An image of what in need to have:

Could somebady please help me along?

# Answer
You have a mistake on your code. Instead of `$variables['content']['links']['node']` you wrote `$variables['content']['links']['comment']`.

Corrected code:

```
function ap_hogeschool_theme_preprocess_node(&$variables){

  $variables['content']['links']['comment']['#links']['comment-comments'] = FALSE;

  if( $variables['type'] == 'wie_zijn_we_' && $variables['view_mode'] == 'teaser' ){

     $variables['content']['links']['node']['#links']['node-readmore']['title'] ='<div class="custom-add-read-more"> </div>';
     // Mistake was in this line:
     $variables['content']['links']['node']['#links']['node-readmore']['html'] = TRUE;
     $variables['content']['links']['comment']['#links']['comment-add']['title'] = '<div class="custom-add-comment"> </div>';
     $variables['content']['links']['comment']['#links']['comment-add']['html'] = TRUE;

   }
  }

```
> 1 votes

---
Tags: 7, comments
---


title: Flowplayer controlbar D7

text:
# Question
Title: Flowplayer controlbar D7
I've been trying to hide the controlbar when the canvas is being shown (the video has't been started up) and show a controlbar once the video has been started up. (see below) Thanks in advance :)

* here is how its now by default
* here how I want it to looks like...

# Answer
As the Flowplayer API states the basic configuration is like this

```
$f("player1", "flowplayer.swf", {
    clip: {
        url: 'KimAronson-TwentySeconds59483.flv',
        autoPlay: true,
        autoBuffering: true
    },
    plugins: {
        controls: null
    },
    onLoad: function(){
        alert("player loaded");
    }
});

```

Note the `controls: null` section this will allow you to render the player without controls.

Read Flash plugins section for more detailed information.
> 0 votes

---
Tags: files
---


# Question
Title: 'Unlinking' a link for users without permission
I have a link which goes to a page created by a custom module. The module implements hook\_permission and hook\_menu so that when a user without permission clicks the link they get sent to the page and are shown the 'You are not authorized to access this page' message.

Is there way I can 'unlink'/'de-anchor' the link, so that the link displays as just unclickable black text to those without permission?

Thanks

# Answer
Here's what I've come up with myself. It works fine:

```
if(user_access('edit record')) {
    $link = l(t('Edit this record'), 'edit-record/' . $nid);
} else {
    $link = t('Edit this record');
}

```

If you know of a 'cleaner' more 'correct' way. Please let me know. Thanks
> 0 votes

---
Tags: users
---


# Question
Title: How Can I change the fields order without using CCK
I want to change the order of the fields in each node. I know that I can use CCK but I would like to do this in hook\_node\_load

Is it possible?

Thx :)

# Answer
> 0 votes
In my views cck will always overwrite the weight you assign programmatically, best way should be arranging the cck fields in order you want. If you want to change order on the fly using javascript can be an option too,but not sure if it is good option for example

```
jQuery('.field-name-field-test-taxonomy').insertAfter('.field-name-field-simple-text-field');

```

where ".field-name-field-test-taxonomy" and ".field-name-field-simple-text-field" are the wrapper div for cck fields respectively.with out the above js code the default taxonomy field was coming before the simple-text field but with we simply change the order. hope it helps.

---
Tags: hooks, entities, nodes
---


title: Scheduling review of content

text:
# Question
Title: Scheduling review of content
I have a content type that includes a date field called expires. I'd like to set up some way to monitor all nodes of this content type and if the current date is close to the expires field value, send an email. I checked the rules module using the built in scheduler, but I didn't see a way to check a specific node, or a series of nodes.

# Answer
Use `hook_cron()` to check the value of that field when cron runs and fire off an email with `drupal_mail_system()` if the value meets your criteria.
> 1 votes

---
Tags: rules
---


# Question
Title: Share single CUSTOM function across multiple themes
I have some repetitive code that I'd like to share across two separate themes. Is there a best practice for something like this?

I know I can simply create an include file in the sites directory and do it that way I just wasn't sure if there was another way to do it that would be cleaner?

Thanks in advance!!

# Answer
Two options that I can think of:

1. Make the themes sub-themes of a parent theme and put the function in the parent theme's template.php file. (I like this solution because other assets (css, js, templates) can easily be shared as well. But unless the function has to do with presentation, it probably doesn't semantically belong in a theme at all.)
2. Create a simple module that contains the function.
> 2 votes

---
Tags: theming
---


# Question
Title: If not hook_init(), what can be used for cached pages?
I created a module to keep query\_string laden links from a client site active (per client's request, background question here).

This code works wonderfully when I'm logged in (as user 1); however, I have later found that `hook_init()` does not run on cached pages.

Should I place this logic into another hook? Should I take a different approach to intercepting and mapping these legacy links?

```
<?php
/**
 * Extends hook_init()
 *
 * Intercepts vidID or PID and forwards to the page's proper Drupal node.
 *
 */

function module_init() {

    if (!menu_get_item($_GET['q'])) {

        $pid    = isset($_GET['PID']) ? $_GET['PID'] : FALSE;
        $vidID  = isset($_GET['vidID']) ? $_GET['vidID'] : FALSE;

        if ($pid) {
            // handler code
        }
        elseif ($vidID) {
            // handler code
        }
    }
}

```

# Answer
> 0 votes
As it turns out, I did take a different approach. In trying to make use of other query string variables, I found it easier to use apache's mod\_rewrite. That is, I used Apache's mod\_rewrite to turn this `/profile/?id=1234` into this `/provile/id/1234`.

In turn, in Drupal, we added aliases of `profile/id/1234` to the appropriate user profile.

All turned out well. It's a much more managable solution. Old URLs are in tact. Result: everyone's happy.

.htaccess

```
# Rewrite old URLS
RewriteCond %{QUERY_STRING} PID=([0-9a-zA-Z]*)
RewriteRule ^faculty/ /faculty/%1/? [R=301,L]

RewriteCond %{QUERY_STRING} vidID=([0-9]*)
RewriteRule ^videos/ /video/id/%1/? [R=301,L]

```

# Answer
> 4 votes
I think you are asking the wrong question.

If a page is cached, it means that it got generated and cached at some point. At this point, your code in `module_init()` did run. If your code generated a redirect (via `drupal_goto()`), this redirect will get cached.

There should not be anything wrong with this scenario, so maybe you should just clear the cache once?

---
Tags: caching, hooks
---


# Question
Title: Creating programatically a node that has a programtically created image field that should stay empty
I'm dealing building several modules that should cope with automatic creation of content synchronized with external sources. The whole process is automatized, e.g. everything had been created programatically. My content type has and image field attached to it. When appempting to create a node without defining what this image field should contain (and it should stay empty), I fall with exception:

```
    PDOException: SQLSTATE[23000]: Integrity constraint violation: 1048
    Column 'fid' cannot be null: INSERT INTO {file_usage} (fid, module, type, id, count)
    VALUES (:db_insert_placeholder_0, :db_insert_placeholder_1, :db_insert_placeholder_2, :db_insert_placeholder_3, :db_insert_placeholder_4);
    Array ( [:db_insert_placeholder_0] => [:db_insert_placeholder_1] => file [:db_insert_placeholder_2] => node [:db_insert_placeholder_3] => 264 [:db_insert_placeholder_4] => 1 )
    in file_usage_add() (line 657 of /usr/local/drupal7/includes/file.inc).

```

When on hook\_node\_presave I'm adding an image to this field all works correctly, but I would like to leave this field empty, that may affect the rest of development process.

If I create the node type programatically but add the image field manually -- all works ok. I tried it, then printed the definition of this field using function `field_info_field()` and copied some values of there into my code, but it didn't help.

Here is my image field definition:

```
...

'field_member_photo' => array(
'label' => t('Member Photo'),
'field_name' => 'field_member_photo',
'type' => 'image',
'module' => 'image',
'active' => '1',
'locked' => '0',
'cardinality' => '1',
'deleted' => '0',
'widget' => 'image_image',
'entity_types' => array('node'),
'settings' => array('uri_scheme' => 'public', 'default_image' => 0,),
),

...

```

Would appreciate any thought about how to solve this problem.

# Answer
I think this is already been covered here some where but i'll answer this any way because creating fields manually is not something easy.

Let's start: 1. First thing - create the field through the UI 2. Export the fields with features. In the latest version of features, features devide the export to to diffrent things: file with all the fileds settings and a file with all the field instances. From the settings of the field that features create you need only the settings: cardinality, field name, module and settings. From the instance you will need the settings: label, required and the widget. You can save them to a function.

1. After you saved the settings you will need to use a couple of functions for next you will install your module or anything like this: field\_info\_field(), this function will let return you the settings of the field if he exists, if not you will need to create it with the function field\_create\_field() like this:

field\_create\_field($field\_config);

The argument you'll need to give her is the settings of the field you saved later. For attaching the field to an entity you'll need to use the function field\_create\_instance that get the instance settings you save with three more keys:

* field\_name - the name of the field
* bundle - node type, message type etc. etc,
* entity\_type - the entity type: node, comment, message etc. etc.

You can see here hot it's done:

```
// This is the instance settings you saved.
$instance;
$instance += array(
  'field_name' => $field_config['field_name'],
  'bundle' => 'article',
  'entity_type' => 'node',
);

field_create_instance($instance);

```

You can have a look in the module OG in the function og\_create\_field() and how he saved fields inside hook. This could very easy and other module you will wrote can be based on this if you have a very a lot of fields.
> 1 votes

---
Tags: nodes, entities, media
---


# Question
Title: How Do I Create a User Role that Can Only CRUD a Single Content-type?
OK, so I know how to create roles and messed around with the People-\>Permissions-\>Roles screen. My goal is to create a single user role that will have only one function -- to administer the calendar events for the client site.

The first thing I did was to create a view to act as the overview of the available content. I added in the Login Destinations module and set it to send the user directly to the Events content overview view.

I checked the following role permissions at the Node level as:

* Access the content overview page
* View published content
* View own unpublished content
* View content revisions
* Revert content revisions
* Delete content revisions

And at the content-type node itself:

* Calendar Event: Create new content
* Calendar Event: Edit own content
* Calendar Event: Edit any content
* Calendar Event: Delete own content
* Calendar Event: Delete any content

So, when I log in as my event administrating user, I am redirected to the overview page, as expected. But when I click on the link to the node, I get this:

"You are not authorized to access this page."

So, my question is two-fold. 1) Is there a better way (read: built-in) to implement the "overview" of the content that I'm not aware of? 2) Am I using the People-\>Permissions-\>Roles as designed? If not, what am I doing wrong?

Thanks in advance,

Scott.

# Answer
> 2 votes
The Permissions section is broken out across content types. You can create a new group, put that user into it, and give that group permission to CrUD one or more content types. Allow this user no other permission in any other content type (outside of calendar).

To overcome the 'overview' page problem, is **View published content** checked?

---
Tags: nodes, users
---


# Question
Title: Change the Order of Fields on Teaser node.tpl
Hello i am struggling here a bit to change the display of my node teasers. I was hoping to take the title and submitted part and put it on top of my body field to the right of my teaser image. Ive tried Panelizer (looks great but the image field stays there if there is an image or not), Entity View Modes (dont know if this is really what i need) and even tried what could be the best way just simply editting the node.tpl and changing the fields about.

I think i'll just go with the last way as i did almost have it but due to a lack of knowledge and trouble finding out more ive had to ask you guys for some help.

I think i need to add

```
    <?php if ($teaser): ?>
        something in here
        <?php endif; ?>

```

but either it just not working (soz ive been up 24hs and im at the end of the line i think. Just hoping for some help either before bed or for when i get up) or else i get 2 body texts and titles appearing. I was just wanting my image on the left then to the right my title nd submitted fields above the body text.

I hate folks that do this but im gonna give it a go as im too tired to think now im sorry. here is my node.tpl Even just a good suggestion of what to do would be great. even better would be reworked code and i wont learn anything at all but i have tried. Tried for the past 4 hours

```
    <article class="node-<?php print $node->nid; ?> <?php print $classes; ?> clearfix"<?   php print $attributes; ?>>

      <?php if ($title_prefix || $title_suffix || $display_submitted || $unpublished ||   !$page && $title): ?>
        <header>
          <?php print render($title_prefix); ?>
          <?php if (!$page && $title): ?>
            <h2<?php print $title_attributes; ?>><a href="<?php print $node_url; ?>"><?php print $title; ?></a></h2>
          <?php endif; ?>
          <?php print render($title_suffix); ?>

          <?php if ($display_submitted): ?>
            <p class="submitted">
              <?php print $user_picture; ?>
              <?php print $submitted; ?>
            </p>
          <?php endif; ?>

          <?php if ($unpublished): ?>
            <p class="unpublished"><?php print t('Unpublished'); ?></p>
          <?php endif; ?>
        </header>
      <?php endif; ?>

      <?php
        // We hide the comments and links now so that we can render them later.
        hide($content['comments']);
        hide($content['links']);
        print render($content);
      ?>

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

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

    </article><!-- /.node -->

```

Thanks in advanced. Ive got to the stage where even posting code on stackexchange is hard work for me :(

# Answer
**Example**

```
<?php if ($teaser): ?>
    <?php print render($content['YOUR_IMAGE_FIELD']); ?>
    <?php print render($title_prefix); ?>
        <?php if ($title): ?>
          <h2><?php print $title; ?></h2>
        <?php endif; ?>
    <?php print render($title_suffix); ?>
    <?php hide($content['YOUR_IMAGE_FIELD']); ?>
    <?php hide($content['links']); ?>
    <?php print render($content); ?>
    <?php print render($content['links']); ?>
<?php else: ?>
   //...show default view mode
<?php endif; ?>

```

Most of the fields are bundled together into the **$content** variable.

We can remove them from being output in the $content variable by using the **hide()** function just before we render it (see above).

We can then print the specific field anywhere we like in the template like. See above where weve put the image field.

To determine what fields you have to play with do a var\_dump($content) at the top of the template or even better use the **Devel** module to do this.
> 1 votes

# Answer
updated node.tpl

```
    <article class="node-<?php print $node->nid; ?> <?php print $classes; ?> clearfix"<?php print $attributes; ?>>

    <?php if ($teaser): ?>
        <?php print render($content['field_imageown']); ?>
        <?php print render($title_prefix); ?>
            <?php if ($title): ?>
              <h2><?php print $title; ?></h2>
            <?php endif; ?>
        <?php print render($title_suffix); ?>
        <?php hide($content['field_imageown']); ?>
        <?php print render($content); ?>
    <?php else: ?>

      <?php if ($title_prefix || $title_suffix || $display_submitted || $unpublished || !$page && $title): ?>
        <header>
          <?php print render($title_prefix); ?>
          <?php if (!$page && $title): ?>
            <h2<?php print $title_attributes; ?>><a href="<?php print $node_url; ?>"><?php print $title; ?></a></h2>
          <?php endif; ?>
          <?php print render($title_suffix); ?>

          <?php if ($display_submitted): ?>
            <p class="submitted">
              <?php print $user_picture; ?>
              <?php print $submitted; ?>
            </p>
          <?php endif; ?>

          <?php if ($unpublished): ?>
            <p class="unpublished"><?php print t('Unpublished'); ?></p>
          <?php endif; ?>
        </header>
      <?php endif; ?>

      <?php
    // We hide the comments and links now so that we can render them later.
    hide($content['comments']);
    hide($content['links']);
    print render($content);
  ?>

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

  <?php print render($content['comments']); ?>
<?php endif; ?>
</article><!-- /.node -->

```
> 0 votes

---
Tags: nodes
---


# Question
Title: How to theme nodes in views based on the author's role?
I have a view listing all recent blog posts that have been published on the website. These blog posts can be created either by *regular* authentified users or by staff members.

I need nodes published by staff members to be themed differentely to be highlighted.

# Answer
> 3 votes
Luckily, Views allows you to add custom row classes through its admin interface, so you can style your view rows according to any field in that row.

Here is what I'd do, in your case, to add a 'staff-author' or 'user-author' class to your view row, depending on who wrote the blog (I'm just assuming those are the roles associated with your two user groups - they may be something else ;-)). Once you've added such a class, you can add css in your custom theme to style those differently.

* Add a 'user' relationship to your blog view. Under the "**Advanced**" section of your view, add the following relationship: "**User: Content authored**". Now you'll be able to add fields from the node author to your view (even if you don't display them)
* Now you can add the 'User: Roles' field to your view - just make sure to select to use the User relationship you've added when configuring the field. You can check to not have it display too!

* Finally, now you can **edit your format settings** to fill in a custom css class, based on any field you choose (from the 'Replacement Pattern' options for your view). In your case, it would be \[rid-role\].

Now, inspect the html of your view using Firebug (or something similar), and your view rows should have the new css class filled in, depending on the role of the node author. Use that to style the entries differently!

---
Tags: views, theming, users
---


# Question
Title: Close the iframe after login with Shadowbox module
I have installed the Shadowbox module and I use it to show the login page in a pop-up iframe.

The problem is when I click on the sign-in form submit button the iframe still appears and the page refreshing inside the iframe is not the original page.

How can I close the iframe after login and make the page reload?

The Ajax error is the following:

> An AJAX HTTP error occurred.
> HTTP Result Code: 200
> Debugging information follows.
> Path: /arabdc/system/ajax
> StatusText: parser error
> ResponseText:
> parent.window.location.reload(true);\[ {"command":"settings","settings":{"basePath":"\u002Farabdc\u002F", "pathPrefix":"", "ajaxPageState":{"theme":"bartik", "theme\_token":"PQ\_SrF6skDNUXCQNOJJg54EPuosNo0QM5sX6fr2Sfko"}, "heartbeat\_language":"ar", "heartbeat\_poll\_url":"http:\u002F\u002Flocalhost:8888\u002Farabdc\u002Fheartbeat\u002Fjs\u002Fpoll", "shadowbox":{"animate":0, "animateFade":0, "animSequence":"wh", "auto\_enable\_all\_images":0, "auto\_gallery":0, "autoplayMovies":true, "continuous":0, "counterLimit":"10", "counterType":"default", "displayCounter":1, "displayNav":1, "enableKeys":1, "fadeDuration":"0.35", "handleOversize":"resize", "handleUnsupported":"link", "initialHeight":160, "initialWidth":320, "language":"ar", "modal":false, "overlayColor":"#000", "overlayOpacity":"0.85", "resizeDuration":"0.35", "showMovieControls":1, "slideshowDelay":"0", "viewportPadding":20, "useSizzle":0}, "custom\_search":{"form\_target":"\_self", "solr":0}}, "merge":true}, {"command":"invoke", "selector":null, "method":"myJavascriptFunction", "arguments":\[ \]}, {"command":"insert", "method":"prepend", "selector":"head", "data":"\u003Cstyle type=\u0022text\u002Fcss\u0022 media=\u0022all\u0022\u003E@import url(\u0022http:\u002F\u002Flocalhost:8888\u002Farabdc\u002Fsites\u002Fdefault\u002Ffiles\u002Ffontyourface\u002Ffont.css?mmj0o1\u0022);\u000A@import url(\u0022http:\u002F\u002Flocalhost:8888\u002Farabdc\u002Fsites\u002Fdefault\u002Ffiles\u002Ffontyourface\u002Flocal\_fonts\u002Fmyride-normal-normal\u002Fstylesheet.css?mmj0o1\u0022);\u003C\u002Fstyle\u003E\u000A", "settings":null} \]

# Answer
> 0 votes
Looks like a Closed \[Fixed\] bug in Issues for Shadowbox From the page here is a patch file.

shadowbox\_login-additional\_links-1488718-25.patch Or read the ISSUE alos check #6

# Answer
> 0 votes
The best way I came up with is; to make the login form use AJAX. So after a successful login the browser will fire a custom javascript function to close Shadowbox iframe window and reload the parent window.

Alter login form to support AJAX

```
/**
 * Implement hook_form_alter().
 */
function mymodule_form_alter(&$form, &$form_state, $form_id) {
  if($form_id == 'user_login') {

    $form['#prefix'] = '<div id="user-login-form-wrapper">';
    $form['#suffix'] = '</div>';

    $form['actions']['submit']['#ajax'] = array(
      'wrapper' => 'user-login-form-wrapper',
      'callback' => 'user_custom_login_ajax_callback'
    );
  }
}

function user_custom_login_ajax_callback(&$form, &$form_state) {
  // if invalid user info return form with error messages
  if(form_get_errors()) {
    return $form;
  }

  // invoke custom jQuery function to close Shadowbox and reload window
  $commands = array();
  $commands[] = ajax_command_invoke(NULL, 'myJavascriptFunction');

  return array('#type' => 'ajax', '#commands' => $commands);
}

```

Create a javascript file with your custom module or put it with your custom them and add the following code in it:

```
(function ($) {

  $.fn.myJavascriptFunction = function() {
    if($('#sb-nav-close', parent.document).length > 0) {
      // reload parent window
      reloadParentPage();
      // close Shadowbox
      $('#sb-nav-close', parent.document).trigger('click');
    }
  };

  // to support reload in all browsers
  function reloadParentPage() {
    var selfUrl = unescape(parent.window.location.pathname);

    parent.location.reload(true);

    parent.window.location.replace(selfUrl);

    parent.window.location.href = selfUrl;
  }

})(jQuery);

```

---
Tags: 7
---


title: Drupal 7 - Login with external Database

text:
# Question
Title: Drupal 7 - Login with external Database
I want my users to be able to login into Drupal with an external user database. I searched for a long time and don't get any module/trick/whatever that is out there. Please help me a little, I'm new to Drupal, I don't know anything about hooks or whatever. Isn't there a module exactly like this: http://drupal.org/project/ppauth only that I can use my own database with?

Help? Please, I'm desperate! :(

# Answer
Is your external database provided by another authentication mechanism? There are mature modules for Active Directory, Social Network login, and many others besides.

If your database for authentication is totally custom, then you will need to write some custom code.

Drupal users generally login using the `user_login` form. When users login, a particular function, user\_login\_authenticate\_validate, is called by the `user_login` form's submit hook. This function validates user credentials against the local database.

`user_login_authenticate_validate` can be replaced with another function by using hook\_form\_alter on the user\_login\_form. You will need to create a new module, and implement code something like the following...

```
/**
* Implements hook_form_FORM_ID_alter().
*/
function mymodule_form_user_login_alter(&$form, &$form_state, $form_id) {
  // Add your own validators to the form.
  $form['#validate'] = mymodule_validators();
}

/**
* Returns an array of user validation function callables.
*
* @see user_login_default_validators().
*/
function mymodule_validators() {
  return array('user_login_name_validate', 'mymodule_authenticate_validate', 'user_login_final_validate');
}

/**
* Validation function, validates users against foo database.
*
* @see user_login_authenticate_validate()
*/
function mymodule_authenticate_validate($form, &$form_state) {
  // Use the password and username from the form, and make sure you set
  // $form_state['uid'] to the correct uid for the auth user.
  $password = trim($form_state['values']['pass']);
  $username = $form_state['values']['name'];

 // Authenticate them against your database, and find their drupal uid....
 $form_state['uid'] = mydatabase_auth_function_that_returns_a_drupal_uid($username, $password);
}

```

Implementing your own authentication is a decision that you should not take lightly. Personally, I would never go down this path. There are serious security concerns when rolling your own authentication mechanism. Wherever possible, you should leverage mature and well-tested solutions.
> 5 votes

---
Tags: database, users
---


title: Drupal way to edit site variables

text:
# Question
Title: Drupal way to edit site variables
what's the best way to go about to hacking core variables? I need to edit a few values in Drupal core's common.inc, for instance:

```
  'name' => 'Generator',
  'content' => 'Drupal ' . $version . ' (http://drupal.org)',

```

and also in user.pages.inc

```
$timeout = variable_get('user_password_reset_timeout', 86400);

```

but if I update drupal core, these values will return. Is there a "Drupal way" of editing these values so that I don't have to do that every time?

Thanks.

# Answer
You should not edit core code, ever.

For variables (set with `variable_set`) can try using something like strongarm module, or you can override using `$conf` in settings.php:

```
 /**
 * Variable overrides:
 *
 * To override specific entries in the 'variable' table for this site,
 * set them here. You usually don't need to use this feature. This is
 * useful in a configuration file for a vhost or directory, rather than
 * the default settings.php. Any configuration setting from the 'variable'
 * table can be given a new value. Note that any values you provide in
 * these variable overrides will not be modifiable from the Drupal
 * administration interface.
 *
 * The following overrides are examples:
 * - site_name: Defines the site's name.
 * - theme_default: Defines the default theme for this site.
 * - anonymous: Defines the human-readable name of anonymous users.
 * Remove the leading hash signs to enable.
 */
 $conf['site_name'] = 'My Drupal site';
 $conf['theme_default'] = 'garland';
 $conf['anonymous'] = 'Visitor';

```

This documentation is from default.settings.php.
> 3 votes

# Answer
To your first question, you can change the meta tag like this inside `template.php`

```
function YOURTHEME_html_head_alter(&$head_elements) {
  $head_elements['system_meta_generator']['#attributes']['content']= // whatever you want
}

```

To the second, you could create a form that changes the variable along these lines:

```
function YOURMODULE_admin_settings_form() {

  $form=array();

  $form['user_password_reset_timeout'] = array(
    '#type' => 'textfield',
    '#title' => t('User Password Reset Timeout'),
    '#default_value' => variable_get('user_password_reset_timeout', 86400),
    '#size' => 28,
    '#maxlength' => 8,
    '#description' => t('Enter the number of seconds for the user password reset timeout'),
  );

  return system_settings_form($form);

}

```

and then use that in a menu:

```
function YOURMODULE_menu() {

  $items=array();

  $items['admin/settings/YOURMODULE'] = array(
    'title' => 'YOURMODULE Admininstration',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('YOURMODULE_admin_settings_form'),
    'access callback' => 'user_access',
    'access arguments' => array('APPROPRIATE_PERMISSION_ON_YOUR_SYSTEM'),
  );

  // other menu items go here

  return $items;

}

```
> 2 votes

---
Tags: updating
---


title: Storing a date created with Form API

text:
# Question
Title: Storing a date created with Form API
Very simply, I'm creating a date of birth field pragmatically like so:

```
  $form['dob'] = array(
    '#type' => 'date',
    '#required' => TRUE,
    '#title' => t('Date of Birth'),
    '#default_value' => $sponsorship->dob,
  );

```

The API says the return value is in the form:

```
array('year' => 2007, 'month' => 2, 'day'=> 15)

```

My question is simply, how should I store this in a database table? I originally set the table column to varchar. But I would like to know what is normal practice and most efficient for handling a date using the Form API for Drupal, both saving to the database and then displaying on a page.

# Answer
Drupal 7 Schema API Data types does not support the `DATE` datatype that you find in popular SQL dialects such as *MySQL*. My preferred solution is the same as the one you suggest (set the column to `varchar` and store it as a an ISO 8601 format date string: `2013-05-07` for May 7, 2013). It is human readable (useful when debugging) and it is the format used by the `DATE` format of most SQL dialects.

For date arithmetic, I use built-in PHP-functions such as gregoriantojd to convert to Julian dates to compute date differences, etc.

While it is *possible* to force Drupal to use the `DATE` type to your SQL dialect of choice - see this answer for details, a `varchar`is the simplest and most portable solution.

For displaying a date in Drupal, you *may* want to use the the Drupal format\_date function (from `common.inc`), as this makes sure that dates are rendered consistent across the site, and adapt month names, etc. to the preferred language. Note that this function takes a Unix timestamp as its first argument, so you need to convert from the ISO 8601-format to a Unix timestamp in order to use this (and this won't work for dates fore 1970-01-01). Because of this limitation I instead use a small custom module with a slightly adapted *copy* of this core function that shares the format templates with the core function, but accepts an ISO 8601 date and datetime as valid input. I also supply my own custom format (you can set up this on the *Home » Administration » Configuration » Regional and language » Date and time » Add Date type* admin page) without any hours, minutes or seconds.

PS: Some people recommend using Unix timestamps (seconds from epoch starting 1970-01-01) for anything that has to to with time and date. However, I do not like to use Unix timestamps for *dates* where the resolution wanted is whole days. In addition to not being human readable, and having a rather limited timespan (making it inappropriate to store the date of birth for someone born before 1970), Unix timestamp dates based upon the local time tend to produce weird bugs when dates cross seasons because DST is being taken into account when you do not expect it. It may be considered strange that I depreciate the Unix timestamp when the format\_date function wants this format - but I find that storing the dates in the database in the ISO 8601 format is so attractive that I put up this extra conversion step when calling the format\_date function.
> 4 votes

# Answer
Unix timestamp is what I prefer.
> -1 votes

---
Tags: 7, forms, datetime
---


# Question
Title: Have administrators approve user accounts after users confirm their e-mail addresses and set passwords
For my current Drupal 7 project I set up the account creation process the following way:

1. User can register for an account.
2. User will receive an email telling him that the account needs to approved by the administrator
3. Email is being sent to the administrator asking him to approve the account.
4. Once the administrator has approved the account another email is sent to the user with a link, leading the user back to the portal to set his new password and to log in.

What I am after is a slight change to this process:

I want the user to get the email first to set his password and therefore confirm his email address.

Once that is done I want the email being sent to the administrator to approve the account.

Is that possible?

Thanks, Uwe

# Answer
Easiest way is kinda like what frazras said, leave the regular auth process but use rules to send an email to admin group/role when a user confirms registration.

You'll probably want to use views to create a view then that looks for the user role (the default confirmed user) and create a confirmed or approved user role (be sure to strip the user role of all permissions & grant permissions to your new role that are how you want them). In the view you are creating make sure to exclude anyone that's a member of any role other than just user & maybe anon.

The link to that view in an email to admins makes it easy to monitor You could probably put in a link to approve via the email though I'd strongly advise not letting users approve users without verification unless you're comfortable with your ability to secure it.

http://drupal.org/project/Rules http://drupal.org/project/views
> 1 votes

---
Tags: users
---


title: FitVids Video Sizes

text:
# Question
Title: FitVids Video Sizes
Using FitVids module. It messes up the sizes of videos in grid display making one column of videos lager than others.

> ex. http://develgobernabilidad.idl.org.pe/idl-sc-en-medios

Any ideas about how to control the size of the videos so that they are consistent?

# Answer
The videos are not different sizes - your descriptions are different lengths, which is breaking the flow of your pages.

You need to make sure that the `views-field-title` field is the same height regardless of the length of the text description.
> 0 votes

---
Tags: files
---


# Question
Title: Clean URL/.htaccess problems with multiple subdirectories
I've inherited a large Drupal web site and now we're updating from Drupal 6 to Drupal 7. I cannot enable CleanURL for more than one subdirectory at a time! I think I've read just about every article on CleanURLs there is, and possibly my situation is unique, or maybe I'm going about things wrong?

We have a couple versions live on our web site using different subdirectories and databases. There are two sites total on one domain, each with a Drupal 6 "live" copy and a Drupal 7 "test" version on the host. They are organized as follows:

```
siteA_D6 -> example.com/
siteB_D6 -> example.com/siteB_D6
siteA_D7 -> example.com/siteA_D7
siteB_D7 -> example.com/siteB_D7

```

We want the subdirectories to work as I've listed them above, but eventually we will retire the D6 versions and redirect D7 to example.com/ and example.com/siteB

Currently, all 4 sites are accessible, **but**, CleanURLs only work on siteA\_D6 (or example.com). Ideally we want to have CleanURL enabled on all of them, so that

```
http://example.com/test/arguments and
http://example.com/siteA_D7/test/arguments

```

resolve to the "same" page in different versions, and we never see ?q=test/arguments in the address bar

Our shared-server web host considers this issue "beyond ordinary technical support"... can't blame them, I've been banging my head up against this wall for days now. I'd really appreciate a solution or just some pointers.

(.htaccess copied below)

```
Options All -Indexes

ErrorDocument 404 "This page was not found on this server"

RewriteEngine On
RewriteBase /

Options +FollowSymLinks

# Closing the back door
RewriteCond %{QUERY_STRING} (ch|php_code)=(.*)
RewriteRule (.*) ##pretend url here, it won't let me post "too many links"## [L]

# Block pharmaceutical hotlink chicanery
RewriteCond %{HTTP_REFERER} ^http://.*pharmacy [NC]
RewriteRule .*\.(jpe?g|gif|bmp|png)$ - [F]

# stuff to let through
# I have been commenting these out when testing new rules
RewriteCond %{REQUEST_URI} "/siteB_D6/" [OR]
RewriteCond %{REQUEST_URI} "/siteB_D7/" [OR]
RewriteCond %{REQUEST_URI} "/siteA_D7/"
RewriteRule (.*) $1 [L]

#this one redirects all requests from domain to new folder
RewriteCond %{HTTP_HOST} ^.*example.org$
RewriteCond %{REQUEST_URI}  !^siteA_D6.*
RewriteRule ^(.*)$ "site_A_D6/$1" [L]

<IfModule mod_suphp.c>
suPHP_ConfigPath /home/username
<Files php.ini>
order allow,deny
deny from all
</Files>
</IfModule>

```

# Answer
> 2 votes
It seems that your `.htaccess` is custom made, first of all you should have a look at the one Drupal provides as you're missing some criticals rules like

```
<FilesMatch "\.(engine|inc|info|install|make|module|profile|test|po|sh|.*sql|theme|tpl(\.php)?|xtmpl)$|^(\..*|Entries.*|Repository|Root|Tag|Template)$">
  Order allow,deny
</FilesMatch>

```

Regarding your problem, I think you should change the `RewriteBase` condition like this:

```
RewriteBase /siteB_D6

```

for each of you subsite (make it matches the subdirectory where it's located).

---
Tags: 7, .htaccess, uri
---


# Question
Title: How to programmatically uncheck 'Generate automatic URL alias' option for all nodes
I've created some nodes programmatically and set the path alias. But when I then go into edit the node the 'Generate automatic URL alias' option is still checked, even though my alias is shown in the 'URL alias' textfield underneath, so consequently gets overwritten on save.

Also, when editing the node using the Entity module and entity\_metadata\_wrapper(), the alias is generated again and my alias is overwritten because of this problem.

When I load a node using node\_load() I expect to see $node-\>path\['pathauto'\] but I don't, so I can't seem to disable it this way. Anyone have any advice?

# Answer
Figured I'd help out -- took me a while to find it.

Pathauto doesn't implement hook\_node\_load, so you won't see it there. My case was I needed to remove an alias in an update hook, and make sure that checkbox is unchecked.

So that's what I did

```
  $node = node_load(17);
  $node->path['pathauto'] = FALSE;
  node_save($node);
  pathauto_node_delete($node);
  node_load($node->nid);

```
> 3 votes

---
Tags: path-aliases
---


# Question
Title: different sort criteria depending on term ID
I'm using views for my taxonomy term page. I want to sort the nodes in some categories by title, while nodes in other categories by weight. I've been poking around the views UI but I can't figure it out. I was thinking that I probably should implement some hook or create a custom query but I don't know where to start. How do I achieve this?

# Answer
> 0 votes
I accomplished what I wanted to do by using `hook_views_pre_build()` and `hook_views_query_alter()`

```
 /* Remove sorting by weight if viewing a category that should be alphabetized.*/
 function commerce_customizations_views_pre_build(&$view) {
   $alphabetize = array('3','58');

   if($view->name == 'taxonomy_term' && $view->current_display == 'page'
   && in_array($view->args[0], $alphabetize)) {
    unset($view->sort['weight']);
   }
 }

 /* Sort by title if viewing a category that should be alphabetized.*/
 function commerce_customizations_views_query_alter(&$view, &$query) {
   $alphabetize = array('3','58');

   if($view->name == 'taxonomy_term' && $view->current_display == 'page'
      && in_array($view->args[0], $alphabetize)) {
        $query->add_orderby('node','title','ASC');
   }
 }

```

---
Tags: views
---


title: Render a file in a specific view mode

text:
# Question
Title: Render a file in a specific view mode
Which is the right way to render a file in a custom view mode? I'm using Media, 7.2 branch, I've custom view modes and I want to print in a tpl a file (based on fid) in the view mode "header\_image".

# Answer
> 4 votes
You'll want to use the file\_view\_file() function provided by the File entity module. The function has three parameters: a file object, the name of a view mode (or an array of custom display settings) and optionally a language code.

If you only have a file ID then you can do a file\_load on the ID to get a full file object to pass to the function.

Note that file\_view\_file() returns a array as expected by drupal\_render() so, depending on how you are incorporating the file into your template, you may have to render the returned array using render().

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


# Question
Title: I have installed contact module and SMTP Authentication Support but do not appear in Structure tab
I have Drupal 7.22 installed, I have installed some modules, but there are two modules that appear correctly installed but I cannot see their configuration in structure. These modules are Contact and SMTP Authentication Support.

Previously I had some issue with the cache in Configuration tab, and I empty the cache, and it worked, but in the Structure tab even if I do it, I don't solve it.

# Answer
You should install the devel module from http://drupal.org/project/devel and after that you can select rebuild menu or flush all cache function. (From the devel menu) If i doesn't work, maybe there was some problems with your installation. You should disable and enable these modules again or run update.php script.
> 1 votes

---
Tags: 7, emails
---


# Question
Title: How to add a custom widget to a node creation form Drupal 6
This may be a dumb question, but nothing I could find really told me what I was looking for. Without furthur ado: I need to add a custom widget that will edit node reference fields on CCK content types. This widget needs to show up in the node creation form, and should consist of a textbox and a button. When the button is clicked, the widget should take the contents of the textbox and use it to create a new node of a different content type and then store a reference in the field it edits. I need the D6 hooks which I need to implement this. Links to their documentation would be helpful.

# Answer
I'd take a look at two modules, the base level Hierarchical Select module and its Hierarchical Select Node Reference submodule. The second module allows you to create "on the fly" a node referenced by the parent node being created and may do what you need without custom coding on your part.
> 1 votes

---
Tags: 6, hooks, entities, nodes
---


title: login form without registration link

text:
# Question
Title: login form without registration link
How can I get rid of the link for registering a new account in the login form/popup?

I want my new users to register through a page but not through the login form.

# Answer
> 1 votes
Another idea for this that you just create your custom module and form\_alter function to modify or change the template for login/register/forgot password form. With this way you can handle everything but just in case you want to build your own module. If you want to do this way. I can give you the example code right here.

By the way which drupal version do you use

# Answer
> 0 votes
Have you tried the LoginToboggan module? This has a number of configurations that are helpful in situations where you would like to customize the login options.

---
Tags: users
---


# Question
Title: How to set published status to a static value while importing a CSV using Feeds
How can I set the published status of a node created by Feeds to unpublished for every node it imports?

I am using a manually uploaded CSV file.

# Answer
> 3 votes
Add a new column to your CSV, fill it with 0, and import that as Published Status.

---
Tags: feeds
---


# Question
Title: Apache solr search words, but the search pages yield no results
I have Drupal 7 set up with Search API and Apache Solr. It was working for a while but after a lot of configuration has been done, modules installed, etc. The search no longer yields results. I added solr auto complete to my search block that uses the solr search, and when I start typing in "pizza" it shows that there are indeed two results that come from that search, but when I click Submit, the search page says there are no results.

Does anyone have any idea why this is not working?

EDIT: I also have facet search enabled. To troubleshoot I disabled the facet api entirely and I'm getting the same issue.

EDIT2: Let me know what other information is needed to diagnose the issue.

# Answer
The issue was that I had added the line as suggested here: http://www.druplitec.de/partial-substring-search-using-solr-server-and-searchapi-module

I took out the line and now it works. I guess I have to find another way to get "fuzzy search" for the solr server to work...

I had added the line to the wrong place. I re-read through the apache solr docs and found the correct places for it to go.
> 0 votes

---
Tags: search
---


# Question
Title: How to map ubercart attributes to CCK fields?
The reason I am trying to map ubercart attributes to CCK fields because I can then use these CCK fields to display price list using views for many use cases.

Is there any fields references module which can do this?

# Answer
If you really want fields and do not want to use your price in your views (though Ubercart is really compatible with views), you can use **Rules** to fill the value of a "hidden" *(I recommend you use field permission for that)* CCK numeric field.

Once you've created the field for your product content type, set the rule like this :

1. Event : **Content is created**
2. Condition : **Is of type** your product content type
3. Condition : **Entity has field** your numeric hidden field
4. Action : **Add a variable** : get your price value
5. Action : **Convert data type** : make it numeric
6. Action : **Set a data value** : set your hidden field value.

*(Maybe this 3 last actions can be done in only 1 with "set a data value", it's worth trying it)*
> 2 votes

# Answer
If you are using drupal 7, then you can use module Ubercart Field attributes. As mentioned in the project page of the module,

> This module links Ubercart's attribute system to Drupal core's fields API and allows to automatically create product attributes from fields and options from the multi-values.

If you are using drupal 6, then there is module Ubercart CCK Attribute.
> 0 votes

---
Tags: 7, views, entities, ubercart, nodes
---


# Question
Title: Is there a trick to getting Mime Mail to recognize by-mailkey theme templates?
I have installed Mime Mail 7.x-1.0-alpha1 and got it set up and working for the most part. The thing I'm having trouble with is getting it to recognize a by-mailkey template. I have been able to copy the `mimemail-message.tpl.php` into my theme directory, modify it and have it apply to the HTML email I am sending just fine. I can put that file anywhere in my theme directory and it finds it and overrides the default. I cannot however get it to recognize a by-mailkey template no matter where I put it in my theme directory.

I have an email with the key `help_wanted` set. I have created a template file called `mimemail-message--help-wanted.tpl.php`, which I believe is the correct template name to apply to the email with that key. I have cleared the cache and sent the email, but the default template is still applied.

I have also tried using `mimemail-message--help_wanted.tpl.php` with no luck.

I know the proper key is being passed because I can set up the `mimemail-message.tpl.php` to override the default template and print out the `$key` variable in the template and get `help-wanted`.

Does anyone have any experience with this and might know what I could be doing wrong?

# Answer
Use latest dev version of Mime Mall module. It doesn't work in 7.x-1.0-alpha1 and 7.x-1.0-alpha2.

But you can also make a quick hack. In file mimemail.module need to comment the row #531

```
$key = str_replace('_', '-', $key);

```

After that you can use `mimemail-message--help-wanted.tpl.php` template.
> 1 votes

# Answer
The templating engine should not use underscores '\_'. They should automatically be replaced by hyphens '-'. So did you try to change something like mimemail-message--help--wanted.tpl.php
> 1 votes

---
Tags: emails
---


# Question
Title: Custom template for content type, How to print a link field as a hyperlinked image
I am making a site for a music festival. I have one content type for attending artists, which includes the following fields of the fields type Link: soundcloud, youtube etc.

I would like to print these fields with an image (small icons) instead of the written link.

How can I do that?

( The path I am looking at for the moment: copy node.tpl.php, rename to node--artist.tpl.php, add some code, put in sites/all/themes/default\_theme. )

# Answer
> 0 votes
It's easier and more practical apply a preproccess hook:

```
Function YOUR_THEME_proprocces_node__artist(&$vars){

 // $vars contain the fields to be renderable in content attribute

}

```

I resolved a similar question a few days ago: change links read more and add comment

Inside of array tree `$vars['content]`, you will have to change the title attribute adding the html mark you want.

If you have a problem to find the tree or change the array, print the array with the `dpm($vars)` in your code and capture an screenshot to publish here.

---
Tags: entities, nodes
---


title: Node Teaser Acting like Full Node

text:
# Question
Title: Node Teaser Acting like Full Node
I have got a problem. I have been upgrading my site from Drupal 6 to 7 and I've reached about 75% of the way. I have updated all my 3rd party modules and custom modules and while I was configuring some setting for my 3rd party modules, like Taxonomy Image, I noticed that in my front page the teasers where displaying a view that I wanted to embed only in the full node view.

I looked at my node.tpl.php, which is where I was adding the view and the if/else for the view looks good, but for some reason, when I debugged it, the if ($teaser) is not the one that it is going to when I load the front page, it is actually going to the else.

This is the code in my node.tpl:

```
  <div class="clearfix">
    <?php if (!empty($content['links'])): ?>
      <div class="links"><?php print render($content['links']); ?></div>
    <?php endif; ?>
        <?php if($teaser): ?>
            <?php print render($content['comments']); ?>
        <?php else: ?>
        <!--    //Add the comments and related_by_term block to the footer_wrapper div -->
            <div id="footer_wrapper">
                <?php print render($content['comments']); ?>
                <?php $related_by_term_block = block_load('views', 'related_by_term-block_1');
                    $block_content = _block_render_blocks(array($related_by_term_block));
                    $build = _block_get_renderable_array($block_content);
                ?>
                    <div id="blackborder_related_by_term_block">
                <?php
                    print render($build);
                ?>
                    </div>
            </div>
        <?php endif; ?>
    </div>

```

I have no idea if any of the 3rd party modules I have are getting in the way. This is the list of my 3rd party modules:

1. FLAG
2. DATE
3. CAPTCHA
4. MOLLOM
5. ADVANCED HELP
6. BETTER FORMATS
7. FLAT COMMENTS
8. FORWARD
9. SEARCH CONFIGURATION
10. SHARED EMAIL
11. VOTING API
12. WYSIWIG
13. AUTHOR PANE
14. PUBLISH CONTENT
15. WORKFLOW
16. THEMEKEY
17. CHAOS TOOL SUITE (CTOOLS)
18. VIEWS
19. ENTITY API
20. VIEWS BULK OPERATIONS (VBO)
21. VIEWS ATTACH (EVA)
22. SIMILAR BY TERMS
23. ADVANCED FORUM
24. RULES
25. LIBRARIES API
26. GRAMMAR PARSER
27. GRAMMAR PARSER LIBRARY
28. HTML PURIFIER
29. TOKEN
30. INVITE
31. FIVESTAR

Any input would be greatly appreciated. Thanks.

# Answer
> 0 votes
It is the Advanced Forum module that is causing the problem. Once I disabled it, it displayed as a teaser. Now, I need to figure out just why. Thanks for your help, Alex, really appreciate it.

---
Tags: views, theming
---


# Question
Title: Views: how to ASC sort the grouping field #1 and sort DESC its content?
I have views grouped by year (grouping field #1) that I want to sort from the most recent to the oldest. I have content referenced to the year.

This returns me a HTML list such as:

```
2013
- alpha
- gamma
- beta
- delta

2012
- zeta
- gamma
- epsilon

```

The years are correctly sorted (DESC) but I would like to have the content of each year sorted ASC to have the content listed alphabetically to have a list like this:

```
2013
- alpha
- beta
- delta
- gamma

2012
- epsilon
- gamma
- zeta

```

I have of course tried to apply a ASC sort on the content but it affects the years also and they become ASC sorted as well.

# Answer
I have created a small test setup in Drupal, containing six nodes with each having a year (integer) and a content (text) field.

The view's configuration is displayed below:

The sort criteria is first on the year field (descending) and then on the content's text (ascending). The view generates the following result:

Note that I have excluded the year field from the display. Instead I'm using the grouping option on year in settings of the unformatted list (however, this is not necessary, but the result resembles your question more closely).
> 2 votes

---
Tags: views
---


title: Drupal 6 Search module double ID's

text:
# Question
Title: Drupal 6 Search module double ID's
I'm currently busy with a website for a costumer. This website has to be W3C validated. There was a problem on the search page of the site with a double ID:

```
<div class="form-item" id="edit-keys-wrapper">
  <label for="edit-keys">Enter your keywords: </label>
  <div class="container-inline"><div class="form-item" id="edit-keys-wrapper">
  <input type="text" maxlength="255" name="keys" id="edit-keys" size="40" value="" class="form-text" />
</div>

```

The ID: `id="edit-keys-wrapper"` comes up two times! This is not W3C allowed.

I've downloaded and installed a clean Drupal 6.28 to be sure it's not a theme error.

Is there a patch for this "problem"? If not, what is the best option to fix this without ruining core?

# Answer
I can confirm this happens out of the box all the way back to at least 6.25.

You can 'fix' it pretty simply with the following code:

```
function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'search_form') {
    unset($form['basic']['#id']);
  }
}

```

That gives this markup in place of the old:

```
<div class="form-item">
  <label>Enter your keywords: </label>
  <div class="container-inline">
    <div class="form-item" id="edit-keys-wrapper">
      <input type="text" maxlength="255" name="keys" id="edit-keys" size="40" value="book" class="form-text error">
    </div>
    <input type="submit" name="op" id="edit-submit" value="Search" class="form-submit">
  </div>
</div>

```
> 10 votes

---
Tags: search
---


# Question
Title: Display a flag link in views based on whether the node has an associated taxonomy term
All of my nodes of a certain content type are given a category by assigning a taxonomy term. I would only like to add the flag, "My Fruits" if the content has the term "Fruit" assigned to it.

So far I've attempted using a views PHP field to add the flag:

This works to simply print the flag:

```
<?php
print flag_create_link("basket_01_t01_fruit", $row->nid);
?>

```

But this, I'm not able to get working:

```
<?php
if ($row->field_item_produce_type == '3') {
print flag_create_link("basket_01_t01_fruit", $row->nid);
}
?>

```

Any ideas would be appreciated.

# Answer
You could achieve this easily using views without using views php field. More specifically you can create a view of content with an EVA (entity views attach) field display where you will add the flag link field and attach it to the nodes of that content type. Just make sure to:

1. Add a contextual filter of Content:Nid
2. Add a relationship of "Content:Taxonomy terms on node"
3. Also add a "Flags: Node flag" relationship (uncheck the include flagged content only checkbox)
4. Add a filter "Content type:...your content type which nodes will have the flag link
5. Add a filter "Taxonomy term: Term ID" that will equal to the tid of the "fruit" term.

After that you can easily choose how to display this eva field on your nodes using Display suite.
> 3 votes

---
Tags: flags
---


# Question
Title: What is the difference between path and theme path in theme registry?
I'm trying to alter the theme registry:

```
function comment_simplify_theme_registry_alter(&$theme_registry) {
  $module_path = drupal_get_path('module', 'comment_simplify') . '/tpl';
  $theme_registry['comment']['template'] = $module_path . '/comment';
  $theme_registry['comment']['theme path'] = $module_path;
  $theme_registry['comment_wrapper']['template'] = $module_path . '/comment-wrapper';
  $theme_registry['comment_wrapper']['theme path'] = $module_path;
}

```

Now this is what I have in theme registry:

```
comment_wrapper
  template: sites/all/modules/comment_simplify/tpl/comment-...
  path: themes/bartik/templates
  type: theme_engine
  theme path: sites/all/modules/comment_simplify/tpl
  render element: content

```

I want to know what the difference between `path` and `theme path` is.

# Answer
> 4 votes
From the `hook_theme()` docs:

* **path**: Override the path of the file to be used. Ordinarily the module or theme path will be used, but if the file will not be in the default path, include it here. This path should be relative to the Drupal root directory.
* **theme path**: (automatically derived) The directory path of the theme or module, so that it doesn't need to be looked up.

---
Tags: 7, theming
---


# Question
Title: How to load conditionally a script depending on whether element exists in DOM?
I have a Drupal.behaviors.leftmenusticky script that converts a left menu to a sticky menu (100% height,position fixed and the like) but I want to drupal\_add\_js it only if the menu actually exists in the page shown.

```
(function ($) {
  if ($(".full-height").length > 0 ) {
  Drupal.behaviors.leftMenuSticky = {
      attach: function (context, settings) {
        var contentHeight = $("#main").innerHeight();
        var viewportHeight = $(window).height();
        var offsetTop = $(".full-height").offset().top;
        if (contentHeight < viewportHeight) {
          jQuery(".full-height").height(viewportHeight-offsetTop);
        }
        else {
          jQuery(".full-height").height(contentHeight-offsetTop);
        }
        leftColumnResizer();
        $(window).bind("resize", leftColumnResizer);
        function leftColumnResizer () {
          var toto = $(".region-sidebar-first").width();
          $("#block-paddle-menu-display-management-level-4").css("width", toto);
        }
      }
    }
  }
  else {console.log('notfound');}
})(jQuery);

```

The Javascript way would be to check whether or not the class I'm targetting exists or not:

```
  if ($(".full-height").length > 0 )

```

but 1) I don't know where to place this check exactly and 2) I'd prefer to have a template.php way of doing that by making use either of settings or of context...

Is this possible?

# Answer
`drupal_add_js()` happens server-side, it can't possibly have exposure to what's in the DOM (unless you pass that info back to the server with AJAX, but that would be a very weird thing to do). The correct solution is the javascript one as you've mentioned.

You want that code to run whenever the DOM is ready, so in the Drupal paradigm immediately inside the `attach` function of your behaviour:

```
(function ($) {
  Drupal.behaviors.leftMenuSticky = {
      attach: function (context, settings) {
        if ($(".full-height").length > 0 ) {
          var contentHeight = $("#main").innerHeight();
          // ...

```
> 3 votes

---
Tags: theming, javascript
---


# Question
Title: Error while mass subscribe using simplenews
I get this error while i am trying to mass subscribe users/email for a newsletter using the simplenews module in D7. How can i solve this error ?

```
PDOException: SQLSTATE[23000]: Integrity constraint violation: 1048 Column
'tid' cannot be null: INSERT INTO {simplenews_subscription}
(tid, snid, status, timestamp, source) VALUES
(:db_insert_placeholder_0, :db_insert_placeholder_1,
:db_insert_placeholder_2,
:db_insert_placeholder_3, :db_insert_placeholder_4);
Array ( [:db_insert_placeholder_0] =>
[:db_insert_placeholder_1] => 1285
[:db_insert_placeholder_2] => 1
[:db_insert_placeholder_3] => 1368003712
[:db_insert_placeholder_4] => )
in simplenews_subscription_save()
(line 1501 of /sites/all/modules/simplenews/simplenews.module).

```

# Answer
> 1 votes
You are getting this error because when it is trying to insert the taxonomy term ID:

```
INSERT INTO {simplenews_subscription} (tid ...

```

The value that is being passed is null:

```
Array ( [:db_insert_placeholder_0] =>

```

Best plan to fix this is to try and determine why it is not passing this taxonomy term. Did you select the term as an option when mass subscribing? This may be a bug or quirk in simplenews itself according to this thread or maybe an issue with corruption of your dataset.

Another way to resolve this if that is the case would be to alter that column to allow nulls (temporarily!), do your mass subscription action, manually add the correct taxonomy term to the database and then finish by restoring the null constraint to the column.

---
Tags: emails
---


# Question
Title: Need Ability to Override Default text field
When the textfield is left blank, a default value populates. But when a value is placed into the text field, that value should show on the front end. It currently does not.

I have admin rights to edit,view any pages. I have enabled everything for adminstartor roles under User Management-\>roles. Even then am unable to update a new value to that field. It is populating the default value.

# Answer
You can change the field default text in the field settings page of the content type, for example:

admin/structure/types/manage/\[your-content-type\]/fields/\[your-field\]

You need to change \[your-content-type\] and \[your-field\] by the real values on your drupal website.
> -1 votes

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


title: jQuery gallery with imageFUpload

text:
# Question
Title: jQuery gallery with imageFUpload
here's the code of kartinkin.php file:

```
<?php

  $node = node_load(707);
  node_view($node);
  //$index = $_GET['index'];
  //dpm($node);

?>

<script type="text/javascript">

  $(document).ready(function(e){
    $('.small-images a').click(function(e) {
      $.get("http://myadress.org/kartinki.php", {"index": index});
      e.preventDefault();
    });
  });

</script>

<?php $index = $_GET['index']; dpm($index); ?>

<div class="imba-slider">
  <a class="left-arrow" href="javascript: void(0);">#</a>
  <a class="right-arrow" href="javascript: void(0);">#</a>

  <div id="big-image-slider">
    <?php if ($index == 0): ?>
      <?php print theme_imagecache('imba', $node->field_pics[0]['filepath']); ?>
    <?php else: ?>
      <?php print theme_imagecache('imba', $node->field_pics[$index]['filepath']); ?>
    <?php endif; ?>
  </div><!--/big-image-slider-->

  <div class="small-images">
    <?php for ($i = 0; $i <= count($node->field_pics); $i++) { ?>
      <a href="?index=<?php print $i; ?>"><?php print theme_imagecache('230x130', $node->field_pics[$i]['filepath']); ?></a>
    <?php } ?>
  </div><!--/small-images-->
</div><!--/imba-slider-->

```

I have included that file with `include_once()` inside a node.

**PROBLEM.** When i click on small-image it reloads the page and after reload my big image changes. With a code above i've tried to do it without a page reload, i even write `e.preventDefault();` But still after clicking on a preview image it reloads the page. How can i make big image changing without reload?

# Answer
> 1 votes
You've got several issues here:

1. PHP runs on the server, JavaScript runs on the client's browser so they don't know about eachothers variables.
2. You're not doing anything with your $.get(..) results, you need to do something with the results of the ajax get request in a success or complete callback.
3. You're calling a URL to a full page, i'm assuming you want just the image.

If your image names follow the naming convention I see where the thumbnails use `/230x130/` in the path and the larger image uses `/imba/` instead, then use the code below instead of your current click event:

```
slideShowIndex = 0;

$('#big-image-slider img.imagecache-imba').load(function(){
  hideSlideLoader();
});

$('.small-images a').click(function(sender){
  sender.preventDefault();
  showSlideLoader();
  var lnk = $(this);
  slideShowIndex = $('.small-images a').index(lnk);
  var imgUrl = lnk.find('img').attr('src').replace('/230x130/','/imba/');
  $('#big-image-slider img.imagecache-imba').attr('src', imgUrl);
  return false;
});

function showSlideLoader() {
  //$('#big-image-slider').html('<img class="loader" src="/sites/all/themes/antisunna/img/ajax-loader.gif" />')
  var loader = $('#big-image-slider .loader');
  if(!loader.length) {
    console.log('creating loader');
    loader = $('<img class="loader" src="/sites/all/themes/antisunna/img/ajax-loader.gif" />')
    $('#big-image-slider').append(loader);
  }
  $('#big-image-slider .imagecache-imba').hide();
  loader.show();
}

function hideSlideLoader() {
  $('#big-image-slider .loader').hide();
  $('#big-image-slider .imagecache-imba').show();

}

$('.left-arrow').click(function(){
  if(slideShowIndex > 0) {
    moveSlideIndex(slideShowIndex--);
  }
});

$('.right-arrow').click(function(){
  if(slideShowIndex < ($('.small-images a').length - 1)) {
    moveSlideIndex(slideShowIndex++);
  }
});

function moveSlideIndex(index) {
  $('.small-images a:eq(' + slideShowIndex + ')').click();
}

```

---
Tags: ajax, javascript
---


# Question
Title: How to secure ajax on automatically save field data
My custom module make ajax request on \_node\_edit form after input changed by user, and menu callback save this field's data (only this field, not all node object). Menu item is as "field-save/NID/FIELD\_NAME", and the input val is on $\_POST\['field\_data'\]. Menu item have own permission per role. Additionally each user have own randomly generated secure string and it is on the same ajax $\_POST\['secure\_phrase'\]. Menu callback checking for permission per role and this secure string per user, if have access going forward to save field data.

The question: Is this enough security to prevent for unauthorised access to save field through this ajax request?

edit: additional for this on "access\_callback" i have

```
if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
  // checking permissions here
}

```

# Answer
It seems pretty secure. Also check the content type permissions for the role ;)
> 1 votes

---
Tags: 7, routes, ajax
---


# Question
Title: How to set start slide for views slideshow jcarousel
I am using viewsslideshow and viewsslideshowjcarousel modules. I am displaying image thumbnail as jcarousel bottom of the Gallery slides using viewsslideshowjcarousel module. It's working perfectly.

Here is the problem. I would like to navigate to slide directly using the URL. Views slide show support this by passing #unique-id:slidenumber as discussed here. But, i can not able to slide automatically to the the thumbnail of the jcarosel pager that image belongs to. I see setting start option as discussed in Documentation should do the job. But adding that is breaking the carousel in below code inside views\_slideshow\_jcarousel.js file.

```
// Add views slieshow api calls for views slideshow jCarousel pager.
Drupal.behaviors.viewsSlideshowJcarouselPager = {
  attach: function (context) {
    // Process pause on hover.
    $('.views_slideshow_jcarousel_pager:not(.views-slideshow-jcarousel-pager-processed)', context).addClass('views-slideshow-jcarousel-pager-processed').each(function() {
      // Parse out the unique id from the full id.
      var pagerInfo = $(this).attr('id').split('_');
      var location = pagerInfo[2];
      pagerInfo.splice(0, 3);
      var uniqueID = pagerInfo.join('_');
      $(this).jcarousel({
        vertical: parseInt(Drupal.settings.viewsSlideshowJCarouselPager[uniqueID][location].orientation),
        scroll: parseInt(Drupal.settings.viewsSlideshowJCarouselPager[uniqueID][location].scroll),
        visible: parseInt(Drupal.settings.viewsSlideshowJCarouselPager[uniqueID][location].visible),
        wrap: Drupal.settings.viewsSlideshowJCarouselPager[uniqueID][location].wrap,
        animation: (isNaN(Drupal.settings.viewsSlideshowJCarouselPager[uniqueID][location].animation)) ? Drupal.settings.viewsSlideshowJCarouselPager[uniqueID][location].animation : parseInt(Drupal.settings.viewsSlideshowJCarouselPager[uniqueID][location].animation),
        initCallback: function(carousel) {
          Drupal.settings.viewsSlideshowJCarouselPager[uniqueID][location]['carouselObj'] = carousel;
        }
      });

      $(this).find('.views_slideshow_jcarousel_pager_item').each(function(index, pagerItem) {
        $(pagerItem).click(function() {
          Drupal.viewsSlideshow.action({ "action": 'goToSlide', "slideshowID": uniqueID, "slideNum": index });
        });
      });
    });
  }
};

```

Any idea how to start jcarosuel based on the slidenum passed in the url ?

# Answer
> 1 votes
Try to add a contextual filter to the view that sorts the results putting the desired element in the first position of the carousel.

There is a nice reference for that: http://www.metaltoad.com/blog/using-drupal-contextual-filters-views

---
Tags: 7, views
---


# Question
Title: How to use nodereference_select in custom form (set default value) D6
I am building a custom form using the Form API. I want to show a nodereference\_select in my form. However I have some difficulties setting the default value and the list of values.

```
//Create array of values
$items['6039']="MT";

// add field
$field = content_fields('field_nodereference_select');
$form['#field_info']['field_nodereference_select'] = $field;
$form += content_field_form($form, $form_state, $field);
$form['field_nodereference_select']['#weight'] = 6;
$form['field_nodereference_select']['#default_value']=$items;
$form['field_nodereference_select']['#options']=$items;

```

When I render the form I see the widget but without any values. When I am able to render the $items array, my next step would be to executing a view (because the nodereference\_select is using a view to select certain values). and fill the $items array with the values.

Any help on this one?

# Answer
> 0 votes
I've managed to use such a field widget in a custom form in the following manner

```
  $field = content_fields('<field name on a node type>', '<node type that uses this field>');
  $form['#field_info']['<field name on a node type>'] = $field;
  $form += content_field_form($form, $form_state, $field);

```

I don't know if it would work without a node type actually having such a field. I had a node type with that reference so I could "invoke" that.

The resulting form element does not look like a simple select element, it does not have '#options' and '#default\_value' is fancy too.

---
Tags: forms, nodes
---


title: How to pass an argument to a view?

text:
# Question
Title: How to pass an argument to a view?
I have a a view with Taxonomy terms on the front page.I want when I click on a taxonomy term,this taxonomy term to be passed to a second view as an argument to an exposed filter.The second view is on another page.How can I accomplish that?Is there any module for this? Thanks in advance

SOLUTION I finally found a solution.I have rewritten the ouput of the taxonomy term to something like that second\_view/\[tid\] .So when I click on a taxonomy term I am redirected to the second view which is filtered by the tid.That's it!

# Answer
There is another solution for that. Try to use the FacetAPI module: http://drupal.org/project/facetapi

Then you can create a view and integrate the taxonomy terms with the drupal search as explained in the following link:

http://envisioninteractive.com/drupal/drupal-7-views-with-faceted-filters-without-apachesolr/
> 1 votes

---
Tags: views
---


# Question
Title: Non-autocomplete Widget for Term Reference Fields on Content Type
The available options at the moment are `Autocomplete term widget (tagging)`, `Select list` and `Check boxes/radio buttons`, but I'd like to use a widget without autocomplete.

Thanks in advance.

EDIT: To clarify: I'd like to use a widget where you're able to add comma separated tags, just like the current one, but without ajax.

# Answer
> 0 votes
The code for the @2pha suggestion:

```
function MODULENAME_form_CONTENTTYPE_node_form_alter(&$form, &$form_state, $form_id) {
  $form['field_name']['#ajax'] = FALSE;
}

```

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


title: Hide fields on the user update form

text:
# Question
Title: Hide fields on the user update form
In dutch, postal codes are formed by four numbers and two letters, e.g., 1274EA. I want to split this info to a field that contains '1274' and another field that contains 'EA' in this case. Can I do this by creating two hidden user fields, or should I create a new entity type with a user reference field and the two fields? I prefer the first option, if possible. CSS is no option.

# Answer
> 0 votes
Have you tried the Postal Code module?

It seems to support dutch postal codes as well.

---
Tags: entities, users
---


# Question
Title: Change label max length on all field types
The default max length for all labels of all field types is 128. The db can handle 255. So no schema change. How can I change the default max length to 250?

# Answer
> 0 votes
You can create a module and include the hook\_form\_alter for the content types you want. This is an example of how to do that:

```
function [MODULE_NAME]_form_alter(&$form, $form_state, $form_id) {
  if($form_id == 'your_form_id'){
    $form['your_field_name']['label']['#maxlength'] = 255;
  }
}

```

Also you can try this module: http://drupal.org/project/remove\_field\_label\_length\_limit

---
Tags: entities
---


# Question
Title: Programmatically Change Pager "Items to Display" value?
I would like to create a custom form to allow a website admin to quickly change the number of "Items to Display" for a particular block display for a particular view, but I don't have a clue how to change this value programmatically on my own, besides the views ui?

# Answer
> 0 votes
First, you retrieve the view with **views\_get\_view()**, then you alter the value, then you save the retrieved view with **views\_save\_view()** like this:

```
function my_custom_function($view, $num) {
  $myview = views_get_view('$view', TRUE);

  $myview->display['default']->display_options['pager']['options']['items_per_page'] = $num;
  views_save_view($myview);

  // Clear the cache for the pager
  $cache = $myview . ':block:results:';
  cache_clear_all($cache, 'cache_views_data', TRUE);
}

```

I also included a little snippet at the end of the custom function to clear the appropriate cache bin if need be.

# Answer
> 0 votes
im not sure of any 3rd party module that allows easy "override the # of items per page". I've done this task a few times for View displays using core drupal apis.

Basically:

1. you use hook\_views\_pre\_build to programmatically alter the view.
2. Use a custom variable to store your items per page value.
3. Make a simple admin page to allow a site administrator alter the value.

EDIT: amended to different views hook function.

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


title: double slash '//' with drupal_goto

text:
# Question
Title: double slash '//' with drupal_goto
I am using drupal\_goto and url methods to try and direct the user to a page.

url returns a string like "/whatever/example" and then I pass that into drupal\_goto and they get sent to

localhost//whatever/example

I checked the value for $base\_url in settings.php that has no trailing slash. what else could cause this behavior?

# Answer
> 4 votes
Whatever you pass to `drupal_goto()` will in turn get passed on to the `url()` function. If you're using `url()` on the path before hand, it'll get run through again and you'll get a double slash.

You can just pass the router path to `drupal_goto()` directly, and it will handle the alias for you:

```
drupal_goto('node/1234');

```

---
Tags: uri
---


# Question
Title: Does using Drupal.ajax() offer any benefits over jQuery.ajax()?
I'm updating a node's references (list of them - rendered entities) manually with AJAX and experiencing performance problems.

`$.ajax()` is used to call a view rendered with the simplest page.tpl.php ever: `print render($page['content'])`.

The filters are simple exposed filters that I pre-handle in the URL level so the url looks like this: `/url-of-view?argone=foo&argtwo=bar&template=minimal`. The view is then built up, rendered, and returned to the client.

The problem is when the site is at it's peak hours this URL (normally) is being bombarded and the server becomes slow to borderline unresponsive.

Will using `Drupal.ajax()` instead of `jQuery.ajax()` give me a performance boost here, or should I look at querying the node data manually instead of relying on Views?

# Answer
There isn't really any difference in this context; at the lowest level both will use a standard XHR, so I reckon there's a good chance the bottleneck is the server-side building of the View.

You can test that by profiling, or in a pinch, returning a static string from the AJAX callback temporarily and stress testing the server. If you don't see the bottleneck, you know that building the View is the expensive bit.

If you're able to build up a query for the node data, and render the HTML manually, you should definitely see a performance improvement. A that point, though, you might want to question if using Views is the right thing in the first place :)
> 0 votes

---
Tags: 7, ajax
---


# Question
Title: hook_form_alter to limit user select list to those referenced in a node
I have a content type called Project. I am linking users to this content type through several user reference fields.

I am also creating related Events (another content type) related to the Project content type pages through the Node Reference URL Widget.

So far so good, but...

In the Event content type I would like to add Attendees, through another user reference field, and limit the list of users to only those referenced in the original Project page. First I tried using a view, but I couldn't find the proper arguments / filters / relationships. Now I am trying through a custom module with hook\_form\_alter.

Could I get some advice on an efficient way to do this? Any ideas would be greatly appreciated.

EDIT: I have been working on this, and it seems I am almost there, but not quite. Bare with me as this is my first custom module and my php skills are quite basic. My structure (content type \> fields) is as follows:

Project:

* field\_users (entity reference)

Event

* field\_project (entity reference, prepopulated from Project on event creation)
* field\_attendees (entity reference)

Then, in a custom module, I added the following code to modify the Event content type form:

```
<?php
function mymodule_form_alter(&$form, $form_state, $form_id) {
  if ($form_id == 'project_event_node_form') {
    $id_project=var_export( $form['field_project']['und']['#default_value'][0], TRUE );
    $project = node_load($id_project);
    $user_ref = array();
    foreach($project->field_users as $u){
      $user_ref[] = $u;
    }
    $form['field_attendees']['#options'] = $user_ref;
  }
}

```

But I still see all users, not just those referenced in the Project. Strangely enough, if I do: dpm($user\_ref); I get this array, which contains the ids of the users I want to be able to choose from:

```
array (
  0 =>
  array (
    0 =>
    array (
      'target_id' => '7',
    ),
    1 =>
    array (
      'target_id' => '8',
    ),
    2 =>
    array (
      'target_id' => '9',
    ),
    3 =>
    array (
      'target_id' => '10',
    ),
  ),
)

```

But somehow I fail to pass that as the options for field\_attendees. Any ideas?

# Answer
> 0 votes
I finally managed to get it working:

```
<?php

function my_module_form_alter(&$form, $form_state, $form_id) {
 if ($form_id == 'project_event_node_form') {
  $node = $form_state['node'];
   if (!isset($node->nid) || isset($node->is_new)) {
    /** This is a new node */
    $id_project=var_export($form['field_project']['und']['#default_value'][0], TRUE);
   }
   else {
    /** This is not a new node */
    $id_project=var_export($form['field_project']['und']['#default_value'][0], TRUE);
    /** horrible hack, but I can't get the nid to behave as an integer no matter what */
    $id_project = substr($id_project, 1, -1);
    /** no need to change the referenced project, hiding the field  */
    $form['field_projet'] = array('#type' => 'hidden');
   }
   /** common code */
   $project = node_load($id_project);
   $user_ref = array();
   foreach(field_get_items('node', $project, 'field_users') as $u){
   $usr_obj=user_load($u['target_id']);
   /** this makes the checkbox form render in a useable way */
   $user_ref[$usr_obj->uid]=$usr_obj->name;
   }
  $form['field_attendees']['und']['#options'] = $user_ref;
 }
}

```

Any suggestions or improvements are welcome, particularly with the dirty hack whith the nid behaving as a string in the node edit.

Although this is a rather simple module it is my first one, so I'd like to thank the patience and support of all those who helped with this, particularly Peyman and Josh at robustLINKS, bnjmnm and Michael.

---
Tags: 7, nodes
---


# Question
Title: Use Bootswatch.com themes with Drupal Twitter bootstrap
I would like to know the easiest, simplest and quickest way to use anyone of the bootswatch.com free themes. There are some great themes there, better than I could spend a good 4+ hours trying to do. I'm merely looking to 'experiment' with CSS styles, swatches and the like. Can someone tell us how we can simply 'drag and drop'. I've tried what I thought it would be but it doesn't seem to do what I want it too, I'm not looking to spend hours on this, just to experiment with D7 for a few visual ideas. I have revieed the drupal.org Themeing documentation but that routed a little too long winded at this stage.

I appreciate there are some general paths that need changing in the CSS file and that JS needs to be correctly pointed to. My recent efforts only result in my backend Admin going a little wayout and I presume that simly 'deleting/over writing current CSS files in the CSS folder isn't exactly the 'quick' way to do things. My long term reason is so I can have a number of preset themes to work with which I prefer and can quickly 'drag and drop' new theme ideas with outspending hours for something which is only for 'eye candy' visuals.

I would rather to it 'hand coding' style rather than a easy 'module' option for those why may suggest in advance.

Thanks in advance.

# Answer
Use the theme bootstrap

Download Bootstrap place it in the bootstrap theme folder as mentioned in the theme page. Update jquery to 1.7 you might have to use the Jquery Update (Use the development version of JQuery Update and not the stable one as the development version has option to update it to 1.7. You can do that by going to admin -\> jquery Update

By default the theme uses the bootstrap.css So you can simply replace that css file with the new one you download from bootswatch and you are good to go...
> 3 votes

# Answer
Bundled these up together since I kept answering the same question for myself when implementing flavors of bootstrap -- https://github.com/btopro/bootswatch\_drupal
> 1 votes

---
Tags: theming
---


title: working with LDAP authorization hook

text:
# Question
Title: working with LDAP authorization hook
While I have been able to use the LDAP authentication hook (`hook_ldap_authentication_allowuser_results_alter`) to perform additional authentication, I have not been able to use what I thought was the LDAP authorization hook (`hook_ldap_authorization_maps_alter`, defined in the LDAP authorization module, file *ldap\_authorization.api.php*) - the hook never gets executed.

The purpose is to assign user roles to newly created, LDAP-authenticated accounts (therefore I need a Drupal ID). We can't currently use LDAP-Drupal user role mappings because our LDAP does not contain the necessary information to determine the role; instead we need to tap a different database to determine this, and I was hoping that there would a hook somewhere during account creation.

# Answer
I've been down this route a few times (looking at using LDAP integration module) each time I ended up writing my own LDAP integration. Everyone implements differently, I just take the pieces I like from the LDAP module out there (6 or 7) and use your own code to do it. As a general rule, anytime the rubber hits the road with integrating Drupal with user authentication / authorization systems in an organization I brute force them together via a custom / forked module. You'll always know your own auth system's specific needs, D.O. will not :)
> 0 votes

---
Tags: 7, hooks, authentication-authorization
---


title: Display value from user input form

text:
# Question
Title: Display value from user input form
I have this form which has 2 radio buttons. If I select the radio button labeled as one way, the return date and time will be invisible; if I select return, the return date and time will be visible. I just want to test if the data have been entered when oneway is selected. This is because when I select return, I can print out all the input values by user, but if I select oneway, I can't do so.

This is the code I am using.

```
echo "<h1>Booking</h1>";
$submit = $_POST['submit'];

if ($submit) {
  // Check the direction selected by user.
  if ($direction == "return") {
    if ($liner && $direction && $from && $f_date && $f_time && $destination && $t_date && $t_time && $txttotal) {
      echo "$liner/$direction/$from /$f_date/$f_time/ $destination/$t_date/$t_time/$txttotal  ";
    }
  }
}

```

# Answer
In the Drupal Examples project you can find the ajax\_example module with a similar form with dependent fields.

http://drupal.org/project/examples
> 0 votes

# Answer
Please use the Drupal form API -- http://api.drupal.org/api/drupal/developer%21topics%21forms\_api\_reference.html/7

You should almost never use the $\_POST / global PHP variables in Drupal communications as they are not sanitized.

To handle submitted content you should be using hook\_form\_submit(). The Devel module http://drupal.org/project/devel is very helpful in debugging / figuring out what data you are passing back and forth for processing.
> 0 votes

---
Tags: forms
---


# Question
Title: How to handle large select lists in content types?
I need to add a city field for a content type in D7. I'm getting it from a federal census table and it's going to be around 35K+ records. Any thoughts on filtering this list down by state and/or county? Without some kind of filtering, I'm afraid I'll bring Drupal to it's knees. BTW, I can't just use a taxonomy list because I need to key the list on a city ID. I also will have county ID info. So, I really need to filter the counties list to just those for the state the user has selected, then the cities by that county.

Here's the general structure: User selects State -\> County-\> -\>Cities.

I tried looking at the references module but the reference field I created didn't seem to be filterable.

Thanks for any assistance!

# Answer
> 2 votes
Sounds like a perfect job for Simple hierarchical select

> Simple hierarchical select defines a new form widget for taxonomy fields to select a term by "browsing" through the vocabularies hierarchy.
>
> The widget is available in node forms and as Views exposed filter.

You can add your locations as a hierarchical taxonomy, and SHS will AJAX-load child terms into a new inline select, then children of those in a new select, and so on. Something like

---
Tags: entities, nodes
---


# Question
Title: How to Modify Views output on every 10th item?
I have a drupal based project that uses views to output some images and markup in a loop. Each content chunk is similar so pretty standard set up. However I now have a request to uniquely modify every 10th ( or so ) content block that gets output to have a different style and markup. I am not sure how to handle this in drupal views. Can somebody please point me in the right direction?

I don't know how many items in total would be output.

# Answer
Views by default wraps each View in a div with a class based on the View's name, eg,

```
<div class="view view-NAME ... "> <!--content of the view here --> </div>

```

and each row in a div with a views-row-# class, eg,

```
<div class="views-row views-row-1 ..."> <!-- content of view row here --> </div>
<div class="views-row views-row-2 ..."> <!-- content of view row here --> </div>
<div class="views-row views-row-3 ..."> <!-- content of view row here --> </div>

```

So, quick and dirty, you could change the first 5 of these with css along the lines of

```
.view-NAME .views-row-10,
.view-NAME .views-row-20,
.view-NAME .views-row-30,
.view-NAME .views-row-40,
.view-NAME .views-row-50 {

   /* different CSS here */

}

```

You can cascade down from there if you need or want to change the CSS of any of the fields in the row as well.

If you want to get fancier, you can also add classes to each row based upon modulo arithmetic inside of the Views theme templates or via a pre\_process hook and then base your css off that class.

ADDITION BASED ON COMMENTARY:

Can you do something like this with the first/last classes? Immediately out of the box it *sort* of does what you want, eg:

creates output like this:

and where last-tenth in this quick and dirty copy and paste is every 10th row?
> 3 votes

---
Tags: views
---


# Question
Title: Force redirect from HTTPS to HTTP in Drupal 7 Multitsite?
I'm trying to serve a Kaltura video running on CentOS 6+ on one server, by plugging the Object code for embedded video inside a node body (or even using the Kaltura Drupal module), running on a Drupal 7 multisite on Ubuntu 10.04LTS.

Most browsers accept it but Chrome, which denies the request as being insecure content. We serve all our D7 sites on HTTPS, forced redirect. But now I want to only serve ONE of the multisite as HTTP so that it could show this Kaltura video, and not have Chrome hiccup.

Here's what I have in the .htaccess file of the D7 parent directory.

```
RewriteCond %{HTTPS} off
RewriteCond %{Request_URI} !^(/mysite/user)
RewriteRule ^(/.*) http://%{HTTP_HOST}%{REQUEST_URI} [NC,R=301]

```

I've tried the Secure Login module, as well as the very close suggestions here - Redirect /user/login to HTTPS, all other requests to HTTP, to straight mode rewrite on apache - https://stackoverflow.com/questions/1816119/using-mod-rewrite-how-do-i-force-https-for-certain-paths-and-http-for-all-othe \- and nothing makes sense.

Note: Not a mod-rewrite expert, but I now feel this is somehow attributed to not doing something correctly with Drupal. Currently, when you visit http://mydomain.com/mysite/user \- I get this message:

```
You are accessing <mysite> using an unencrypted connection. For your
security, <mysite> only supports account logins using
a secure protocol such as HTTPS.

```

I believe this is a very popular question, but didn't really see anyone else trying to go from secure to insecure on multisite. Please advise. Thanks,!

# Answer
> 3 votes
Maybe you should try and and change the object embed code code to use a protocal-relative URL such as `//YOURSITENAME.COM/some/path/to/video/file.mp4` you can do this easily with a WYSIWYG editor or like `hook_node_view` and regexing for your domain url and an object tag and removing the `http://` or `https://` as needed ...

Simply google for protocol-relative url and you'll find a bunch of information.

---
Tags: users, multi-sites, uri
---


title: creating a date field for date range?

text:
# Question
Title: creating a date field for date range?
I'm working on a date range field. The date field only provides you the ability to input a date. I'd like to construct a field that displays the length of time from the date start field and the date end field.

**My Use case:** The content type is a job. E.g. I worked at that job from january 1, 2001-January 23rd, 2002.

**Desired output:** e.g. (11 months) or (3 years 2 months)

How do you create a field that calculates the length of duration? Is there a module that currently exists? or would a formatter be needed?

# Answer
Ended up using the interval field

> Interval field gives you a simple field and widget to allow users to enter interval values eg
>
> 2 months 3 days 4 years
> 0 votes

# Answer
I have an idea! How about if you add an additional field to your Job content type called 'Time at job' that's simply a **text field**.

Then, create a new rule with the rules module that fires off when a Job node is saved or modified. In that rule, you can simply set the 'Time at job' field by calculating its value from the values of the two date fields (using php).

For the php code calculating the length of time between two dates, there are countless of tutorials online. Here's just one that's quite comprehensive: https://stackoverflow.com/questions/676824/how-to-calculate-the-difference-between-two-dates-using-php.

Would that fit your scenario? Calculating a third field upon node save/edit and displaying that instead?
> 2 votes

---
Tags: datetime, entities
---


# Question
Title: hook_menu() not available for ajax loaded links
I'm loading a datatable and its data into a panel, through ajax. Below is the link which can add the row(entry) to favorites. When I click the link, the jquery animation is executed properly but the hook\_menu and it's callback function is not being executed. It looks like the hook\_menu is not 'available'

This is the link

```
$link = array(
    '#type' => 'link',
    '#title' => t('Favorite'),
    '#href' => 'favorite/' . $item->nid,
    '#attributes' => array(
    'class' => array('use-ajax', 'favorite_item_button'),
    ),
);

```

And this is the hook\_menu

```
function favorite_item_menu() {
  $items = array();
  $items['favorite/%'] = array(
    'title' => 'favorite item',
    'page callback' => 'favorite_item',
    'page arguments' => array(1),
    'type' => MENU_CALLBACK,
  );

  return $items;
}

```

Do you see any mistakes? Am I doing something wrong, forgetting something?

Advice is much appreciated.

**Edit:** \- no php error logs \- no js error logs

tried: sitename.com/favorite/501 - got the error 'access denied'

# Answer
> 1 votes
You need to add `'access callback' => TRUE,` to your menu item.

Your menu callback should look like the following:

```
function favorite_item_menu() {
  $items = array();

  $items['favorite/%'] = array(
    'title' => 'favorite item',
    'page callback' => 'favorite_item',
    'page arguments' => array(1),
    'access callback' => TRUE,
    'type' => MENU_CALLBACK,
  );

  return $items;
}

```

---
Tags: 7, ajax, routes
---