title: Custom fields for every page

text:
# Question
Title: Custom fields for every page
I have few pages and need to add custom color and background image to every page and need to edit it from admin.

The best solution for me is adding custom variables in view or menu item. And then use it in **page.tpl.php**.

Is there any way to do it without a module?

# Answer
> 1 votes
ok let us try this ,,, maybe help

1- add new image field to your content type (background field)

2- open node.tpl.php in your theme

3- test if this node from this content type ,, then get the value of the background field image

4- do some thing to make this image url as a background

do the same with a little bit different for the styles :)

**For Specific URL (this way maybe not professional):**

1- create new content type `(Backgrounds)` with two fileds (URL + Image)

2- open `page.tpl.php` and write some php code can test if the current URL exists in any node from content type `(Backgrounds)`

3- if yes =\> get the image field and make it as background

---
Tags: 7
---


# Question
Title: strcmp() expects parameter 2 to be string error on configuration and system status page
I am getting the following error on the configuration and the system status page:

> Warning: strcmp() expects parameter 2 to be string, array given in
> \_system\_sort\_requirements() (line 2805 of /srv/bindings/00fd0ded5def4c8289075262cb552d75/code/modules/system/system.module).
>
> Warning: strcmp() expects parameter 2 to be string, array given in \_system\_sort\_requirements() (line 2805 of /srv/bindings/00fd0ded5def4c8289075262cb552d75/code/modules/system/system.module).
>
> Warning: strcmp() expects parameter 1 to be string, array given in \_system\_sort\_requirements() (line 2805 of /srv/bindings/00fd0ded5def4c8289075262cb552d75/code/modules/system/system.module).
>
> Warning: strcmp() expects parameter 2 to be string, array given in \_system\_sort\_requirements() (line 2805 of /srv/bindings/00fd0ded5def4c8289075262cb552d75/code/modules/system/system.module).
>
> Warning: strcmp() expects parameter 1 to be string, array given in \_system\_sort\_requirements() (line 2805 of /srv/bindings/00fd0ded5def4c8289075262cb552d75/code/modules/system/system.module).
>
> Warning: strcmp() expects parameter 2 to be string, array given in \_system\_sort\_requirements() (line 2805 of /srv/bindings/00fd0ded5def4c8289075262cb552d75/code/modules/system/system.module).
>
> Warning: strcmp() expects parameter 2 to be string, array given in \_system\_sort\_requirements() (line 2805 of /srv/bindings/00fd0ded5def4c8289075262cb552d75/code/modules/system/system.module).
>
> Warning: usort(): Array was modified by the user comparison function in system\_status() (line 2351 of /srv/bindings/00fd0ded5def4c8289075262cb552d75/code/modules/system/system.admin.inc).

Has anyone seen this before? It's something to do with core but I have no idea what's caused it.

# Answer
> 1 votes
It looks like this issue can occur if two modules return the same array key from `hook_requirements`?

Here's a similar result affecting LinkedIn Integration:

According to that issue, this will happen if two separate modules add a requirements check with a key of `curl`. The solution is to namespace requirements checks (use a key of `linkedin_curl`, `simpletest_curl` and so forth).

You could debug this and check the issue queue for the affected module(s).

* Disabling the most recently added modules might help you identify the cause (see if the symptom goes away).
* If you still feel stuck and don't feel able to dig further, try updating your question with the list of enabled modules on your site. That may help narrow it down.
* If you're running all contrib modules, googling for "strcmp \_system\_sort\_requirements drupal" might show results that help you identify the affected module.
* If you have Drush + Devel module, try `drush fn-hook requirements` to see which installed modules are implementing `hook_requirements`.
* Or just start hacking on your system settings page and trace the problem down old-school :)

If this is the cause, once you identify the module(s) causing the issue you should check the issue queue, file an issue if none already exists, and help be a part of getting it fixed!

I've tagged several affected modules in #933684 - Same requirements from different modules causes warnings in \_system\_sort\_requirements()

# Answer
> 0 votes
It was the SimplePie Core module, turning it off made the error go away.

---
Tags: 7
---


# Question
Title: How to direct authenticated and anonymous users to different ( custom ) front pages?
I want anonymous users to always see `/node/1` but authenticated users to see `/myview/uid` where uid is the current user's id.

I don't want to use **Rules**, but would prefer a code solution.

# Answer
> 0 votes
You can use hook\_user\_login function to achieve this.

```
function custom_module_user_login(&$edit, $account){
  if($acount->uid > 0) {
          $redirection = 'myview/'.$acount->uid;
  } else{
      $redirection = 'node/1';
  }

  // Unless there is already a redirection going, or the user is trying to reset his password, we redirect to $redirection.

  if (!is_null($redirection) && (!isset($_POST['form_id']) || $_POST['form_id'] != 'user_pass_reset')){
    $_GET['destination'] = $redirection; // Should we use $edit['redirect'] instead..?
    $GLOBALS['destination'] = $redirection; // Should we use $edit['redirect'] instead..?
  }

```

}

For more info check here

# Answer
> 0 votes
In my case I wanted anonymous users to always see the login page which happens to be the front page and authenticated users to be redirected to `/dashboard`. My solution is thus:

1. Create theme template file `page--front.tpl.php` ( You should aready have `page.tpl.php`).
2. Add the following code to the top of the page:

```
if($logged_in){
    drupal_goto('dashboard');
}

```

In your case you can just add the following code on the top of `page.tpl.php` and it should work just fine.

```
if($logged_in && request_path() != 'myview/uid'){
    drupal_goto('myview/uid');
}
if(!$logged_in && request_path() != 'node/1'){
    drupal_goto('node/1');
}

```

This will redirect all authenticated users to `/myview/uid` and all anonymous users to `node/1`

---
Tags: redirection
---


# Question
Title: Error: Class 'Drupal' not found in bootstrap.inc
Please tell me what I'm doing wrong. I'm unable to run `drush`, see error below:

```
[~/public_html/d8]# drush -d status
Bootstrap to phase 0. [0.01 sec, 1.86 MB]                            [bootstrap]
Drush bootstrap phase : _drush_bootstrap_drush() [0.01 sec, 1.98 MB] [bootstrap]
Cache HIT cid:                                                       [debug]
6.0-rc4-commandfiles-0-6046c80192c5b97fbcd88f24c7e529ed [0.02 sec, 1.99 MB]
Bootstrap to phase 0. [0.09 sec, 5.27 MB]                            [bootstrap]
Drush bootstrap phase : _drush_bootstrap_drupal_root() [0.14 sec, 5.28 MB] [bootstrap]
Initialized Drupal  root directory at /home3/public_html/d8    [notice] [0.15 sec, 5.39 MB]
Drush command terminated abnormally due to an unrecoverable error.   [error]
Error: Class 'Drupal' not found in /home3/public_html/d8/core/includes/bootstrap.inc, line 164  [0.15 sec, 5.4 MB]

```

I'm using:

* Drush Version : 6.0-rc4
* drupal 8.0.0-beta7
* PHP 5.4.38
* MySQL 5.5.42-37.1

# Answer
Drush 6.x only works with Drupal 6 or 7, upgrade to Drush 7.x.

Source
> 3 votes

---
Tags: drush, bootstrapping
---


# Question
Title: How to create a contact form using FAPI in a custom module?
I want to create a contact form using FAPI my custom module.

I created 2 files: one is `.info` and the other is `.module`. But I do not understand how I should link that module with my template name `page--contact-us.tpl.php` as I already activated that module from module list.

I used the code below in my `module_name-module`:

```
<?php
  function my_module_form($form,&$form_state) {
  $form['name'] = array(
    '#type' => 'textfield',
  );
  $form['company'] = array(
    '#type' => 'textfield',
  );
  $form['phone'] = array(
    '#type' => 'textfield',
  );
  $form['email'] = array(
    '#type' => 'textfield',
  );
  $form['message'] = array(
    '#type' => 'textfield',
  );
  return $form;
  }

```

And in my `template.php` file I wrote this code:

```
<?php
 function mytheme_theme($existing, $type, $theme, $path) {
 $items['my_module_form'] = array(
 'render element' => 'form',
 'template' => 'page--contact-us',
 'path' => drupal_get_path('theme', 'mytheme') . '/template',
  );
  return $items;
  }
  ?>

```

Finally I wrote a single line of code in my `page--contact-us.tpl.php` file to check whether a `name field` is appearing or not:

`<?php print render($form['name']); ?>`.

But nothing is happening on my contact-us page ... Why?

**UPDATED**: I also implemented hook\_menu, here it is:

```
 function form_module_menu() {
 $items = array();
 $items['contact-us'] = array(
 'page callback' => 'drupal_get_form',
 'page arguments' => array('form_module_form'),
 'access callback' => TRUE
 );
 return
 $items;
 }

```

# Answer
When dealing with Form API in Drupal 7 there are two major steps:

# Step 1: Create and implement the form in a module

In this step 1, you will setup the form, and then validate and submit the form, as further detailed below.

## a) Setup the form

```
    function form_example() {
       $form['first_name']=array(
       '#type' => 'textfield',
       '#title' => t('First name'),
       '#description' => t('Enter first name'),
        );
        $form['last_name']=array(
        '#type' => 'textfield',
        '#title' => t('Last name'),
        '#description' => t('Enter last name'),
        );
    $form['submit_button'] = array(
        '#type' => 'submit',
        '#value' => t('Click Here!'),
        );

    return $form;
    }

    function form_example_validate($form, &$form_state) {

    }
    function form_example_submit($form, &$form_state) {

    }

```

## b) Validate and submit the form

Now the form is ready to be displayed.

One way to display the form, is to theme the form in the module and then print the form.

```
function mytheme_theme($existing, $type, $theme, $path) {
   'theme_contact_form' => array (
        'variables' => array(
            'contact_form' => FALSE,
            ),
        'template' =>'theme-contact-form',
    ),
 }
function mytheme_block_info() {
   $blocks['block_contact_form'] = array(
      'info' => t('My Theme Contact form'),
      );
   return $blocks;
}
function mytheme_block_view($delta = '') {
  $block = array();
  switch ($delta) {
  case 'block_contact_form':
        $block['content'] = array(
            '#theme' => 'theme_contact_form',
            '#contact_form' => drupal_get_form('form_example'),
            );
        break;
  }
  return $block;
}

```

Then create `theme-contact-form.tpl.php` in the module file and print the form:

```
<?php print render($contact_form); ?>

```

With all previous steps complpeted, the form is created and implemented in the module.

# Step 2: style the form

To style the form from theme layer, refer to How to a use a template file to theme a form?
> 1 votes

# Answer
You are missing a hook\_menu to define your page.

> This hook enables modules to register paths in order to define how URL requests are handled. Paths may be registered for URL handling only, or they can register a link to be placed in a menu (usually the Navigation menu). A path and its associated information is commonly called a "menu router item". This hook is rarely called (for example, when modules are enabled), and its results are cached in the database.

By having the hook\_menu you can created the path on your website.
> 0 votes

# Answer
Try these working Code

**form\_module.module** contents

```
<?php

function form_module_menu() {
  $items = array();
  $items['contact-us'] = array(
    'page callback' => 'drupal_get_form',
    'page arguments' => array('my_module_form'),
    'access callback' => TRUE
  );
  return $items;
}

function my_module_form($form, &$form_state) {
  $form['name'] = array(
    '#type' => 'textfield',
  );
  $form['company'] = array(
    '#type' => 'textfield',
  );
  $form['phone'] = array(
    '#type' => 'textfield',
  );
  $form['email'] = array(
    '#type' => 'textfield',
  );
  $form['message'] = array(
    '#type' => 'textfield',
  );
  return $form;
}

function my_module_form_submit($form, &$form_state) {

}

function my_module_form_validate($form, &$form_state) {

}

function form_module_theme($existing, $type, $theme, $path) {
  $items['my_module_form'] = array(
    'render element' => 'form',
    'template' => 'page--contact-us',
    'path' => drupal_get_path('module', 'form_module') . '/template',
  );
  return $items;
}

```

AND **form\_module/template/page--contact-us.tpl.php** contents

```
MY FORM CUSTOM
<?php echo drupal_render($form['title']); ?>
<div class="company">
    <?php echo drupal_render($form['company']); ?>
</div>
<?php echo drupal_render_children($form); ?>

```
> 0 votes

---
Tags: forms
---


# Question
Title: How to use Drupal Code Sniffer in windows?
How do you configure and use Drupal Code Sniffer in Windows?

# Answer
> 2 votes
On the project page there are instructions for each IDE.

The one you're after (Eclipse) is here.

In case anyone uses something else, the other instructions are as follows:

Vim, Sublime Text, and Komodo

Netbeans

PHPStorm (install the Codeing Standards globally first, as described here, then Drupal should be available in the list or rulesets.

You won't get this working in Notepad.

On another note, I'd probably also just stop using Notepad. If you must use a basic tool, then Notepad++ is a million times better.

# Answer
> 1 votes
Drupal Code sniffer has been merged into Coder 7.x-2.x! This project is deprecated and bugs should be reported to the coder issue queue.

---

For the installation of coder module here are the useful links

1. Read Coder Module Documentation
2. Installing Coder Sniffer

There are many ways to install Code Sniffer i.e. via Composer, Pear or Drush. Following are the links to firstly install these packages.

1. Composer's installation instructions
2. PEAR's installation instructions
3. Drush's installation instructions

Note: *Coder 7.x-2.x is only compatible with PHPCS 1.x. You need to use 8.x-2.x for PHPCS 2.x.*

As I am using Windows 7. I installed Code sniffer package via pear.

# Answer
> -1 votes
You can try

Drupal API for Dreamweaver

Drupal for Eclipse

---
Tags: 7
---


title: Drupal site is compromised by backdoor

text:
# Question
Title: Drupal site is compromised by backdoor
My Drupal site has been compromised.

Although I applied all modules updates and update my Drupal core to 7.35, it is still compromised.

What would the next logical step to take be?

# Answer
> 4 votes
Sorry to hear that. The steps you should take are as follows:

* If you have drush access, install drupalgeddon by typing `drush dl drupalgeddon`.
* Run `drush drupalgeddon-test`. You will likely find several accounts which you did not create. Remove them.
* Install hacked to find out which (if any) files have been changed.
* Read this article.

---
Tags: views, 7, theming, updating, cron
---


# Question
Title: Upgrading Drupal 7 version from DEV to PROD
I've updated from Drupal 7.22 to 7.34 on my Development Machine along with some Module updates. Now I am going to update my Production environment.

Question: Do I have to upload the entire root directory or can I just upload the Sites folder? I'm assuming I have to upload the entire root directory as this is a Drupal 7 version core update.

P.S. Got the database update stuff covered. P.S.S Would use Drush, but I'm just not comfortable with it yet.

Regards,

John

# Answer
Even thought you said that you are not comfortable with Drush. I would strongly suggest for you to used Drush to update your modules and core. Its just easier and faster. If you decide to give a try you can update modules and core by running.

```
drush up -y

```

If you want to update just the core use `drush up drupal -y`

You can upload a copy of the latest Drupal version on your production website and then replace sites folder with your dev sites folders. And this would take care of Drupal Core updates.
> 1 votes

# Answer
It is always recommended to keep the core up to date. You will have to replace the updated files of the core which were updated with the fixes. For e.g. An update from the Drupal version 7.31 to 7.32, which was a fix for the SQL injection issue, changed the following files

1. `includes/database.inc`, and
2. All the info files in the core modules, themes, and profiles.

So, you would need to update all the files. It is strongly recommended to use a code version control system like git when working with Drupal. So that you only need to push the changes and not the complete code again and again. Also, as @darol100 mentioned in his answer, using drush saves a lot of time! So, I would suggest you to spend some time learning it.

For steps on how to update the Drupal core, refer: https://www.drupal.org/node/1494290
> 1 votes

# Answer
If you have stage environment (which should be exact mirror of your prod), you may upgrade your stage environment first (`drush up` or manually) and then once tested, synchronise the files via `rsync`, in example (when having configured drush aliases):

```
drush rsync -vur @stage @prod

```

---

Here is simple script which will deploy the changes from *qa* to *prod* (including the backup):

```
#!/bin/sh
# Script to deploy files between remote environments by updating the changed files only.
[ -z "$2" ] && { echo Usage: $0 @remote.src @remote.dst; exit 1; }

DIR=$(git rev-parse --show-toplevel 2> /dev/null)
SRC="$1"
DST="$2"

shift
cd $DIR
drush $DST arb --tags=$DST,$USER
if [ $(drush site-alias --fields=host --format=csv $SRC) = $(drush site-alias --fields=host --format=csv $DST) ]; then
  # Remotes are the same.
  drush $* $DST rsync -vur `drush dd $SRC` @self
else
  # Remotes are not the same.
  drush $* rsync -vur $SRC $DST

```

This script will do the full backup (code, files, and database) before deploying your changes to prod (`arb` = `archive-dump`). So if your deployment to prod fails, then you can easily restore it (`archive-restore`).
> 1 votes

# Answer
Here is what I do for the site that I've been working on. I have created a git repo to apply changes from dev to prod. I never work on prod, only dev. When I update something, I add those changes to the git repo with the commands `git add -A && git commit -m "your commit message" && git push origin master`. Then I go to prod's docroot, and type `git pull`. Very convenient. You can find out how to create a git repo on this very useful article.
> 1 votes

---
Tags: 7, updating
---


title: Simple data requests inside of Drupal

text:
# Question
Title: Simple data requests inside of Drupal
So I've done some pretty hacky things with Drupal, one of them being for simple data requests.

For example, say I have a simple form that asks for a registration ID number. This ID number is saved in a non-Drupal table in the same database. All I want my script to do is return whether or not that ID number is valid or whatever operation, but all I need to return is a string of "true" or "false" on an Ajax call that is called when the ID form field is blurred.

We don't have access to modules, so just adding in our own isn't an option, and we run on a multi-site environment, so adding a php file to our themes folder ends up becoming a terribly long string.

One thing I have done in the past is just create a new basic page and then use a php script in the page area to die("true"); but that always just feels so hacky.

My end goal would be to find some way to use drupals router and just print something without building a whole page around it, and I'm not exactly sure how I would be able to go about that.

Edit: also sometimes when I die("some text") in a basic page in Drupal that "some text" will appear in every page in the footer, even on pages where it shouldn't even be getting anywhere near the die("some text"); line. Why does this happen in Drupal?

# Answer
> My end goal would be to find some way to use drupals router and just print something without building a whole page around it

Assuming your question is "how do I do that?", then it's very easy.

Just don't return anything from your page callback, print it instead:

```
function my_page_callback() {
  echo 'This will print to the buffer, but not invoke the page theme wrappers';
  drupal_exit();
}

```
> 3 votes

---
Tags: 7
---


# Question
Title: Taxonomy term custom view page for all sub terms
I have taxonomy called Sections and it has several terms,their children and grand children. How can i set same display page or display format for all the sub section pages irrespective of their depth.

# Answer
https://www.drupal.org/project/tvi

This module will help you for sure :)

Read the documentation at https://www.drupal.org/node/577646
> 0 votes

---
Tags: taxonomy-terms
---


# Question
Title: Entity reference - which side of the relationship is it best to put the field in?
I an adding entity references to an existing site with a lot of data, and I want to make sure I get it right first time. My question is - is it best practice to put an entity reference in the container content type, or in the contained content type? In other words, is it best practice for the entity reference to be in the album content type, or the track content type (also applies to team/team member, book/chapter or whatever)?

In an ideal world these relationships would be in both content types, but that doesn't seem to be built-in and the relevant module (Corresponding Entity Reference) seems to be in Alpha. So what is best-practice?

# Answer
> 2 votes
Where you definitely have a 'container' vs 'contained' relationship, I would say the best way to go is to put the reference field on the **contained** field. If you put the reference field on the *container* then every time you make a new item to be **contained** you have to edit the *container* as well.

Frequently I find that 'containers' end up with many more child objects than were originally intended, putting the reference field on the child object helps keep it manageable.

Also, when you are rendering the content or using it in views, you can use the reverse relationship. So if you have *books* with many **pages** and each **page** references the *book* it belongs to, you could have a view that is based on *books* but also contains information about the **pages**. And yes, that is using CER, so far for me it works quite well.

---
Tags: entities, views
---


# Question
Title: Is it possible to get Entity Connect and Entity Reference View Widget to work together and if so how?
It seems to me this should be a fairly common problem, but I can't seem to find and answer despite looking!

Here is my use case: I have two types of content: Activity and Participants. When I create a new Activity I want to be able to add multiple Participants to the Activity, and allow the user either to pick the Participants from a list of those already in the system, or to create new ones "on the fly".

I'm using an "Entity Reference" field in the Activity content type, to reference one or more Participants

So far, I have managed to do one part of my use case, or the other, but not both at once. Entity Connect works fine and creates a modal window in which I can create a new Participant or modify an existing one. Entity Reference View Widget also works fine, and allows me to create a view which I can then use to multi-select existing Participants. But I can't get both to play together (although the Entity Connect project page suggests it should work). Entity Connect only seems to work with the autocomplete widget, whereas Entity Reference View Widget only works with its own widget (logically!).

Has anyone been able to get these two modules to work nicely together and if so how, or should I be using another combination (References Dialog and something else for example)?

# Answer
This week a patch for both modules was released that may fix the issue (see Can't get Entity Connect to work with Entity Reference View Widget, which also links to the second patch). As of today (23 Mar 14), the patches still need review.
> 0 votes

---
Tags: entities
---


# Question
Title: How to add sidebar to taxonomy page or node page?
Thought a bit more how people use Drupal CMS to update categories. Categories will be taxonomies in a view so that they can refer nodes to the categories.

Also at the most when click on category, it will be either a full taxonomy page or node page.

Sidebar will have taxonomy categories on left column and right column will explain more information. So if it is on same taxonomy, the menu item will be highlighted to let user know where they are on.

The problem is how to add sidebar to either taxonomy page or node page and set menu item active / highlighted?

# Answer
> 1 votes
Normally I'd advocate writing it yourself, but in this case there are modules that do exactly what you want.

Create a block for the taxonomy you want to display and only display it on certain URL's (I'd use the path alias module to create a specific URL for relevant content e.g. '/CONTENT\_TYPE/CONTENT\_TITLE`and test for`/CONTENT\_TYPE/\*\` on the block admin page)

https://www.drupal.org/project/taxonomy\_block

You can use the Menu Trail By Path module to indicate what the active trail should be in the menu.

---
Tags: theming
---


title: Post image via webservices

text:
# Question
Title: Post image via webservices
I tried to create a node through external application using web services. This having only two fields node title and cck field image. i will grateful if anyone share the JSON format to post the images. I tried using format that mentioned below link but its failed means image not uploaded.

https://www.drupal.org/node/2195165

Any one guide me do this.

Thanks..

# Answer
> 1 votes
URL: http://example.com/service\_enpoint/file

Method: POST

file: (file to be uploaded in base 64 encoded format)

filename :plus-box.jpg

uid: 55

The jpg file should be uploaded in base 64 encoded format.

As response you will get a fid , which you will have to pass in the image field while creating the node.

---
Tags: services
---


# Question
Title: How can I check that the file is present in database entry and also in files folder?
I want to write a script where I want to check whether the files are present in files folder of drupal/sites/default/files and is it existing in the database table file\_managed.

```
        $sql=db_query("SELECT * FROM `file_managed` WHERE `filename`LIKE '%.pdf' OR `filename`LIKE '%.doc' OR `filename` LIKE '%.doc' AND `timestamp` < UNIX_TIMESTAMP('2014-01-01')")->fetchAll();

function file_destination($destination, $replace) {

  if (!file_destination($uri, FILE_EXISTS_ERROR)) {
    switch ($replace) {
      case FILE_EXISTS_REPLACE:
        // Do nothing here, we want to overwrite the existing file.
        break;

      case FILE_EXISTS_RENAME:
        $basename = drupal_basename($destination);
        $directory = drupal_dirname($destination);
        $destination = file_create_filename($basename, $directory);
        break;

      case FILE_EXISTS_ERROR:
        // Error reporting handled by calling function.
        return FALSE;
    }
  }
  return $destination;

```

i am not able to find any way to get the fields delete.

# Answer
```
function deleteunrecoredfile()
{
  $results = db_query("SELECT * FROM `file_managed` WHERE `filename`LIKE '%.pdf' OR `filename`LIKE '%.docx' OR `filename` LIKE '%.doc' AND `timestamp` < UNIX_TIMESTAMP('2014-01-01')")->fetchAll();

  foreach ($results as $result) {
        $path =  drupal_realpath($result->uri);
       if(!file_exists($path)) {
          db_delete("file_managed")
              ->condition("fid",$result->fid)
              ->execute();

      }
  }
}

```
> 0 votes

# Answer
You can use `file_destination()` drupal function to check if file already exists in `sites/default/files` with second parameter as `FILE_EXISTS_ERROR`.

```
if (!file_destination($uri, FILE_EXISTS_ERROR)) {
  // The file exist
  // Do something
}

```
> 1 votes

---
Tags: files
---


title: IMCE directory per user

text:
# Question
Title: IMCE directory per user
I'm working on a scenario where users should not be able to access others' files. So, I wrote a custom module that creates a folder names user's name, then I went on to /admin/config/media/imce to set permissions and I typed `php: return 'users/'.$user->name` as instructed on the same page. However, that gives me `Parse error: syntax error, unexpected end of file in DRUPAL_ROOT/sites/all/modules/imce/inc/imce.page.inc(789) : eval()'d code on line 1` and `There is no valid directory specified for the file browser!`. What to do? Any suggestions?

# Answer
Its a syntax error, generated because you're missing some parenthesis or other required syntax. Do you have a semicolon at the end of return 'users/'.$user-\>name? Should be: `'users/'.$user->name;`
> 0 votes

---
Tags: 7, files
---


title: Theming user pictures

text:
# Question
Title: Theming user pictures
Trying to theme user pictures, in the following statement:

```
 print '<a href="' . $base_url . '/user/' . $friend_id . '" ><img src="' . _drupal_wall_user_profile_picture($friend_id) . '" width="32px"></a>';

```

How do I replace the *"width="32px"* by the "thumbnail" image style?

Thanks. :)

# Answer
> 1 votes
You need to (really should) use a render array. You can use theme\_image\_style:

```
// first, make a render array for your image, as a thumbnail...
$image_ra = array(
    '#theme' => 'image_style',
    '#path' => _drupal_wall_user_profile_picture($friend_id),
    '#alt' => 'Some alt value',
    '#title' => 'Some image title value',
    '#style' => 'thumbnail'
);

// now make your link render array...
$ra = array(
    '#theme' => 'link',
    '#text' => drupal_render($image_ra),
    '#path' => $base_url . '/user/' . $friend_id,
    '#options' => array(
        'html' => TRUE,      // this says the #text value is HTML markup
    )
);

// now you can render your image link into markup...
$image_markup = drupal_render($ra);

```

I took the long way to show you that you need to handle the image first, and then render it as #text in the link. I also did this to make the case that you really, really, really, really should use render arrays and stay away from writing the HTML. Let Drupal do that work. Just build a render array, pass it to drupal\_render, and be done with it.

# Answer
> 0 votes
As per **Drupal coding standards**, you should not create links this way or render image this way. Use this code instead. For now I am using global (logged in) user, if you have to pass a friend user, load that user and follow the below approach.

```
global $user;
$file_user_picture = file_load($user->picture);
print l(theme('image_style', array(
  'path' => $file_user_picture->uri,
  'style_name' => 'thumbnail'
)), 'user/' . $user->uid, array('html' => TRUE,));

```

---
Tags: media
---


# Question
Title: Force access denied on 'admin/structure/menu' for everyone except admin
I need to write a "simple" feature in custom module which returns access denied for all the users except admin who tries to rich 'admin/structure/menu'. I've tried with hook\_page\_alter, hook\_page\_build and also with hook\_menu\_alter, but none of those functions work. Function hook\_menu\_alter is caching menus so it sets flag:

$items\['admin/structure/menu'\]\['access callback'\] = FALSE

to all users and I (as admin) can't see this page also. Any help?

# Answer
Menus are cached, but decision making functions aren't. So what you need is:

```
function MYMODULE_menu_alter(&$items) {
  $items['admin/structure/menu']['access callback'] = 'MYMODULE_menu_admin_access';
}

function MYMODULE_menu_admin_access() {
  return $GLOBALS['user']->uid == 1; // Or whatever makes most sense for your use case.
}

```
> 2 votes

---
Tags: 7, routes, hooks, theming
---


# Question
Title: How to convert a Drupal website to standalone exe file?
I'm trying to convert my Drupal website to a standalone .exe file. I tried some popular applications like ZZEE PHPExe or ExeOutputPHP, `ZZEE PHPExe` returns the error that `/includes/boostrap.inc` is not found in the output directory, while I copied that folder in there. The `ExeOutputPHP` errors `File not Found` and nothing else! it doesn't even tell me what file is not found!

Any suggestion to convert Drupal website to standalone exe file?

# Answer
> 1 votes
You should generate a static copy of your site first.

For that you can either use a module like the static module, or just "copy" your entire site with wget or curl.

So for example you can do something like this :

```
wget -p --convert-links http://localhost/ -P ~/site_static_copy

```

(This assumes that you're accessing your localhost with http://localhost/ and that you want to copy under your ~/site\_static\_copy directory )

Once you've done that you'll be able to package the copy with the tools you mention.

# Answer
> -2 votes
I will suggest you to create the profile for your site and then you just need to install it all the time whenever you needed.

---
Tags: 7
---


title: Menu function of urls

text:
# Question
Title: Menu function of urls
I know how to use Drupal's Menu and how to manage rights to access them function of profiles but I need to show secondary menu function of urls. For example: \- A partner menu is only shown in page where url starts with /partners/ \- This partener menu becomes beneficiary if url starts with /beneficiary.

Do you idea how can I manage it ? I cannot usse session :-(

Thank you.

# Answer
> 1 votes
Try to use any of these modules. I hope any of these modules solve your issues :

1. NodeSymlinks

> This is useful when you want to have the same page reachable though multiple menu items, each with its own URL, menu trail and breadcrumb path.

2. Menu Trail By Path

> Menu Trail By Path sets the active-trail on menu items according to the current url.

---
Tags: routes
---


# Question
Title: modal window "loading" not loading in SCALD
I'm working on a site using SCALD – and for some reason the modal media upload window does not work anymore. It's stuck with the status "loading…" but not going anywhere.

I first had it running like a charm – then I 'just' wanted to add multi-language support to the website adding i18n… Then when I checked again on SCALD this is all I get:

**Firebug console** is showing the following two messages:

`Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience. For more help xhr.spec.whatwg.org ...A.onload=A.onreadystatechange=null;r&&A.parentNode&&r.removeChild(A)}}}r.insertB…" (jquery.js?v=1.4.4 line 139)`

and

`uncaught exception: The editor instance "edit-body-und-0-value" is already attached to the provided element.`

**Firebug network:** "POST ajax 200 OK"

So for what I can see from other modules ajax is up and running. Checking on other forum questions here on drupal-stackexange concerning modal window problems didn't help yet – so I just hope somebody has some pointers that would direct me in some direction… ThankYou!

–EDIT- manual upload (atom/add/image) works and also using the SCALD library incl. drag'n'drop works fine. Just opening the modal dialogue either through "add" or "edit" form the SCALD sidebar does not load.

PS: not using the jQuery update module

# Answer
Fixed it: the problem was that after going through the SCALD installation process the CKEditor was activated and the plugins declared in two locations:

1. under WYSIWYG Profiles
2. under CKEditor Profiles

This also corresponds with the error message I had in FF console:

```
uncaught exception: The editor instance "edit-body-und-0-value" is already attached to the provided element.

```

I simply deleted the WYSIWYG Profile and the problem was gone – modal window loading as it should. The detailled documentation of the process finding the error can be found over here: https://www.drupal.org/node/2454845#comment-9749453
> 1 votes

---
Tags: ajax, javascript, scald
---


title: Ckeditor image center alignment option

text:
# Question
Title: Ckeditor image center alignment option
Does anyone know how to include a center alignment option for images in ckeditor?

The image below shows what I see:

# Answer
> 0 votes
Should be possible using the 'new' image plugin "Enhanced Image" which relies on the powerful widget plugin, introducing the Widget API and its capability of handling 'templates' within CKEditor.

PS: See also this discussion about centering images with CKEditor. And here you can customize your CKEditor build with different plugins etc.

# Answer
> 0 votes
The standard ckeditor alignment just adds a CSS float left or right, there is no float:center in css. You could add the plugin to ckeditor and that will give you more options.

A plugin is being worked on for this at the moment. You could download the beta and give it a shot. It goes in the

http://dev.ckeditor.com/ticket/10659

You'll need to install the plugin and add some javascript to make it work. There's another post here that shows the process for the justify plugin: https://stackoverflow.com/questions/14782152/inline-ckeditor-toolbar-has-no-alignment-buttons-for-h2-elements/14810988#14810988

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


# Question
Title: Creating a Date Field that will display 'Year' to 'Current'
I want to create a field that will ask the user for the date they started their job to when they left. If they are still currently working at the job, the user will click 'I currently work there' or something similar. The date module currently can be setup to have a 'to' and 'from' field. The tricky part is how do I save 'Current/Present' to the database. How do I go about this?

# Answer
> 6 votes
This is doable using Conditional Fields despite its rather minor limitation (http://drupal.org/node/360824). You can't trigger fields' display by a checkbox's off value. That will require you to negate the *"I currently work here"* checkbox to something like *"Past position"*. You can still decide if you want it checked by default or not, and using JavaScript you can hide the *"Past position"* checkbox and control its value using the desired checkbox with the opposite meaning.

Saving 'Current/Present' to the database is not an issue really. You only need to check the value of the checkbox field and you can disregard the 'Current/Present' value if this is an ongoing position. To make the *To date* field work as expected, though, make it *Required* and choose an arbitrary *Default value* for it, which will be used even when the field is not displayed. *Now* would be a good bet.

Here's an image which pretty much wraps up the 5 minute content type setup.

It's obviously going to take a little more than that to make the form look and behave the exact way you want. For information on theming the resulting form, see Theming a form with conditional fields.

Also see Conditional Fields Docummentation

# Answer
> 4 votes
I would create 2 date fields to reproduce the "to-from" behavior of date: `field_job_start` and `field_job_end`. Then I'll create the checkbox and make it control `field_job_end` using Conditional Fields so that if it's checked `field_job_end` disappears.

Then a little theming for the node to show `field_job_start to present` if the checkbox is checked or `field_job_start` to `field_job_end` if not. You can also create this with a computed field.

# Answer
> 3 votes
I see two options...

1) You don't have to save "current/present" in your database. You can just determine if there's a "to" date on the Date field. If there isn't, they still work there. If there is a value for "to", then they don't still work there. That way you're just storing the date field instead of creating another field for "current/present". You can still use Conditional Fields for controlling whether the "to" part of the date is enabled or not.

2) Use that "I currently work here" check box (which can easily be created using a field, you probably already are) as your check for whether they currently work there. If the field is already in your form, go ahead and use it!

# Answer
> 0 votes
I am not fully aware of how to achieve this, but I am wondering if the CCK Select Other module might help.

# Answer
> 0 votes
@Jan Tomka has a great answer. Allow me to share an alternative and simpler solution that I used:

Install String Overrides to change the text "Show End Date" to "I no longer work here."

The downside of this approach is that it changes it site-wide, for all date fields. However it may be preferable to the conditional fields approach.

---
Tags: entities
---


title: node information and messages

text:
# Question
Title: node information and messages
I created a user login page, and used the login destination module to redirect my user to a new "front page" I created using views.

On this "front page" I call all the nodes created by the logged in user, so a user can see newly created nodes.

My question is, how do I call a message or view which tells my user when a node has been deleted or edited? This "front page" acts as a 'notification wall', which the user can see everything that is added or edited. It will become more complex later where admins will be able to edit user nodes. So I need to let the user know when he/admin has edited or deleted a node.

# Answer
> 0 votes
For long term logging of activities on a website to show on a wall look at Message module. It helps to support the idea of an *Activity Stream* on a site.

> The Message module is the core of the message stack. It enables logging and displaying system events in a number of different use cases. Events that are recorded over time are sometimes call activity streams. Exportable messages subtypes can be created for different use cases with custom fields and display (view) modes.

# Answer
> 0 votes
You can used Rules, and/or Views Rules.

Here is the rule that you need to created:

1. **Event:** When a node from a content have been delete or updated.
2. **Condition:** based on role.
3. **Action:** message display if a node from an specific content type have been remove or updated

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


# Question
Title: Any way to alter script tag for some javascript and add custom attributes?
In order to work with Cloudflare's Rocket Loader service, certain scripts need to have their script tags updated with the cf-async="false" attribute like so:

```
<script type="text/javascript" cf-async="false">

```

Specifically, I need to add this attribute to the Drupal settings script tag, that gets added inline at the top of every page.

My first thought was to do this via hook\_js\_alter(), like:

```
function custom_helper_js_alter(&$javascript) {
  $javascript['settings']['cf-async'] = 'false';
}

```

But it doesn't seem to be possible to add custom attribute tags via this function. So my question is, is there any way at all to do what I want without hacking core?

# Answer
There is, but it's not pretty. The markup produced by `drupal_get_js()` is pretty closed off; it uses `theme_html_tag()`, but what it provides for variables means identifying the Drupal.settings script is a pain.

This is about as good as you'll get. In custom module:

```
function MYMODULE_preprocess_html_tag(&$vars) {
  if ($vars['element']['#tag'] == 'script' && strpos($vars['element']['#value'], 'jQuery.extend(Drupal.settings') === 0) {
    $vars['element']['#attributes']['cf-async'] = 'false';
  }
}

```

As you rightly mentioned through the comments you could also attack it at the theme override level instead of the module level. In template.php:

```
function MYTHEME_preprocess_html_tag(&$variables) {
  if ($variables['element']['#tag'] == 'script' && strpos($variables['element']['#value'], 'jQuery.extend(Drupal.settings') === 0) {
    $variables['element']['#attributes']['cf-async'] = 'false';
  }
}

```

If you have modules that mess with JavaScript (e.g. LabJS), the string match will be slightly different.
> 4 votes

---
Tags: 7, javascript
---


# Question
Title: How do I get all the users in an organic group with specific role programatically?
I'm trying to use rules to send an email to all users with a specific role in an organic group when someone requests to join the group.

This code almost works. It returns all users from a specific group ($GID) with the specified role ($RID), but it doesn't restrict the role to that group. In other words, if they have the appropriate role in another group, they're included in the results.

```
$current_members = db_select('og_membership', 'om');
$current_members->join('og_users_roles', 'ogur', 'om.etid = ogur.uid');
$current_members->condition('om.gid', $GID);
$current_members->condition('om.entity_type', 'user');
$current_members->condition('ogur.rid', $RID);

$result = $current_members->execute();
while ($res = $result->fetchAssoc()) { $members[] = $res['etid']; }

// Remove duplicate items.
$members = array_keys(array_flip($members));

```

What do I need to change to restrict the results so that it only returns users with the specified role ID within the specified group?

# Answer
It's just a simple sql query, no joins needed:

ie. select uid from og\_users\_roles where rid=3 and gid=835;

```
  $members = array();
  $current_members = db_select('og_users_roles', 'ogur');
  $current_members->fields('ogur', array('uid'));
  $current_members->condition('ogur.rid', $rid);
  $current_members->condition('ogur.gid', $gid);

  $result = $current_members->execute();
  while ($res = $result->fetchAssoc()) { $members[] = $res['uid'];}

  // Remove duplicate items.
  $members = array_keys(array_flip($members));

```
> 1 votes

---
Tags: 7, rules, organic-groups
---


# Question
Title: Best way to allow multiple users to edit a node but require approval?
I am looking for a way to allow multiple "normal users" to suggest changes to existing nodes, but only once they are approved by admin, should they take effect. I am not sure how this would work in the case where multiple users make changes, but if stackoverflow and drupal stack exchange can do it, I'm sure it must be possible.

I had a look at Node Changes, but its not technically ready. Is that the only option available to me?

# Answer
> 1 votes
You can look into the revisioining module

Revisioning is a module for the configuration of workflows to create, moderate and publish content revisions. You can set the role based permision for create , edit, view and delete revision of a content.

---
Tags: nodes
---


# Question
Title: How to add tracking scripts from external sites?
We want to use several lead tracking snippets of code on various pages.

```
<script type="text/javascript">llfrmid=123456</script>
<script type="text/javascript" src="https://formalyzer.com/formalyze_init.js"></script>
<script type="text/javascript" src="https://formalyzer.com/formalyze_call_secure.js"></script>

```

...I can use drupal\_add\_js() but it seems to want to wrap the first line in --CDATA-- and I'm unclear if that makes a difference.

I came across this post: How to add script to \<head\>?. Is that accepted answer still recommended for D7? ie. just concatenating text to the header with drupal\_get\_html\_head() Or is there a way to use drupal\_add\_js so it does not wrap the text in --CDATA--?

TIA

# Answer
You can add the JavaScript on the theme level. You added on `template.php` or any other template that you wish to appear the javascript.

An example is a little bit tricky because is all depend on how the theme is was created. But I can provide an example base on my theme.

I'm using a sub-theme base on Boostrap so on my page.tpl.php I would add the JS on the bottom. So your goal would be to find the footer region and add the JS below that.

```
<?php

?>
<header id="navbar" role="banner" class="<?php print $navbar_classes; ?>">
  <div class="container">
  <div class="col-md-3">
</div>
    <div class="navbar-header">
      <?php if ($logo): ?>
      <a class="logo navbar-btn pull-left" href="<?php print $front_page; ?>" title="<?php print t('Home'); ?>">
        <img src="<?php print $logo; ?>" alt="<?php print t('Home'); ?>" />
      </a>
      <?php endif; ?>

      <?php if (!empty($site_name)): ?>
      <a class="name navbar-brand" href="<?php print $front_page; ?>" title="<?php print t('Home'); ?>"><?php print $site_name; ?></a>
      <?php endif; ?>

      <!-- .btn-navbar is used as the toggle for collapsed navbar content -->
      <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
        <span class="sr-only">Toggle navigation</span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
      </button>
    </div>

    <?php if (!empty($primary_nav) || !empty($secondary_nav) || !empty($page['navigation'])): ?>
      <div class="navbar-collapse collapse">
        <nav role="navigation">
          <?php if (!empty($primary_nav)): ?>
            <?php print render($primary_nav); ?>
          <?php endif; ?>
          <?php if (!empty($secondary_nav)): ?>
            <?php print render($secondary_nav); ?>
          <?php endif; ?>
          <?php if (!empty($page['navigation'])): ?>
            <?php print render($page['navigation']); ?>
          <?php endif; ?>
        </nav>
      </div>
    <?php endif; ?>
  </div>
</header>

<?php if ($page['Featured']): ?>
  <div class="BannerColor">
    <?php print render ($page['Featured']); ?>
  </div> <!-- /. Featured -->
<?php endif; ?>

<div class="main-container container">

  <header role="banner" id="page-header">
    <?php if (!empty($site_slogan)): ?>
      <p class="lead"><?php print $site_slogan; ?></p>
    <?php endif; ?>

    <?php print render($page['header']); ?>
  </header> <!-- /#page-header -->

  <div class="row">

    <?php if (!empty($page['sidebar_first'])): ?>
      <aside class="col-sm-3" role="complementary">
        <?php print render($page['sidebar_first']); ?>
      </aside>  <!-- /#sidebar-first -->
    <?php endif; ?>

    <section<?php print $content_column_class; ?>>
      <?php if (!empty($page['highlighted'])): ?>
        <div class="highlighted jumbotron"><?php print render($page['highlighted']); ?></div>
      <?php endif; ?>
      <?php if (!empty($breadcrumb)): print $breadcrumb; endif;?>
      <a id="main-content"></a>
      <?php print render($title_prefix); ?>
      <?php if (!empty($title)): ?>
        <h1 class="page-header"><?php print $title; ?></h1>
      <?php endif; ?>
      <?php print render($title_suffix); ?>
      <?php print $messages; ?>
      <?php if (!empty($tabs)): ?>
        <?php print render($tabs); ?>
      <?php endif; ?>
      <?php if (!empty($page['help'])): ?>
        <?php print render($page['help']); ?>
      <?php endif; ?>
      <?php if (!empty($action_links)): ?>
        <ul class="action-links"><?php print render($action_links); ?></ul>
      <?php endif; ?>
      <?php print render($page['content']); ?>
    </section>

    <?php if (!empty($page['sidebar_second'])): ?>
      <aside class="col-sm-3" role="complementary">
        <?php print render($page['sidebar_second']); ?>
      </aside>  <!-- /#sidebar-second -->
    <?php endif; ?>

  </div>
</div>
<footer class="footer container">
  <?php print render($page['footer']); ?>
    /**
        Load Custom JS
    **/
  <script type="text/javascript">llfrmid=123456</script>
 <script type="text/javascript" src="https://formalyzer.com/formalyze_init.js"></script>
 <script type="text/javascript" src="https://formalyzer.com/formalyze_call_secure.js"></script>
</footer>

```
> 0 votes

---
Tags: 7, javascript
---


# Question
Title: How can I limit Webform submissions by date
I want to have a select list on the webform node with options to decide how many times each user may submit the form. for example once a day, once a week, once a month... How can I do it? Thanks!

# Answer
Download Webform 7.x-4.0-beta3

On the Webform \> Form Settings, half way down the page you can set the total submissions limit, and set time frames for limitations.
> 3 votes

# Answer
On the webform configuration you can set it up on **Per User submisstion.** Here is image with an example.

To find the configuration page `/node/[nodeid]/webform/configure`
> 0 votes

---
Tags: webforms
---


# Question
Title: How to allow only certain users access to certain fields of a node?
I have product information on my site. Only some users can view pricing for certain suppliers. So each product has a supplier field, which is a node entity reference to an instance of a "supplier" content type.

When User A logs in, who only has access to Products Offered by Supplier B, he must only see the "cost price" of items that he is linked to. This link is currently accomplished using a Profile Field, which is private and set by administrators.

What is the best way to now restricting users based on this relationship. The end result would be that certain users see the full node with the cost price, while others will see everything except the cost price.

How can I get this right?

# Answer
> 0 votes
I needed to override hook\_field\_access. This is the only way I could easily create custom code that checks the current entity and compares it to a profile field of a user. And seeing as the entire entity is passed along, there is no need to do further node\_load queries. I.e. It's pretty fast!

# Answer
> 1 votes
Install Field Permission module. In this module you can set permission on every filed of content types for different roles.

---

You can also modify hook\_field\_display\_alter to check for the user and the field id and see if the user is allowed or not. you should copy this in to your template file.

---
Tags: users
---


title: What's the Drupal equivalent of Sentry?

text:
# Question
Title: What's the Drupal equivalent of Sentry?
I use getsentry for my Django deployments. It's awesome for automatically emailing me when a user experiences a bug in the code, and sending me the stack trace for any exceptions that occur.

Does Drupal have anything equivalent? I've seen the Drupal Sentry plugin but it doesn't look like it's under active development.

What's the best way of monitoring bugs in production for Drupal?

# Answer
You can use New Relic.

> **Database performance**
>
> Viewing slow SQL queries is a breeze. Most Drupal sites rely heavily on Views and CCK which can generate non-optimal SQL queries. New Relic allows you to quickly pinpoint these types of queries.
>
> **Modules Monitoring**
>
> You can identify which modules are slowest by call count or by slowest call time. This may help you identify which modules may be running rogue within your application.
>
> **Apdex**
>
> New Relic uses Apdex scoring to help you evaluate how well your Drupal application is performing for your end-users according to an industry-standard measurement. This helps you provide better data as well as have a clearer understanding of what percentage of your users are frustrated or satisfied. Apdex scoring also provides more specific context than a general “the site is slow” complaint that may not even get to you until hours after the incident. Apdex also gives you a more objective way to measure your end-users’ experience with your performance improvements.
>
> **Function Performance**
>
> Using Web Transaction Traces, you can see which functions are the slowest in your application. You can use this to identify slow functions in custom modules you have written, or to track delays in your application caused by community module functions that do things like authenticate with third-party systems.
>
> **Front-end performance**
>
> All that wonderful flexibility within blocks, views, and panels can sometimes result in complex page renderings that need to be processed by the browsers of your end-users. New Relic’s Real User Monitoring (RUM) will actually gather timing information and show you which hotspots in DOM rendering time may be causing your page to take several seconds to load.
> 1 votes

# Answer
AppDynamics has a similar tool to New Relic that allows introspection of a running php application with detailed reports and exceptions.
> 1 votes

---
Tags: 7
---


# Question
Title: Modules appear to install, but don't show up
I'm trying to install new modules via the url installer and uploader. I supply my sftp credentials. It says everything is fine. Then it says my module was installed successfully. However the new module doesn't show in the listing and it isn't in the sites/all/modules folder. What could I be missing?

# Answer
I found the problem. In CentOS 7 my system is using systemd. By default systemd has `PrivateTmp=true` Because of this apache wasn't able to see the files that were uploaded via sftp so they couldn't copy them to the modules folder. I had to disable this. On my system that meant editing `/usr/lib/systemd/system/httpd.service` change 'PrivateTmp' to false. Save. Run `systemctl daemon-reload`. Then `systemctl restart httpd.service`.
> 0 votes

# Answer
We had this problem recently with a Centos server. If this is your scenario try

`# chcon -Rv --type=httpd_sys_content_t ./sites/all/modules`

From `man chcon` change security context, recurse, verbose, type is web content.

Note. Probably a good idea to check what type the files that *are* working are first.

`$ sudo ls --lcontext google_analytics/
-r--r--r--. 1 unconfined_u:object_r:httpd_sys_content_t:s0 apache apache 31504 Jan 15 14:41 googleanalytics.admin.inc`
> 0 votes

---
Tags: 7
---


title: Change date format in forum

text:
# Question
Title: Change date format in forum
Is there a way to change the date format in main forum table? I changed the date format in views for topic list, but the date format wasn't changed on main forum page

# Answer
What I did to change the date format. In modules/advanced\_forum/includes/theme.inc I found the function advanced\_forum\_preprocess\_forum\_submitted(&$variables) and changed line 249 to `$cutoff = variable_get('advanced_forum_time_ago_cutoff', 0) * 60 * 60;` and line 254 - to `$variables['date_posted'] = format_date($timestamp, 'custom', 'j M Y, G:i');`
> 1 votes

# Answer
You generally don't want to edit Core or contributed modules but instead make a module that implements a hook to get your changes to work without effecting your ability to update.

To make this change I created a custom date format via the UI in Drupal 7 at 'admin/config/regional/date-time/formats'

Then I set my module's weight to 1 higher than the advanced forum module's weight in the drupal\_system table via direct database manipulation. This allows your module's hook to run after the advanced\_forum module's hooks.

I then added a function to a custom module that implements hook\_preprocess\_HOOK

```
/**
 * Implements hook_preprocess_HOOK().
 *
 * Changes date format for latest posts on forum listing page "/forums"
 *
 * requires module to be set as higher weight than the advanced_forum module (default 15) in drupal_system
 * this module must be set to weight 16 to make sure the preprocess functions happen after advanced_forum
 */
function forum_enhancements_preprocess_forum_submitted(&$variables) {
  if (isset($variables['topic']->created)) {
    $timestamp = $variables['topic']->created;
    $interval = REQUEST_TIME - $timestamp;
    $variables['time'] = format_interval($interval);

    // For items posted more than $cutoff hours ago, offer an actual date.
    $cutoff = variable_get('advanced_forum_time_ago_cutoff', 48) * 60 * 60;
    if ($interval > $cutoff) {
      $variables['date_posted'] = format_date($timestamp, 'forum');
    }
    else {
      unset($variables['date_posted']);
    }
  }
}

```
> 1 votes

# Answer
You can accomplish this task in multiple ways. The easier is to override forum-list.tpl.php or forum-topic-list.tpl.php and change the date format directly from the template file.
> 0 votes

# Answer
In order to change date format for main forum table, you need to override `template_preprocess_forum_list` by placing it in your Drupal custom theme or Drupal custom module

```
function MODULE_NAME_OR_THEME_NAME_preprocess_forum_list(&$variables) {
  foreach ($variables['forums'] as $id => $forum) {
    $variables['forums'][$id]->last_reply = format_date($forum->last_post->created);
  }
}

```

For more details check Drupal formate\_date
> 0 votes

# Answer
One thing you should keep in mind while working with Drupal is that you should Never hack Core and its features. You should not be looking at a way to change the date format in table, instead, you should be looking towards a way to manipulate the template where you need to show.

Currently, you should change the way it is shown while rendering in the template file.
> 0 votes

---
Tags: 7, nodes
---


# Question
Title: What to do when you can't upgrade modules?
I have some old sites running "dead" versions of modules in my drupal (I made the upgrade to the last current Drupal core version).

But some of the modules used in this site are not longer supported or they need a "major" upgrade. This will break my site for sure, because some of them are used.

What do you think it's the best approach to fix this ? Because this represents a serious risk for the security of the website.

# Answer
> 2 votes
Major upgrades of modules should not be a problem if the module is still supported. Just do `drush up moduleshortname` in the CLI (or replace the old code in the module directory with the new if you don't have *drush*). Updating a module is integrated in Drupal. If you do this manually (*drush* will do it automatically) just make sure you run *Update* on your site after updating the module (*Update* is linked to on *Reports-\>Status Report* page if you need to run it). *Update* should take of *all* incremental updates of the module, its schema, and the data in the schema, automatically. Unless there are a bug in the code to update the module, there should be no data loss.

Modules that are no longer supported, especially if they're unsupported because they have security vulnerabilities the maintainer did not fix, are a problem.

The first thing to do is to review the unsupported module and the features it brings to your site. Is this features your site cannot live without? If the answer is "no", just disable and uninstall it.

If the unsupported module provides functionality you need, try to find some supported replacement for each unsupported module. If you find a replacement, you need to migrate all data from the old unsupported module to the new one. If you're not a developer, you may need to hire a consultant to help you with migration.

If you don't find a replacement, and you *are* a developer, you may consider fixing the insecure module. If you follow the process for dealing with unsupported projects, and work with the security team, you should be able to fix the problem. The security team is a helpful bunch and may provide some guidance.

As a last resort, you may hire a consultant to fix an insecure module you absolutely need, forking the result as a *custom module* for your site.

As already described by *Darvanen*, you need to do all this on a development server first and only repeat the procedure on your production server when you're sure the update did not damage anything. And make a backup before you start, just in case.

# Answer
> 1 votes
It sounds like you don't have a development copy of your site...

1. Always have a development copy of your site where you can try things out. VirtualBox is a very good tool to generate your development environment, using Ubuntu and Lazy Dubuntu or a direct mirror of your production environment (for instance, the web host I use only supports CentOS instances).
2. Before you start each upgrade procedure, take a snapshot of your virtual server, it can be rolled back quite easily and means you don't have to start from scratch if you break things.
3. Upgrade the modules one by one, starting with the one you feel is least secure.

Note that a vulnerability in core won't necessarily be replicated in modules, so if they're relatively simple and no longer maintained, they could well be safe. If you're concerned, look at their code and think about what they do: if they require user input make sure any database writes are properly parsed; if they connect to an external service ensure that they're still following best practice.

I'm sure there's plenty more to be said on this topic but this is a start.

---
Tags: 7, updating
---


# Question
Title: How do I create an AJAX callback to Drupal video link?
We have a number of videos which are hosted locally and are simple HTML5 video tags. We want to keep track of play clicks. So to be clear, we don't want to track clicks on the URL, we want click tracks on the video tag.

So I want to write a little jQuery() to get the onclick() and then call a Drupal function to update a Drupal entity to store the # of clicks and their source.

I've written AJAX in other environments (PHPBB, Wordpress) but not Drupal. I guess I'm looking for a 'starter kit' which demonstrates interfacing Drupal CRUD functions with js.

# Answer
You need a route and callback defined in a hook\_menu. Below is a kickstarter not a complete example ;)

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

  // an endpoint to add an entity to the default flag_list
  $items['node/%/play'] = array(
    'page callback' => 'example_module_video_count',
    'page arguments' => array(1),
    'access callback' => 'user_access',
    'access arguments' => array('access content'),
    'type' => MENU_CALLBACK,
    'delivery callback' => 'ajax_deliver',
  );
  return $items;
}

```

Here is the callback

```
function example_module_video_count($nid = NULL) {
    /* do you stuff */
    $node = node_load($nid);
    $commands = array();
    /* add some ajax commands if required, look at ajax_command_invoke */
    return array('#type' => 'ajax', '#commands' => $commands);
}

```

Hit the URL from jQuery.ajax()

```
$.post("/node/1/play", function(data) {});

```
> 1 votes

---
Tags: 7, ajax
---


# Question
Title: Problem with images on a slideshow of product displays (Views Slide, Flexslider)
Kind of a strange problem with trying to make a slide show of my product displays. I am creating a slideshow from content of type product display (ordered by newest first). The issue I have is that adding the fields Content: Image, Content: Product Image, or Field: Product Image doesn't load an image. I get asked about image styling, so clearly drupal knows that it's an image. I wouldn't think that I would need to add a relationship, because I have almost an identical view elsewhere that readily brings in the images. So can someone set me straight here?

# Answer
> 0 votes
I added a relationship to "Content: Referenced Product" and this solved the issue. For anyone who is new to Drupal, it isn't obvious that this is (field SKU), but this is how to link back to the content in the Product Nodes in commerce.

---
Tags: commerce, views, javascript
---


title: Data not being visible in CSV file

text:
# Question
Title: Data not being visible in CSV file
I am trying to open .csv file but when I open it Iam not getting any data but only getting headers.

> The below is the module file for that particular csv file.The file getting downloaded but when I open the file only headings being visible but not the data.

```
<?php

define('BIOTWEAKS_AU_ONLY_SETTINGS', 'a:6:{s:4:"view";a:4:{i:0;i:5;i:1;i:7;i:2;i:4;i:3;i:3;}s:8:"view_own";a:2:{i:0;i:5;i:1;i:3;}s:6:"update";a:1:{i:0;i:3;}s:10:"update_own";a:1:{i:0;i:3;}s:6:"delete";a:1:{i:0;i:3;}s:10:"delete_own";a:1:{i:0;i:3;}}');
define('BIOTWEAKS_NZ_ONLY_SETTINGS', 'a:6:{s:4:"view";a:4:{i:0;i:5;i:1;i:7;i:2;i:6;i:3;i:3;}s:8:"view_own";a:2:{i:0;i:5;i:1;i:3;}s:6:"update";a:1:{i:0;i:3;}s:10:"update_own";a:1:{i:0;i:3;}s:6:"delete";a:1:{i:0;i:3;}s:10:"delete_own";a:1:{i:0;i:3;}}');

function biotweaks_menu() {
  $items = array();

  $items['admin/upload-product-csv'] = array(
      'title' => 'Upload product CSV file',
      'page callback' => 'drupal_get_form',
          'page arguments' => array('biotweaks_form'),
      'access arguments' => array('access content'),
      'type' => MENU_CALLBACK
    );

  $items['admin/upload-product-csv-download'] = array(
    'page callback' => 'biotweaks_product_csv_download',
    'access arguments' => array('access content'),
    'type' => MENU_CALLBACK
  );

  return $items;
}

function biotweaks_perm() {
    return array('true');
}

function biotweaks_form() {
    $form['description'] = array(
        '#type' => 'markup',
        '#value' => t('Please make sure that the CSV file you upload is in the right format with the columns in the correct order. If you are unsure, please contact the website administrator.'),
    );
    $form['download'] = array(
        '#type' => 'markup',
        '#value' => '<p><a href="/admin/upload-product-csv-download">Download a CSV of the current products</a></p>',
    );
    $form['csv'] = array(
        '#type' => 'file',
        '#title' => 'CSV file',
    );

    $form['#attributes'] = array('enctype' => "multipart/form-data");

    $form['submit'] = array('#type' => 'submit', '#value' => t('Upload CSV') );
    return $form;
}

function biotweaks_product_csv_download() {

    $fpath = '/home/biolab/public_html/';
    $fname = 'products.csv';

    $output_file = true;

    if ($output_file) {
        $fp = fopen($fpath.$fname, 'w');
    }

    $header = array('Product Code', 'Product Description', 'Size', 'Pallet Qty', 'DG Class', 'Category ID', 'Category Name', 'Subcategory Name', 'Subsubcategory Name', 'AU Case Price (ex. GST)', 'AU Price List 21', 'AU Price List 22', 'AU Price List 23', 'AU Price List 24', 'AU Price List 25', 'AU Price List 26', 'AU Price List 27', 'NZ Case Price (ex. GST)', 'NZ Price List 21', 'NZ Price List 22', 'NZ Price List 23', 'NZ Price List 24', 'NZ Price List 25', 'NZ Price List 26', 'NZ Price List 27', 'Image directory', 'Image filename');

    if ($output_file) {
        fputcsv($fp, $header);
    }

    $q = db_query('SELECT fid, price from {uc_fees}');
    global $fees;
    $fees = array();
    while ($r = db_fetch_array($q)) {
        $fees[] = $r;
    }

    function get_fee($fid) {
        global $fees;
        foreach ($fees as $fee) {
            if ($fid == $fee['fid']) {
                return $fee['price'];
            }
        }
        return 0;
    }

    $sql = "SELECT  n.status, n.nid,  n.title, tn.tid, ucp.model, ucp.sell_price,  upp.price,  ca.settings FROM  {uc_products} as ucp,  {term_node} as tn,  {node} as n left join {uc_price_per_role_prices} as upp on n.nid = upp.nid left join {content_access} as ca on n.nid = ca.nid   WHERE  ucp.nid = n.nid and  n.nid = tn.nid  AND n.nid=1452 and n.status = 1 ORDER BY tn.tid";
    $q = db_query($sql);

//print_r(db_fetch_array($q));exit;
    while ($r = db_fetch_array($q)) {

    echo '<pre>';
    //print_r($r);exit;

        $parents = taxonomy_get_parents_all($r['tid']);
        $parent_count = count($parents);

        $fields = array();
        for ($i = 0; $i<26; $i++) {
            $fields[] = '';
        }
        $fields[0] = $r['model'];
        $fields[1] = $r['title'];
        $fields[5] = $r['tid'];
        $fields[6] = $parents[$parent_count-1]->name;
        $fields[7] = ($parent_count > 1) ? $parents[$parent_count - 2]->name : '';
        $fields[8] = ($parent_count > 2) ? $parents[$parent_count - 3]->name : '';

        $sql2 = "SELECT fid FROM {uc_product_fees} WHERE nid ='%d'";
        $q2 = db_query($sql2, $r['nid']);
        //print '**'.$r['nid'].'**';
        //print_r($q2);

        if (!db_result($q2)) {

            $product_fees = array();
            foreach ($fees as $fee) {
                $product_fees[] = $fee;
            }echo 'sd';
            //print_r($fields[9]);exit;
            if (empty($r['settings']) || $r['settings'] == BIOTWEAKS_AU_ONLY_SETTINGS) {
                //put in AU prices
                $fields[9] = $r['sell_price'];
                foreach ($product_fees as $pf) {
                    $fields[9 + $pf['fid']] = $r['sell_price'] + $r['sell_price'] * (get_fee($pf['fid']) / 100);
                }
            }
            if (empty($r['settings']) || $r['settings'] == BIOTWEAKS_NZ_ONLY_SETTINGS) {
                //put in NZ prices
                $fields[17] = $r['price'];
                foreach ($product_fees as $pf) {
                    $fields[17 + $pf['fid']] = $r['price'] + $r['price'] * (get_fee($pf['fid']) / 100);
                }
            }

        } else {

            $product_fees = array();
            while ($r2 = db_fetch_array($q2)) {
                $product_fees[] = $r2;
            }
            if (empty($r['settings']) || $r['settings'] == BIOTWEAKS_AU_ONLY_SETTINGS) {
                $fields[9] = $r['sell_price'];
            }
            if (empty($r['settings']) || $r['settings'] == BIOTWEAKS_NZ_ONLY_SETTINGS) {
                $fields[17] = $r['price'];
            }
        }

        //$fields[22] = $r['status'];

        if ($output_file) {
            fputcsv($fp, $fields);
        } else {
            print_r($fields);
        }
    }
    if ($output_file) {
        fclose($fp);

           header('Content-type: application/excel');
           header('Content-Disposition: attachment; filename="'.$fname.'"');
           readfile($fpath.$fname);
    }
    return;
}

function biotweaks_form_submit($form_id, $form_values) {
    $fieldName = 'csv';

    $dir = variable_get('file_directory_path', 'files');
    if (isset($_FILES['files']) && is_uploaded_file($_FILES['files']['tmp_name'][$fieldName])) {
        // attempt to save the uploaded file
        $file = file_save_upload($fieldName, array(), $dir, FILE_EXISTS_REPLACE);

        // set error if file was not uploaded
        if (!$file) {
          form_set_error($fieldName, 'Error uploading file.');
          return;
        } else {
          _process_csv($file);
        }
    } else {
        form_set_error('Can\'t upload file!');
        return;
    }
}

function _process_csv($file) {

    global $DEBUG_BT_PROCESS;
    $DEBUG_BT_PROCESS = false;

    //set to just test a single product
    global $CHECK_ONE;
    $CHECK_ONE = true;

    if (0) {
    //delete all products
        $sql = "select nid from node where type = 'product'";

        $r = db_query($sql);
        while ($ra = db_fetch_array($r)) {

        }

        print 'all products deleted.';
    }

    //set all products to unpublished
    if (!$DEBUG_BT_PROCESS) {

        if (!$CHECK_ONE) {
            $sql = "update node set status='0' where type='product'";

            db_query($sql);

        }
    }

    function _fix_currency($str) {
        if ($str == "FREE") {
            return "0";
        } else {
            $ret = str_replace('$', '', $str);
            $ret = str_replace(',', '', $ret);
            return $ret;
        }
    }

    function _get_title($fields) {
        $description = $fields[1];
        $size = $fields[2];

        if (!empty($size)) {
            $ptitle = $description . " - ".$size;
        } else {
            $ptitle = $description;
        }
        $ptitle = str_replace("*NEW", "", $ptitle);
        $ptitle = str_replace("  ", " ", $ptitle);
        $ptitle = str_replace("  ", " ", $ptitle);
        return $ptitle;
    }

    function _update_product_node($nid, $fields) {
        $sku = $fields[0];
        $description = $fields[1];
        $size = $fields[2];
        $pallet_qty = $fields[3];
        $dg_class = $fields[4];

        $ptitle = _get_title($fields);
        $node = node_load($nid);

        $node->title = $ptitle;
        $node->status = 1;
        $node->model = $sku;
        $node->shippable = 1;
        $node->default_qty = 1;

        $tid = $fields[5];
        $term = taxonomy_get_term($tid);

        if (!$term) {
            drupal_set_message('No category id?');

            return;
        }
        $node->taxonomy[$tid] = $term;
        if ($fields[9]) {

            $node->sell_price = _fix_currency($fields[9]);
        }
        if ($fields[17]) {

            $r = db_fetch_array(db_query("SELECT vid, nid FROM {uc_products} WHERE model = '%s'", $sku));

            $case_price = _fix_currency($fields[17]);

            $nz_rid = 6;

            db_query("DELETE FROM uc_price_per_role_prices WHERE nid = %d", $r['nid']);

            db_query("INSERT INTO uc_price_per_role_prices (vid, nid, rid, price) VALUES (%d, %d, %d, '%f')", $r['vid'], $r['nid'], $nz_rid, $case_price);

            $node->role_prices[$nz_rid] = $case_price;
        } else {
            $r = db_fetch_array(db_query("SELECT vid, nid FROM {uc_products} WHERE model = '%s'", $sku));
            $nz_rid = 6;
            db_query("DELETE FROM uc_price_per_role_prices WHERE nid = %d", $r['nid']);
            if (isset($node->role_prices[$nz_rid])) {
                unset($node->role_prices[$nz_rid]);
            }
        }

        if ($fields[9] && !$fields[17]) {

            $settings = BIOTWEAKS_AU_ONLY_SETTINGS;

            db_query("delete from content_access where nid = '".$r['nid']."'");
            db_query("insert into content_access (settings, nid) values ('%s', %d)",$settings, $r['nid']);
        } else if ($fields[17] && !$fields[9]) {

            $settings = BIOTWEAKS_NZ_ONLY_SETTINGS;

            db_query("delete from content_access where nid = '".$r['nid']."'");
            db_query("insert into content_access (settings, nid) values ('%s', %d)",$settings, $r['nid']);
        } else {

            db_query("delete from content_access where nid = '%d'", $r['nid']);
        }

        db_query("delete from {uc_product_fees} where nid = '%d'", $nid);

        if (!function_exists('_exclude_discount')) {
            function _exclude_discount($fid, $nid) {

                db_query("delete from uc_product_fees where nid = '%d' and fid = '%d'", $nid, $fid);
                db_query("INSERT INTO {uc_product_fees} (nid, fid, price, is_active) VALUES (%d, %d, '0', '0')", $nid, $fid);
            }
        }

        for ($i = 0; $i<7; $i++) {

            if ($fields[9]) {

                if (!$fields[10 + $i]) {

                    _exclude_discount(1 + $i, $nid);
                }
            } else if ($fields[17]) {

                if (!$fields[18 + $i]) {
                    _exclude_discount(1 + $i, $nid);
                }
            }
        }

        if ($fields[26]) {

            $image_directory = $fields[25] ? $fields[25]."/" : "";
            $filepath = $_SERVER['DOCUMENT_ROOT'].'/sites/default/files/'.$image_directory.$fields[26];

            if (file_exists($filepath)) {

                $field = field_file_save_file($filepath, array(), file_directory_path());
                $node->field_image_cache = array(0 => $field);
            }
        }

$n= db_query("select nid from prod_node_relation where nid=".$sku);

$y = db_fetch_object($n);
if($y->nid)
{
db_query("update node set type='product' where nid=".$y->nid);
db_query("update term_node set tid=".$term." where =".$y->nid);
}
else
{

    node_save($node);
}

db_query("INSERT INTO prod_node_relation (nid, sku) VALUES (%d, %d)", $node->nid, $sku);
    }

    $file_name = $file->filepath;
    $fd = fopen ($file_name, "r");

    drupal_set_message('Importing products');

    $fields = fgetcsv($fd, 4096, ",");
    $count = 0;

    while (($fields = fgetcsv($fd, 4096, ",")) !== FALSE) {

        $sku = $fields[0];

        $sql = "select nid from uc_products where model = '%s'";
        $q = db_query($sql, $sku);
        $r = db_fetch_array($q);

        if ($r) {

            _update_product_node($r['nid'], $fields);
            drupal_set_message('Updated product: '.$sku);

        } else {
            $sql2 = "select nid from node where title = '%s'";
            $q2 = db_query($sql2, $fields[1]);
            $r2 = db_fetch_array($q2);

            if ($r2) {
                _update_product_node($r['nid'], $fields);
                drupal_set_message('Updated product: '.$fields[1]);
            } else {

                drupal_set_message('Create product: '.$sku);
                if ($fields[0]) {

                    if ($DEBUG_BT_PROCESS) {
                        drupal_set_message('Need to create product:'.$fields[0]);
                    } else {
                        $node = (object)array(
                            'uid'=>1,
                            'name'=> 'admin',
                            'type'=> 'product',
                            'title'=> _get_title($fields)   );
                        $contenttype = content_types('product');
                        foreach ($contenttype['fields'] as $fieldname => $field) {
                            if(isset($field['widget']['default_value'])) {
                                $node->$fieldname = $field['widget']['default_value'];
                            }
                        }

                        node_save($node);

                        $nid = $node->nid;

                        _update_product_node($nid, $fields);
                        drupal_set_message('Created and updated product: '.$sku);
                    }
                } else {

                }
            }
        }
        break;
        $count++;
    }
    drupal_set_message('Finished importing.');

}

```

This is how it is being visible now when I open CSV file

This is frontend

# Answer
> Need to replace below code in place of same action in old code ,it's working fine in our end.

```
function biotweaks_product_csv_download() {

    $fpath = '/home/biolab/public_html/';
    $fname = 'products.csv';

    $output_file = true;

    if ($output_file) {
        $fp = fopen($fpath.$fname, 'w');
    }

    $header = array('Product Code', 'Product Description', 'Size', 'Pallet Qty', 'DG Class', 'Category ID', 'Category Name', 'Subcategory Name', 'Subsubcategory Name', 'AU Case Price (ex. GST)', 'AU Price List 21', 'AU Price List 22', 'AU Price List 23', 'AU Price List 24', 'AU Price List 25', 'AU Price List 26', 'AU Price List 27', 'NZ Case Price (ex. GST)', 'NZ Price List 21', 'NZ Price List 22', 'NZ Price List 23', 'NZ Price List 24', 'NZ Price List 25', 'NZ Price List 26', 'NZ Price List 27', 'Image directory', 'Image filename');

    if ($output_file) {
        fputcsv($fp, $header);
    }

    $q = db_query('SELECT fid, price from {uc_fees}');
    global $fees;
    $fees = array();
    while ($r = db_fetch_array($q)) {
        $fees[] = $r;
    }

    function get_fee($fid) {
        global $fees;
        foreach ($fees as $fee) {
            if ($fid == $fee['fid']) {
                return $fee['price'];
            }
        }
        return 0;
    }

    $sql = "SELECT  n.status, n.nid,  n.title, tn.tid, ucp.model, ucp.sell_price,  upp.price,  ca.settings FROM  {uc_products} as ucp,  {term_node} as tn,  {node} as n left join {uc_price_per_role_prices} as upp on n.nid = upp.nid left join {content_access} as ca on n.nid = ca.nid   WHERE  ucp.nid = n.nid and  n.nid = tn.nid  AND n.status = 1 ORDER BY tn.tid";

    $q = db_query($sql);

    while ($r = db_fetch_array($q)) {

        $parents = taxonomy_get_parents_all($r['tid']);
        $parent_count = count($parents);

        $fields = array();
        for ($i = 0; $i<26; $i++) {
            $fields[] = '';
        }
        $fields[0] = $r['model'];
        $fields[1] = $r['title'];
        $fields[5] = $r['tid'];
        $fields[6] = $parents[$parent_count-1]->name;
        $fields[7] = ($parent_count > 1) ? $parents[$parent_count - 2]->name : '';
        $fields[8] = ($parent_count > 2) ? $parents[$parent_count - 3]->name : '';

        $sql2 = "SELECT fid FROM {uc_product_fees} WHERE nid ='%d'";
        $q2 = db_query($sql2, $r['nid']);

        if (!db_result($q2)) {

            $product_fees = array();
            foreach ($fees as $fee) {
                $product_fees[] = $fee;
            }

            if (empty($r['settings']) || $r['settings'] == BIOTWEAKS_AU_ONLY_SETTINGS) {

                $fields[9] = $r['sell_price'];
                foreach ($product_fees as $pf) {
                    $fields[9 + $pf['fid']] = $r['sell_price'] + $r['sell_price'] * (get_fee($pf['fid']) / 100);
                }
            }
            if (empty($r['settings']) || $r['settings'] == BIOTWEAKS_NZ_ONLY_SETTINGS) {

                $fields[17] = $r['price'];
                foreach ($product_fees as $pf) {
                    $fields[17 + $pf['fid']] = $r['price'] + $r['price'] * (get_fee($pf['fid']) / 100);
                }
            }

        } else {

            $product_fees = array();
            while ($r2 = db_fetch_array($q2)) {
                $product_fees[] = $r2;
            }
            if (empty($r['settings']) || $r['settings'] == BIOTWEAKS_AU_ONLY_SETTINGS) {
                $fields[9] = $r['sell_price'];
            }
            if (empty($r['settings']) || $r['settings'] == BIOTWEAKS_NZ_ONLY_SETTINGS) {
                $fields[17] = $r['price'];
            }
        }

        if ($output_file) {
            fputcsv($fp, $fields);
        } else {
            print_r($fields);
        }
    }
    if ($output_file) {
        fclose($fp);

           header('Content-type: application/excel');
           header('Content-Disposition: attachment; filename="'.$fname.'"');
           readfile($fpath.$fname);
    }
    return;
}

```
> 1 votes

---
Tags: 7
---


title: OnClick Event not Captured

text:
# Question
Title: OnClick Event not Captured
I am currently developing a module in Drupal. I made a button that show a dialog box whenever it's clicked.

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

  drupal_add_js(drupal_get_path("module", "myid") . "/js/myid.js");
}

function myid_menu() {
  $items = array();

  $items['admin/settings/myid'] = array(
    'title' => 'myid Settings',
    'description' => 'Configuration options for the myid module',
    'page callback' => 'myid_admin_settings',
    'access callback ' => 'user_access',
    'access arguments' => array('administer site configuration'),
  );

  return $items;
}

function myid_admin_settings() {
   return drupal_get_form('myid_settings_form');
}

function myid_settings_form() {
  $form = array();

  $form['myid_registrar_button'] = array(
    '#type' => 'button',
    '#value' => '...',
    '#attributes' => array(
      'id' => 'myid_registrar_button',
    ),
  );

  return $form;
}

```

The JavaScript code is the following

```
$(function(){
  $('#myid_registrar_button').on('click', function(e) {
    e.preventDefault();
    alert("Eww");
  });
});

```

Whenever I click a button, it refreshes and it doesn't show anything.

It seems the event is not captured. The console doesn't show errors.

What am I missing?

# Answer
> 0 votes
You shouldn't be adding JQuery like that. It's automatically included in core, so you don't need to include it yourself. To stay up with the latest JQuery version, install the jQuery Update module.

For your JS file, this should work:

```
(function ($) {
    Drupal.behaviors.myid.registrar_button = {
        attach: function (context, settings) {
            $('#myid_registrar_button').on('click', function(e) {
                e.preventDefault();
                alert("Eww");
            });
        }
    };
})(jQuery);

```

---
Tags: forms, javascript
---


title: Changing block position in Bartik theme

text:
# Question
Title: Changing block position in Bartik theme
I am using bartik theme to develop a website.I need the User menu and search block to be beside the logo and main menu block to be below the logo. But all the menu and search blocks appear below the logo.How can I move the user menu and search block to right top corner of the page.

Thank you in advance.

# Answer
> 1 votes
you can change a position of menu and search block from structure \> block link and assign it to *** custom made region ***, also use custom css can fix your problem.

also you can Demonstrate the all region of theme from admin/structure/block/demo/bartik

hope this will help you

---
Tags: theming
---


# Question
Title: How to add multiple taxonomy terms to node?
I'm new to PHP and Drupal module development. I'm having a site on which the users can create their own posts(nodes).

Can someone help me with how to save multiple taxonomy terms to a node. The users are filing their post in a form and the data is sent back through ajax. For example the taxonomy terms are sent to the server in this format: apple, banana, orange. I don't know how to save all these terms to a node.

# Answer
First of all, be sure that the taxonomy reference field exist in manage field page of your content type, then you can attach that field to your node via the function field\_attach\_update, before attaching that field to node let's get it from your data passed through Ajax :

```
 $terms = $form_state['values']['your_tax_field'];

 // attach to node :
 $node = new stdClass();
 $node->nid = $nid // Make sure that the nid exist;
 $node->type = 'your_content_type';
 $node->your_tax_field = $terms;
 field_attach_update('node', $node);
 entity_get_controller('node')->resetCache(array($node->nid));

```

Not tested but should work like that! You can use devel module to debug your data passed in the form.
> 1 votes

# Answer
---

Go to Administration » Structure » Content types

Click on Manage Fields for Article.

Change the Widget Type of field Tags to Autocomplete term widget.
> 0 votes

---
Tags: taxonomy-terms
---


# Question
Title: Adding a radio buttons in views exposed filters for published and unpublished drupal 7
The above view shows articles content type, which is exposed filter.I want to add a radio buttons as i have shown in image for published and unpublished,can I get this functionality programmaticaly and how

# Answer
> 1 votes
This can be achieved using Better Exposed Filters module. If you need to do this programmaticaly then you may need to look at the code of this module. You need to implement the hook\_theme as done in better\_exposed\_filters.module and implement the code to display as radio button as done in better\_exposed\_filters.theme(Function: theme\_select\_as\_radios)

I would suggest using the module directly if that is an option.

# Answer
> 0 votes
I would suggest using Views Bulk Operations:

> This module augments Views by allowing bulk operations to be executed on the displayed rows. It does so by showing a checkbox in front of each node, and adding a select box containing operations that can be applied. Drupal Core or Rules actions can be used.

Even if it can't do exactly what you want, you could modify it into a custom module that could. Gives a good starting point for the code.

---
Tags: hooks, views
---


title: How auto load items on page

text:
# Question
Title: How auto load items on page
Taxonomy page will have sidebar which will have taxonomy menu items and grid layout with image and brief details.

For example, taxonomy items have brand by certain names, price range, etc. User click on brand name, the grid layout will auto load the brand products without have going to /products/brand\_name. On page, it will be /products, and then every brand name will show different products automatically loading on same page.

Is there such a way to do this? Or there is a module which can do that?

Example I found is http://www.cynosure.com/products/

Click on any from menu on left column, you will see the products reloaded by menu click.

# Answer
This can be achieved using exposed filters feature of the Views module. Here is an article explaining this process in detail.

http://www.bryanbraun.com/2013/08/06/drupal-tutorials-exposed-filters-with-views

You would also need the Better Exposed Filters(BEF) module for displaying the filters as links.
> 0 votes

# Answer
Views module will do this for you. If the items in the column is limited and you know what they are, you can create different pages for every one, each page indicates certain filtering. but you need Ajax call to load information in the same page. if your View name is product and then you need some thing like this

```
        $.ajax({
            url: Drupal.settings.basePath + 'views/ajax',
            type: 'POST',
            dataType: 'json',
            data: 'view_name=product&view_display_id='+view_display_id,
            success: function(response) {
              var output = response[1].data;
              $("#A_CONTAINER_TO_DISPLAY_CONTENT").html(output);
            },
            error: function(data) {
                $("#A_CONTAINER_TO_DISPLAY_CONTENT").css("display","none");
                alert('An error occured!');
            }
          });

```

`view_display_id` is the machine name in here:

And don't forget to set the use Ajax to `yes`
> 0 votes

---
Tags: theming
---


# Question
Title: Create Drupal Commerce stores as a Service
I'd like to leverage the power of Drupal Commerce to sell completely unrelated products and thus would like to create 2 different stores and brands. I could of course create a Drupal multisite but this is overkill and I really want to have only one site and one Drupal Commerce setup. If tomorrow I want to create new stores, I'd be able to do so with this layout without having to go through the headache of managing different installs.

My idea is thus to try and set up Drupal Commerce as a service with the following in mind:

* Each store would be completely isolated from the others (products, clients...)
* Provisioning a new store would only be a matter of assigning a role to a new user
* Say the root domain is mysite.com, I'd like to have one store at mysite.com/store1 and the other at mysite.com/store2 (using subdomain would be pretty much the same)

I've been thinking about using Organic groups but it's not obvious to me if a) it is the right tool and b) how to achieve that with the module.

Any pointer or feedback would be very much appreciated.

Thanks!

# Answer
> 4 votes
This is known as the "marketplace" use case.

There is a 250-comment discussion on this in the Drupal Commerce issue queue: http://drupal.org/node/990204 See http://drupal.org/node/990204#comment-5880498 for a fairly simple implementation plan. Of course, it goes into details that your project might not need, but you can just ignore those.

Quoting the relevant part about the basics needed:

> 1) An entity that represents the store. That can either be the user, a store entity clicked together through the ECK module, or a store entity provided by a module.
>
> 2) Entityreference. Then a bunch of entityreference fields that point to the "store" entity (or user). One on products, one on product displays, one on orders.
>
> 3) Form alters that hide the entityreference fields on product displays and products (or just use a "hidden" widget) and fill it in with the known value (you always know which store the user has. If not, give him a dropdown...).
>
> 4) A custom submit handler for the add to cart form (replacing the existing submit handler) that adds a product to an appropriate order (since there's an order per store for each customer), and if the order doesn't exist yet, creates it and sets the value of the entityreference field.
>
> 5) Custom view for cart/ that shows all active carts to a customer.
>
> 6) Custom views filtered by the entityreference field that show the merchant the products and orders for his store.

Organic Groups fits neatly on top. You then need to figure out how you're handling payments, see the linked issue for various approaches.

# Answer
> 0 votes
I have implemented a marketplace feature in my site. I used the below path.

1. 2 type of order type/bundle main\_order , vendor\_order.
2. On checkout (main\_order) a list of vendor\_orders gets created for each store through rules and little bit of coding.
3. Each vendor will have permissions for vendor\_orders only. so this limits their of useage.
4. on front-end it user doesn't see different stores, just like amazon or ebay

---
Tags: commerce, organic-groups
---


# Question
Title: Create custom meta tag with the metatag module
Just this. I need to create some metatag using the metatag module: https://www.drupal.org/project/metatag

Something like:

```
<meta property="og:locale" content="en_US" />
<meta property="og:type" content="website" />

```

I can't see how to get this in its setting.

Then after I will need to use these metatags in nodes and views.

# Answer
> 2 votes
You can either use Custom Meta module or roll your own module:

From Custom Meta project page:

> The module allows you to define and manage custom meta tags. Simply select the Meta attribute (property, name, http-equiv) and set the value and content value in the format and the module will add your meta tags to all non-admin content for your site.

An example of writing your own module:

**my\_metatag.info**

```
name = My Metatags
description = Provides my custom Metatags.
core = 7.x
version = 7.x-1.x
dependencies[] = metatag
files[] = my_metatags.metatag.inc

```

**my\_metatag.module**

```
<?php

/**
 * Implements hook_ctools_plugin_api().
 */
function my_metatags_ctools_plugin_api($owner, $api) {
  if ($owner == 'metatag' && $api == 'metatag') {
    return array('version' => 1);
  }
}

```

**my\_metatag.metatag.inc**

```
<?php
//
// Implements hook_metatag_info().
//
function my_metatags_metatag_info() {
  $info['groups']['my_metatags'] = array(
    'label' => t('My Custom Metatags'),
  );

  $info['tags']['my_custom_metatag'] = array(
    'label' => t('My Custom Meta Tag'),
    'description' => t('This is a custom meta tag'),
    'class' => 'DrupalTextMetaTag',
    'group' => 'my_metatags',
  );

  return $info;
}

//
// Implements hook_metatag_config_default_alter().
//
function my_metatags_metatag_config_default_alter(array &$configs) {
  foreach ($configs as &$config) {
    switch ($config->instance) {
      case 'global':
        $config->config += array();
        break;

      case 'global:frontpage':
        $config->config += array();
        break;

      case 'node':
        $config->config += array(
          'my_custom_metatag' => array('value' => 'This is a default value.'),
        );
        break;

      case 'taxonomy_term':
        $config->config += array();
        break;

      case 'user':
        $config->config += array( );
        break;
    }
  }
}

```

Hope that helps.

---
Tags: meta-tags
---