# Question
Title: Views Output field as a link - Two tokens, use only one of them
I have content type which has field\_pdf.
I have made view to show content and there is a field which has set: Output field as a link. In link path settings I have two tokens: \[field\_pdf\]\[path\]. Idea is to link field either straight to PDF (if there is PDF file in node) or to content node.

How to get view to use only \[field\_pdf\] when this field\_pdf has content and not use \[path\] at all?

Now I'm getting double url for example: *http://url.com/pdf-file.pdfhttp://url.com/pdf*

# Answer
> 1 votes
**Modules You Need:**

1. Views
2. Views PHP

Assuming your content type is having these fields:

# The VIEWS Code:

Simply go to `admin/structure/views/import` and then Import the below mentioned code:

```
$view = new view();
$view->name = 'pdf';
$view->description = '';
$view->tag = 'default';
$view->base_table = 'node';
$view->human_name = 'PDF';
$view->core = 7;
$view->api_version = '3.0';
$view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */

/* Display: Master */
$handler = $view->new_display('default', 'Master', 'default');
$handler->display->display_options['title'] = 'PDF';
$handler->display->display_options['use_more_always'] = FALSE;
$handler->display->display_options['access']['type'] = 'perm';
$handler->display->display_options['cache']['type'] = 'none';
$handler->display->display_options['query']['type'] = 'views_query';
$handler->display->display_options['exposed_form']['type'] = 'basic';
$handler->display->display_options['pager']['type'] = 'full';
$handler->display->display_options['pager']['options']['items_per_page'] = '10';
$handler->display->display_options['style_plugin'] = 'default';
$handler->display->display_options['row_plugin'] = 'fields';
/* Field: Content: PDF */
$handler->display->display_options['fields']['field_pdf']['id'] = 'field_pdf';
$handler->display->display_options['fields']['field_pdf']['table'] = 'field_data_field_pdf';
$handler->display->display_options['fields']['field_pdf']['field'] = 'field_pdf';
$handler->display->display_options['fields']['field_pdf']['label'] = '';
$handler->display->display_options['fields']['field_pdf']['exclude'] = TRUE;
$handler->display->display_options['fields']['field_pdf']['alter']['make_link'] = TRUE;
$handler->display->display_options['fields']['field_pdf']['alter']['path'] = '[field_pdf][path]';
$handler->display->display_options['fields']['field_pdf']['element_label_colon'] = FALSE;
/* Field: Global: PHP */
$handler->display->display_options['fields']['php']['id'] = 'php';
$handler->display->display_options['fields']['php']['table'] = 'views';
$handler->display->display_options['fields']['php']['field'] = 'php';
$handler->display->display_options['fields']['php']['label'] = '';
$handler->display->display_options['fields']['php']['element_label_colon'] = FALSE;
$handler->display->display_options['fields']['php']['use_php_setup'] = 0;
$handler->display->display_options['fields']['php']['php_output'] = '<?php
if (isset($data->field_field_pdf[0][\'rendered\'][\'#markup\'])) {
    $pdf_url = $data->field_field_pdf[0][\'rendered\'][\'#markup\'];
    print $pdf_url;
} else {
    global $base_url;
    $node_url = $base_url . \'/node/\' . $data->nid;
    print $node_url;
}
?>';
$handler->display->display_options['fields']['php']['use_php_click_sortable'] = '0';
$handler->display->display_options['fields']['php']['php_click_sortable'] = '';
/* Sort criterion: Content: Post date */
$handler->display->display_options['sorts']['created']['id'] = 'created';
$handler->display->display_options['sorts']['created']['table'] = 'node';
$handler->display->display_options['sorts']['created']['field'] = 'created';
$handler->display->display_options['sorts']['created']['order'] = 'DESC';
/* Filter criterion: Content: Published */
$handler->display->display_options['filters']['status']['id'] = 'status';
$handler->display->display_options['filters']['status']['table'] = 'node';
$handler->display->display_options['filters']['status']['field'] = 'status';
$handler->display->display_options['filters']['status']['value'] = 1;
$handler->display->display_options['filters']['status']['group'] = 1;
$handler->display->display_options['filters']['status']['expose']['operator'] = FALSE;
/* Filter criterion: Content: Type */
$handler->display->display_options['filters']['type']['id'] = 'type';
$handler->display->display_options['filters']['type']['table'] = 'node';
$handler->display->display_options['filters']['type']['field'] = 'type';
$handler->display->display_options['filters']['type']['value'] = array(
  'pdf' => 'pdf',
);

/* Display: Page */
$handler = $view->new_display('page', 'Page', 'page');
$handler->display->display_options['path'] = 'pdf';

```

I'm sure you might be having some dummy content for that content-type, if not then do create couple of ones. Some with values in field\_php and some with not!

and Voila! Here is your required output:

# Updated Code:

```
$view = new view();
$view->name = 'pdf';
$view->description = '';
$view->tag = 'default';
$view->base_table = 'node';
$view->human_name = 'PDF';
$view->core = 7;
$view->api_version = '3.0';
$view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */

/* Display: Master */
$handler = $view->new_display('default', 'Master', 'default');
$handler->display->display_options['title'] = 'PDF';
$handler->display->display_options['use_more_always'] = FALSE;
$handler->display->display_options['access']['type'] = 'perm';
$handler->display->display_options['cache']['type'] = 'none';
$handler->display->display_options['query']['type'] = 'views_query';
$handler->display->display_options['exposed_form']['type'] = 'basic';
$handler->display->display_options['pager']['type'] = 'full';
$handler->display->display_options['pager']['options']['items_per_page'] = '10';
$handler->display->display_options['style_plugin'] = 'default';
$handler->display->display_options['row_plugin'] = 'fields';
/* Field: Content: PDF */
$handler->display->display_options['fields']['field_pdf']['id'] = 'field_pdf';
$handler->display->display_options['fields']['field_pdf']['table'] = 'field_data_field_pdf';
$handler->display->display_options['fields']['field_pdf']['field'] = 'field_pdf';
$handler->display->display_options['fields']['field_pdf']['label'] = '';
$handler->display->display_options['fields']['field_pdf']['exclude'] = TRUE;
$handler->display->display_options['fields']['field_pdf']['alter']['make_link'] = TRUE;
$handler->display->display_options['fields']['field_pdf']['alter']['path'] = '[field_pdf][path]';
$handler->display->display_options['fields']['field_pdf']['element_label_colon'] = FALSE;
/* Field: Global: PHP */
$handler->display->display_options['fields']['php']['id'] = 'php';
$handler->display->display_options['fields']['php']['table'] = 'views';
$handler->display->display_options['fields']['php']['field'] = 'php';
$handler->display->display_options['fields']['php']['label'] = '';
$handler->display->display_options['fields']['php']['alter']['make_link'] = TRUE;
$handler->display->display_options['fields']['php']['alter']['path'] = '[php]';
$handler->display->display_options['fields']['php']['alter']['absolute'] = TRUE;
$handler->display->display_options['fields']['php']['element_label_colon'] = FALSE;
$handler->display->display_options['fields']['php']['use_php_setup'] = 0;
$handler->display->display_options['fields']['php']['php_output'] = '<?php
if (isset($data->field_field_pdf[0][\'rendered\'][\'#markup\'])) {
    $pdf_url = $data->field_field_pdf[0][\'rendered\'][\'#markup\'];
    print $pdf_url;
} else {
    global $base_url;
    $node_url = $base_url . \'/node/\' . $data->nid;
    print $node_url;
}
?>';
$handler->display->display_options['fields']['php']['use_php_click_sortable'] = '0';
$handler->display->display_options['fields']['php']['php_click_sortable'] = '';
/* Sort criterion: Content: Post date */
$handler->display->display_options['sorts']['created']['id'] = 'created';
$handler->display->display_options['sorts']['created']['table'] = 'node';
$handler->display->display_options['sorts']['created']['field'] = 'created';
$handler->display->display_options['sorts']['created']['order'] = 'DESC';
/* Filter criterion: Content: Published */
$handler->display->display_options['filters']['status']['id'] = 'status';
$handler->display->display_options['filters']['status']['table'] = 'node';
$handler->display->display_options['filters']['status']['field'] = 'status';
$handler->display->display_options['filters']['status']['value'] = 1;
$handler->display->display_options['filters']['status']['group'] = 1;
$handler->display->display_options['filters']['status']['expose']['operator'] = FALSE;
/* Filter criterion: Content: Type */
$handler->display->display_options['filters']['type']['id'] = 'type';
$handler->display->display_options['filters']['type']['table'] = 'node';
$handler->display->display_options['filters']['type']['field'] = 'type';
$handler->display->display_options['filters']['type']['value'] = array(
  'pdf' => 'pdf',
);

/* Display: Page */
$handler = $view->new_display('page', 'Page', 'page');
$handler->display->display_options['path'] = 'pdf';

```

Let me know if you need anything else from this.

Cheers!

---
Tags: 7, views
---


# Question
Title: Migrate is putting map tables in legacy database
I'm getting some really strange behavior with my custom migration class where the map tables are all being put into the legacy (6) database rather than the destination (7) database. This happens for all of my custom migration classes and not the ones using d2d. I believe it has something to do with my $this-\>map in the migrations with the final argument being 'legacy' or possibly it's the $query = Database::getConnection('default', 'legacy') part of the migration.

My custom class for term migration does import the data into the new site from the old correctly, but the map tables are still going to the legacy database.

I've found a few sources of others having issues getting multiple databases to work in a migration but they seem to be conflicting with each other.

Here is my class:

```
class myUserProfileMigration extends myMigration {
  public function __construct($arguments) {
    parent::__construct($arguments);
    $this->arguments = $arguments;

    $this->description = t('My User Profiles Migration');

    $dependencies = array(
      'User'
    );

    $this->dependencies = $dependencies;

    $query = Database::getConnection('default', 'legacy')
          ->select('node', 'n');
    $query->condition('n.type', 'person_profile_page', '=');
    $query->join('users', 'u', 'u.uid = n.uid');
    $query->fields('u', array('name', 'uid'));
    $query->fields('n', array('uid', 'nid'));
    $query->join('content_type_person_profile_page', 'p', 'p.nid = n.nid');
    $query->fields('p', array(
      'field_about_me_value',
      'field_likes_value',
      'field_dislikes_value',
      'field_google_plus_value',
      'field_twitter_handle_value',
    ));

    $this->source = new MigrateSourceSQL($query);

    $this->destination = new MigrateDestinationUser();

    $this->addFieldMapping('uid', 'uid')
         ->sourceMigration('User');
    $this->addFieldMapping('field_likes', 'field_likes_value');
    $this->addFieldMapping('field_dislikes', 'field_dislikes_value');
    $this->addFieldMapping('field_about_me', 'field_about_me_value');
    $this->addFieldMapping('field_about_me:format')
         ->defaultValue('filtered_html');
    $this->addFieldMapping('field_google_id', 'field_google_plus_value');
    $this->addFieldMapping('field_twitter_handle', 'field_twitter_handle_value');

    $source_key = array(
      'uid' => array(
        'type' => 'int',
        'not null' => TRUE,
        'description' => 'Original Author UID',
        'alias' => 'n',
      )
    );
    $this->map = new MigrateSQLMap($this->machineName, $source_key, MigrateDestinationUser::getKeySchema(), 'legacy');

  }

}

```

And here is my settings.local.php:

```
$databases = array (
  'default' =>
  array (
    'default' =>
    array (
      'database' => 'dest_db',
      'username' => 'root',
      'password' => '',
      'host' => 'localhost',
      'port' => '',
      'driver' => 'mysql',
      'prefix' => '',
    ),
  ),
  'legacy' =>
  array(
    'default' =>
    array(
      'database' => 'legacy_db',
      'username' => 'root',
      'password' => '',
      'host' => 'localhost',
      'port' => '',
      'driver' => 'mysql',
      'prefix' => '',
    ),
  ),
);

```

# Answer
> 2 votes
Read up on the documentation on Map Tables under the heading *Map Tables* on that page. If you define `legacy` as the connection to make the map tables on -- then that's where they will go.

> When you construct the MigrateSQLMap object, add a fourth argument to tell it explicitly the connection on which to create the mapping tables.

---
Tags: 7, migrations
---


# Question
Title: Change text displayed when cart is empty
I'm using Drupal 7 with Commerce and I'd like to change the text shown when the user visits `/cart` and they have not added any items, from the default "Your shopping cart is empty." to a custom message, preferably that contains HTML.

I have tried adding custom text under no results behavior commerce\_cart\_form view with no luck.

What is the best way to do this?

# Answer
I think a theme function called `commerce_cart_empty_page` is used. So you should be able to add a function:
`MYTHEME_commerce_cart_empty_page()`
to your themes template.php file and return whatever html you want.

You can also do the same for the cart block with a theme function `MYTHEME_commerce_cart_empty_block()`
> 4 votes

---
Tags: 7, views, commerce
---


title: How to speed up Batch API processing

text:
# Question
Title: How to speed up Batch API processing
Ok, so I've got a script that's going to go through about 13000 nodes (which might be part of the problem, but I don't think it is).

I can either put them as one large array, which seems to go through the nodes fairly quickly, but eventually leads to a timeout after 600 seconds (10 minutes).

My batch is being produced with this code:

```
function revision_published_lr_build_batch($items) {

   $count_items = count($items);

    $i = 0;

   foreach ($items as $item) {
    $i++;
    // Here we can add multiple operation using an array variable.
    $operations[] = array('revision_published_process_data', array($item, 'details' => t('(Importing item @item  of  @count)', array('@item ' => $i, '@count' => $count_items)))); // operation with argument
    }
  //$operations[] = array('revision_published_process_data', array($items, 'details' => t('(Importing items)')));
  //Define your batch operation here
  $batch = array(
    'title' => t('Batch operation process'),
    'operations' => $operations,
    'finished' => 'revision_published_lr_build_batch_finished',
    'init_message' => t('Initializing...'),
    'progress_message' => t('Operation @current out of @total.'),
    'error_message' => t('Found some error here.'),
  );

  return $batch;
}

```

Each batch item should be just an MD5 hash.

However, when going through everything, it is taking forever - the process has been running for hours and it is only on the 86th or so node.

Note, the ONLY major difference in speed appears to be whether or not I put in the foreach loop and create a lot of different operations, or whether I just put $items straight into the operations variable.

Why would this difference cause such a marked speed difference? Batch API seems like it would be more suited to work with lots of small items, rather than one big one.

I suppose one solution would be putting 100 nodes in one batch item, increasing speed for processing and decreasing the probability of a timeout during processing, but this seems like an inelegant solution.

So in short - how do I make batch API process faster?

To clarify, changing the code to this (and removing the foreach loop) is what makes processing faster (but eventually leads to a timeout because the processing is all happening at once):

```
$operations[] = array('revision_published_process_data', array($items, 'details' => t('(Importing item @item  of  @count)', array('@item ' => $i, '@count' => $count_items))));

```

# Answer
> 3 votes
You're asking alot of questions ... here are some general answers.

* The batch api is used to take a set of data and partition out the data into workable batches. The batch api does not guarentee that timeouts will not occur. you need to find a batch size that that is the sweet spot for your dataset size.
* typically you would choose a batch size of say 5, 10, 15 or 20 items. and called `node_save` for example 25 times before going onto the next batch (page refresh). The page refreshes per batch do slow down your import process ... due to the HTTP requests.
* if you're querying data say from a Queue or something if you can try to avoid re-fetching the data and using a static php variable to store information you can save some time.
* The Migrate module is designed to solve these kind of problems by using Drush.

If ordering of the data doesnt matter. I find parallelizing (eg, multiple worker threads) can help with these types of imports look at Background Process and Ultimate Cron Queue Scalar.

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


# Question
Title: Feeds : creating a node dependencies at importation
The Excel file I'm trying to import is comprised of two part, the first three columns describe a node that might or might not exist currently, and the three last columns are my entity informations. To date I've created a Feeds plugin to provide a custom processor for my entity and I've explored Rules.

What I'd like is to import the three last column into a entity and before saving it, check if a node with the existing account number exists. If it doesn't, create one with the three first columns. After that, I'd store the nid into the entity as a foreign key (my entity has a n-to-1 relationship with the node).

I've tried to use Rules "Before saving an entity" event, but I can't access unmapped columns this way. I've tried adding mapping to non-existing properties of the entity thinking they would be set and simply forgotten once the entity goes out of scope, but I instead get an unknown property error at importation. I've even tried to override the setTargetElement function in my processor, but the error still occurs. It seems to me I've got little choice but to store the unwanted data in the table and duplicate it in the node afterward (exactly what I'm trying to avoid).

Does someone have either a way to create these non-persisted property, have a better way to create and store a node relationship in an entity (Entity reference maybe) or even another solution6

Thanks

# Answer
I have done something similar with importing images. If the image exists in the files table I just add the fid, and if it does not yet exist I create it.

I created a custom module and implemented hook\_feeds\_processor\_targets\_alter, and hook\_feeds\_dimension\_set\_target

Aside from that I don't know of an answer that does not require a bit of coding.
> 0 votes

# Answer
Quite bad to answer my own question but here how I've did it. First I created a Feeds importer to import my Node dependencies from the file. Afterward, using a custom rule action, I trigger another feeds importer that pull the 4 others columns into an entity. Using the Feeds Tamper module and the EFQ plugin, I'm joining the two using the account number. I'll submit the Rules action to either Feeds or Feeds Rules module for common good.
> 0 votes

---
Tags: rules, feeds, entities
---


# Question
Title: How can I list all Twig functions and filters with their description?
I want a list of all available Twig filters and functions and for each one of them I need to have a description of the function/filter so the user can see what functions and filters are available and how to use them in templates.

I know how to get the list of functions and filters(How to get all filters and functions available in Twig templates?) but I don't know how to get their descriptions.

I don't know how to find out in which file the filter/function resides so I can parse it for the description of the function.

# Answer
> 0 votes
https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Template%21TwigExtension.php/class/TwigExtension/8 Twig functions have no descriptions. You can run `getCallable` on a twig function/filter object and then do `$reflection = new \ReflectionFunction($callable); $doxygen = $reflection->getDocComment()` to get the doxygen which is the closest to "description".

---
Tags: 8, theming
---


# Question
Title: Is possible to use multiple taxonomy terms name (not tids) as contextual filter in Views?
For example: `example.com/TermName1+TermName2+TermName3`.

It seems that the "Allow multiple values" option only works with tids.

# Answer
> 0 votes
Maybe too late for this to matter, but you may be able to do this with `hook_views_pre_view()`.

Possible example:

```
function MYMODULE_views_pre_view(&$view, &$display_id, &$args) {
  if (!empty($args)) {
    // change the argument to term IDs
    $term_names = explode('+', $args[0]);
    foreach ($term_names as $term) {
      $terms[] = taxonomy_get_term_by_name($term)->tid;
    }
    $view->args[0] = implode('+', $terms);
  }
}

```

---
Tags: views
---


title: How to use Views Rules?

text:
# Question
Title: How to use Views Rules?
I've looked here: https://www.drupal.org/project/views\_rules but can't get past 2.2 *Add a "Rules" display*.

I don't know what that means. I've installed Views Rules but can't find any Rules option anywhere in my Views.

# Answer
First of all: thanks for mentioning the Views Rules module. I didn't know it, but I'm sure it will be handy in the future.

It seems that you're not quite familiar with the Views module. While creating or editing your View, you should click the "add" button at the top, right underneath "Displays". When you select "Rules", a new display is added and there appears a little button with the text "Rules" in it. (I've already added one in the picture underneath.)

Afterwards, configure the Rules' settings by clicking "edit the field info" and choose the desired data types.

Finally, select the View you would like to use in your Rule. In my case, the View is called "Test".
> 1 votes

---
Tags: views, rules
---


# Question
Title: dynamically choose filters/fields in an aggregation table on a View
I need users to customize which kind of aggregation to apply to a table (view).

Example: let´s choose counts of species X and Y in an area. This means apply two filters. I also want to give the option to choose fields 'species', 'area' and 'place'. The table resulting of applying these 3 filters would give a completely different table than before.

Insert all the (3) filters into the same view creates allways the same result. I don't think there is some way of let user choose 'disabling' one of the filters.

Should I create two different views (each one with its corresponding filters) inserted into a panel or there is some better way to solve that?

To make more clear, here are two screenshots:

1) Without 'Place' field (and filter): for especie Cuniculus paca, number of counts is 60.

2) With'Place' field: as for each especie we have different places names, the results are completely different.

In fact I think the question should not be exclusively about filters but also about Views.

There is a chance to avoid a Field to be 'executed' (applied to the resulting View) allways? 'Exclude from Display' with Aggregation options YES doesn't do any effect, the results are grouped by this new field also, changing completely all the results.

# Answer
You can expose the filters (and for markup and additional functionality, there is a nice module Better exposed filters). You can find it when adding a filter "Expose this filter to visitors, allow tthem to change it", under the advanced sction on the right (by default collapsed) you can group them into a block and then add them to your site whereever you need them.

Hope I understood the question the right way.
> 0 votes

---
Tags: views, panels, theming
---


title: Order confirmation with attachment

text:
# Question
Title: Order confirmation with attachment
I'm sending order confirmation messages via the module message-notify. As mail system i'm using MimeMail. Is there a possibility to add an attachment to the email with the key: commerce\_order\_order\_confirmation?

I tried to add the attachment in hook\_mail()

```
function mymodule_mail($key, &$message, $params) {

    if(isset($key)) {
        if($key == 'commerce_order_order_confirmation') {
            $attachment = array(
                'filecontent' => file_get_contents(DRUPAL_ROOT . '/sites/default/files/pdf/myattachment.pdf'),
                'filename' => 'myattachment.pdf',
                'filemime' => 'application/pdf',
            );

            $message['params']['attachments'][] = $attachment;
        }
    }
}

```

# Answer
> 3 votes
You want to change the email before it is sent. So try this as a starting point (put together with the help of:
1. your post
2. https://drupal.stackexchange.com/a/98559/34326
3. https://www.drupal.org/node/2057703#comment-8343071):

```
function mymodule_mail_alter(&$message) {

    if ($message['id'] == 'message_notify_commerce_order_order_confirmation') {
        $file = file_create_url(file_build_uri('path-to-file-relative-to-your-files-folder.pdf'));
        $attachment = array(
            'filecontent' => file_get_contents($file),
            'filename' => 'test.pdf',
            'filemime' => 'application/pdf',
        );

        $message['params']['attachments'][] = $attachment;
    }
}

```

The file should be located in sites/default/files or whatever applies to your site. You should also change filemime to what matches your file.

I am getting errors "realpath() expects parameter 1 to be a valid path" and "is\_file() expects parameter 1 to be a valid path", but the email with the attachment is sent anyway, which is why I am posting this.
The errors seem to be related to the 'filepath' parameter which is mentioned in the 3rd link, because depending on what I define, the results vary: eg. `'filepath' => $file,`, which gives me no attachment and no error or `'filepath' => $file->uri,`, which gives me an additional error about a "non-object" and no attachment.

`http://passivemanagement.net/blog/2014/01/let-drupal-send-email-attachment-using-mimemail-module` uses a different markup for the file, but right now I can't figure out, how to adapt it to the task at hand.

---
Tags: commerce, emails
---


# Question
Title: ftp uploaded files are not in the library of Media module
I installed media module in Drupal 7 to browse the uploaded files on the server. I created a new field called `media3` and this is its configuration.

This is the next page :

The problem is when I'm trying to add new content to this content type and select them in the library tab from media module, only the image files that are already uploaded through `http` protocol are displayed.

If I check the `Allowed URI schemes` checkbox, nothing will be displayed in the library tab. how do I can browse the ftp uploaded files? where they should be to be visible to media module?

# Answer
> 1 votes
The media module, like pretty much all of the file related modules on Drupal, relies on the managed files system which involves adding data to the db for files that are uploaded, simply using ftp to place them in the appropriate directory bypasses the "drupal way" and doesn't create these database rows, so the media module doesn't know about the files. I have used this method with other modules but not media:

::I do not claim that this is the best way to handle it, but it has worked for my use cases::

The following are the contents of a custom module I through together and assume a few things, first that your node type is "picture", second that you are just using the default "file" field that comes with drupal, and lastly that only files you are aware of exist in the directory "/sites/default/files/importer":

```
function MYMODULE_menu(){
    $info['db_pics']=array(
        'title' => 'NCD Callbacks',
        'page callback' => 'db_pics_callback',
        'access callback' => 'pics_is_admin',
    );
    return $info;
}
function pics_is_admin(){
    global $user;
    return ($user->uid==1);
}
function db_pics_callback(){
    $url='./sites/default/files/importer';
    $files=traverse($url);
    foreach($files as $source){
        $node=new stdClass();
        $node->type='picture';
        $node->uid=1;
        $node->status=1;

        //This part is optional and just allowed me to create a node using metadata from the image file
        //Get file info
        $fn=exif_read_data($source);
        if(!isset($fn['DateTime'])){
            $fn['DateTime']=$last_dt;
        }else{
            $last_dt=$fn['DateTime'];
        }

        $node->title=$fn['FileName'];
        $names[]=$node->title;
        $node->created=strtotime($fn['DateTime']);

        //Fetch the actual data from the image file
        $image = file_get_contents($source);

        // Returns the new file object after saving the image to the appropriate Drupal File schema
        $file = file_save_data($image, 'public://'.$fn['FileName'], FILE_EXISTS_RENAME);
        $node->field_image['und'][0]=(array) $file;
        node_save($node);
    }
    return '<ul><li>'.implode('</li><li>',$names).'</li></ul>';
}

//quick and dirty utility function assumes only files you want are in the specified directories
function traverse($url){
    $entries=array();
    $dir=scandir($url);
    foreach($dir as $entry){
        if(in_array($entry,array('.','..'))) continue;
        elseif(is_dir($url.'/'.$entry)){
            $entries=$entries+traverse($url.'/'.$entry);
        }else{
            $entries[]=$url.'/'.$entry;
        }
    }
    return $entries;
}

```

This is a little different than what you asked for, but I see people asking for this functionality frequently so I wanted to give a complete answer about importing files as nodes, for your specific use case the callback function can be significantly shortened to:

```
function db_pics_callback(){
    $url='./sites/default/files/importer';
    $files=traverse($url);
    $saved_files=db_query('SELECT filename FROM file_managed')->fetchAll(PDO::FETCH_COLUMN);
    foreach($files as $source){
        $image = file_get_contents($source);
        $fn=substr($source,strrpos($source,'/')+1);
        if(!in_array($fn,$saved_files)){
            file_save_data($image, 'public://'.$fn, FILE_EXISTS_RENAME);
        }
    }
    return 'Finished';
}

```

That should add all of your files to the managed files database table and allow you to view them in the "Library" tab. Good luck!

---
Tags: media, files
---


# Question
Title: Pulling user data from external database
I have a game that utilizes mongodb to store the user information. What I am trying to do is use drupal as a community front so users can register for the game in drupal. The problem is that I don't know where to begin since I'd need to pass the user info created in drupal into mongodb so they would be able to log in and play the game.

Is there a way that I can pass the registered user info into mongo so the users can log into the game?

Also I'm running drupal on MySQL.

Any help would be appreciated!

# Answer
> 1 votes
That is too broad to give any real specifics, but in general:

* create a form (or utilise the user registration form) to register all the relevant information
* override the submit function for that form, and include a call to a php function that will access and append the mongo db. keep in mind that if the db in on a different server, security settings on the server may prevent this from being possible. If this were the case, you would need to send a POST call or similar to a php file on that server (or use an API if available) in order to update the server db.

to get you started on the form:

Drupal Form API Reference

WebForm

Form Builder

---
Tags: javascript
---


title: View: No Result = Last

text:
# Question
Title: View: No Result = Last
I have a field 1 Name and another field 2 Year and have it sorted in Views first by Name and second by Year. If Year is empty I want it to be placed last under each letter. So lets say I have 5 James in my list and 4 of them have a Year and the one without Year to appear last in the list of those names but before Jane.

I've installed Rules and Views Rules but I don't know how use Rules for this kind of thing. Any suggestions?

# Answer
> 0 votes
Assuming that the Name field is text and the Year field is an integer, if you sort the Names ascending and the Years descending, the empty year of James should come last and before Jane (which should be what you are after). That's the default behavior of Views. If your views has contextual filters or relationships, you may be getting different results.

In any case, you can configure the Year field and under the "No Results Behavior" you can set a very low (or high depending on what you want) value for year and hide it. This way, you will guarantee that it will be sorted as expected.

---
Tags: views, entities, rules
---


# Question
Title: How to show only user assigned contents in his dashboard?
I have more than 270 pages in my website.

There are some Content Creators, Content Editors, Reviewers and Publisher. I have assigned each user a different role. Each user can view, edit and publish each others' pages.

I wanted to create something like; When user logged in with his user name and password, first he can see only his own created/assigned content pages when he clicks on content tab.

How to show only user assigned contents in his dashboard?

# Answer
In your view simply follow these steps:

1. Click the **Advance Tab** under the **RELATIONSHIPS** add a new relationship `Content:Author`
2. Keep the **Identifier** as it is, but remember to check the `Require this relationship` option.
3. Now, under **FILTER CRITERIA** add a new filter `User: Current` and check the `Is the logged in user` as `Yes`

# The exported code:

```
$view = new view();
$view->name = 'article';
$view->description = '';
$view->tag = 'default';
$view->base_table = 'node';
$view->human_name = 'Article';
$view->core = 7;
$view->api_version = '3.0';
$view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */

/* Display: Master */
$handler = $view->new_display('default', 'Master', 'default');
$handler->display->display_options['title'] = 'Article';
$handler->display->display_options['use_more_always'] = FALSE;
$handler->display->display_options['access']['type'] = 'perm';
$handler->display->display_options['cache']['type'] = 'none';
$handler->display->display_options['query']['type'] = 'views_query';
$handler->display->display_options['exposed_form']['type'] = 'basic';
$handler->display->display_options['pager']['type'] = 'full';
$handler->display->display_options['pager']['options']['items_per_page'] = '10';
$handler->display->display_options['style_plugin'] = 'default';
$handler->display->display_options['row_plugin'] = 'fields';
/* Relationship: Content: Author */
$handler->display->display_options['relationships']['uid']['id'] = 'uid';
$handler->display->display_options['relationships']['uid']['table'] = 'node';
$handler->display->display_options['relationships']['uid']['field'] = 'uid';
$handler->display->display_options['relationships']['uid']['required'] = TRUE;
/* Field: Content: Title */
$handler->display->display_options['fields']['title']['id'] = 'title';
$handler->display->display_options['fields']['title']['table'] = 'node';
$handler->display->display_options['fields']['title']['field'] = 'title';
$handler->display->display_options['fields']['title']['label'] = '';
$handler->display->display_options['fields']['title']['alter']['word_boundary'] = FALSE;
$handler->display->display_options['fields']['title']['alter']['ellipsis'] = FALSE;
/* Sort criterion: Content: Post date */
$handler->display->display_options['sorts']['created']['id'] = 'created';
$handler->display->display_options['sorts']['created']['table'] = 'node';
$handler->display->display_options['sorts']['created']['field'] = 'created';
$handler->display->display_options['sorts']['created']['order'] = 'DESC';
/* Filter criterion: Content: Published */
$handler->display->display_options['filters']['status']['id'] = 'status';
$handler->display->display_options['filters']['status']['table'] = 'node';
$handler->display->display_options['filters']['status']['field'] = 'status';
$handler->display->display_options['filters']['status']['value'] = 1;
$handler->display->display_options['filters']['status']['group'] = 1;
$handler->display->display_options['filters']['status']['expose']['operator'] = FALSE;
/* Filter criterion: Content: Type */
$handler->display->display_options['filters']['type']['id'] = 'type';
$handler->display->display_options['filters']['type']['table'] = 'node';
$handler->display->display_options['filters']['type']['field'] = 'type';
$handler->display->display_options['filters']['type']['value'] = array(
  'article' => 'article',
);
/* Filter criterion: User: Current */
$handler->display->display_options['filters']['uid_current']['id'] = 'uid_current';
$handler->display->display_options['filters']['uid_current']['table'] = 'users';
$handler->display->display_options['filters']['uid_current']['field'] = 'uid_current';
$handler->display->display_options['filters']['uid_current']['relationship'] = 'uid';
$handler->display->display_options['filters']['uid_current']['value'] = '1';
$handler->display->display_options['filters']['uid_current']['expose']['operator_id'] = '';
$handler->display->display_options['filters']['uid_current']['expose']['label'] = 'Is the logged in user';
$handler->display->display_options['filters']['uid_current']['expose']['operator'] = 'uid_current_op';
$handler->display->display_options['filters']['uid_current']['expose']['identifier'] = 'uid_current';
$handler->display->display_options['filters']['uid_current']['expose']['required'] = TRUE;

/* Display: Page */
$handler = $view->new_display('page', 'Page', 'page');
$handler->display->display_options['path'] = 'article';

```

Cheers!
> 1 votes

# Answer
In Views, under the Advanced Tab, create a relationship to content:author, required.

Set a Filter Criteria to User:Current

This should restrict the View to content authored by the currently logged in user.
> 0 votes

---
Tags: 7, views, users
---


# Question
Title: how to output image file from database drupal 7?
I have created testing module that will upload image and outputting it to my page. but, I can't seem to output my image file from my database. here's my code

```

function database_ex_menu() {
  $items = array();
  $items['database-ex'] = array(
    'title' => 'My Database Form',
    'type' => MENU_NORMAL_ITEM,
    'access arguments' => array('submit database_ex'),
    'page callback' => 'drupal_get_form',
    'page arguments' => array('database_ex_form'),
  );
  return $items;
}

function database_ex_form($form, $form_state) {
  $form['myimage'] = array(
    '#type' => 'file',
  );
  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Add item'),
  );
  return $form;
}

function database_ex_form_submit($form, $form_state) {
  $fe_id = db_insert('example')
    ->fields(array(
      'myimage' => $form_state['values']['myimage'],
    ))
    ->execute();

  drupal_set_message(t('Your entry has been added'));
}

//This function supposedly will output my image file inside a div.

function database_ex_submission(){
  //What to do From here!
}

```

# Answer
> -1 votes
To output the image from database you can use theme\_image

```
<?php
  $variables = array(
      'path' => 'path/to/img.jpg',
      'alt' => 'Test alt',
      'title' => 'Test title',
      'width' => '50%',
      'height' => '50%',
      'attributes' => array('class' => 'some-img', 'id' => 'my-img'),
      );
  $img = theme('image', $variables);
?>

```

# Answer
> 1 votes
Firstly save image to your server and then you can output the image.

You can save image by using file\_save\_upload().

> **file\_save\_upload** : Saves a file upload to a new location.

```
$file = file_save_upload('myimage',array(), 'public://');

```

Get fileid(fid) of the image

```
$fid=$file->fid;

```

And then save this $fid to your database.

After it get fid from database

```
  $upload_record = file_load($fid);
  $url = $upload_record->uri;

  $render_image = theme(
    'image_style',
    array(
      'style_name' => 'Style_name',
      'path' => $url,
      'getsize' => TRUE,
      'attributes' => array(
        'width' => '250',
        'height' => '162')
      )
    );

```

Now print `$render_image` variable where you want to display image.

---
Tags: 7, hooks, database, media
---


title: user not logged in php file

text:
# Question
Title: user not logged in php file
I want use drupal functions in php files,I did it with below code

```
$path = $_SERVER['DOCUMENT_ROOT'];
chdir($path);
define('DRUPAL_ROOT', getcwd()); //the most important line
require_once './includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);

```

Its ok and good fine, after this all drupal function exist,but my problem is here when user logged in before this page when redirect to this page it not know as logged in user (it know as anonymous user ), how can have logged in user in php file ?

I try `drupal_session_regenerate()` after below code but nothing happened, how can solve this problem?

# Answer
This forum post on d.o explains what may be your problem.

You need to:

> Set $cookie\_domain='example.com'; explicitly in your settings.php file.

According to the post, Drupal keeps a long session ID string in a cookie, and without a proper cookie domain, the current user is anonymous.
> 1 votes

---
Tags: users, sessions
---


title: Views caching dont show changes

text:
# Question
Title: Views caching dont show changes
I'm having a problem with views and caching. Within a custom module, i do changes on my database, which is working fine, but my view won't show that changes until I clear all caches.

I tried to deactivate views-caching here "admin/structure/views/settings/advanced" Caching in the view is deactivated too And the whole caching is deactivated here "admin/config/development/performance"

But I still have to clear all caches on every change I make to see what I did. Is there a chance to stop caching for that view by code in the module? Or any other possibility?

EDIT: I now tried a module called "CacheExclude" and

```
$GLOBALS['conf']['cache'] = 0;
drupal_page_is_cacheable(FALSE);
$conf['cache'] = FALSE;

```

but no change :(

EDIT 2: Here is the code where I change the field in the database:

```
foreach($books as $book) {
    $query = db_update('field_data_field_zuordnung')
        ->fields(array(
            'field_zuordnung_value' => 'verkauft',
            ))
        ->condition('entity_id', $book->product_id, '=')
        ->execute();
}

```

The change is done in the DB, but it isn't shown in the view. After that, I use drupal\_goto to move to a "you're done site".

# Answer
> 1 votes
You should ideally be using the Field Attach API to avoid these problems.

Or for a quick solution have a look at field\_attach\_update where at the end of the function, it clears the field cache:

```
$entity_info = entity_get_info($entity_type);
if ($entity_info['field cache']) {
  cache_clear_all("field:$entity_type:$id", 'cache_field');
}

```

---
Tags: views, 7, caching
---


# Question
Title: Create a user profile on user creation in drupal 6
I have a problem and can't seem to find the answer. I'm creating a user via a rest service and it's not creating a user profile along with it. I'm not sure how to even create the profile. our user profiles have custom fields that i can pull with my user\_get, but when i try to create a user with just a blank profile, it doesn't like it.

any help would be appreciated

```
function user_services_create_user() {
    $user_name = $input['user_name'];
    //the users email address
    $email = $input['email'];
    if(array_key_exists('password', $input)){
        $password = $input['password'];
    }
    else {
        $password = user_password(8);
    }

    //set up the user fields
    $fields = array(
        'name' => $user_name,
        'mail' => $email,
        'pass' => $password,
        'status' => 1,
    );
    //the first parameter is left blank so a new user is created
    $user_account = user_save('', $fields);
    if(!empty($user_account) && $user_account->uid != '') {
        user_services_send_response('New user has been successfully created', 1, 200,    $user_account);
    }
    else {
        user_services_send_response('New user cannot be created. Please try again later', 0);
    }
}

```

Changed Code:

```
function user_services_create_user() {

//the user name of the new user
$user_name = $input['user_name'];
//the users email address
$email = $input['email'];
if(array_key_exists('password', $input)){
    $password = $input['password'];
}
else {
    $password = user_password(8);
}
user_services_check_user($input);
//set up the user fields
$fields = array(
    'name' => $user_name,
    'mail' => $email,
    'pass' => $password,
    'status' => 1,
);
//the first parameter is left blank so a new user is created
$user_account = user_save('', $fields);
if(!empty($user_account) && $user_account->uid != '') {

    $node = new stdClass();
    $node->uid = $user_account->uid;
    $node->type='profile';
    $node->title=$user_account->name;
    $node->name=$user_account->name;
    $node->field_receipt_suppress_name[0]['value'] = user_fill_value_from_request('receipt_suppress_name');
    $node->field_receipt_suppress_points[0]['value'] = user_fill_value_from_request('receipt_suppress_points');
    $node->field_phone_number[0]['value'] = user_fill_value_from_request('phone_number');
    $node->field_first_name[0]['value'] = user_fill_value_from_request('first_name');
    $node->field_last_name[0]['value'] = user_fill_value_from_request('last_name');
    $node->field_user_phone_number[0]['value'] = user_fill_value_from_request('user_phone_number');
    $node->field_points[0]['value'] = user_fill_value_from_request('points');
    $node->field_date_points_last_checked[0]['value'] = user_fill_value_from_request('date_points_last_checked');
    $node->field_last_reward_issued_store[0]['nid'] = user_fill_value_from_request('last_reward_issued_store');
    $node->field_last_reward_issued_date[0]['value'] = user_fill_value_from_request('last_reward_issued_date');
    $node->field_last_reward_redeemed[0]['value'] = user_fill_value_from_request('last_reward_redeemed');
    $node->field_last_reward_redeemed_store[0]['nid'] = user_fill_value_from_request('last_reward_redeemed_store');
    $node->field_last_reward_redeemed_date[0]['value'] = user_fill_value_from_request('last_reward_redeemed_date');

    node_save($node);

    user_services_send_response('New user has been successfully created', 1, 200, $user_account);
}
else {
    user_services_send_response('New user cannot be created. Please try again later', 0);
}

```

}

# Answer
Changed Code:

```
    function user_services_create_user() {

    //the user name of the new user
    $user_name = $input['user_name'];
    //the users email address
    $email = $input['email'];
    if(array_key_exists('password', $input)){
        $password = $input['password'];
    }
    else {
        $password = user_password(8);
    }
    user_services_check_user($input);
    //set up the user fields
    $fields = array(
        'name' => $user_name,
        'mail' => $email,
        'pass' => $password,
        'status' => 1,
    );
    //the first parameter is left blank so a new user is created
    $user_account = user_save('', $fields);
    if(!empty($user_account) && $user_account->uid != '') {

        $node = new stdClass();
        $node->uid = $user_account->uid;
        $node->type='profile';
        $node->title=$user_account->name;
        $node->name=$user_account->name;
        $node->field_receipt_suppress_name[0]['value'] = user_fill_value_from_request('receipt_suppress_name');
        $node->field_receipt_suppress_points[0]['value'] = user_fill_value_from_request('receipt_suppress_points');
        $node->field_phone_number[0]['value'] = user_fill_value_from_request('phone_number');
        $node->field_first_name[0]['value'] = user_fill_value_from_request('first_name');
        $node->field_last_name[0]['value'] = user_fill_value_from_request('last_name');
        $node->field_user_phone_number[0]['value'] = user_fill_value_from_request('user_phone_number');
        $node->field_points[0]['value'] = user_fill_value_from_request('points');
        $node->field_date_points_last_checked[0]['value'] = user_fill_value_from_request('date_points_last_checked');
        $node->field_last_reward_issued_store[0]['nid'] = user_fill_value_from_request('last_reward_issued_store');
        $node->field_last_reward_issued_date[0]['value'] = user_fill_value_from_request('last_reward_issued_date');
        $node->field_last_reward_redeemed[0]['value'] = user_fill_value_from_request('last_reward_redeemed');
        $node->field_last_reward_redeemed_store[0]['nid'] = user_fill_value_from_request('last_reward_redeemed_store');
        $node->field_last_reward_redeemed_date[0]['value'] = user_fill_value_from_request('last_reward_redeemed_date');

        node_save($node);

        user_services_send_response('New user has been successfully created', 1, 200, $user_account);
    }
    else {
        user_services_send_response('New user cannot be created. Please try again later', 0);
    }
}

```
> 0 votes

---
Tags: 7, services
---


# Question
Title: How do I change theme for tables rendered with theme_table()?
I'm willing to change look and feel of Drupal tables. I was building my own theme using Zen's STARTERKIT, and the current look and feel is not pretty.

How can I change template for tables? Specifically, I like the table theme being displayed in Administration theme/Admin panel. How do I use that theme for my tables?

# Answer
These are the styles defined by the Seven theme for tables:

```
table {
  width: 100%;
  font-size: 0.923em;
  margin: 0 0 10px;
  border: 1px solid #bebfb9;
}
table td,
table th {
  vertical-align: middle;
  padding: 8px 10px;
  border: 0;
  color: #000;
}
tr.even,
tr.odd {
  border-width: 0 1px 0 1px;
  border-style: solid;
  border-color: #bebfb9;
  background: #f3f4ee;
}
tr.odd {
  background: #fff;
}
tr.drag {
  background: #fe7;
}
tr.drag-previous {
  background: #ffb;
}
table th {
  text-transform: uppercase;
  background: #e1e2dc;
  font-weight: normal;
  border-width: 1px;
  border-style: solid;
  border-color: #bebfb9;
  padding: 3px 10px;
}
table th.active {
  background: #bdbeb9;
}
table th a {
  display: block;
  position: relative;
}
table th.active a {
  padding: 0 25px 0 0; /* LTR */
}
table th.active img {
  position: absolute;
  top: 3px;
  right: 3px;
}
table td.active {
  background: #e9e9dd;
}
table tr.odd td.active {
  background: #f3f4ee;
}
table tr.selected td.active,
table tr.selected td {
  background: #ffc;
  border-color: #eeb;
}
table.system-status-report tr {
  border-bottom: 1px solid #ccc;
}
table.system-status-report tr.ok {
  color: #255b1e;
  background-color: #e5ffe2;
}
table.system-status-report tr.info {
  color: #040f37;
  background-color: #bdf;
}
table.system-status-report tr.warning {
  color: #840;
  background-color: #fffce5;
}
table.system-status-report tr.error {
  color: #8c2e0b;
  background-color: #fef5f1;
}
/**
 * Exception for webkit bug with the right border of the last cell
 * in some tables, since it's webkit only, we can use :last-child
 */
tr td:last-child {
  border-right: 1px solid #BEBFB9;
}

```

Drop that into your theme's CSS file (after removing any existing rules for tables) and your tables should look pretty much identical to those in the Seven theme. Obviously you can edit this 'till your heart's content.
> 1 votes

# Answer
I think that what you need is just to change the CSS styles used for the table, as Clive suggested. That would not change the output produced from `theme('table')`, but it would change how that output is rendered.

If you really want to change the output, because you want to add HTML tags to what normally output for the tables, you need to override the theme function. If THEMENAME is your theme's name, then you need to write the `THEMENAME_table()` function in the template.php file for your theme. you can look at the code of theme\_table() as example of which code to write. Normally you want to add output, or slightly change the output, and in that case you use most of the code already used in `theme_table()`.

In Drupal 7 there is another alternative, which is possible if what you want to do is alter the value of the variables passed to the theme function: Each theme function, even the ones not using a template, have a preprocess function. In this case, the variables used from the theme function are the following ones:

* `$variables['header']`
* `$variables['rows']`
* `$variables['attributes']`
* `$variables['caption']`
* `$variables['colgroups']`
* `$variables['sticky']`
* `$variables['empty']`

Writing code in a function called `THEMENAME_preprocess_table()` (with `$variables` as parameter), you can alter the value of those variables before they are passed to the theme function.

> How can I change template for tables?

For the table theme function, there aren't template files involved; it is possible to use a template file in this case too, but you should write more code to gain few. I can report how to do this, but I would not suggest doing it.

> How do I use that theme for my tables?

You just call the theme function with `theme('table', $variables)`, where `$variables` is an array containing the values required from the theme function, which are:

* header: An array containing the table headers. Each element of the array can be either a localized string or an associative array with the following keys:
    + "data": The localized title of the table column.
    + "field": The database field represented in the table column (required if user is to be able to sort on this column).
    + "sort": A default sort order for this column ("asc" or "desc").
    + Any HTML attributes, such as "colspan", to apply to the column header cell.
* rows: An array of table rows. Every row is an array of cells, or an associative array with the following keys:
    + "data": an array of cells
    + Any HTML attributes, such as "class", to apply to the table row.
    + "no\_striping": a boolean indicating that the row should receive no 'even / odd' styling. Defaults to FALSE.
* Each cell can be either a string or an associative array with the following keys:
    + "data": The string to display in the table cell.
    + "header": Indicates this cell is a header.
    + Any HTML attributes, such as "colspan", to apply to the table cell.
> 7 votes

# Answer
You could use everything the same as in the answer by Serjas, but adding class attribute:

First header

```
$header = array(
  array('data' => 'Servie Name', 'class' => array('my_class')), // you can add any html attributes or just add class atribute and then change table cell with css.
  array('data' => 'Number of Passengers', 'width' => '10%'),
);

```

Next rows

```
$rows = array(
  array('data' => $servie_name),
  array('data' => $pax),
);

```

Now you will get table

```
$table = theme('table',$header,$rows);

```

In the css file you can style table cell like:

```
.my_class { background-color: red; }

```
> 1 votes

# Answer
Almost all styling can be done with css, but lots may seems bit difficult to style cell width,cell class etc. Here is the code to do that using theme('table').

First header

```
$header = array(
  array('data' => 'Servie Name', 'width' => '35%', 'bgcolor' => '#000'), // you can add any html attributes.
  array('data' => 'Number of Passengers', 'width' => '10%'),
);

```

Next rows

```
$rows = array(
  array('data' => $servie_name),
  array('data' => $pax),
);

```

Now you will get table

```
$table = theme('table',$header,$rows);

```
> 0 votes

---
Tags: 7, theming
---


# Question
Title: Clearing a Date Field value in the Edit Node form
I have a content type with a date field (field\_acquisition\_date) and I'm using the Popup Calendar widget in the form UI. If a user...

* puts a value into that field and save the node
* then edits the node again
* clears out the value
* and saves the node a second time

the original value is still in that date field. How can the user set that field value to empty/NULL while using the edit form?

# Answer
You just need to set the default value to 'No default value' in the content type of where the field is created.

Please see in the screenshot
> 1 votes

---
Tags: 7, datetime
---


# Question
Title: How to export field's default image in Features
I have Image field type and provide Default Image. This default image doesn't seem to be exported by Features. Is there another module that need to be added so the image also exported? Or are there another way or alternative to achieve this?

# Answer
Is not possible yet, there's an issue about this:

Support imagefield default images

A workaround using hook\_field\_default\_fields\_alter() is explained, but be aware is not working completely (Feature seems to be overriden).
> 1 votes

# Answer
Try the Default image ft module looks like it is what you need.

> Remember when you wanted to featurize that default image for that profile picture? Yeah, that's not possible, because the feature would save a fid in its code, and we all know it's not good to have id's in features. Plus, the website manager might want to change the default profile picture.
> 2 votes

---
Tags: features
---


# Question
Title: Converting db_query from Drupal 6 to Drupal 7: Invalid parameter number: number of bound variables does not match number of tokens
I have a custom localisation function in a Drupal 6 module that I would like to convert to Drupal 7 but I have hit a wall with the db\_query function. I have the following code (in d6 and d7):

```
// Drupal 6
db_query("REPLACE INTO {locales_target} (lid, translation, language) VALUES ((SELECT lid FROM {locales_source} WHERE source = '%s' LIMIT 1), '%s', 'sv')", $name['eng'], $name['swe']);

// Drupal 7 (not working)
db_query("REPLACE INTO {locales_target} (lid, translation, language) VALUES ((SELECT lid FROM {locales_source} WHERE source = :source_eng LIMIT 1), ':source_swe', 'sv')", array(':source_eng' => $name['eng'], ':source_swe' => $name['swe']));

```

I get the following error message when I try to use the d7 version:

> PDOException: SQLSTATE\[HY093\]: Invalid parameter number: number of bound variables does not match number of tokens

D7 API for db\_query

Could somebody help me out figuring why the db\_query isn't working?

# Answer
> 0 votes
You've quoted one of the parameters when you shouldn't have.

PDO interprets this:

```
':source_swe'

```

as a string, and it (correctly) doesn't try to change it.

What you're looking for is simply

```
:source_swe

```

So that parameter replacement can occur. As in,

```
db_query("REPLACE INTO {locales_target} (lid, translation, language) VALUES ((SELECT lid FROM {locales_source} WHERE source = :source_eng LIMIT 1), :source_swe, 'sv')", array(':source_eng' => $name['eng'], ':source_swe' => $name['swe']));

```

---
Tags: i18n-l10n, database
---


# Question
Title: How to display Views fields as a drop down menu?
I have several fields in a View which I would like to appear as a drop down when another field is hovered over. It is possible to create a jump menu and a fieldset in Views, but how does one create a drop down menu? I have tried using the Block Reference module but this doesn't seem to show in Views. The only other option I can think of is writing the HTML in a global Views field and using replacement patterns, but there's got to be a better way. How can this be done?

# Answer
> 1 votes
It depends on the specific context - are you simply wanting to use the view results as a menu (in which case Menu Views would do this), or are you wanting to display a number of items e.g. users, and have more detailed info on the items spill out on hover (in which case, a display format such as Views App Folders might be what you're looking for).

---
Tags: views, navigation
---


title: Tracking clicks on each link separately

text:
# Question
Title: Tracking clicks on each link separately
I have create a website that, on the same page, will offer several links to the exact same section (node). For example the link to the "Contact us" node appears 3 different times (in 3 different places) on the home page.

Is there any way to track each click separately and to know which links were clicked to reach the contact us page?

I am already using the "Google Analytics" Drupal module, but the same link is tracked as a single unit, regardless of the number of times it appears on a page.

# Answer
> 0 votes
You can append a different query string to each link, which will allow you to track each one individually. Lets say your contact page is at mysite.com/contact. You can create several url's with a query string that lead to the same page. Ex:

mysite.com/contact?link=1

mysite.com/contact?link=2

mysite.com/contact?link=3

etc.

You can always append a query to a URL without creating any aliases or anything. Simply add ?key=value (obviously you can change 'key' and 'value' to anything you'd like). Google Analytics will track all of these separately.

The only downside is that Google Analytics won't batch all your contact page visits under 1 url anymore, but instead each different query will be listed separately.

---
Tags: navigation, google-analytics
---


# Question
Title: Superfish - how to integrate main & user menu together
I am using superfish module to decorate the menu system but found one issue. i need to show my "main menu" & "user menu" blocks on header region. so that if user is logged in, they can see all the main menu along with "user menu" otherwise only they can see the "main menu" items such as \[home, Games, Blog\]. Please suggest some alternative if this approach is not recommended or proper.

Drupal version - 7.23 Bartik 7.23 Superfish module 7.x-1.9

# Answer
> 0 votes
Go to main menu and add ***My account*** with path `user` and add ***Log out*** with path `user/logout`

SO that links will appear as you expected

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


# Question
Title: Show product commerce by taxonomy parent with childs
I want to show several products filtered by apples. Apple is a hierarchy taxonomy and not always the values from the parents are in the childs.

**Example:** apple (apple can have other results that are not in big\_apple nor small\_aplle) -big\_apple -small\_apple

**Question:** How can I create a view that when it's 'fruit/apple' shows apple + big\_apple + small\_apple and whent it's 'fruit/big\_apple' it will only be 'big\_apple' ?

I think with this in contextual filters can help but it's far from working:

```
$id= taxonomy_get_term_by_name($argument);
$children = array_keys(taxonomy_get_children($id));
if(!empty($children))
{
    $handler->argument .= '+' . implode('+', $children);
    return TRUE;
}else
    return FALSE;

```

# Answer
Well, I am my most popular fan so I will answer myself:

**1.** It's not possible to add that PHP code to the view, as **it's a known bug** that the view doesn't allow multiple contextual filter variables as a PHP. Although you can use them through the URL and changing the 'code PHP' option by 'Multiple Terms ID separated by ',' OR '+''. --\> I don't like that option as the URL won't be very clean and can be a bit complicated.

**2.** **Found a better option!!** I decided to select the parent when one of its childs are selected. This option can be activated as automatically, when installing the Taxonomy Term Reference Tree Widget module:

> **About this module**
>
> This module provides an expandable tree widget for the Taxonomy Term Reference field in Drupal 7. This widget is intended to serve as a replacement for Drupal's core Taxonomy Term Reference widget, which is a flat list of radio buttons or checkboxes and not necessarily fit for medium to large taxonomy trees.

**Note:** I don't know why but my tree view is not as nice as in the picture and I needed to use a fix but it works perfect.
> 0 votes

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


# Question
Title: custom HTML in search form ( site/search)
I'm trying to customize the html of the search block form. I know that I can use templates.php to modifiy the fields and customize it but I'm trying here to change the whole html block. I've tried to use search-form-block.tpl.php, but it didn't work (yes I've cleared cache).

I guess I'm missing something here ...

Any help appreciated thanks !

Ps : I'm using solr in an acquia environment.

# Answer
You can use hook\_form\_alter and use render API to alter the html attributes. You can add attributes such as class, id, wrapper tags(prefix and suffix), attaching css and js file to the rendered form this way too. It would be something like this.

```
function yourMod_form_alter(&$form, &$form_state, $form_id) {
 if(strstr($form['#form_id'], 'search_form')) {
   $form['#attributes'] = array(
    'class'=> array('search-form-custom-class'),
    'id' => array(),
    );
   $form['#attached'] => array(
     'css' => array( drupal_get_path('module', 'yourMod') . '/css/yourMod.css' ),
   );
   $form['#prefix'] = "<div class='wrapper-for-search'>";
   $form['#suffix'] ="</div>";
 }
}

```

I advise to read more on the render API to see all attributes that you can alter.
> 1 votes

# Answer
You can use hook\_form\_alter(&$form, &$form\_state, $form\_id) in template.php.

Like

```
function hook_form_alter(&$form, &$form_state, $form_id)
{
if($form_id=='search_form')
{
 // change values in $form.
}
}

```
> 0 votes

---
Tags: search
---


# Question
Title: entityfieldquery, return several results
I want get several entries of database. Im a entityfieldquery novice and I misunderstand how I do for get several results who contain certain fields (here, the fields that interest me are : delta, field\_top\_value and field\_top\_revision).

By example, I try this code :

```
$query = new EntityFieldQuery();
$query
    ->entityCondition('entity_id',$nid_device)
    ->entityCondition('entity_type','node');
$result = $query->execute();
dpm($result); //show just one only node...but I would like get the five entries, with field "delta, field_top_value and field_top_revision_id"

```

I "tried" to read the documentation, but my english reading isn't very good, and I don't find example for my case..

Thanks for help !

# Answer
Whenever you load data by **entityfieldquery()**, then it will return you everything in term of node.

1. Here entity\_id from table and nid of node is same
2. vid parameter in node is same as revision\_id in the table
3. delta specifies multiple value saved w.r.t a particular field e.g. a field **category** with table **field\_data\_field\_category** has multiple values testcategory1 ,testcategory2.

Then it will saved in the database as delta 0 for testcategory1 and 1 for testcategory2.

And when it will be returned in node all values are assembled to show in the particular field w.r.t which it belongs in the form of array.

Also you can load the node data separately by node\_load() function by passing entity\_id/node id to load all data w.r.t that particular node in assembled mode.
> 0 votes

# Answer
The table in your screenshot is a *field* table. It stores field data for entities, for both multiple and single cardinality fields.

When you use an `EntityFieldQuery`, you're querying for *entities*, not fields. It wouldn't make sense for you to receive data for anything else.

The connection you need to encourage your brain to make is that **the fields are attached to the entities**. So, if you want to know about multiple field values for a node, you just need to go and get them:

```
// Keep track of the delta, you mentioned you wanted it...
$delta = 0;
foreach (field_get_items('node', $node, 'field_foo') as $item) {
  $field_value = $item['value'];

  $delta++;
}

```

If that isn't what you're looking for, then `EntityFieldQuery` probably isn't the tool for the job. If that's the case, and you're using MySQL as the storage backend for fields, I'd recommend manually querying the `field_data_field_foo` table to get what you're after directly.
> 1 votes

# Answer
Your code is looking for a specific node with a specific nid. nid or entity\_id is a unique key. Use different properties to query your entities.
> 0 votes

---
Tags: database
---


# Question
Title: How to log user in when in the middle of Drupal Commerce Checkout
I have created a commerce checkout page which, under certain conditions, is presented to the user with a custom login screen

```
$form['username'] = array(
    '#title' => t('Username'),
    '#type' => 'textfield',
    '#size' => 30
  );
  $form['password'] = array(
    '#title' => t('Password'),
    '#type' => 'password',
    '#size' => 30,
  );
```

In the submit handler, I log the user in

```
$username = $form_state['values']['user_login']['username'];
  $password = $form_state['values']['user_login']['password'];
  $login_array = array($username, $password);
  if($uid = user_authenticate($username, $password)) {
      global $user;
      $user = user_load($uid);

      $login_array = array ('name' => $username);
      user_login_finalize($login_array);
    }
  else {
    drupal_set_message('Invalid username or password');
  }
```

However, what happens is, is on next page, /checkout/order-id/review, it says the user is logged in but page not found. This is because the newly logged in user doesn't have anything in his cart. Is there an easy way of transfering the old cart to this new user? I see that there is a Rule - Assign an anonymous order to a pre-existing user, which I enabled and thought it would do the trick, but it doesn't

In case it helps: there is one rule defined by commerce -- Create a new account for an anonymous order -- which I disabled because I don't want that functionality. I don't know why this would effect anything, but just mentioning it in case it does.

# Answer
I ended up simply using commerce\_cart\_order\_convert($order, $user); I was able to assign the order to the correct user, and I decided not to log him in at point in time. If I really need to log him in, I will do so after checkout is over when I don't need to access the checkout review page anymore.
> 0 votes

# Answer
Commerce Checkout Login provides this functionality at checkout, transferring the current cart when doing so.
> 0 votes

---
Tags: commerce, users
---


# Question
Title: Render alternative content if user is logged in instead of redirecting to user/uid
I have a menu router with type MENU\_CALLBACK and it's 'page callback' property points to a function that implements render API, as follow:

```
 /** Implements hook_menu **/
function custom_render_menu() {
  $items['register-profile'] = array(
    'page callback' => 'custom_render_register_profile',
    'type' => MENU_CALLBACK,
  );
  return $items;
}

/** Implements callback page for register-profile **/
function custom_render_register_profile() {
  $user_register_form = drupal_get_form('user_registration_form');
  $markup = user_is_logged_in() ? t("Alternative Content") : drupal_render($user_register_form);
  $output = array( '#markup' => $markup);
  return $output;
}

```

If the user is not logged in, the registration form displays correctly, but if the user is logged in, the page was redirected to user/uid router, showing user's profile. How can I display an alternative content instead of redirecting the user to their user page?

# Answer
Scott's answer helped me on this. For some reason, if you had called drupal\_get\_form('user\_register\_form'), even if you assigned it to a variable that isn't being concatenated to '#markup', drupal will still go through the process of checking if the user is logged in or not.

Calling the drupal\_get\_form('user\_register\_form') right when assigning the '#markup' does the trick.

```
function custom_render_register_profile() {
  $output = array(
    '#markup' => user_is_logged_in() ? t("Alternative Content") : drupal_render(drupal_get_form('user_registration_form'));
  );
  return $output;
}

```

**edited:** The code above will work but will result in a strict warning: only variables should be passed by reference. Use elaborated if statement instead:

```
function custom_render_register_profile() {
  $output = array();
  if(user_is_logged_in()) {
    $output['#markup'] = t('Alt. Content');
  }else{
    $form_registration = drupal_get_form('user_register_form');
    $output['#markup'] = drupal_render($form_registration);
  }

 $output += array(
  //Add more attributes to your $output
 );
 return $output;
}

```

As to why the ternary version of the if statement wouldn't work, I'm not sure.
> 1 votes

# Answer
How about this:

```
/** Implements callback page for register-profile **/
function custom_render_register_profile() {
  $markup = user_is_logged_in() ? t("Alternative Content") : drupal_render(drupal_get_form('user_registration_form'));
  $output = array( '#markup' => $markup);
  return $output;
}

```
> 1 votes

# Answer
```
function custom_render_register_profile() {
global $user;
global $base_url;
$uid=$user->uid;
if($uid)
{
drupal_goto('url where you want to take login user..like $base_url./node/1');
}
else
{
  $user_register_form = drupal_get_form('user_registration_form');
  $markup =drupal_render($user_register_form);
  $output = array( '#markup' => $markup);
  return $output;
}
}

```
> 0 votes

---
Tags: forms, users, routes, theming
---


# Question
Title: Create a custom view, and add a custom sortable column
I want create a view for display a list of contents. (same type) (its my first fully custom view x) )

I want display the view like this :

```
//form : the user select a Date field, its an exposed filter field

COLUMN1           COLUMN2_sortable
-----------------------------------
content_title0    "special_value0"
content_title1    "special_value1"
content_title2    "special_value2"
...
content_titleN    "special_valueN"

```

First, can you tell me a good web tutorial for learn to create a fully custom view (so, create the user select form (contain exopsed filter) , the content of the view). After several google search, I difficulty finding a good guide...

Second, the COLUMN2\_sortable contain a integer data. And this data is calculed via an another custom module (this value depends on the date entered in the exposed filter field). I have no ideas how add a custom column (here, the COLUMN2\_sortable) in my view. Because this is my first try in fully creating of view, can you advise me about the good way for implement that ?

# Answer
> 0 votes
You can make a column sortable by clicking on your type of view "fields" and check the "make sortable" checkbox.

---
Tags: views
---


# Question
Title: Boost + Expire: Front Page not expiring from cache
I am using Boost and Cache Expiration. My site generates nodes automatically and adds them via `node_save()`. I have setup Expire to get triggered on node insert, update and delete and to let the front page and the node page expire (see screenshot).

The problem is now: When the site is under high traffic, the front page does not get expired. When the traffic is low, the expiration works as it should.

I could reproduce this error even locally: While adding a node, I let `wget` constantly accessing the front page on my local host. As on the production server, the front page did not expire.

My hunch for the reason now is that the following happens within some milliseconds:

1. When calling `node_save()`, the new node get only scheduled to be saved but not saved yet.
2. The cache although, gets flushed immediately.
3. A new request to the front page is made, it gets delivered and its old version gets cached again.
4. The scheduled node save operation finally gets written to the database. But it has no effect to the front page, since it is already cached.

Do you think that my hunch is correct? If yes, what should I do? And if no, what could be the reason instead and what should I do?

# Answer
You may try to add the `<front>` page to the rules action "Clear URL(s) from the page cache":
> 2 votes

---
Tags: nodes, caching
---


# Question
Title: How to tell variable_get to get the value from the database and not the $conf array?
variable\_get seems to always used $conf array which is fetched a single time. In a long running process where the value of a variable may have changed during operations this causes problems. Is there a simple mechanism in Drupal to tell variable\_get to refetch the array from the database rather than using the in-memory variable?

# Answer
I don't think Drupal core has anything like that, no. For speed and efficiency, the variables array is in memory pretty much as soon as settings.php has been processed.

You've always got `db_query()`:

```
$var = db_query('SELECT value FROM {variable} WHERE name = :name', array(':name' => 'var_name'))->fetchField();
$var = unserialize($var);

```

It would be trivial to build up an efficient `variable_get_from_db` function based on that.
> 1 votes

---
Tags: configuration
---


title: Issue with Workbench setting

text:
# Question
Title: Issue with Workbench setting
I'm creating workflow for my Drupal 7 site. On this site we installed Workbench, Workbench Access, Workbench Moderation and Workbench Media. I'm following this setting, but still having 2 issues with Workbench.

1) My drafts are not showing on "My Drafts" tab. It only show if I give the permission "Bypass content access control", which I dont want to do that.

2) I wanna hide "All Recent Content" on My Content tab. Currently, it how Logout page, and Thank you for creting an account page, which I dont wanna show these too.

# Answer
Nobody can give you this answer, check your permissions against what is typical in the documentation page you listed. Have you checked this page selecting the given Role you want to examine:

> If non-administrative users encounter access denied (403) errors or fail to see notifications about moderation states, the "Check permissions" tab can help you determine what permissions are missing. Visit:
>
> Admin \> Configuration \> Workbench \> Workbench Moderation \> Check Permissions

The *My Content* page in Workbench Moderation is a View. You can customize its filters or conditions to meet your needs -- but be careful it's provided by the Workbench module so if you update the module you will likely loose your changes to the View unless you implement your changes using `hook_views_default_alter`.
> 1 votes

---
Tags: users, workflows, workbench
---


# Question
Title: Parsing XML files to populate form fields
I need conceptual clarification. I have fields of a form that I want to populate by letting a user use an XML file so my custom form module can parse and assign XML to form fields. I do not need to keep the XML file permanently.

First question: When using the file field widget on my form, after I select my file and the file name appears on the form, Drupal or the browser seem to have it stored in memory somewhere. It is possible to parse the XML file from this location in memory with a submit handler that populates the form? (So 2 submit handlers on the form, one to submit the XML to populate form and the other to submit the form to create node.)

Last question: Would this be easier if I have a form with a single file widget that uploads an XML file to a temp directory and builds + renders a form on the node after it has parsed the data?

Thanks all!

# Answer
I suggest you use the Feeds module. (I believe you may need to also read up on its SimplePie integration to help with the XML.)

Basically, it provides you with the form and functionality for importing, storing, and reading your XML file. It is also designed to create a node using the info read from the XML file.

If you don't want a new node, then you can interrupt the process using hook\_feeds\_presave to work with the info that Feeds has read from the uploaded file. (For example, to load and populate a form with the imported info. I'm looking into doing just that, myself.)

If you didn't want to use Feeds, then read up on the File interface and File API, which let you work with the uploaded file, store it temporarily, read data from it, etc. I've found that very useful.
> 2 votes

---
Tags: 7, forms, files
---


# Question
Title: Combining 2 drupal 7 sites - how to move modules?
I am combining 2 drupal sites in to one, was not really my decision. What things I should be careful of and what pitfalls to avaoid?

List of things I will be combining

1. Content Types - Bundle copy module
2. View - Export functionality
3. Content Data - Feeds Importer
4. Blocks - Block Import Export module
5. Modules - I am going to install the standard modules from drupal projects and copy over any custom modules. How can I move the modules configurations?
6. Menus - How to move over the menus settings?
7. Users - Do not need to be migrated

There is not much taxonomy on the other site. Anything else I am missing ? Any suggestions on the sequence to do this?

Thanks.

# Answer
I don't know for the menus, but for modules that doesn't implement any export functionality (either custom or contrib), take a look into the 'variables' table.

for how unpractical it may sounds, export the table data, keep only the 'module\_\*' entries of the module you need and insert the in the new site database, after you install the modules. You will have to change the sql from inserts to updates too.

yes, extremely unpractical, but i can't think to an automated routine for it.

also, probably you are forgetting to export users too (and custom roles).
> 0 votes

---
Tags: migrations, multi-sites, backups
---


title: Expand content if sidebar isn't used

text:
# Question
Title: Expand content if sidebar isn't used
I've been learning Drupal myself for over a year now. I've mainly used templates all the time and changed the `css`. This time I made my own template and put `php` in it for the first time. Everything worked but I was wondering how I can expand my content box if a sidebar isnt used? Oh, I'm using `Bootstrap's` css

Snippet of php:

```
<div class="container">
<div class="row">
    <?php if ($page['sidebar_first']): ?>
  <div id="sidebar-first" class="column sidebar span4"><div class="section">
    <?php print render($page['sidebar_first']); ?>
  </div></div> <!-- /.section, /#sidebar-first -->
<?php endif; ?>
<div id="content-area" class="span4">
          <?php print render($page['content']) ?>
        </div>

    <?php if ($page['sidebar_second']): ?>
      <div id="sidebar-second" class="column sidebar span4"><div class="section">
        <?php print render($page['sidebar_second']); ?>
      </div></div> <!-- /.section, /#sidebar-second -->
    <?php endif; ?>
    </div>
</div>

```

They all have `span4` but what I want is when sidebar 1 isn't used, then content id changes to `span8`

# Answer
> 0 votes
I think the simplest solution would be:

```
<div id="content-area" class="span<?php echo $page['sidebar_first'] ? '4' : '8'; ?>">

```

---
Tags: 7
---


# Question
Title: Pathauto insert taxonomy term custom url
I have change the url of an taxonomy term. Now when i use a field with taxonomy term the url is showing like this:

```
[node:field-taxonomy:parents:join-path]/[node:field-taxonomy:name]/[node:title]

```

**auto/safety-tools/audi**

The taxonomy term has name **Safety Tools** but i have change the url to just **tools**.

like **auto/tools/audi**

How i can load to my node the custom term url path.

I tried \[node:field-taxonomy:url\],\[node:field-taxonomy:url:absolute\],\[node:field-taxonomy:url:relative\] without success

# Answer
You can use the following pattern:

```
[node:field-taxonomy:parents:join-path]/tools/[node:title]

```

(manually set the middle part of the pattern).

Or, if you have several terms (not just Safety Tools), you can use

```
[node:field-taxonomy:parents:join-path]/[node:field-taxonomy:url:path]/[node:title]

```

(\[node:field-taxonomy:url:path\] is the path component of the term's URL)
> 1 votes

---
Tags: 7, taxonomy-terms, path-aliases
---


title: Writing a field formatter for D6

text:
# Question
Title: Writing a field formatter for D6
So I'm almost embarrassed to ask this, but it's been so long since I've touched Drupal 6. We've been asked for something which requires another Field Formatter for a File field.

Form the code below, I'm able to select `File download formatter` in Content Type Display. However, when looking at the rendered page, I see no output for this field.

During `drush cc all` I see the reponse "TEST ONE" print in the console denoteing that MODULE\_theme() is running. But there is not a connection to `theme_MODULE_viewer`.

Once I get this wired up, I'm sure I can finish this in a hour, but what am I missing?

```
<?php
**
* Implementation of hook_field_formatter_info().
*/
function MODULE_field_formatter_info() {
  return array(
    'socf' => array(
      'label' => t('File download formatter'),
      'field types' => array('filefield'),
      'description' => t('TO DO: add description'),
    ),
  );
}

/**
* Implements hook_theme().
*/
function MODULE_theme() {

  print "TEST ONE";

  return array(
    'MODULE_viewer' => array(
      'arguments' => array('element' => NULL),
    ),
  );
}

function theme_MODULE_viewer($element) {

  print "TEST TWO";
  return 'Future response here. ';
}

```

From my understanding `hook_theme` creates an awareness of `theme_MODULE_viewer` in the array key `MODULE-viewer`.

In the Devel Tab, I see that the field contains data in both Load and Render panels.

# Answer
> 0 votes
Well I did this in a slightly different way. By using `hook_preprocess_content_field()`, I search through all of the fields in a node and do a `str_replace()` on those items. This does solve my problem but I'm open to a more elegant solution.

```
function MODULE_preprocess_content_field(&$variables) {

  for ($i=0; $i < count($variables['items']); $i++) {
    $searchfor = variable_get('file_directory_path') . '/special_folder';
    $replacewh = 'portfolio/asset';
    $variables['items'][$i]['filepath'] = str_replace($searchfor, $replacewh, $variables['items'][$i]['filepath']);
    $variables['items'][$i]['view'] = str_replace($searchfor, $replacewh, $variables['items'][$i]['view']);
  }
}

```

Side note: The path portfolio/asset is part of this same module and defined in `hook_menu`. I would have preferred to have this done with a field formatter in the above code, but I've got to move on.

---
Tags: 6, entities
---


# Question
Title: Exporting Site Configuration Settings into Features
This is on a Drupal 6 site, and we want to export several settings (like CSS aggregation) into features, however it doesn't appear like there's anyway to do this. Do we need to write a custom feature hook?

We installed Ctools and are going to install Features Extra, but nothing seems to support CSS aggregation - a basic site configuration setting - out of the box.

How can we accomplish this?

# Answer
In order to export Drupal 6 system settings like the CSS and JS aggregation. Or anything else stored in the {variables} table, you can use the strongarm module. https://www.drupal.org/project/strongarm
> 2 votes

---
Tags: 6, features
---


title: Views API - how to replace PHP fields

text:
# Question
Title: Views API - how to replace PHP fields
So a client that I inherited has multiple PHP fields in each of their views.

I'd like to replace them. They're using PHP Code module as well as Views Customfield.

Would I have to write a custom views handler? Or is there some sort of alter that would allow me to basically replace each of these fields/data sources with my own information, without exposing a PHP filter to a user (even an admin user).

Basically I am trying to increase site security.

# Answer
> 0 votes
In cases like this, I usually use:

https://api.drupal.org/api/views/views.api.php/function/hook\_views\_pre\_render/7

For pre-processing the views render array.

---
Tags: 6, views
---


# Question
Title: How to move D7 from /sites/sitename to /site/default?
I was successful at this once and now I forgot how I did it. I'm copying a site's files from my local computer to a host GoDaddy. What I'm doing is installing D7 at the host's control panel, updating the site to D7.29 then copying files from my local D7.29 install to the web and then importing the database. It worked with no problems once a month ago. Now no luck. The best I can do is get the site to appear to be all up and running, all CSS works, can even log in and manage modules if desired, but NO pictures show up. It's as if the folder structure is not known for those files. The reason I believe is that I'm copying from sites/sitename (all the local site specific files) (and then fixing settings.php of course) and then since Drupal on GoDaddy only seems to want to work with /sites/default I'm copying the files to that location, default. Like I said I did it once no problem, now not so... Beautiful site with all CSS and content but no pix. I've even tried this locally and it doesn't work, same problem, wondering what to fix.

Newbie Dave N

# Answer
Adjust the path where your public files are stored - here: admin/config/media/file-system (Configuration -\> File system -\> Public file system path) - also review the temporary directory.
> 1 votes

# Answer
Welcome to Drupal.

1st lets check the *status report*:

* Log in as administrator
* Append `admin/reports/status` to your base URL

And see if there are any *red* items.

Usually if you simply copied over folder from your computer to your GoDaddy space, the permissions might not be right.

See what permissions the folder `sites/default/files` has. The user that your web server is running as needs to be able to read and write to this folder (and its children).

Another potential problem could be that the path to your files directory might be wrong.

Goto `admin/config/media/file-system` (by appending that to your base URL) and double check that your paths point to `sites/default/files` and not `site/somesite/files`.

This might actually be the reason Drupal is not loading your images, since you had it installed in `sites/somesites/files` on your local, but changed it to `sites/default/files` on GoDaddy. In your database, that you imported, Drupal is looking for your assets in the folder that you specified when working on your local install -- which would be `sites/somesites/files`.

In any case, it might save you time if you start your troubleshooting by visiting `admin/reports/status` first!

Lastly, a `PROTIP:` Drupal stores its settings in the variables table in your database and you can usually override these from settings.php (but don't go doing this until you have a comfortable understanding of the system).
> 1 votes

---
Tags: 7
---


title: Multiple Context block order / weight

text:
# Question
Title: Multiple Context block order / weight
I have 2 Contexts set up that each place a block in the same region.

There are times when both these contexts will happen at the same time and as such both blocks appear together.

Currently when both appear they are not in the order I require, is there a way of weighting these across contexts? I know the weighting works within a context however this is not what I need at this point.

Currently using: Drupal 6.22, Context 6.x-3.0

**UPDATE:**

*Hi All,*

*This post appears to get quite of interest but I'm afraid I don't use Drupal anymore or have any time (or sites) to check these answers. If any answer gets enough interest and appear to be right then I'll happily mark it correct but I can't actually verify anything.*

# Answer
> 2 votes
This patch worked for me. Enable the patch at *admin/build/context/settings*.

There is a lot that gets discussed after that comment and one contributor even created a module. I haven't read much of the other comments, implemented the module nor any of the patches posted after the one I referred to above.

# Answer
> 1 votes
There's still no definitive solution for this problem, you might have a look at Block weights when multiple contexts are set or maybe context\_respect. You can also have a look at Way to Weight Blocks that Show From Multiple Contexts for some background information.

One work-around is to export all your context to code (using features) and edit the weight inside the created code files, the only problem is that if you re-export your feature, your manual changes will be reverted. We use this approach for the moment because it fits in our workflow.

# Answer
> 1 votes
I just fixed this for myself (while using version 7.x-3.x), using `hook_context_load_alter()`. Basically, you can implement this in your own misc module, print out what you're getting with `dpm()`, and then adjust as needed. Here's what I ended up doing:

```
/**
 * Implements hook_context_load_alter().
 */
function example_misc_context_load_alter(&$context) {
  // We need to make sure that the mobile section menu is printed before these menus,
  // so we set the weights to -9 here so they appear after it.
  if ($context->name == 'about') {
    $context->reactions['block']['blocks']['menu_block-15']['weight'] = -9;
  }
  if ($context->name == 'traveler') {
    $context->reactions['block']['blocks']['menu_block-1']['weight'] = -9;
  }
}

```

# Answer
> 0 votes
The weight context assign to a block is a number, that will effect the position of all the blocks that any context will add to any region. There isn't an UI to tweak these weights to mix blocks from several contexts, but there is a way around it.

The easiest solution I could find, was to run some custom JavaScript in a browser console:

```
 $(".form-item").show()

```

This will show all the weights that control the sorting. Tweaking these would allow you to sort the blocks like you want.

# Answer
> -2 votes
You can edit (carefully) the serialised values in the context table through phpMyAdmin. This has to be done again every time the context is edited through the UI. But it's not a bad solution which avoids the overhead of installing extra modules to solve this.

---
Tags: blocks, 7
---


title: Wrap div around results

text:
# Question
Title: Wrap div around results
In a content node, I wanted to wrap a div around some results. For example: I have this inputs:

Image Title Body Address Email Name

And I wanted to have divs like this: DIV Image Title /DIV DIV body Adress Email /DIV DIV Name /DIV

Is this in any way possible?

# Answer
> 0 votes
So, if you create a new .tpl.php for your content type, you can simply print the divs as html, and echo the vars as php.

example:

```
<div class="MyClass">
<?php print $title; ?>
</div>
<div class="MyOtherClass">
<?php echo render($content['some_field']); ?>
</div>

```

See https://stackoverflow.com/questions/8074485/drupal-7-how-to-render-custom-field for a starting point on pulling specific custom fields, for separation, if needed.

be sure to have a copy of your original node.tpl.php in your theme folder as well, or your node--my-content-type.tpl.php wont work! Again, see https://www.drupal.org/node/17565.

---
Tags: nodes, theming
---


# Question
Title: when a button_field is presses, how do I access the node that owns the button?
I have a button (button\_field) on a content type which is rendered by a view. The view will display a list of items and each will have a clickable button. When the user clicks a button, I need write a rule that will set a node reference (attached to the use) to the node that was clicked. the button\_field provides several rules for detecting button clicks, but I have yet to find a rule action or rule token that gives me access to the fields on the 'node that was clicked' How do I gain access to that node?

Edit =============

Link added. I am using the actions that came with the module (no additional code added.) I was hoping when I used the 'button pressed' action, rules would give me accesses to entity:... so that I could use the fields on the entity (the one with the button that was pressed.) However, this data option is not available. Honestly, I could use flags to do this, but I thought that a flag was a bit more functionality than I needed.

# Answer
I was trying to do something similar. It looks like as you can have button\_field on any entity, you need to DEFINE what entity has button\_field in your rules. It worked for me thinking like that.

What I mean is in your rules’ conditions section after checking ‘Clicked button comparison’ with your\_button\_field\_name if you check ‘Entity is of type’ Node and ‘Content is of type’ Your\_content\_type, then all of the fields of your content type including nid will be available in Actions section under entity. Check out Using Button Field
> 0 votes

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