# Question
Title: For User i am giving option of color selections for a theme
I am giving user the option of selecting the color(color scheme option like bartik) for the theme.For multiple users how do i save there color values for the theme and show their values alone depending on their login ? Colors for their header ,footer etc...

Help me provide with a solution.Thanks in advance

# Answer
well, usually there are pre-defined color sets (like in batrik), so you save set name and then on hook\_preprocess\_page you chose which css to include. So either this or you can add inline css styling using the same function drupal\_add\_css.

As for how to save this for each user, you can add extra field to user profile at Home » Administration » Configuration » People » Account settings and then programmatically update it with needed value - example below, details here.

```
global $user;
$existing = user_load($uid);
unset($existing->pass);
$edit = (array) $existing;
$edit['field_somefield']['und'][0]['value'] = 'blah';
user_save($user, $edit);

```
> 0 votes

---
Tags: 7, theming, javascript
---


# Question
Title: How to build select lists for search_api views
I am building a small website for a charity and am trying to integrate search\_api to search the list of projects.

I have a content type named "Project" with the following fields:

* Title ( Project Name )
* Body
* Project Image ( Image field )
* Project Countries ( Multi valued taxonomy of all Countries this project operates in )

I need to build a search page that has:

* A free text search box that will search Title/Body as a fulltext search
* A select list or autocomplete field that allows you to select the country you are searching

So far I have:

* Created a new solr search server using search\_api
* Indexed the Project content type in a new search index
* Added all taxonomy values and fields to the search index ( in the hope one would work )
* Created a view linked to this index
* Added all of the above taxonomy fields as exposed group search filters but none of them pick up the values of the taxonomy.

I can happily freetext search on the indexed fields but if I want to use dropdown filters or even checkboxes to filter the results it just doesn't work.

Clearly I am doing something wrong here, what is the best way to achieve what I am trying to do?

# Answer
> 3 votes
In this case I would create a Facet. You'll need to enable Search Facets (shipped with Search API) and Facet API.

Once you have that in place go to `Configuration -> Search and metadata -> Search API` and click edit on your Search index. In the dropdown there is a new choice called Facets now.

Enable the facet for you field `Project Countries`. That field also needs to be indexed under your fields settings for your search index. Facet API will provide a block for you with the Facet that you need to place on your search page.

Facets work in a way that they only show options available in your search result. If "Sweden" is not present in the field `Project Countries` in any of the nodes you have indexed it will neither be available in the Facet. So facets work in a way that they narrow down search results and usually doesn't show options that will result in an empty search. That's the biggest difference I see between a facet and a normal filter in Views.

Facets are normally displayed as checkboxes or links (see display settings for your Facet). You mentioned in your question that you have it now in the View as a dropdown. You you want to keep it as a dropdown instead of checkboxes / links you could checkout Facetapi select

---
Tags: views, search
---


# Question
Title: joining profile types using views module
According to this thread, click here, I need to use `relationships` to inner join different content types.

I used the same method with profile types but I ended up with the following result.

Instead of using the views UI, do I need to custom code it?

Thanks

# Answer
Currently it's creating a join for each relationship (each profile type) that's why you see several rows. Question is what would happen if a user has several profile types (can they have that)?

You might get by with putting **Distinct** on your query.

In Views, fold out Advanced and look for Query settings under Other. Choose settings and check Distinct. Hit save.
> 0 votes

---
Tags: views, users
---


# Question
Title: How to use hook_views_data_alter to display select list on user reference field?
I want to allow administrator to edit user reference field value on the fly when browsing entities list (view as table). In every row select list with user to choose should appear.

Current code:

```
function rpke_document_assign_views_data_alter(&$data) {
    $data['field_data_field_assignee']['applicant_chooser'] = array(
        'real field' => 'field_applicant_target_id',
        'field' => array(
            'title' => t('Applicant chooser'),
            'help' => t('Applicant chooser based on select list. Extends views_handler_field_user_name'),
            'handler' => 'rpke_field_handler_applicant_chooser',
        ),
    );
}

```

field\_assignee is custom CCK field add to entity based on node.

When I try to add this field to a view I am getting error:

> Invalid column name 'field\_applicant\_target\_id'.

# Answer
You could checkout Editable Views which let's you create Views where the fields are editable directly. It works with Field API fields which it looks like your field is.
> 0 votes

---
Tags: 7, views
---


# Question
Title: Only show the complete form at the end of the quiz
In the Quiz module, After each question that the user answers, it shows a page that have some information (such as: right or wrong, question, answers, etc.).

And in the last of quiz it shows a complete form too.

I want to change this, so that the form is shown just at the end and not after each question. Is there a template I should change or some other way I can change the normal module behaviour?

# Answer
I don't know enough about the Quiz module to say for sure but have you checked out the theme functions available for Quiz?

There is a theme function called `theme_quiz_take_summary()`. It has a form that it adds if the quiz is set to display\_feedback. Maybe it's a setting for the quiz somewhere?

```
// Get the feedback for all questions. These are included here to provide maximum flexibility for themers
if ($quiz->display_feedback) {
  $form = drupal_get_form('quiz_report_form', $questions);
  $output .= drupal_render($form);
}

```

If you want to have your own version of that theme function you should place the whole function in your theme and replace theme\_quiz\_take\_summary() with NAMEOFYOURTHEME\_quiz\_take\_summary().
> 0 votes

---
Tags: theming, quiz
---


title: Appearance of search in Views

text:
# Question
Title: Appearance of search in Views
I use Views module and I've got search to specify results.

In the search I've got filter for field cena. I set operator between so user can fill in min cena and max cena.

How can I change the appearance of that search? For and foremost I'd like to remove "And" between inputs for min cena and max cena. If it's possible I also want to create placeholders in inputs for min cena and max cena.

# Answer
To remove the **And** title you need to implement hook\_form\_alter(). It would look something like this.

```
/**
 * Implements hook_form_FORM_ID_alter().
 */
function mymodule_form_views_exposed_form_alter(&$form, &$form_state){
  if ($form['#id'] == 'views-exposed-form-search-page') {
    unset($form['field_price1_value']['max']['#title']);
  }
}

```

You will also need to find out the `$form['#id']` so that your code doesn't attempt to change all exposed forms generated by views. Install the Devel module and run.

```
/**
 * Implements hook_form_FORM_ID_alter().
 */
function mymodule_form_views_exposed_form_alter(&$form, &$form_state) {
  dsm($form['#id']);
}

```

The devel module will now set a message with each views exposed form and it's `#id`. Copy that and replace `views-exposed-form-search-page` in the first code example. After that you can add a `dsm($form);` to find out what your field name is called in the array (to replace `field_price1_value`).
> 1 votes

---
Tags: 7, views, search
---


title: form does not validate

text:
# Question
Title: form does not validate
```
function formexample_nameform(){

$form['user_name'] = array(
'#title' => t('your name'),
'#type' => 'textfield',
'#description' => t('Please enter your name.'),
);

$form['submit'] = array(
'#type' => 'submit',
'#value' => t('Submit'),
);

return $form;
}

```

if i add this:

```
'#name' => 'new name attribute',

```

it looks like this:

```
function formexample_nameform(){

$form['user_name'] = array(
'#title' => t('your name'),
'#name' => 'new name attribute',
'#type' => 'textfield',
'#description' => t('Please enter your name.'),
);

$form['submit'] = array(
'#type' => 'submit',
'#value' => t('Submit'),
);

return $form;
}

```

and it does not validate any more, it always let the inputs pass through.

my validate function:

```
function formexample_nameform_validate($form, &$form_state){
if ($form_state['values']['user_name'] == 'King Kong') {
    form_set_error('user_name',
    t('King Kong is not allowed')
    );
}
}

```

question: what has the name attribute with validation to do?!

# Answer
> 0 votes
As per the FAPI the element textfield has no `name` attribute

Available Properties are

```
#access, #after_build, #ajax, #attributes, #autocomplete_path (default: FALSE),
#default_value, #description, #disabled, #element_validate, #field_prefix, #field_suffix,
 #maxlength (default: 128), #parents, #post_render, #prefix, #pre_render, #process, #required,
 #size (default: 60), #states, #suffix, #text_format, #theme, #theme_wrappers, #title,
#title_display, #tree, #type, #weight

```

**I am not sure about the reason that the form is not validating, Excited to know the reason.**

---
Tags: forms
---


# Question
Title: How do I create customer/order relationship with entities?
I am fairly new to Drupal 7 and especially new to the entity concept. I need to create a site which records customer data (name, address etc) as well as other objects/entities such as orders, which are related to the customer with a parent/child relationship. I don't know how to do this in Drupal 6 and definitely not in Drupal 7. I know you can create a node reference as a field, but that is not what I want.

I'm pretty sure this has to do with entities, as entities are paralleled to objects, and what I really need is an object to own another object. I am presently listening through tutorials about Entities, but can someone point me in the correct direction to see what exactly I should be looking for (and to perhaps clarify the Entity concept to me).

# Answer
You should look at Drupal Commerce, a suite of modules that sets up e-commerce in Drupal. You will have a much easier time adapting Drupal Commerce to fit your needs than you will writing a store from scratch in Drupal.
> 2 votes

---
Tags: 7, entities
---


title: How to host 4000+ Images for download

text:
# Question
Title: How to host 4000+ Images for download
I have around 4300 images that I want to share with around 100 people. In total they are 15gb. I have a Drupal 7 webserver with unlimited traffic and enough free storage to upload them on but I don't know an elegant / simple solution to distribute them.

The only simple approach I can think of, is zipping a few images together in a way I would get 15x 1gb files and just send everyone a link to these 15 files.. but that would be pretty lame wouldn't it? It would also be problematic for people with instable / slow internet because they might not be able to download 1gb large files without interruptions.

Is there any good solution? The people who need to recieve the images are "standard user" so it has to be a simple solution. I thought of a flash app of some sort which would run in the browser and download all the images one file at a time but I don't know if something like that exists.

I don't think it should be database related, because the Images are not getting used elsewhere on the site.. I would love to just upload them into a folder and having some easy way for the clients to download it.

# Answer
> 1 votes
I would think rsync would be a bit better suited to this task, I would simply place all the files on a server for example in

```
/srv/photoshare

```

Create a group to share to:

```
groupadd photoshare

```

Then create user for each person in the group, and add them to that group:

```
useradd -G photoshare photouser1

```

Or add an existing user to the group

```
gpasswd -a photouser2 photoshare

```

then each person can sync to local directory with this command:

```
rsync -ave ssh photouser1@HOSTNAME:/srv/photoshare ./

```

alternatively, if you don't have shell access, you can just stick them all in a subdomain, turn on directory indexing with an .htaccess file:

```
Options +Indexes

```

and use wget:

```
wget -m www.example.com

```

also you could try a gallery plugin, but from your request I think that is not what you want.

# Answer
> 1 votes
also you might want to try dropbox or one of it's alternatives:

https://owncloud.com/

http://sparkleshare.org/

http://labs.bittorrent.com/experiments/sync.html

http://seafile.com/en/home/

# Answer
> 1 votes
Okay for a simple downloader with resuming nothing is going to beat wget, using either the gigantic zip file or the directory with indexes turned on method

But you say your users refuse to use a command line? Probably windows users, so:

http://sourceforge.net/projects/winwget/

there is also a perl gui for multiplatform support:

http://www.martin-achern.de/wgetgui/

the -c option for wget will automatically resume, and the -m is a collection of options that will 'mirror' the link recursively.

# Answer
> 0 votes
Ok, and there is a drupal option apparently: the Resumable Download module. Here is a quote about it (from the module's project page):

> Drupal does not support download resume , meaning that downloading large private files can be troublesome because if for any reason the download fails, there is no way to continue downloading from where it stopped and the whole file should be downloaded again.
>
> **Features**:
>
> * Multi Part/Section file download
> * Resumable file download
> * Download speed limit support
> * Automatic client download abort detection

---
Tags: media, files
---


# Question
Title: How to remove the value Search from the site search form?
I would like to style the Submit button and use an icon instead of the standard button. I would also like to remove the text/value Search.

How would I go about doing this?

# Answer
> 0 votes
Sorry: you can use an image as a submit button:

```
<input type="image" src="images/login.jpg" alt="Submit Form" />

```

alternatively you can also place an image an trigger a function that will call

```
form.submit()

```

by using the img tag's `onclick` handler

---
Tags: search
---


# Question
Title: Customizing system response emails outside of the admin panel
Can registration emails be customized through code rather than through the admin panel? I have message content that's reliant on values entered by user. Thanks.

# Answer
> 0 votes
You can use tokens (provided by the Token module) in administrative e-mails. If you need a token for a value not provided by the Token module, you can programatically create a token.

---
Tags: 7, users, emails
---


# Question
Title: How do I add taxonomy terms and vocabularies to an exportable deployment plan?
I'm in the process of developing an installation profile for a new site. We're using Features to export much of our functionality, and are very interested in using the Deploy module integration with UUID to handle the thorny issues stemming from exported content not having the same unique IDs on multiple deployments. Being able to export entities into a deployment plan and import them with Features would be an absolute godsend, and this is working with basic node content from what I've seen so far (I'm familiar with the concept of creating a fetch-only deployment plan and exporting it later).

However, I have a content type that references multiple taxonomies, each with a closed, pre-defined vocabulary. These vocabularies (and their terms) need to be exported, so that they can be referenced by the appropriate fields (for instance, a list of terms representing venues should be selectable from a drop-down). I haven't yet found a way to add these to a deployment plan, despite hearing on the soon-to-be-deprecated UUID Features issue queue that this should be possible. Is there something I've overlooked, or is there a better approach?

# Answer
> 3 votes
I seem to have stumbled my way through to a solution. Vocabularies don't need to be exported via UUID, as they already have their own machine name, but any terms within those vocabularies still need to be added to a deployment plan so they can be exported (inadvertently adding a vocabulary to the plan throws errors).

Using the latest development snapshots (as of March 14, 2012) of UUID, Deploy, Entity Dependency API, Views and Rules, it is possible to stitch together a UI for adding taxonomy terms to a plan. First, a managed fetch-only deployment plan must be created.

Next, a Rules component must be created using Rules, with a taxonomy term as a single parameter and a single action that adds the entity to the selected deployment plan. Note, however, that the current development snapshot of Deploy does not allow you to use Rules to add to a fetch-only managed deployment plan (I had to write a trivial patch that allows this behavior).

Next, one should create a view of all taxonomy terms, adding a Bulk Operations checkbox using Views Bulk Operations. If you have created your Rules component as above, VBO will allow you to select your component as a task to perform on all checked entities.

Now that your form is configured, all that's left to do is visit the view and add the necessary taxonomy terms, and select the relevant components to export via Features. Gotcha: There is no dependency checking in Features after adding the taxonomy terms via uuid\_entities. You have to remember adding the vocabulary yourself, or tragedy and error messages will ensue.

# Answer
> -2 votes
For Drupal 7 :

There are a few ways to do this

* If you are importing the terms from another Drupal site use Node export module - drupal.org/project/node\_import
* If you are planning to export or import from a csv file : drupal.org/project/taxonomy\_csv
* If you just want to cut and paste the list (one per line) and add to a vocabulary : drupal.org/project/batch\_add\_terms

---
Tags: 7, taxonomy-terms, features, deployment
---


# Question
Title: add title to front page teaser news feed
I would like to add a title to my news feed. I have tried to edit node--teaser.tpl.php and added

```
<?php if($page['feed-title']): ?>
<!-- start feed title -->
<?php print render($page['feed-title']); ?>
<!-- end feed title -->
<?php endif; ?>

```

on top, then I added

```
regions[feed-title] = Feed Title

```

in my theme.info file. I created a block which is assigned to this region but still, nothing is being displayed, why not? Am I doing something wrong or can I not add regions into a region template file?

Thanks!

# Answer
> 2 votes
If you look at the page.tpl.php template file used by the Bartik module, you will notice it uses code like the following to render a region.

```
  <?php if ($page['triptych_first'] || $page['triptych_middle'] || $page['triptych_last']): ?>
    <div id="triptych-wrapper"><div id="triptych" class="clearfix">
      <?php print render($page['triptych_first']); ?>
      <?php print render($page['triptych_middle']); ?>
      <?php print render($page['triptych_last']); ?>
    </div></div> <!-- /#triptych, /#triptych-wrapper -->
  <?php endif; ?>

```

node--teaser.tpl.php is not used to render a page, but a node into a page. It is hierarchic, someway: html.tpl.php wraps the content of page.tpl.php, which wraps the content of node.tpl.php.
Regions are part of a page, not a node; therefore, the template file where to render the regions is page.tpl.php or any suggested templates used instead of that one.

# Answer
> -1 votes
When you add a region in theme.info file, you have to render the region in `page.tpl.php`.

That's where you are doing wrong. You are doing it in `node.tpl.php`.

Don't forget to clear the cache after you render your region in `page.tpl.php`.

---
Tags: blocks, theming, nodes
---


title: Feeds Importer Filters

text:
# Question
Title: Feeds Importer Filters
I would like to import some nodes from csv file using feed\_import module in Drupal 7. The original CSV file has around 500k entries and I have to do some filtering before importing. (the result will be under 40k).

Now, I have seen on drupal.org that feed\_import has the possibility of adding some filters, but I cannot find the way to apply them.

Anyways I haven't seen nothing about the lenght of the field or about the type of content (numeric, alphanumeric, letters only), and I have to filter on these criteria.

Can that be made? Or should I try to do the filtering in PHP before using feed\_importer?

# Answer
> 3 votes
You can create a new module and implement the hook\_feeds\_presave() function like the following example:

```
function hook_feeds_presave(FeedsSource $source, $entity, $item) {
  // create your filter conditions here
  if ($entity->feeds_item->entity_type == 'node') {
    // Skip saving this entity.
    $entity->feeds_item->skip = TRUE;
  }
}

```

# Answer
> 1 votes
I am using feed importer for long & I like this module very much. Filtering data while importing can be done but there is no direct option in the feed importer setting which you are looking for.

First filter is, field setting. As feed importer import data for fields, so the imported data always depend upon field setting first.

Then there is another module which can make your life easier while importing data, named Feed Tamper. You can add several plugin for any mapping like - **trim**, **truncate**, **keyword filter**, **implode/explode**, **convert case**, **find replace**, **REGEX** etc.

All plugins are handy and easy to use & it work like charm with feed importer.

---
Tags: feeds, importing-exporting
---


# Question
Title: Best way to build bio content specific to the user
I'm creating a website where users can report on news in their area. Needless to say, I'm hoping to have thousands of users eventually.

I'm wondering what's the best way to give them a place to add/manage a biography about themselves. What should I do between the following options?

1. Add a field in the user profile database and call the database on my template override
2. Create a new content type named bio, treat it as a page and use entity/views to display the correct bio page based on the search

Originally I was going to go with the user database path, but something inside me is nagging me to treat bio's as pages for easier theming/searching. I think it's because I want the bio to be searchable like the articles are, and display as a whole page when selected without having to write a lot of backend code or more template overrides.

# Answer
If the bio pages can be created for people without an account on the site, then I would create a new content type to use for the bio data; if the bio data needs to be strictly linked to the user profile, I would add new fields to the user accounts.

I would also create a new content type if I want the bio information to be completely searchable. When searching for users, the User module looks just for the username or the user email (in the case the user who is searching as the permission of administering users).

```
  $find = array();
  // Replace wildcards with MySQL/PostgreSQL wildcards.
  $keys = preg_replace('!\*+!', '%', $keys);
  $query = db_select('users')->extend('PagerDefault');
  $query->fields('users', array('uid'));
  if (user_access('administer users')) {
    // Administrators can also search in the otherwise private email field,
    // and they don't need to be restricted to only active users.
    $query->fields('users', array('mail'));
    $query->condition(db_or()->condition('name', '%' . db_like($keys) . '%', 'LIKE')->condition('mail', '%' . db_like($keys) . '%', 'LIKE'));
  }
  else {
    // Regular users can only search via usernames, and we do not show them
    // blocked accounts.
    $query->condition('name', '%' . db_like($keys) . '%', 'LIKE')->condition('status', 1);
  }

```

To search users basing on the content of any field attached to user accounts, you should use a module that implements user search differently from the User module, or create yourself one.

As for changing the template used for user accounts, that is not different from changing it for a node; the only difference is the template file used by default: user-profile.tpl.php for a user account, and node.tpl.php for a node.

You could also use the Profile 2 module; in this case, the profiles would be an entity different from nodes, and they would be fully searchable with the Views module or the Search API module.
> 1 votes

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


# Question
Title: Inline add/edit/delete data in views in Drupal 7
I am trying to create a content type (say Meter). Each Meter consists of a "Meter Reading". This meter reading content contains three fields, say title, date range and usage. I have a Panel page where I display all the Meter Readings related to a parent Meter. I have displayed the Meter Readings in a tabular format.

I want the user to be able to add new Meter Readings without going to the default Meter Readings creation page. Rather than the default form kind of page, the user should be able to enter the data in the table view provided and it should be automatically saved into the project itself.

So, I want the functionality to be like:-

1. Display all the meter readings with two links, i.e., Edit and Delete,
2. When the user clicks on Edit link, the meter reading row should become editable and the user should be able to make the changes inline in the same table,
3. In the footer there should be a link for adding a new meter reading and when the user clicks on it, a new blank row should be added dynamically to the table and the user should be able to make a new entry into it.

Is there a module in Drupal 7 for doing so?? I have already tried out several modules for this such as SlickGrid, jQGrid and jEditable.

Any help would be great. Thanks in advance.

# Answer
I think Editable Fields module should do the trick for you. It lets you edit the fields in both node and views. Checkout the project page image for more details.

Regarding the delete option you may need to do some tweaking. Adding a 'add new meter reading' should not be very difficult. Just get the nodes value from the context and generate the add link.
> 1 votes

# Answer
Trust me :) use this modules: field\_collection , field\_collection\_views use field\_collection\_views formatter for your field\_collection field. This would automatically create the add edit and delete links to those who have permission to do so both in views as well as node view.
> 0 votes

---
Tags: views, entities
---


title: Date form element

text:
# Question
Title: Date form element
I am using the following code.

```
function mymodule_form($form, &$form_state) {
  $form = array();

  // Creating the date/time element starts here.

  // Provide a default date in the format YYYY-MM-DD HH:MM:SS.
  $date = '2008-12-31 00:00:00';

  // Provide a format using regular PHP format parts (see documentation on php.net).
  // If you're using a date_select, the format will control the order of the date parts in the selector,
  // rearrange them any way you like. Parts left out of the format will not be displayed to the user.
  $format = 'Y-m-d H:i';

  $form['date2'] = array(
     '#type' => 'date_select', // types 'date_popup', 'date_text' and 'date_timezone' are also supported. See .inc file.
     '#title' => t('Date'),
     '#default_value' => $date,
     '#date_format' => $format,
     '#date_label_position' => 'within', // See other available attributes and what they do in date_api_elements.inc
     '#date_timezone' => 'America/Chicago', // Optional, if your date has a timezone other than the site timezone.
     '#date_increment' => 15, // Optional, used by the date_select and date_popup elements to increment minutes and seconds.
     '#date_year_range' => '-3:+3', // Optional, used to set the year range (back 3 years and forward 3 years is the default).
    '#datepicker_options' => array(), // Optional, as of 7.x-2.6+, used to pass in additional parameters from the jQuery Datepicker widget.
  );

  return $form;
}

```

`$form['date2']` is an array that contains a time. I want to use just the year or the day of this array. What should I do?

# Answer
According to the comments, you can change $format to show only the elements you want, so you can do

```
$format = 'Y';

```

to select only the year, and

```
$format = 'd';

```

for the day.
> 1 votes

---
Tags: datetime
---


title: Images problem after migration

text:
# Question
Title: Images problem after migration
I have a strange problem. Today I moved a site from staging to production and the site work fine but I cannot se the images.

I can see in ftp the picture but drupal do not serve it in the page. I already tryed to clear cache.

In the reports log I there is a lot of

```
Unable to generate the derived image located at public://styles/ensemble-small/public/anne ristorcelli s.png.

```

errors but I do not understand what I can do. The GD tookit works fine.. I checked it. I tryed to re-upload some images but do not work and I can't see they in the editing page too.

Can someone help me to solve this?

UPDATE: I tryed to delete the images generaten in the staging server to verify the correct working of the images modules. The images was ok. So the problem is in server request?

If I try to see the image directly I have this error:

```
    Internal Server Error

The server encountered an internal error or misconfiguration and was unable to complete your request.

Please contact the server administrator, postmaster@ensemble05.it and inform them of the time the error occurred, and anything you might have done that may have caused the error.

More information about this error may be available in the server error log.

```

# Answer
> 1 votes
I fixed this problem going to sites/default/files/.htaccess file and commenting

```
# Options None
# Options +FollowSymLinks

```

After that I had some other broken images but there are some wrong address in the nodes tags linked to
/subdirectory-of-staging-server/sites/default/files
instead
/sites/default/files

Thank you for all the comment who help me to debug the error ^^

---
Tags: media, migrations
---


# Question
Title: Do migrate module migrations continue in background if terminal session ends?
I'm working on a migration that involves some long migration times - many hours to migrate some tables. I use the drush commands to perform my migrations, but often something happens in the middle. The window closes by accident, or I lose my Internet connection for a minute, whatever. When I open a new terminal and run 'drush ms' I see my migration marked "importing"... but is it really going to finish at some point?

# Answer
> 2 votes
You don't specify an operating system in your question, so I'll assume it's Linux/OSX.

Really, this isn't specific to drush. An applications will be sent the `SIGHUP` signal when their parent terminal exits.

The very simplest way around that is to wrap your application in `nohup`, causing it to ignore the signal.

`nohup drush status`

However, that still leaves you without control of the application should your shell close.

A better solution, is to use tmux, which runs a terminal server in the background from which you can detach, and later reattach, and one or several terminals can keep running indefinitely.

You launch tmux by simply running it.

`tmux`

Then you run whatever command you need

`drush migrate [options]`

And you can now detach, (or close the window), with `CTRL+B D`, and you will be back to the terminal where you launched tmux.

List your running tmux sessions with `tmux ls`

If you didn't name your session, an advanced feature, it will just be called 0.

Re-attach with `tmux at -t 0`, and you'll be back to your drush command.

Tmux can do a lot more than this, but figuring that out is left as an exercise to the reader.

# Answer
> 1 votes
I believe not. That is why Migrate supports a `reset` option migrations if they are orphaned or otherwise fail. Typically you run migrations as a shell user (yourself) on the system. Unless you're using something else to keep your processes alive -- they die when the terminal they're connected to die.

# Answer
> 0 votes
To ensure that your drush jobs will continue across sessions, use the screen command.

---
Tags: 7, drush, migrations
---


# Question
Title: How can I change Menus depending upon domains (url name)?
I want to change main menu items depending upon domain and sub domains url in a single site.

I could have done it easily with roles, but issue w.r.t anonymous users. How would I show or not certain items in the main menu?

# Answer
This is how I would do it:

* Create a main menu per site
* Create a context condition plugin for domain names
* Create a context per domain
* Create a context per site and place the menu block in the navigation region for each context

Profit

If you need to put the same links in multiple menus, check out the multiple node menu module.
> 1 votes

---
Tags: 7, routes
---


# Question
Title: Can theme() call a theme function from another module?
In a module I created, can I add a call to `theme()` similar to `theme('example_def', $var)` where example\_def is a theme function defined from another module?

```
function def_theme() {
return array(
  'example_def' => array(
    'arguments' => array('nid' => NULL)
  ));
}

function theme_example_def() {}

```

# Answer
> 2 votes
Yes, a module can call, with `theme()`, a theme function that is defined from another module. If it were not so, no module could use theme\_link(), since that is defined as one of the System module theme functions. This is contrary to Drupal philosophy; limiting a module to use the theme functions it defines would not make sense.

See system\_theme() which calls drupal\_common\_theme() to add link to the theme function it *implements*.

```
function drupal_common_theme() {
  return array(

    // From theme.inc.
    'html' => array(
      'render element' => 'page',
      'template' => 'html',
    ),
    'page' => array(
      'render element' => 'page',
      'template' => 'page',
    ),
    'region' => array(
      'render element' => 'elements',
      'template' => 'region',
    ),
    'status_messages' => array(
      'variables' => array('display' => NULL),
    ),
    'link' => array(
      'variables' => array(
        'text' => NULL,
        'path' => NULL,
        'options' => array(),
      ),
    ),
    // …
  );
}

```

Notice that the correct theme function definition that works for Drupal 7 is the following one; the one you are using is only for Drupal 6 or previous versions.

```
function def_theme() {
  return array(
    'example_def' => array(
      'variables' => array('nid' => NULL)
    )
  );
}

```

Since your example of calling the function is `theme('example_def', $var)`, I take you are using Drupal 7, for which your definition would not work.

---
Tags: theming
---


title: How can I create logo for each user

text:
# Question
Title: How can I create logo for each user
I want each user to create their own site-logo. This is not multi-site, this is a single site only. How can I do it?

# Answer
> 6 votes
Add a field to the user profile and use this as a replacement for the logo. Use the page\_preprocessor to add the user logo to the page template. Replace the logo by the one the user provided or show a default one.

Read more about this:

# Answer
> 5 votes
If you want each user to have their own logo, then in the account settings of admin section you can create a logo field of type image. Then in edit section of account page you can upload the image.

Then with this custom code you can able to assign logo based on each user logged in :

So in the page.tpl.php of your theme folder you can make this modifications:

```
<?php if ($logo): ?>
        <?php global $user; ?>
    <?php if($user->uid == 1 || $user->uid == 0)?>
       <a href="<?php print $front_page; ?>" title="<?php print t('Home'); ?>" id="logo">
       <img src="<?php print $logo; ?>" alt="<?php print t('Home'); ?>">
       </a>
    <?php else :?>
    <?php
         $uid = $user->uid;
         $userDetails = user_load($uid);
         $filename = $userDetails->field_site_logo['und'][0]['uri'];?>
         <a href="<?php print $front_page; ?>" title="<?php print t('Home'); ?>" id="logo">
           <img src="<?php print image_style_url('sitelogo',$filename);?>" />
         </a>
    <?php endif; ?>
<?php endif; ?>

```

Hope this helps you and saves time:)

---
Tags: 7, users
---


title: Views exposed filter selection

text:
# Question
Title: Views exposed filter selection
I want to use view to show car parts.

I have 2 exposed fields (car manufacturer and car part like doors light etc) The view work nice but what i want is to have a way for example when user click at the first list (example Audi) to show if there is any part in the another list for parts.

Ex. In Audi i have only Doors and not lights When user select from first list Audi the list for part only show Doors.

So if Audi only have nodes for Doors will show in second exposed filter only the Doors option.

Drupal 7 views 3

# Answer
From what you're describing it sounds like you need Faceted search. I'm not sure if Views filters can give you the functionality you're looking for.

Have a look at the Search Api module, it provides faceted search widgets which behave the way you described.

https://drupal.org/project/search\_api
> 0 votes

# Answer
Reference field option limit is fine to acomplish this. You want to create a term reference field in vocabulary «parts» referencing terms in vocabulary «manufacturers». I did explain it detailed in an issue.

Also for views integration this module needs a patch you can find here.
> 0 votes

---
Tags: views
---


# Question
Title: How to resolve notice : Undefined offset: 3 in user_node_load()
I have moved my entire site and got this when I want to add content:

`Notice: Undefined offset: 3 in user_node_load() (line 3604 of /storage/content/39/170239/<mysite>.se/public_html/modules/user/user.module).`

Can it have to do with the fact that I have different users now on my site and that some nodes is connected to users that may not exists? If that is the case, can I resolve this by editing my DB?

# Answer
I'd guess you might be right. I think I have a different version of the user module from you (different line numbers), but user\_node\_load() adds stuff back in from the users table.

If you are missing a user with uid 3, you will get this error.

You probably need to update all of the nodes authored by user 3 to another user, the following SQL should do the trick (replace {new\_user\_uid} by the uid of the user you want to move the nodes to):

```
UPDATE node SET uid = {new_user_uid} WHERE uid = 3;

```
> 5 votes

---
Tags: nodes, users
---


title: Disable rich text editor by default

text:
# Question
Title: Disable rich text editor by default
I am using WYSIWYG module with TinyMce as Rich Text Editor. I need to make the rich text editor disabled only for a particular text area in a create content page, i.e., when I click Enable rich-text link, it must get activated. How can this be done?I am using drupal 6

# Answer
> 1 votes
Basically, you need to alter the edit form. This is what I did for Drupal 7.

```
function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
  // Disable WYSIWYG just in this field.
  if ($form_id === 'FORM_ID_OF_EDIT_FORM') {
    $form['field_CUSTOM'][LANGUAGE_NONE][0]['#wysiwyg'] = FALSE;
  }
}

```

You may want to use `$language->language` instead of `LANGUAGE_NONE`.

# Answer
> -2 votes
I always use Wysiwyg module with the following steps:

1. Install wysiwyg module
2. Download TinyMce library to libraries (sites/add/libraries) folder
3. Create a new input format, called Wysiwyg (admin/config/content/formats)
4. Set the correct roles to this input format
5. Set this as a full html format (don't convert line breaks to brs etc)
6. Connect wysiwyg profile to this (admin/config/content/wysiwyg)

This solution is for Drupal 7 but you can do it on D6 too with the same steps, just change the administration urls.

---
Tags: 6, nodes, wysiwyg
---


# Question
Title: Error programmaticaly adding image to node using file_copy
I am trying to add an image to the article content type in Drupal 7, When I create a simple note i.e. article it works , but when I try to add the image to the article it gives an error

> The specified file E:\WS\_IntPOC\_Test4\sites\all\modules\my\_module\errorwinmobilesdk.jpg could not be copied, because the destination is invalid. More information is available in the system log

In log I can see the message as

> File E:\WS\_IntPOC\_Test4\sites\all\modules\my\_module\errorwinmobilesdk.jpg could not be copied, because the destination is invalid. This is often caused by improper use of file\_copy() or a missing stream wrapper.

I have checked the wrapper public and private is there. As if I created the Article from GUI. It is created with image loaded in public folder. Please help

```
$body_text = 'node body text';

  $node = new stdClass();
  $node->type = 'article';
  node_object_prepare($node);

  $node->title    = 'Node Created Programmatically on ' . date('c');
  $node->language = LANGUAGE_NONE;

  $node->body[$node->language][0]['value']   = $body_text;
  $node->body[$node->language][0]['summary'] = text_summary($body_text);
  $node->body[$node->language][0]['format']  = 'filtered_html';

// Some file on our system

$path ='E:\WS_IntPOCTest4\sites\all\modules\my_module\errorwinmobilesdk.jpg' ;
$file = (object) array(
          'uid' => 1,
          'uri' => $path,
          'filemime' => file_get_mimetype($path),
          'status' => 1,
 );

//$file = file_copy($file, 'public://'); // Save the file to the root of the files
$file = file_copy($file);
$node->field_image[LANGUAGE_NONE][0] = (array)$file;
//associate the file object with the image field:
node_save($node);

```

# Answer
> 1 votes
You can try this code:

```
//$filepath = drupal_realpath('misc/image.jpeg');
 [**UPDATED ANSWER**:]
 $filepath =  $_SERVER['DOCUMENT_ROOT'].base_path() .drupal_get_path('module','payment_details').'/MDSO_20.jpg';

$file = (object) array(
       'uid' => 1,
       'uri' => $filepath,
       'filemime' => file_get_mimetype($filepath),
       'status' => 1,
  );
  $file = file_copy($file, 'public://');
  $node->field_image[LANGUAGE_NONE][0] = (array)$file;
  node_save($node);

```

Hope this works for you :)

For me it created a node as you below :)

---
Tags: media
---


# Question
Title: How do I display my custom menu in administrative menu?
In my D7 website, I want to display my own custom menu in administrative menu (as in Dashboard, Content, etc.,).

I want those custom menu's available only for particular roles. How can I achieve this functionality without lot of code?

# Answer
Thats Easy. You need to goto `structure >> menus >> Management`. From there you can click on `add link` and add the menu link in that , it will automatically get added to the administrative menu toolbar.

Making that to be visible for specific roles , you need to give permission for `overlay` in that you need to enable this permission for that role `Access the administrative overlay`.

That will make your menu appear as administrative menu for what ever role you specified in permission tab of admin.
> 1 votes

---
Tags: 7, routes
---


# Question
Title: One-time URL to change a user's field value
How can I create a one-time URL (sent through email messages) users can use to change the value of a custom field?

# Answer
> 1 votes
Fortunatelly, there is a way.

You can copy function "user\_pass\_reset\_url" and form "user\_pass\_reset" and customize it for your needs. With first you create custom link and with the second you can get "one-time-link" logic.

# Answer
> 1 votes
Unfortunately Drupal requires that users reset their passwords when using the one time login link.

The easiest way to avoid that would be to use a module like URL Login, which generates login links for each of your users. There are a couple of modules which cater for similar use cases so you'll need to find out which one works best for you.

You can then use LogginToboggan to redirect your users to your custom page where they can edit the custom field. You may need to create a custom User Role depending on the need for access control.

---
Tags: users, uri
---


title: Add custom page

text:
# Question
Title: Add custom page
We can add a custom block with php code easily. Just enable php code and add a block. But what about a page? How can I add a page with custom php code?

# Answer
Since you already know how to provide a block through a custom module here is what you need to add:

```
/**
 * Implements hook_menu().
 */
function modulename_menu() {

  $items['your/special/path'] = array(
    'type' => MENU_NORMAL_ITEM,
    'title' => t('Title'),
    'description' => 'My custom and very special page',
    'page callback' => 'modulename_special_page',
    'access callback' => 'user_access',
    'access arguments' => array('access content'),
  );

  return $items;
}

/**
 * Page callback.
 */
function modulename_special_page() {
  $content = 'Hello World';
  // ... do something and add to $content;
  return $content;
}

```

So first you need to register a path by implementing hook\_menu and there you need to provide a page callback which itself returns the contents of your page.

Check out the example modules for further variations. There is one submodule that shows a lot of examples regarding registering new pages/tabs/etc.
> 11 votes

---
Tags: 7
---


title: Strict warning Error

text:
# Question
Title: Strict warning Error
I am getting this error when I create a new wiki...does anyone have any idea why this is happening and how to solve it?

> Strict warning: Creating default object from empty value in PanelizerEntityDefault-\>hook\_field\_attach\_submit() (line 1113

Thanks!

# Answer
> 2 votes
It is a bug. However, there is a workaround for it.

In admin/config/content/panelizer make sure to mark "Panelize", "Allow Panel Choice", and "Provide Default Panel".

Here is a link to where i found the solution

---
Tags: panels
---


# Question
Title: How to only display Second level of menus in Superfish?
I am using Superfish to display the menus in the left sidebar. I am using the Main Menu navigation structure which only displays the top/first level. In the sidebar, I would like to display only the second level menus. But I cannot figure out how to do this.

At the moment, the complete menu is being displayed...

PS. the reason I am using superfish is because I need the sidebar menu to be able to slide out/drop down menu items.

I have extracted https://github.com/mehrpadin/Superfish-for-Drupal/archive/1.x.zip to sites/all/libraries/superfish I have extracted http://ftp.drupal.org/files/projects/superfish-7.x-1.9.zip to sites/all/modules/superfish I have extracted ftp.drupal.org/files/projects/libraries-7.x-2.1.zip to sites/all/modules/libraries

My superfish menu parent is set to Main menu, Menu depth is set to 2 and Path levels is set to 1.

However, the superfish menu in the sidebar is always the same, regardles of what level of the menu I am in :(

# Answer
Hit 'configure block' on your superfish menu block. Under 'Menu depth' make your desired changes. This sets number of child levels starting with the parent selected above. -1 means all of them, 0 means none of them. (Default: -1)
> 1 votes

---
Tags: navigation
---


title: populate cck fields

text:
# Question
Title: populate cck fields
I have requirement, which deals with Order placing. I am not using uber cart module or any other eCommerce related modules. I have created a new content type names 'order placing', now the client requires that the title field should be filled by users name which I have added in user registration form. The second requirement is that the 'order placing' content type has a serial number field, which has to be auto generated depending on the database values.

Any ideas how could I achieve this?

Anyone?

# Answer
> 1 votes
You can use the Auto Nodetitle module along with the Token module for your title requirement. As for the second, you could hook into hook\_nodeapi() if Drupal 6, or hook\_node\_presave() if Drupal 7, to populate your number field.

---
Tags: nodes, entities
---


# Question
Title: What Hook to Use to Execute a PHP on Header and Footer in Every Page?
I have the following code that needs to be executed at the top of the page:

```
<?php
$time = microtime();
$time = explode(' ', $time);
$time = $time[1] + $time[0];
$start = $time;
?>

```

The code above should be used in my module:

```
<?php
/**
 * Implements hook_help.
 *
 * Displays help and module information.
 *
 * @param path
 *   Which path of the site we're using to display help
 * @param arg
 *   Array that holds the current path as returned from arg() function
 */
function site_visitors_help($path, $arg) {
    switch ($path) {
    case "admin/help#site_visitors":
        return '<p>' . t("Displays links to nodes created on this date") . '</p>';
        break;
    }
}

/**
 * Implements hook_init().
 */
function site_visitors_boot() {
    site_visitors_insert();
}

/**
 * Custom visitor function.
 *
 * Insert IP Address, URL to the database
 *
 * @return
 *   A result set of the targeted posts.
 */
function site_visitors_insert(){
    $tracker = array(
        'database' => 'c1tracker',
        'username' => 'c1tracker',
        'password' => 'mypass',
        'host' => 'localhost',
        'driver' => 'mysql',
    );

    Database::addConnectionInfo('tracker', 'default', $tracker);
    db_set_active('tracker');

    //This code requires the code above to compute the start time. This will compute the total page load.
    $time = microtime();
    $time = explode(' ', $time);
    $time = $time[1] + $time[0];
    $finish = $time;
    $total_time = round(($finish - $start), 4);
    $t = $total_time;
    //$url = $_GET['url'];
    $url = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
    $current_ip = $_SERVER['REMOTE_ADDR'];
    $user_agent = $_SERVER['HTTP_USER_AGENT'];
    $date = date("Y-m-d");
    $time =  date("h:i:s");

    function is_bot()
    {
        $botlist = array("Teoma", "alexa", "froogle", "Gigabot", "inktomi",
        "looksmart", "URL_Spider_SQL", "Firefly", "NationalDirectory",
        "Ask Jeeves", "TECNOSEEK", "InfoSeek", "WebFindBot", "girafabot",
        "crawler", "www.galaxy.com", "Googlebot", "Scooter", "Slurp",
        "msnbot", "appie", "FAST", "WebBug", "Spade", "ZyBorg", "rabaz",
        "Baiduspider", "Feedfetcher-Google", "TechnoratiSnoop", "Rankivabot",
        "Mediapartners-Google", "Sogou web spider", "WebAlta Crawler","TweetmemeBot",
        "Butterfly","Twitturls","Me.dium","Twiceler");

        foreach($botlist as $bot)
        {
            if(strpos($_SERVER['HTTP_USER_AGENT'], $bot) !== false)
            return true;
        }
    return false;
    }

    if (is_bot())
        $isbot = 1;
    else
        $isbot = 0;

    db_insert('ap_visits')
        ->fields(array(
            'id' => NULL,
            'length' => $t,
            'url' => $url,
            'current_ip' => $current_ip,
            'user_agent' => $user_agent,
            'date_start' => date("Y-m-d H:i:s"),
            'is_bot' => $isbot,
            'is_logout' => 0
        ))
        ->execute();

    db_set_active();
}

```

I'm wondering how can I put the first code to be called at the very top of the page and the second code (module) to be called in the footer. My purpose here is to compute the page load and put it in `length` variable.

BTW, I'm using drupal 7.

# Answer
`hook_init()` is run at the beginning of the page request. So this is where you should start your timer.

`hook_exit()` is run at the end of most regular page requests. And it's here you should stop your timer.

I did a search on similar modules and found Arooga, maybe you can find some ideas there. Also Devel has functionality to log page execution time, slow queries etc.
> 4 votes

---
Tags: 7, hooks
---


# Question
Title: What Hook to Use to Execute a PHP on Every Page?
I'm new to creating module in Drupal 7 and wondering what hook to use to execute a PHP script.

I use this tutorial but it it explain a different approach.

What I want is simply execute this code in every page:

```
db_insert('ap_visits')
    ->fields(array(
        'id' => NULL,
        'length' => $t,
        'url' => $url,
        'current_ip' => $current_ip,
        'user_agent' => $user_agent,
        'date_start' => date("Y-m-d H:i:s"),
        'is_bot' => $isbot,
        'is_logout' => 0,
    ))
    ->execute();

```

Note that I have already created .module and .info file. All I need is to know what hook to put the code above.

Thanks for any help.

# Answer
I would look into hook\_init() if you don't require this to be run on cached pages, hook\_boot() if you do.
> 4 votes

# Answer
Since you want to write in the database, I would do what the Statistics module that comes with Drupal does.

```
function statistics_exit() {
  global $user;

  // When serving cached pages with the 'page_cache_without_database'
  // configuration, system variables need to be loaded. This is a major
  // performance decrease for non-database page caches, but with Statistics
  // module, it is likely to also have 'statistics_enable_access_log' enabled,
  // in which case we need to bootstrap to the session phase anyway.
  drupal_bootstrap(DRUPAL_BOOTSTRAP_VARIABLES);

  if (variable_get('statistics_count_content_views', 0)) {
    // We are counting content views.
    if (arg(0) == 'node' && is_numeric(arg(1)) && arg(2) == NULL) {
      // A node has been viewed, so update the node's counters.
      db_merge('node_counter')->key(array('nid' => arg(1)))->fields(array(
        'daycount' => 1,
        'totalcount' => 1,
        'timestamp' => REQUEST_TIME,
      ))->expression('daycount', 'daycount + 1')->expression('totalcount', 'totalcount + 1')->execute();
    }
  }
  if (variable_get('statistics_enable_access_log', 0)) {
    drupal_bootstrap(DRUPAL_BOOTSTRAP_SESSION);

    // For anonymous users unicode.inc will not have been loaded.
    include_once DRUPAL_ROOT . '/includes/unicode.inc';
    // Log this page access.
    db_insert('accesslog')->fields(array(
      'title' => truncate_utf8(strip_tags(drupal_get_title()), 255),
      'path' => truncate_utf8($_GET['q'], 255),
      'url' => isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : '',
      'hostname' => ip_address(),
      'uid' => $user->uid,
      'sid' => session_id(),
      'timer' => (int) timer_read('page'),
      'timestamp' => REQUEST_TIME,
    ))->execute();
  }
}

```

`hooK_boot()` is invoked Drupal has not yet completed its bootstrap. That means, for example that not all the module functions are not available. As for the Drupal functions, not all the functions are available, since some include files are loaded when Drupal completes its bootstrap. See \_drupal\_bootstrap\_full().

```
  require_once DRUPAL_ROOT . '/' . variable_get('path_inc', 'includes/path.inc');
  require_once DRUPAL_ROOT . '/includes/theme.inc';
  require_once DRUPAL_ROOT . '/includes/pager.inc';
  require_once DRUPAL_ROOT . '/' . variable_get('menu_inc', 'includes/menu.inc');
  require_once DRUPAL_ROOT . '/includes/tablesort.inc';
  require_once DRUPAL_ROOT . '/includes/file.inc';
  require_once DRUPAL_ROOT . '/includes/unicode.inc';
  require_once DRUPAL_ROOT . '/includes/image.inc';
  require_once DRUPAL_ROOT . '/includes/form.inc';
  require_once DRUPAL_ROOT . '/includes/mail.inc';
  require_once DRUPAL_ROOT . '/includes/actions.inc';
  require_once DRUPAL_ROOT . '/includes/ajax.inc';
  require_once DRUPAL_ROOT . '/includes/token.inc';
  require_once DRUPAL_ROOT . '/includes/errors.inc';

  // Detect string handling method
  unicode_check();
  // Undo magic quotes
  fix_gpc_magic();
  // Load all enabled modules
  module_load_all();
  // Make sure all stream wrappers are registered.
  file_get_stream_wrappers();

```

As for `hook_boot()` and `hook_exit()` being invoked, that happens depending on the value of a Drupal variable, since the code being used in \_drupal\_bootstrap\_page\_cache() is the following.

```
  // If the skipping of the bootstrap hooks is not enforced, call
  // hook_boot.
  if (variable_get('page_cache_invoke_hooks', TRUE)) {
    bootstrap_invoke_all('boot');
  }
  drupal_serve_page_from_cache($cache);
  // If the skipping of the bootstrap hooks is not enforced, call
  // hook_exit.
  if (variable_get('page_cache_invoke_hooks', TRUE)) {
    bootstrap_invoke_all('exit');
  }

```

A hook that is always called when Drupal completes its bootstrap is, for example, hook\_page\_alter(). It is invoked when Drupal is rendering a page with drupal\_render\_page(); if you are checking when a user visits a page, that could be hook you could use.
> 1 votes

---
Tags: 7, hooks
---


title: Exclude tpl files in multisite theme

text:
# Question
Title: Exclude tpl files in multisite theme
I'm working in a multisite, the theme had `page--front.tpl.php` file for the main site, but I want to exclude this file in the other sites.

How can I do this?

# Answer
> 0 votes
Its trickier to 'remove' the template on sites you don't want it on because Drupal will always recognize the file format as a valid template and add it to theme suggestions. An easier option would be to affirmatively add it using a custom module only on the sites you want it on. For example, following this answer, here's how you would register a particular template file only on the subsites you want by just selectively enabling the module where you need it:

```
/*
 * Implementation of hook_theme().
 */
function YOUR_SUBSITE_MODULE_theme($existing, $type, $theme, $path){
  return array(
    'YOUR_SUBSITE' => array(
      'variables' => array('content' => NULL),
      'file' => 'page--front', // place your file in 'theme' folder of you module folder
      'path' => drupal_get_path('module', 'YOUR_SUBSITE_MODULE') .'/theme'
    )
  );
}

function YOUR_SUBSITE_MODULE_page(){

  // some code to generate $content variable

  return theme('YOUR_SUBSITE', $content); // use $content variable in moon.tpl.php template
}

```

---
Tags: theming, multi-sites
---


title: create table with sticky head

text:
# Question
Title: create table with sticky head
how can I create table with sticky head. I try theme\_table but it output a simple table without floating head.

# Answer
> 0 votes
In drupal 6, table will have sticky header by default. I did not see this because my table has few rows and my site has not any scroll :). its described on API: theme\_table

# Answer
> 0 votes
This is what I did:

```
/* Make table headers stick to the top */

/* Put tables inside two divs */
var tables = $("table");
tables.each(function(){
    var parent = $(this).parent();
    var container = $("<div class='table-container'></div>");
    container.append($(this));
    parent.append(container);
});

var inners = $(".table-container");
inners.each(function(){
    var parent = $(this).parent();
    var container = $("<div class='outer'></div>");
    container.append($(this));
    parent.append(container);
});

var widths = new Array();

//create array of <th> widths
var i = 0;
$('tbody tr:first td').each(function () {
    widths[i] = $(this).width();
    i++;
});

// Make th have same size as td
i = 0;
$('thead > tr > th').each(function(){
    $(this).width(widths[i] + 1);
    i++;
})

/* ------------- Reposition the thead so it won't overlap -----------------*/
var h = 0;
// Move the thead up.
$('thead').each(function(){
    h =$(this).height();
    $(this).css('top', -$(this).height() + 1)
})

 //Now move the whole table down same distance
$('.outer').each(function(){
     $(this).css('top', h);
})

```

And then add this css:

```
/*----------------Sticky Headers ---------------------*/

```

.outer{ position:relative; }

.table-container{ overflow-y:auto; padding-right: 1px; }

.outer thead{ position:absolute; }

Important: Remember to set a max height for your tables so you can see it working. Note: this method won't make it stick to the top of the browser, but into its container div.

---
Tags: 6, theming
---


# Question
Title: Is there a function for drupal that can identity if a certain page and its children are being viewed?
So I have nav that looks like this:

```
<li>
  <a href="/some-parent-url">Parent Url</>
  <ul>
    <li>
       <a href="/some-parent-url/child-url-2">Child Url</a>
    </li>
    <li>
       <a href="/some-parent-url/child-url-2">Child Url</a>
    </li>
  </ul>
</li>

```

I would like to add an "active" class to the Parent URl if a user is on the page with url "some-parent-url" or any of it's parent url?

Ideally something like

```
<a href="/some-parent-url" <?php if (some_drupal_code_for_this){ echo 'class="active"'; } ?>>Parent Url</>

```

# Answer
You could use Menu Trail By Path module.

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

For example if you are at yoursite.com/blog/category1/article1 Menu Items with these paths will get the active-trail class on them and expand accordingly.
> 1 votes

# Answer
In Drupal 7, you can achieve this by using contributed modules and also by programatically.

**Using Context module**.

* Go to admin » structure »context » add
* While adding new context go to **Conditions** category and click **\<add a condition\>** and select **PATH** in the list and add **YOUR\_PATH**.
* Now its time to ACTIVE the MENU. Go to **Reactions** category and click **\<add a reaction\>** and and select **MENU** in the list. And select the MENU which you want to be active.
* For this example I have selected **Article** as an active menu item.
* I have made **Article** as an active menu item for the following contexts. Each contexts have different path, but have same active menu item.

**Programatically** :

* By using menu\_get\_active\_trail and menu\_set\_active\_item we can achieve it
* **menu\_get\_active\_trail** \- To gets the active trail of the current page.
* **menu\_set\_active\_item** \- To sets the active trail of the current page.

```

function THEMENAME_preprocess_page(&$vars) {
    $trail = menu_get_active_trail();//get the active menu trail
        if (count($trail) >= 3) {//if there are children menu items
        menu_set_active_item($trail[1]['link_path']);//set the active menu
    }
}

```
> 1 votes

# Answer
If this isn't a menu you may want to use Drupal args and check if your anchor's URL equals the args. If this is a menu consider to use menu\_get\_active\_trail() .
> 0 votes

# Answer
You could use Crumbs \+ Menupoly.

With Crumbs, you make sure that any child page where you want the parent item to be highlighted is in the breadcrumb.

With Menupoly, you can display a menu, where items are expanded and highlighted if they are in the Crumbs breadcrumb trail, even if the current page is not in the menu.

E.g. if the menu only goes as deep as "Parent \> Child", but your page is at "Parent \> Child \> Grandchild \> Grandgrandchild" (without being in any menu), then Menupoly would still expand / highlight the "Parent \> Child" menu links in the menu.

So, the effect is similar to Menu Trail By Path as suggested by Nikhil M. You need to figure out which of them is more practical for your taste.

You need a little bit of programming to make the menupoly menu show up. This is explained on the module page.
> 0 votes

---
Tags: paging, views
---


# Question
Title: How to pass a nid to panel, and load a node with the given nid as context?
The panel has a custom path, Like this: http://example.com/mypanel/something/theNID/something\_else

So the arguments to the panel are:

1. something
2. theNID
3. something\_else.

How can I load a node with some variable nid (*theNID* in this case), and have it available as a `context` in the panel, and then, make all of it's fields accessible directly in that panel?

If I create a view and load the node (with *theNID*) within the view, the view won't pass the loaded node as context to panels.

# Answer
1. Settings -\> Basic -\> Path -\> something/%node/something\_else
2. Settings -\> Arguments -\> Change -\> Content: ID

Then at 'Variants -\> Contexts' you should see the loaded 'Argument 1'.
> 2 votes

# Answer
The answer is: For sending panel an argument, A % sign must be used, And just using panel option "Path string from URL" or something like that is NOT the fun/right way, Instead, The path should be: http://exmaple.com/something/%nid/%what

Then panel will ask what %nid is, Saying it's a node, Panel will load it as an available context automatically.

Short Answer: Use %nid instead of nid when choosing panel path on panel setting form.
> 0 votes

---
Tags: panels
---


title: Payment to make a node featured

text:
# Question
Title: Payment to make a node featured
I want users of a particular role to pay for featured nodes. On my site, the user role "premium member" is able to create nodes of type "products," but they have to pay to make their node (product) featured--for this I have a CCK checkbox field which will be checked on payment.

I am using moneyscript module for subscriptions, but I do not understand how to use it for my requirements.

I am thinking about using a custom module, but I'm also not understanding where to start and what should be the approach.

# Answer
> 0 votes
I presume you're using the MoneyScripts "Membership Suite" module? You'll want to install the Rules contrib module, which will allow you to modify content (your node's CCK field) when a payment is made:

> New Rules Integration allows you to take action when users purchase a new membership, make a payment, cancel their membership, etc! The possibilities are limitless!

---
Tags: commerce
---


# Question
Title: How to remove the grid from a zone in Omega
I have an Omega subtheme that I am working on, and a request has come in to have a zone and all regions within the zone not be gridded. By not gridded, I mean that I need the zone and all regions inside it to not be bound by any of the widths that 960.gs imposes. Just having the full width wrapper around the zone is not sufficient for that the requested layout.

I am not sure what the best way to do this is.

Inside `template_process_zone()` I can remove the grid classes from `$variables["content_attributes_array"]["class"]` and inside `template_process_region()` I can remove them from `$variables["classes_array"]`. This is a little messy because it assumes prior knowledge of all the grid classes (or at least the patterns), but it mostly managable.

The problem is that I can't see how I can figure out what zone I am in from within a region. I want to avoid hardcoding region names in the `template_process_region()` for those to degridify.

I could also override the grid with CSS for a particular zone, but there are a lot of rules to override to future proof any changes.

Is there a well tested solution to this or other options that I am not considering?

# Answer
Could you elaborate on what it means not to be gridded inside a zone? If you just make a single region inside the zone that is as wide as the zone, then you could lay out content in the region however you want. Your CSS would just have the zone or region class as a prefix to anything else in that region.

Or, are you trying to get rid of the gutters? If so, you could make a custom grid of some number of columns with zero-width gutters. Then you have to add padding and margins yourself to your content. I have a site with an Omega grid-based layout with zero-width gutters, and do some non-grid-based layout inside certain regions.. For instance, I have pairs of images side by side inside the right sidebar. They are not aligned with the grid columns.
> 1 votes

# Answer
If I understand correctly, easy to do with css. On the zone...add position:absolute and width: 100%. On the region inside it (assuming there is only 1 region)...add width:100%
> 0 votes

---
Tags: 7, theming
---


title: How to add new fields in Drupal

text:
# Question
Title: How to add new fields in Drupal
I'm just starting out with Drupal, and I have no idea what I'm doing.

I already have the postal code which I can convert to latitude and longitude using the Google Geocoding API.

My problem is how to create the fields that will store the latitude and longitude and how to insert those values in the database so that I can use them in a search view which uses the Search API Solr search module.

All I need is for someone to point me out to what I need to do, maybe some tutorials or resources that will enlighten me so that I know what I'm doing. Please help, thanks!

# Answer
> 1 votes
Assuming you use Drupal 7, it is trivial to add fields to any entity using the build-in *Fields* module. (If you see references to "CCK", note that this is not for Drupal 7, but to an older version of this feature.) With fields, you can enhance Drupal 7 with new data types and entity types from the front end admin interface.

The term "field" refers to a given piece of content within an entity. A field is characterised by having a *field name*, *field type* and *widget*. A widget in this context can be a HTML form element or jQuery widget that is to be used for data entry.

To have latitude and longitude fields in your entity, you should install the Geofield module. This will give you access to geofields as native datatypes, and also a widget for entering map coordinates if you need that.

To add fields to an entity, start by navigating to *Structure → Content types*, and click on *manage fields* for the content type you want to add new fields to. This can be one of the build-in content types, or a custom content type you've defined.

Clicking on *manage fields* brings up a form that shows what fields are already present in the entity. Here you can delete or add new fields to the entity. Add your geofields and click *Save*.

However, if you want to insert values into those fields programatically (instead of interactively using a widget), you need to create a small custom module that uses the Drupal database API to insert the values into the fields in the database.

Here are links to some fields tutorials that tells you more about how to use fields:

---
Tags: entities
---


# Question
Title: How to set the comment body field to be required?
I have created a comment section in my node. But it is not displaying the required option. if the comment is posted no validation occurs.

# Answer
> 1 votes
For What ever content type you are giving comments options, you need to go to

`structure >> Content types >> Edit the particular content type >> there will be comments fields tab >>` over there will be list of comments field, in that comment\_body(machine name) wil be required by default.

If not, make it required by editing that field.

---
Tags: comments, forms
---


# Question
Title: Where should libraries be copied to sites/all or sites/all/modules?
I currently have it in both locations, but figure this is incorrect. The problem is, when I try to remove it from sites/all/modules the superfish module complains, and says that it's needed.

What am I doing wrong?

# Answer
> 1 votes
It should be in the `sites/all/libraries`. For your information you need to create that libraries folder.

\[**UPDATED ANSWER**\]

You need to install Libraries Module too in this location `sites/all/modules/libraries`(this is a module).

Where as what you created as folder in `sites/all/libraries` folder, you will copy third party js files etc. (example is that you need to copy for superfish module, a set of library files superfish.js file in this place only(`sites/all/libraries/superfish`))

If you do all this things then there will be no issues.

Also remember to give permission for newly created libraries folder(`sites/all/libraries`).

# Answer
> 2 votes
You must create a directory `libraries` inside `sites/all folder`.

---
Tags: navigation, theming
---


title: How to avoid that Drupal encodes my url

text:
# Question
Title: How to avoid that Drupal encodes my url
I use hook\_url\_outbound\_alter to change my url to /q=anything, but the url in browser is shown as /q%3Danything. How can I avoid that Drupal encodes the url?

Other choice would be to send q=anything as query, but then hook\_url\_outbound\_alter includes the "?" character, and I can't include it.

```
if (preg_match('|^search/node/(.*)|', $path, $matches)) {
  $path = 'q=' . $matches[1];
}

```

Any idea? Thanks in advance.

# Answer
> 1 votes
you shouldn't need to add the "q=" drupal will deal with that side of things, especially when you turn on clean urls.

# Answer
> 0 votes
If you want to add `?q=anything` to the path you should add your query as an option to the `$options` array.

```
if (preg_match('|^search/node/(.*)|', $path, $matches)) {
  $options['query'] => array('q' => 'anything');
}

```

# Answer
> 0 votes
You cannot get a path like q=anything without encoding the equal sign; that is done to avoid problems with a path like q=anything?parameter=value. Your alternatives are just two:

* Get the question mark before the q doing as Pontus Nilsson said
* Avoid using q=anything, and use q/anything

The latter is what Drupal normally does. In fact, the path for a node is node/node-id, not node=node-id; the path for a user profile is user/user-id, not user=user-id.

Keep in mind that a clean path like node/1 is translated to index.php?q=node/1 in the .htaccess file. In your case, q=anything would be translated to index.php?q=q=anything. That is the reason why the second equal sign needs to be encoded.

---
Tags: uri
---


# Question
Title: How do I get translated strings into Drupal.locale.strings?
So I'm trying to use the Drupal.t() function in some of my custom Javascript code (in my theme).

How do I get the strings I need populated in the Drupal.locale.strings object? I see some strings in there, but of course the entire database can't be loaded. What's the best way to add to it? I would like to use the PHP t() function so that the strings added can be edited in the Translate interface.

# Answer
Drupal handles populating the needing strings into the javascript object. Much like the entire collection of strings isn't loaded on every page, only the needed strings are added to the JavaScript.

I believe this is done by traversing the script files before they are actually added to the page.

So if you add `Drupal.t('Some string');` to your JavaScript code, you should be able to translate that in the translate interface.
> 8 votes

# Answer
Just ran into this same issue today and researched it a bit more. Chris above has a good comment, but it's ultimately incorrect. You do not need to use Drupal.behaviors for it to work.

As noted by JonMcL himself in his last comment, the function \_locale\_parse\_js\_file in locale.inc is responsible for the parsing of Drupal.t("somestring") patterns starting from row 1493 (in Drupal 7.22):

```
preg_match_all('~
[^\w]Drupal\s*\.\s*t\s*                       # match "Drupal.t" with whitespace
\(\s*                                         # match "(" argument list start
(' . LOCALE_JS_STRING . ')\s*                 # capture string argument
(?:,\s*' . LOCALE_JS_OBJECT . '\s*            # optionally capture str args
  (?:,\s*' . LOCALE_JS_OBJECT_CONTEXT . '\s*) # optionally capture context
?)?                                           # close optional args
[,\)]                                         # match ")" or "," to finish
~sx', $file, $t_matches);

```

It's just a "dumb" parsing function that doesn't care about semantics and simply finds all instances of Drupal.t("something") in any file it receives.

What could be a common gotcha is that you need to have the whole string in your source code in the Drupal.t("translateme") form, because (obviously) no javascript gets executed when the file is opened through file\_get\_contents in php. That means you can never do Drupal.t(somevariable) and hope Drupal will catch all string-containing javascript variables that you throw at Drupal.t.

If you want to translate "women" for a chart and give the string a context, the syntax would be:

```
Drupal.t("women", {}, {context: "charts"}

```

Also, if you have drush installed, verify your js file is parsed with the command;

```
drush vget javascript_parsed

```

Then you can clean your cache with

```
drush cc all

```

... and repeat the vget command above to verify the list of already parsed files is empty. This way your file will get reparsed next run (verify that too).
> 6 votes

# Answer
Couple gotchas I've run into while implementing multilingual JS in Drupal 7:

1. First, make sure your JS file is **not being included inline**. As of Drupal 7.22, `Drupal.locale.strings` doesn't seem to automatically update itself if you're inlining JavaScript files in Drupal. The translation interface still picked up the string anyway, adding to my confusion.
2. Second, make sure you're using Drupal.behaviors to attach your JS to the page. Regular JS closures will not trigger Drupal's "magic" parsing of `Drupal.t()` invocations. This is technically something you should be doing anyway ;)

From there it really is pretty painless. Just use `Drupal.t()` around text you want translated, clear your cache each time you update the file, and your translators should see the new string in the interface at `/admin/config/regional/translate/translate`. It's quite nice once you get it working.
> 0 votes

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


# Question
Title: To get a table in drupal 7 same as content_type_[your_field_name] in drupal 6?
In the **Drupal 6** database, for every content type, there is a table that's called **content\_type\_\[your\_field\_name\]**  Now I have a database query as follows in drupal 6 :
```
db_query("SELECT n.nid FROM {node} n INNER JOIN {content_type_field_abc} s ON n.vid = s.vid
                          INNER JOIN {def_table} sts ON s.nid = sts.nid
                          WHERE n.type = 'trans' AND s.field_study = '%s' AND sts.status = 1", $account->name);

```
Then how can I use db\_query in **drupal 7** to get **a table containing all the fields of the content type as columns** same as drupal 6 ?

Or
Simply, how can I write the **above given query** in drupal 7 ?

# Answer
That depends what fields you have defined in your content type.

An easier way is to load the node object and fetch your data from it.

`$node = node_load($nid);`

If you install the Devel module you can do `dpm($node);` and find how to access all data attached to your node.
> 1 votes

---
Tags: 7
---


# Question
Title: How to Modify Download Link using Module
I am using `display suite` to customize the look of my node. I created a `code field` in `display suite` named `Download Code` and customize the downloading of file field called `field_code_file` using the following code:

```
<?php
global $user;

if (!isset($_SESSION['downinc'])) $_SESSION['downinc'] = 1;

if ($user->uid) $_SESSION['downinc'] = 0;
?>

<form id="form1" name="form1" method="post" action="/download-code">
    <input type="hidden" name="download_code" id="download_code" value="[node:field_code_file]" />
    <input type="hidden" name="uri" id="uri" value="[node:url:relative]" />
    <input type="submit" class="downloadButton" value="Download Code">
</form>

```

When my visitors download the code, he/she will be redirected to the download-code page. A normal `Page` node I created with PHP Code as text format. Since I learned that it is not advisable to use PHP code in node, I have created a module (not for this one) and transfer all the code from it to my simple module. You can find the module that I have created at this link. That works great. But what I want now is also transfer the code I have above and below into a module.

Here's my code in the download-page node:

```
<script language="javascript">
var time_left = 5;
var cinterval;

function time_dec(){
  time_left--;
  document.getElementById('countdown').innerHTML = time_left;
  if(time_left == 0){
    clearInterval(cinterval);
  }
}

cinterval = setInterval('time_dec()', 1000);
</script>

<?php
header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
header("Cache-Control: no-store, no-cache, must-revalidate"); // HTTP/1.1
header("Cache-Control: post-check=0, pre-check=0", false);
header("Pragma: no-cache"); // HTTP/1.0
header("Expires: Sat, 26 Jul 1997 05:00:00 GMT"); // Date in the past

if (!isset($_SERVER['HTTP_REFERER']))
{
    echo 'Do not call this file directly';
    exit();
}

$tracker = array(
    'database' => 'c1tracker',
    'username' => 'c1tracker',
    'password' => 'mypass',
    'host' => 'localhost',
    'driver' => 'mysql',
);

Database::addConnectionInfo('tracker', 'default', $tracker);
db_set_active('tracker');

$current_ip = $_SERVER['REMOTE_ADDR'];
$referrer = $_SERVER['HTTP_REFERER'];
$user_agent = $_SERVER['HTTP_USER_AGENT'];

global $user;

if (!isset($_SESSION['downinc'])) {
    //set session here since it was not set from the referrer page because of caching.
    $_SESSION['downinc'] = 1;

    $error = "Invalid download. No Session.";

    $sql = "INSERT INTO `download_log` (`id`, `error`, `ip_address`, `referrer`, `user_agent`, `date_time`) VALUES (NULL, '$error', '$current_ip', '$referrer', '$user_agent', now())";

    db_query($sql);
}

if (!isset($_POST['download_code'])){
    $error = "Invalid download. File not set.";

    echo "<p>$error</p>";
    echo "<p>Please clear your browser's cache.</p>";
    echo "<h4><a href=\"http://www.mysite.com/user/register\">Sign up</a> now or <a href=\"http://www.mysite.com/user/login\">login</a> if you are an existing member.</h4>";

    $sql = "INSERT INTO `download_log` (`id`, `error`, `ip_address`, `referrer`, `user_agent`, `date_time`) VALUES (NULL, '$error', '$current_ip', '$referrer', '$user_agent', now())";

    db_query($sql);
}else{
    $file = $_POST['download_code'];

    if ( $_SESSION['downinc'] < 4 || $user->uid ) {
        header("Refresh: 5; URL=$file");

        $_SESSION['downinc'] = $_SESSION['downinc'] + 1;

        echo "<p>Your download will start in <span id=\"countdown\">5</span> seconds...</p>";
    }else{
        $uri = substr($_POST['uri'],1);

        echo "<p>You have downloaded code 3 times.</p>";
        echo "<p>To continue downloading, please login or register.</p>";
        echo "<h3><a href=\"http://www.mysite.com/user/register?destination=$uri\">Sign up</a> now or <a href=\"http://www.mysite.com/user/login?destination=$uri\">login</a> if you are an existing member.</h3>";
    }
}

db_set_active();
?>
<p>Problems with the download? Please go back to previous <a href="<?php echo $referrer ?>">page.</a></p>
<p>If you have problem downloading this file, kindly <a href="http://www.mysite.com/contact">contact us</a>.</p>

```

So anyone can guide me on where to start? What hook do I need in order to catch the link from `Download Code` created using `display suite`?

BTW, I'm using drupal 7.

# Answer
I'm not sure how to integrate with Display Suite, I have some idea for putting a form in an individual page and then make your logic work.

In your module you should implement hook\_menu() to tell Drupal that there's an URL to handle. For that URL you could specify a callback that will show your form.

Using Drupal's From API, you can build a nice form (with CSRF protection) with all the logic you need.

Here's some code example. Please keep in mind that this is untested code and it should only give you some ideas to write yours.

```
function site_visitors_menu() {
  $items['download-code'] = array(
    'title' => 'Download my stuff',
    'page callback' => 'drupal_get_form('site_visitors_download_form')',
    'access arguments' => array('access content'),
  );
  return $items;
}

function site_visitors_download_form($form, &$form_state) {
  $form['download_code'] = array(
    '#type' => 'hidden',
    '#value' => token_replace('[node:field_code_file]', array('node' => $node)), //not sure how to deal with this, you should load the node first with a node_load()
  );
  $form['uri'] = array(
    '#type' => 'hidden',
    '#value' => token_replace('[node:url:relative]', array('node' => $node)), //same as above
  );
  $form['submit'] = array(
    '#type' => 'button',
    '#value' => t('Download Code'),
    '#weight' => 10,
  );
  return $form;
}

function site_visitors_download_form_validate($form, &$form_state) {
  if (!empty($form_state['values']['download_code'])){

      $sql = "INSERT INTO `download_log` (`id`, `error`, `ip_address`, `referrer`, `user_agent`, `date_time`) VALUES (NULL, '$error', '$current_ip', '$referrer', '$user_agent', now())";

      Database::addConnectionInfo('tracker', 'default', $tracker);
      db_set_active('tracker');
      db_query($sql);
      db_set_active();
      form_set_error('download_code', "<p>Invalid download. File not set.</p><p>Please clear your browser's cache.</p><h4><a href=\"http://www.mysite.com/user/register\">Sign up</a> now or <a href=\"http://www.mysite.com/user/login\">login</a> if you are an existing member.</h4>"); //not sure about this, because the field is hidden
  }
}

function site_visitors_download_form_submit($form, &$form_state) {
  $js = "var time_left = 5;
  var cinterval;

  function time_dec(){
    time_left--;
    document.getElementById('countdown').innerHTML = time_left;
    if(time_left == 0){
      clearInterval(cinterval);
    }
  }

  cinterval = setInterval('time_dec()', 1000);"
  drupal_add_js($js, 'inline');

  drupal_add_http_header("Last-Modified", gmdate("D, d M Y H:i:s") . " GMT");
  drupal_add_http_header("Cache-Control", "no-store, no-cache, must-revalidate"); // HTTP/1.1
  drupal_add_http_header("Cache-Control", "post-check=0, pre-check=0", false);
  drupal_add_http_header("Pragma", "no-cache"); // HTTP/1.0
  drupal_add_http_header("Expires", "Sat, 26 Jul 1997 05:00:00 GMT"); // Date in the past

  /* this should not be necessary any more
  if (!isset($_SERVER['HTTP_REFERER']))
  {
      echo 'Do not call this file directly';
      exit();
  }
  */
  $tracker = array(
      'database' => 'c1tracker',
      'username' => 'c1tracker',
      'password' => 'mypass',
      'host' => 'localhost',
      'driver' => 'mysql',
  );

  $current_ip = $_SERVER['REMOTE_ADDR'];
  $referrer = $_SERVER['HTTP_REFERER'];
  $user_agent = $_SERVER['HTTP_USER_AGENT'];

  global $user;

  if (!isset($_SESSION['downinc'])) {
      //set session here since it was not set from the referrer page because of caching.
      $_SESSION['downinc'] = 1;

      $error = "Invalid download. No Session.";

      Database::addConnectionInfo('tracker', 'default', $tracker);
      db_set_active('tracker');

      $sql = "INSERT INTO `download_log` (`id`, `error`, `ip_address`, `referrer`, `user_agent`, `date_time`) VALUES (NULL, '$error', '$current_ip', '$referrer', '$user_agent', now())";

      db_query($sql);
      db_set_active();
  }

  /* moved into _validate()
  if (!isset($form_state['values']['download_code'])){
      $error = "Invalid download. File not set.";

      echo "<p>$error</p>";
      echo "<p>Please clear your browser's cache.</p>";
      echo "<h4><a href=\"http://www.mysite.com/user/register\">Sign up</a> now or <a href=\"http://www.mysite.com/user/login\">login</a> if you are an existing member.</h4>";

      $sql = "INSERT INTO `download_log` (`id`, `error`, `ip_address`, `referrer`, `user_agent`, `date_time`) VALUES (NULL, '$error', '$current_ip', '$referrer', '$user_agent', now())";

      db_query($sql);

  }else{*/
      $file = $form_state['values']['download_code'];

      if ( $_SESSION['downinc'] < 4 || $user->uid ) {
          drupal_add_http_header("Refresh", "5; URL=$file");

          $_SESSION['downinc'] = $_SESSION['downinc'] + 1;

          return "<p>Your download will start in <span id=\"countdown\">5</span> seconds...</p>";
      }else{
          $uri = substr($form_state['values']['uri'],1);

          return "<p>You have downloaded code 3 times.</p><p>To continue downloading, please login or register.</p><h3><a href=\"http://www.mysite.com/user/register?destination=$uri      \">Sign up</a> now or <a href=\"http://www.mysite.com/user/login?destination=$uri\">login</a> if you are an existing member.</h3>";
      }
  //}
}

```
> 0 votes

---
Tags: 7, hooks
---


# Question
Title: Drupal content type node not overwriting the default node.tpl.php
I have a content type with a machine name of 'school' after reading the documentation I should be able to just create a node-school.tpl.php to toy with the output of this in my theme.

Yet it does not seem to be overwriting it. I am trying to hack something together and I am using the twitter bootstrap Drupal theme.

# Answer
If its drupal6 site then it is `node-school.tpl.php` . If Druapl7 then tpl should be `node--school.tpl.php`.

After Creating the files you need to clear the performance cache once.
> 2 votes

# Answer
It should be **node--school.tpl.php** for drupal 7 and **node-school.tpl.php** for drupal 6. And make sure to clear your cache
> 1 votes

---
Tags: theming, nodes
---


# Question
Title: Mark only Event's start date on calendar?
I am using calendar module, I created a view of calendar type that showing the event start date and end date. I just only want to mark the start date of event (Like change the background color.). How to do that?

Currently showing like this :

# Answer
I took different `Start date` and `End date` field.
> 0 votes

# Answer
Try setting the end date the same as the start date
> 0 votes

---
Tags: 7, datetime
---


title: A gallery display formatter for Media

text:
# Question
Title: A gallery display formatter for Media
I'm using Media, version 7.X, and I'm looking for a module that creates a display widget as a gallery for a "file" field.

I'v tried Media Gallery but I can't use "dev" versions.

Any suggestion?

# Answer
Create Block using views module and show in sidebar.
> -1 votes

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


# Question
Title: Multiple image sizes from one uploaded image?
In my content type, I've got an image uploader. That image then gets processed by an Image Style that scales the image. I want to produce multiple scaled sizes of that image though. So essentially, I need to assign multiple Image Styles to that one image upload. In the UI, I can only assign one. This is Drupal 7, by the way.

So, for example: I start by uploading an 800x600 image and I've applied an Image Style to output it at 400x300. Now I want to apply another Image Style to get a 200x150 version. And so on...

Surely, I'm missing something here! Seems like a straightforward request. Thanks in advance!

# Answer
This is the function that I was looking for:

```
image_style_url($style_name, $path)

```

More info here.

(*Should have done a little more digging via Google before I asked!*)
> 2 votes

# Answer
```
drush image-flush

```

is a very useful command to regenerate all images associated to any defined Image Style. Use

```
drush image-flush -h

```

for details.
> 1 votes

---
Tags: 7, media
---


# Question
Title: Adding value to multi-delta textfield programmatically
I have a phone field in a form, which is just a textfield with its default widget. I'm trying (and failing) to add values to this field programmatically through ajax calls.

I have an ajax call elsewhere on the form, the purpose of which is to add several values to the phone (text) field, and let the user continue to edit them or add more.

My strategy in the ajax callback function has been to take the first textfield delta as a template, and reproduce it to add more. That's not working, because there are too many values to set that have side effects, like \['#delta'\] or \['#max\_delta'\]. The modules that manage this even seem to use #id suffixes to control behaviours.

The code below loads the values all right (3 of them show up on the form after the call), but when I press "Add another item", the field collapses from 3 values to 2. A subsequent "Add another item" call then opens up a blank new item, ie starts to behave normally. So something amiss after my ajax operation on the form structure, but gets reset with the first subsequent "Add another item" call. But I haven't been able to isolate what the problem is.

In any case, I think I'm using a bad strategy, and instead need some kind of helper function, or at least a strategy that conforms to Drupal-wide patterns.

So, how do I do this? I need a strategy or an example.

Here's my current ajax callback. The parts other than phone update are working, but the phone part is a mess. The phone part demonstrates what I want to do with updating phones, and the complexity shows why my current strategy isn't working for that phone part.

```
function rc_business_card_populate_from_staff($form,&$form_state)
{
       // ===============================================
       // THIS PART WORKS
    $selected_staff_id = $form_state['values']['line_item_fields']['field_staff']['und'][0]['profile_id'];
    if (is_null($selected_staff_id)) return $form; // do nothing
    // assemble input fields for data
    $address = &$form['line_item_fields']['field_recipient_address']['und'][0];
    $street_block = &$address['street_block'];
    $locality_block =  &$address['locality_block'];
    $organisation_block =  &$address['organisation_block'];
    $name_block =  &$address['name_block'];
    $values = array(
        // address field:
        'name_line' => &$name_block['name_line']['#value'],// Full Name
        'organisation_name' => &$organisation_block['organisation_name']['#value'], // Company
        'thoroughfare' => &$street_block['thoroughfare']['#value'], // Address 1
        'premise' => &$street_block['premise']['#value'],// Address 2
        'locality' => &$locality_block['locality']['#value'], // City
        'administrative_area' => &$locality_block['administrative_area']['#value'], // Province
        'postal_code' => &$locality_block['postal_code']['#value'],// Postal Code
        // independent fields:
        'field_designation' => &$form['line_item_fields']['field_designation']['und'][0]['value']['#value'], // Designation
        'field_email' => &$form['line_item_fields']['field_email']['und'][0]['email']['#value'],// Email
        'field_website' => &$form['line_item_fields']['field_website']['und'][0]['value']['#value'], // Website
        // phone field, independent:
    );
       // ===============================================
       // THIS PART DOESN'T WORK
    $field_phone = &$form['line_item_fields']['field_phone']['und'];
    $field_phone_template = $form['line_item_fields']['field_phone']['und'][0];
    // assemble input data
    $entities = entity_load('commerce_customer_profile',array($selected_staff_id));
    if (empty($entities)) return $form;
    $entity = reset($entities);
    $source_phones = $entity->field_phone['und'];
    $source_phones[2] = $source_phones[1];
    $source_phones[2]['value'] = 'test'; // ADD A THIRD VALUE FOR TESTING PURPOSES
    $phones = array();
    $length = count($source_phones);
        // HACKING - TRYING TO SET VALUES THAT MAKE THE TEXTFIELD BEHAVE - NOT WORKING
    foreach ($source_phones as $key => $source_phone) {
        $phones[$key] = $field_phone_template;
        $phones[$key]['value']['#value'] = $source_phone['value'];
        $phones[$key]['#delta'] =
        $phones[$key]['#weight'] =
        $phones[$key]['value']['#delta'] =
        $phones[$key]['value']['#weight'] =
        $phones[$key]['_weight']['#default_value'] =
        $phones[$key]['_weight']['#value'] = $key;
        $phones[$key]['_weight']['#delta'] = $length + 1;
        $phones[$key]['value']['#id'] = 'edit-line-item-fields-field-phone-und-' . $key . '-value--' . ($length + 1);
        $phones[$key]['value']['#name'] = 'line_item_fields[field_phone][und][' . $key . '][value]';
        $phones[$key]['_weight']['#id'] = 'edit-line-item-fields-field-phone-und-' . $key . '-weight--' . ($length + 1);
        $phones[$key]['_weight']['#name'] = 'line_item_fields[field_phone][und][' . $key . '][weight]';
        $phones[$key]['#id'] = 'edit-line-item-fields-field-phone-und-' . $key;
    }
        // THIS SUCCESSFULLY LOADS THE DATA FOR PRESENTATION, BUT DOESN'T BEHAVE PROPERLY ON "Add another item"
    if (!empty($phones)) {
        foreach ($phones as $key => $phone) {
            $field_phone[$key] = $phone;
        }
        $form['line_item_fields']['field_phone']['und']['#max_delta'] = $length + 1;
//        $form['line_item_fields']['field_phone']['und']['add_more']['#id'] =
//            'edit-line-item-fields-field-phone-und-add-more--' . ($length + 1);
        $form['line_item_fields']['field_phone']['#id'] = 'edit-line-item-fields-field-phone--' . $length;
    }
       // ===============================================
       // THIS REMAINING PART WORKS
    $source_address = $entity->commerce_customer_address['und'][0];
    $values['name_line'] = $source_address['name_line'];
    $values['organisation_name'] = $source_address['organisation_name'];
    $values['thoroughfare'] = $source_address['thoroughfare']; // Address 1
    $values['premise'] = $source_address['premise'];// Address 2
    $values['locality'] = $source_address['locality']; // City
    $values['administrative_area'] = $source_address['administrative_area']; // Province
    $values['postal_code'] = $source_address['postal_code'];// Postal Code
//    dpm($entity);
    // apply input data to input fields
//    $value = 'something';
//    $form['line_item_fields']['field_designation']['und'][0]['email']['#value'] = $value;
    dpm($form);
    $form['line_item_fields']['#suffix'] = rconnection_get_debug_data();
    return $form;
}

```

# Answer
> 0 votes
To answer my own question (it happens):

The critical part for the subsequent behaviour of "Add another item" is to set field\_state\['items\_count'\] (yes field state) for the NEXT ajax call from the "Add another item" button.

You can use this as a guide.

* Henrik

---
Tags: entities, ajax
---