title: Using Pathauto URL alias in link fields

text:
# Question
Title: Using Pathauto URL alias in link fields
In a view, I have several fields that I would like to link to the original content. The `title` field's default behaviour is like this, but I want to have the trimmed `body` and the `image` fields to behave the same way too.

For this, using the `content:path` field and then rewriting the other fields using this one as a token has been recommended here. But this gives me the Drupal path, not the URL alias.

Another idea is to use Global Redirect module and to set it to always use URL aliases. But this obviously requires to install yet antoher module. I am hoping to manage without it.

The content pages behave according to the URLs so I need to have the aliased ones.

Is there a way to get the URL aliases in views link fields?

(I am using Drupal 7.23, Views 7.x-3.7 and Pathauto 7.x-1.2)

# Answer
I do not see any problem here. You can do it like this:

1. Add the view
2. Add the fields
3. Add NID, exclude it from display, and move it to top of list
4. Open the field setting which you want to change, expand the Rewrite results fieldset, and check "Output this field as link"
5. As link path input, enter *node/\[nid\]* (this is the token)
> 2 votes

---
Tags: views, path-aliases
---


title: create date type in install profile

text:
# Question
Title: create date type in install profile
I want the german date format in my install profile.

I tried in my setup script:

```
drush en l10n_update -y
drush vset site_default_country de
drush language-add de
drush language-default de
drush vset date_format_short "d.m.Y"

```

but it is not sufficient. It would not show up in the UI-\>configuration.regionalsettings as custom date format

manually I have to create a custom date format ("d.m.Y") first and then I can set is as wanted "date type",

I would do it via drush php-eval or better in profile-install function

**update:** clarified a bit

**update2** meanhile I discovered hook\_date\_format\_types :-) trying...

# Answer
> 0 votes
If you want to use a custom date format, you should write this as a record in the database. In your `profile-install` function, you can use following code to accomplish this:

```
system_date_format_save(array(
    'format' => 'd.m.Y',
    'type' => 'custom',
    'locked' => 0,
    'is_new' => true,
));

```

---
Tags: drush, datetime
---


# Question
Title: Apache AddDefaultCharset utf-8 - filename not saving in utf-8
Using file field to upload image which has utf-8 filename, but when it is uploaded to site filename is not saving in utf-8 format.But original name is saved as link in database making it not found when accessed.

`AddDefaultCharset utf-8` is added to `httpd.conf` and server restarted before testing.

```
original filename - noëlle_châtelet.jpg(same is saved in database)
saved filename -noÃ«lle_chÃ¢telet.jpg

```

# Answer
> 1 votes
According detailed explanation at https://bugs.php.net/bug.php?id=47096 temporary solution would be, explicitly converting filename encoding using iconv().Now it raising new warning message(shall I have to open another issue thread for this?)

```
Warning: filesize() [function.filesize]: stat failed for public://noëlle_châtelet12.jpg in file_save() (line 566 of C:\server\www\drup_dlist_mys\includes\file.inc)

```

temporary solution until it is fixed in php move\_uploaded\_file() function. In file.inc I added the line in drupal\_move\_uploaded\_file function block

```
+$uri= iconv("UTF-8","ISO-8859-1//TRANSLIT", $uri);
$result = @move_uploaded_file($filename, $uri);
// PHP's move_uploaded_file() does not properly support streams if safe_mode
// or open_basedir are enabled so if the move failed, try finding a real path
// and retry the move operation.
.
.

```

This is only happening in WAMP and working fine in linux. I don't know how this new iconv statement will affect in unix/linux environment.Can it be possible to check whether the current locale supports for utf-8 just before iconv() statement?.

# Answer
> 1 votes
The only thing `AddDefaultCharset` does is to add `charset=utf-8` to the HTTP header Content-type if the previous part is missing. Nothing to see with uploads or downloads.

On a Windows system, PHP functions relative to file system do not handle UTF-8 but ANSI code page (CP1252 for French) as PHP use ANSI functions and not Unicode functions (UTF-16) of Windows API.

IMO, in general, the best way to handle uploads is to generate unique file names and ignore client file names or, at least, ignore bytes \> `0x7F`.

```
$filename = filter_var($_FILES['upload']['name'], FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_LOW | FILTER_FLAG_STRIP_HIGH);

```

> Can it be possible to check whether the current locale supports for utf-8 just before iconv() statement?

You can use `setlocale` (to get current locale `FALSE !== strpos(setlocale(LC_CTYPE, '0'), 'UTF-8')` and/or returns `FALSE` if it is unavaible `if (!setlocale(LC_CTYPE, 'fr_FR.UTF-8'))`).

**UPDATE**: as of PHP 7.1.0, PHP can now use UTF-8 encoded paths on Windows (set internal\_encoding to UTF-8, for example - should be the case by default).

---
Tags: files
---


# Question
Title: Single webform on multi-language site with different url aliases
I have multi-language site with webform. I want to use the same (single) webform for each language so I used *Webform Localization* module to translate the webform via string translation. Everything works, but the urls now looks like `/en/node/123` and `/cs/node/123`.

I'd like to have separate url aliases for each language, e.g. `/en/my-form` and `/cs/muj-formular`. How to achieve this?

# Answer
> 3 votes
You can achieve that using administration interface.

Firs, Go to admin/config/search/path and click "Add alias".

On "Add alias" page:

1. Select language.
2. Fill the field "Existing system path" with your webform node/{nid\_number}
3. Fill the field "Path alias" with desired alias for that language.

---
Tags: webforms, i18n-l10n, path-aliases
---


title: Form and gated content

text:
# Question
Title: Form and gated content
UPDATED from earlier:

I am using a simple Drupal form that collect user info before allowing the user access to donwloadable content. NOTE: This is using the form API and I am no longer using a modal; just using a regular page created by a hook. Here is the scenario:

```
<?php

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

  $items['form/userinfo'] = array( //this creates a URL that will call this form
    'title' => 'Download Form', //page title
    'description' => 'A form that gathers user infomation',
    'page callback' => 'drupal_get_form', //this is the function that will be called w           hen the page is accessed.  for a form, use drupal_get_form
    'page arguments' => array('my_form'), //name of the form
   'access callback' => TRUE
 );

 return $items;
}

function my_form() {
 if (!empty($_COOKIE['Drupal_visitor_downloadbypass'])) {
 drupal_goto('this is where the pdf file will go'); // rest of the page will not execute because drupal_goto ends the request.
}
 $form['name']['first'] = array(
'#type' => 'textfield',
'#title' => t('First name'),
 '#required' => TRUE,
 );
$form['name']['last'] = array(
'#type' => 'textfield',
'#title' => t('Last name'),
 '#required' => TRUE,
 );
$form['name']['title'] = array(
'#type' => 'textfield',
'#title' => t('title'),
 '#required' => TRUE,
 );

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

 );

 return $form;
 }
   function my_form_submit($form, &$form_state) {
 // $form_state['values']['example'] contains the submitted value of 'example' element.
 user_cookie_save(array('downloadbypass' => 1));
  $form_state['redirect'] = 'this is where the pdf file will go';
  }

```

So here is my question: Now my form page is not showing up and I didnt change the hook except for the form name argument. The form will need to redirect back to the previous page and open the file in a new window upon submission.

Thanks!

phi

# Answer
You didn't mention whether you are using ctools modal forms or a custom modal form.

For general form API submissions, the submit handler will only be executed when the form validation has passed, including the regular CSRF checks.

Suppose you have a form like this:

```
<?php
function my_form() {
  if (!empty($_COOKIE['Drupal_visitor_downloadbypass'])) {
    drupal_goto('download/able/file.here'); // rest of the page will not execute because drupal_goto ends the request.
  }
  $form['example'] = ...;// your form building goes here
  ..
  ..

  return $form;
}

function my_form_submit($form, &$form_state) {
  // $form_state['values']['example'] contains the submitted value of 'example' element.
  user_cookie_save(array('downloadbypass' => 1));
  $form_state['redirect'] = 'download/able/file.here';
}

```

If you are using a ctools modals, you can check the $form\_state in your ctools form builder to do the same cookie check and redirect above.

Your ctools form builder can be as follows. Note the $form\_state check.

```
<?php
function my_ctools_form_wrapper($js = NULL) {
  ctools_include('ajax');
  ctools_include('modal');
  $form_state = array(
    'ajax' => TRUE,
    'title' => t('My Ajax Form'),
  );

  $output = ctools_modal_form_wrapper('my_form', $form_state);

  if (!empty($form_state['executed'])) { // is the form submitted ?

    // Add the responder javascript, required by ctools
    ctools_add_js('ajax-responder');

    // Create ajax command array, dismiss the modal window.
    $output = array();
    $output[] = ctools_modal_command_dismiss();
    $output[] = ctools_ajax_command_reload();
  }

  print ajax_render($output);
  exit();
}

```
> 0 votes

---
Tags: forms
---


title: Implementation of PDF generation

text:
# Question
Title: Implementation of PDF generation
I am working on a requirement where I have a link "get report". When User clicks it, the information is fetched from DB and a PDF report is generated. Finally the PDF file will be shown to the User to download or view in browser. I want to know what is the better way of implementing the link, onclick functionality. Do I have to use Ajax module or something else. Please help.

# Answer
> 1 votes
That should prove easy to do with Views PDF. It is easily customisable compared to other PDF modules. However if you're planning yo do complex reports that is one thing drupal doesn't excel in.

# Answer
> 1 votes
I'm using Views PDF with the TCPDF library (as suggested) and it is AWFUL. The comments mention rendering will be slow, and that is an understatement. It is ATROCIOUS.

I'm looking for a better solution myself, but be wary. Generating a PDF is not only time consuming with the Views PDF/TCPDF combo, but it is practically unusable and offers a horrendous user experience.

# Answer
> 0 votes
Have you tried the Fill PDF module. This may be the one you are looking for.

---
Tags: ajax, files
---


title: Moving elements to other page regions

text:
# Question
Title: Moving elements to other page regions
I want to move the page breadcrumb to the content region in Bartik (D7.)

I assume it is theming but I can't find anywhere (style.css, layout.css) where the breadcrumb is assigned in the first place.

Does anyone know how to do this?

Thanks. :)

# Answer
I will again answer my own question here:

The change is made in the *page.tpl.php* template found the the template directory of your theme.

In this case, all I had to do is move the following:

```
<?php if ($breadcrumb): ?>
  <div id="breadcrumb"><?php print $breadcrumb; ?></div>
<?php endif; ?>

```

from it's present location under the *main-wrapper* to its new location under the *content* heading. Then I cleared the theme registry cache.

Make sure that if you move an "if" statement, that you always move its corresponding "endif" statement too.

:)
> 0 votes

---
Tags: theming, breadcrumbs
---


title: Interactive filter options for views

text:
# Question
Title: Interactive filter options for views
I have setup a view with contextual filters; it works great.

Now I just need to setup a few drop downs to allow users to filter on criteria. Does the Views module support this in Drupal 7?

Should I just build a quick module using the form API, set the module to block level, and show the block above the listings?

What's the best practice here?

# Answer
You can allow your users to filter the view data by "exposing" your filters. See screenshot:
> 1 votes

---
Tags: 7, views, forms
---


# Question
Title: How to redirect to original page after node create
I have a link to a create node form from a particular page. After the user creates the node and saves, I want to redirect the user back to that page (and not to the new node URL).

What is the best way to do that?

# Answer
> 3 votes
I figured it out. Just add the '?destination=the/url/you/want/to/redirect/to' to the /node/add/your-content-type' link.

---
Tags: 7, nodes, redirection
---


# Question
Title: create text box search for multi select field in view
I have a custom content type in my drupal installation called Stores. While creating a new content for Stores I have a checkbox where I can select multiple zip codes.

I have created a view with my store listing and I want to add an option for the user to have a text box where s/he can enter a zip code and the store list gets filtered based on this. I have exposed the zip code field as a filter in the view. However since this is a multi-select field the filter shows up as a drop down to the user instead of a text box. I want a empty free-flow text box instead of a drop-down with all the zip codes in it.

I really appreciate any help or pointers regarding this..

# Answer
> 2 votes
You are looking for Finder module, it will display the autocomplete dropdown list to the users.

> Finder allows Drupal site administrators to create flexible faceted search forms to find entities such as nodes or users based on the values of fields and database attributes.

---
Tags: views, search
---


# Question
Title: How can I build a view that shows other nodes that reference the same node the current node references?
Let's say I have homes and neighborhoods (homes reference the neighborhood they're in via a node reference field). On the home detail page I want to show other homes in the same neighborhood.

Seems simple enough, and I've found this: Create a view on a node reference field but it is not quite what I need to do, since I need to find other homes that reference the same neighborhood as the current home does (not ones that reference the current home).

I also found this: Node references view: get other nodes that also reference the same node but I am only using 2 content types (homes and neighborhoods). Any ideas? My brain is tired after trying to think through the relationships and arguments of this thing :)

# Answer
> 2 votes
You should be able to do this with a relationship. Add the neighborhood node reference field as the relationship. Add NID as your argument and apply the neighborhood relationship that you just created as the relationship to that NID argument. This will tell views to use the NID of the node reference field as the argument.

# Answer
> 1 votes
What you are doing is commonly called a reverse node reference. You are querying to find all the nodes that have a node reference field referring to the current node. Here's how to do this:

1. Add the node reference field as an argument to the view.
2. Add `$args[0] = arg(1);` as the argument handling code.

Its important to note that you will create a block display for the view so that the arguments will get evaluated properly.

# Answer
> 1 votes
The easiest way is to use Viewfield module.

1. First, install Token and Viewfield
2. Add new view for home content type with two arguments (contextual filters):
    * Your reference field to neighborhoods
    * Content:Nid with default content id from URL and check «Exclude». Optional, to exclude node which is viewed.
3. Go to your home content type and add new field of type Views.
4. Configure field with tokens help.
    * NOTE: I don't know how this will work with multiple references, but with single reference value it works great. Anyway you will be able to solve it by PHP Validate code in Views.

***Update****: Relationships are better choice in this task, but I found strange bug on my Drupal with it so I suggested way with Viewfield.*

# Answer
> 0 votes
Hopefully this will help someone...

Taken from https://drupal.org/node/131547 Exclude the current node from a list view.

Views 3

1. Click on the "advanced" tab.
2. Click on add under "contextual filters".
3. Choose Content:nid.
4. Under "when the filter variable is not available, choose "provide default value".
5. From the drop down menu select "content id from url".
6. Scroll all the way down to the bottom of the window and click on the "More" link.
7. Click "Exclude"

---
Tags: views, 6, nodes
---


# Question
Title: How do I change assigned redirect url to drupal root url?
Sorry I really don't know how to actually ask this.... But let me explain.... I have my drupal installed in a subdirectory (www.mydomain.com/my-drupal-install). If I type that in the browser url address bar it works fine - drupal loads and I can navigate all links within the domain and the user and admin configuration loads as well. I have set a domain name to that directory in godaddy shared hosting so if I now type (www.my-drupal-install.com) the first page loads but it will not allow me to navigate to any links not even the user or admin login links. I get a 504 error... How can I fix this?

# Answer
Fixed......... You just have to reset the base url ($base\_url = 'http://www.example.com';) in your main settings.php file to whatever your desired url is and refresh the page... It should work fine afterwards.

Thanks anyways.
> 1 votes

---
Tags: installation, uri
---


# Question
Title: Save button missing on User Account Edit form
I have months old problem of missing "Save" button on the user account edit form. Which is annoying to the point that now I have to find the solution.

I don't usually use account edit form since there is only one user. I have updated many modules and different cores but problem always remained there. Right now I am running latest core which is 7.23. And all modules are updated. This is a multilingual website.

Since this problem has appeared I am unable to save any change in any user account. Please have a look on the image attached. Please help.

Thanks.

# Answer
> 0 votes
Try disabling i18n synchronization module.

There is another question similar to yours. Save button missing from content type edit form Problem: save button missing from content type edit form. Reason: bug in i18n synchronization module. Solution: none here, but...

There is another case where i18n synchronization causes an infinite loop and there is patch along the lines of

```
if (function_exists(i18n_sync)) i18n_sync(FALSE);

```

This is the link, the patch is at #3. https://drupal.org/node/1372500 Maybe that will help you to the right direction.

---
Tags: forms, users
---


# Question
Title: How to view what query was ran when a form is submitted?
Im using drupal 7, I'm trying to find out where abouts in the database certain values are submitted.

Is it possible to view what sql query was ran after a form was submitted?

Thanks for any help

# Answer
> 0 votes
Install the devel module https://drupal.org/project/devel, and choose the option display query log. The queries will be shown on the bottom of each page.

In admin/config/development/devel:

Check 'display query log'

Sometimes, I prefer just switching on logging in my.cnf for MySQL, because it shows the complete query as executed. If you do that, do not forget to switch logging off again when you are done. Otherwise, you'll fill up your disk/partition.

In the \[mysqld\]section, add:

```
log=/var/log/mysqld

```

Restart mysqld.

---
Tags: database
---


# Question
Title: What is the best way to write a cron that deletes a very large number old nodes and comments?
I am writing a module the preferably implements a cron job, and possibly a queue, to run sql queries to delete old nodes and their comment. Approximately 20 Million nodes, and about 40 mil comments. I want to run pure mysql queries and bypass the drupal api (as much as I can), for performance reasons. I have already developed the relevant queries and would like to know what would be the best way I could implement this so it does not user Drupal api? This is on drupal 7 by the way.

# Answer
I would never think running raw SQL queries is a good idea because that can mess up a lot of things such as site maps, search index, caches, etc.

it's just a node\_delete() and shouldn't be much slower that deleting a bunch of rows in multiple tables.

Whatever that is, you will need to implement hook\_cron and retrive nodes to be deleted from 'node' table.

If you run a node\_delete you won't need to delete comments.

You can limit the number of nodes to delete in a single cron run using LIMIT keyword.

Update: You might want to have a look at Delete All module. and there is a patch (which I submitted) to use the Batch API to do the job. From my experience I know even the Batch API can't handle it (or you have to wait several days with the browser open).

You can just use hook\_cron to load a bunch of nodes to be deleted, and then delete them in your preferred way (node\_delete or raw SQL). Let the cron finish, and in the next run, it will grab some other nodes. Just get your nodes from node table and limit it with a LIMIT.
> 3 votes

# Answer
I think you should use cron and queue api together with `hook_cron_queue_info()` hook\_cron\_queue\_info()

> Declare queues holding items that need to be run periodically. While there can be only one hook\_cron() process running at the same time, there can be any number of processes defined here running. Because of this, long running tasks are much better suited for this API. Items queued in hook\_cron() might be processed in the same cron run if there are not many items in the queue, otherwise it might take several requests, which can be run in parallel.
> 2 votes

# Answer
VBO, or VBO-like functionality.

VBO allows you to specify "entity load capacity", meaning "the number of entities I can load and process at once". The default is 10, but you can easily set it to 100-200 on a system with a bigger memory limit (a gigabyte for instance). It also allows you to delay execution to cron.

Then, you create a view of 20 million nodes, and use the "select all on all pages" to select them all. VBO will then enqueue them in groups of "entity load capacity" (so each queue item would have 100-200 items, for example), and then on cron each group will be loaded separately, after which entity\_delete() will be called for each individual item.

I consider direct db queries in Drupal very unwise. Be very careful if you decide to go that way.
> 0 votes

# Answer
Below is what I eventualy ended up doing. As I mentioned before, with a database with ~20 million nodes and ~90 million comments, all solutions that relies on the drupal API failed because and took way too much time. For example, invoking path delete was taking too much time for with this query SELECT DISTINCT SUBSTRING\_INDEX(source, '/', 1) AS path FROM url\_alias; for each node. With this query, deleting 1000 nodes did not even finish (queries often timed out). I had to comment out the function responsible for it to be able to finsh on node. I commented out path\_delete in path.inc. This took down the average time for deleting 1000 nodes to aporx~ 200 seconds. Still was not good enough to run on a live db. So I needed to get as close as I could to pure SQL. Here is what I did:

1.Find out all the nodes I am willing to keep and keep their idsin a table.
2. Select all the nodes that I am going to delete based on a criteria and using limits of course. 3. Select all the ids comments of these nodes
4. Delete everything that referecnce them.
The whole operation was then placed in a drush command that takes params and calls the function below.

```
function _deletes_multiple_from_tables($nids, $cids) {
$transaction = db_transaction();
try {
// fields
db_delete('field_data_body')
->condition('entity_id', $nids, 'IN')
->condition('entity_type', "node", "=")
->execute();

//field_revision_body
db_delete('field_revision_body')
  ->condition('entity_id', $nids, 'IN')
  ->execute();

  if (!empty($cids)) {
    db_delete('field_revision_comment_body')
    ->condition('entity_id', $cids, 'IN')
    ->execute();

    db_delete('field_data_comment_body')
      ->condition('entity_id', $cids, 'IN')
      ->execute();
  }
  // Delete Comments fields

db_delete('field_data_taxonomy_forums')
 ->condition('entity_id', $nids, 'IN')
 ->condition('entity_type', "node", "=")
 ->execute();

  // Delete Comments
db_delete('comment')
  ->condition('nid', $nids, 'IN')
  ->execute();

db_delete('forum')
  ->condition('nid', $nids, 'IN')
  ->execute();

 db_delete('forum')
  ->condition('nid', $nids, 'IN')
  ->execute();

 db_delete('forum_index')
  ->condition('nid', $nids, 'IN')
  ->execute();

 db_delete('node_comment_statistics')
  ->condition('nid', $nids, 'IN')
  ->execute();

db_delete('opengraph_meta')
  ->condition('nid', $nids, 'IN')
  ->execute();

db_delete('print_mail_node_conf')
  ->condition('nid', $nids, 'IN')
  ->execute();

```
> 0 votes

# Answer
First thing i would like to mention is the function entity\_delete\_multiple or the function node\_delete\_multiple which they both get a bunch of node/entity ids and delete them.

A very good example exist in OG where the module delete nodes referenced to group once it deleted - it use a cron. In the cron worker the module search 250 nodes which need to be deleted.

Another good place to look at is the Message UI module which update in cron/batch massive amount of nodes. You can rely on the code just to get overview on how this need to be done.
> 0 votes

# Answer
If it were me, I'd create a menu callback function that does a db\_query on your nodes. Then write a cron job on your server that calls that URL.
> -1 votes

---
Tags: cron
---


# Question
Title: user login screen is gone after using panels
I've been trying to login with /user, /?q=user, and /?q=user/login but when I load the pages I can only see my header and nothing else.

This is likely because in the process of trying to learn how to use panels I somehow turned it off. The default node variant was the first I created, where I put basic header information (site name, slogan, navigation) in the header, body content in the middle, and regular footer content in the footer with the new node-template variant. As I recall I disabled this page/variant after I realized it applied it to every page and messed up a different system page. Even though I disabled it and it was fine last time i was on the site, it seems to be back.

Is there any easy way to fix this? Is there any thing I cut paste into a php file to load my user login block so i can at least get back into my site?

# Answer
Used drush to disable panels ( drush dis panels).

Thanks to 4life for the suggestion. (i don't know why it won't let me credit him with the answer on here)
> 0 votes

---
Tags: panels, users
---


# Question
Title: Using Modal Forms - Relative paths don't work
I'm using the Modal Forms module to provide Modal Login and Register Forms across my site. Unfortunately it only seems to work if I access the link from a page which is one deep from the host folder. i.e.

* Localhost/drupal/myform - Works
* Localhost/drupal/node/31 - Doesn't Work

The error that throws says that

`/drupal/node/modal_forms/ajax/login` can't be found. Which is correct because the login form is kept at:

`/drupal/modal_forms/ajax/login`

It's adding the relative path on the end of the current page path.

A. Has anyone come across or solved this before?

IF NOT:

B. I think the code path is being pulled from hook\_menu:

```
function modal_forms_menu() {
    $items['modal_forms/%ctools_js/login'] = array(
      'title' => 'Log in',
      'page callback' => 'modal_forms_login',
      'page arguments' => array(1),

```

I tried changing the link to a direct path (not relative), but this doesn't do anything. What should I be trying to change to get the path to either load from `/drupal/` each time or become direct?

# Answer
> 0 votes
This was due to how I implemented the modal forms. I'd put the following path: "modal\_forms/%ctools\_js/login" in my menu links.

Changing this to an absolute rather than relative path solved the problem.

---
Tags: 7, forms, javascript
---


# Question
Title: How to split node fields into view blocks
I am using Omega, and I want to assign fields for a node type to regions of a template. I created a view, with a page (to get a URL) and block views with fields. I then assigned the blocks of fields to their regions to only display for that node type. It's not working. I have a contextual filter for NID, and if not found, to default to the Content ID in the URL.

I feel like this should work, but I'm missing something.

# Answer
Check out this solution here.
> 1 votes

---
Tags: 7, views, theming
---


# Question
Title: Import issue in other languages using csv file to drupal node creations
I am trying to import a csv file using `parsecsv-for-php` library.The given csv file is in `Catalan language`.

The thing is that when i just try to create nodes with given csv data it is throwing me this error like this while importing `PDOException: in field_sql_storage_field_storage_write() (line 448 of /modules/field/modules/field_sql_storage/field_sql_storage.module).`

To resolve this issue, what i did is that used **utf8\_encode** function for each fields and avoided that error.

After successfully importing, the issue over here is that, this is the body text in csv

Thomas Alva Edison va anunciar la invenció del fonògraf l’any 1877, fent una demostració aquest mateix any. L’any 1878 el va patentar als Estats Units. Inicialment per enregistrar va fer servir cilindres de cartró recoberts d’estany, per finalment utilitzar cilindres de cera sòlida. Aquests van ser comercialitzats l’any 1889. La competència amb els discos sonors va acabar per eliminar els cilindres de cera cap els anys 1920s. Tot i així van sobreviure uns anys més com a suports d’enregistrament a oficines amb el dictàfon.

and the imported body text in the drupal i have displayed as image

If u compare both u will know there are certain differences in the body text such as

l\`any in csv body text is getting imported in drupal as lany

d\`estany is getting imported in drupal as destany

d\`enregistrament is getting imported in drupal as denregistrament

I just want the same text to imported in drupal too with out missing any symbols or special characters. what am i doing wrong.

I have attached the my uploaded csv file formats too.

Only this character(**'**) is not coming up properly in drupal.**Any help on this is really appreciated.Thanks in advance**

# Answer
> 1 votes
I found a way to overcome this issue. What I exactly did is that, in the imported view, I just added another `charset=ISO-8859-1` which retrieves back the symbols or characters from db and displayed them properly.

```
<?php
drupal_add_http_header('Content-Type', 'text/html; charset=ISO-8859-1,utf-8');
$new_output = utf8_decode($output);
echo $new_output;
?>

```

That put back all special characters or symbols which was missing.

# Answer
> 0 votes
Can you check what markup gets saved to database? The table field\_data\_body seems to be in utf8 by default. That would rule down the possibility of field\_formatters messing the characters in presentation layer.

If the data in database is corrupted, try getting the output of utf8\_encode logged to some file for example. Is it possible to encode the csv to utf8 with some external tool before using the import tool?

File encodings are tricky and even using wrong encoding in module file can alter the markup. I need to output some xml-files as ISO-8859-1 to serve another system updated content from my service and even using ide-with default encoding can break the modules output by chanching file format. So narrow down more and you will find the break point.

The original pdo-exception could be indication that ´-char was read correctly, but assumed to be text separator. Using escaping should work in that case. In that case run the original importion with using something like $row\_field = '"'.addslashes ( $row\_field ).'"'; before saving to database.

Alternative to addslashes would be check\_plain($row\_field) .

If these dont work then its quite possible that the database doesnt support 'utf8mb4, which is "real" '.

---
Tags: 7, nodes, importing-exporting
---


# Question
Title: Fatal error in include, the file is there
When trying to run a custom module script triggered by the use of a 'one time login' sent by an email for users to reset their passwords I have to include 'user.pages.inc'

This is the URL (edited for anonymity, I hope)

`MYSITE/user/THE-USERS-UID/edit?pass-reset-token=DR8wV7YGtmp5Ia8HQvU1YMs94IRBHsa7-lubQuaLTNs`

I started off with this:

```
module_load_include('inc', 'user', 'user.pages');

```

but that leads to this error when I do finally get to the include in the script.

`Fatal error: require_once(): Failed opening required '/var/www/html//user.pages.inc' (include_path='.:/usr/share/pear:/usr/share/php') in /var/www/html/includes/menu.inc on line 515`

I imagine this `/var/www/html//user.pages.inc` might well be where the problem lies as that location definitely doesn't exist, but 1) I'm not sure 2) I don't know how that would be occurring or how to fix it.

It was working fine on my development environment, then when it didn't run on the production environment I tried...

```
include_once DRUPAL_ROOT . 'modules/user/user.pages.inc';
//module_load_include('inc', 'user', 'user.pages');

```

which also lead to the same error

I got onto the thread of pear being important etc. (http://ubuntuforums.org/showthread.php?t=1025510)

I followed some guides on installation and set it up....

https://stackoverflow.com/questions/5428778/installing-pear

http://pear.php.net/manual/en/installation.checking.php

The original php.ini....

```
;;;;;;;;;;;;;;;;;;;;;;;;;
; Paths and Directories ;
;;;;;;;;;;;;;;;;;;;;;;;;;

; UNIX: "/path1:/path2"
;include_path = ".:/usr/share/php"

```

became this...

```
;;;;;;;;;;;;;;;;;;;;;;;;;
; Paths and Directories ;
;;;;;;;;;;;;;;;;;;;;;;;;;

; UNIX: "/path1:/path2"
include_path = ".:/usr/share/php:/usr/share/pear/PEAR"
;

```

I restarted apache `service httpd restart`

My error message is now...

`Fatal error: require_once(): Failed opening required '/var/www/html//user.pages.inc' (include_path='.:/php/includes:/usr/share/pear') in /var/www/html/includes/menu.inc on line 515`

I did some more checking...

```
# pear config-get php_dir
/usr/share/pear

# php --ini
Configuration File (php.ini) Path: /etc
Loaded Configuration File:         /etc/php.ini
Scan for additional .ini files in: /etc/php.d
Additional .ini files parsed:      /etc/php.d/curl.ini,
/etc/php.d/dom.ini,
/etc/php.d/fileinfo.ini,
/etc/php.d/gd.ini,
/etc/php.d/json.ini,
/etc/php.d/mbstring.ini,
/etc/php.d/mcrypt.ini,
/etc/php.d/mysql.ini,
/etc/php.d/mysqli.ini,
/etc/php.d/pdo.ini,
/etc/php.d/pdo_mysql.ini,
/etc/php.d/pdo_sqlite.ini,
/etc/php.d/phar.ini,
/etc/php.d/sqlite3.ini,
/etc/php.d/wddx.ini,
/etc/php.d/xmlreader.ini,
/etc/php.d/xmlwriter.ini,
/etc/php.d/xsl.ini,
/etc/php.d/zip.ini

```

I've since written a php info file which tells me this...

`include_path .:/php/includes:/usr/share/pear .:/php/includes:/usr/share/pear`

I've confirmed that `/modules/user/user.pages.inc` DOES exist (it's core anyway, right?)

and my other scripts are working (at least they seem to be?!)

By the way - I'm having to include the `user.pages.inc` because 'user\_profile\_form' isn't included for some reason.

I lost the drupal.org link to a topic that was set as closed because it's 'working as intended' but here's a token stackoverflow post that might help explain what I mean: https://stackoverflow.com/questions/6572882/drupal-7-insert-user-profile-form-into-a-page

I've just started looking into the idea that it's a permissions problem, but the rest of the codebase seems to have the same 644 permissions and that's running fine.

EDIT: I'm also using Domain Access, but a colleague set that up and is away so I'm not sure if that's relevant at all but I thought I'd point it out.

I've also cleared Drupal's caches

I didn't emphasise it originally but it's important to note that the trigger for this fatal error comes when I use the one-time-only password reset URL that leads to the error. When a user requests a password reset, it is the link from the email sent out that I've been pasting in which has lead to the error. However this is integral, so removing it is not an option (plus it worked on my development environment...)

It leads the user to the `hook_menu()` in user.module which I've hijacked with `hook_admin_menu_alter()` in my custom module (MYMODULE) for a bespoke area of the site that required dynamic redirection after.

```
$items['user/reset/%/%/%'] = array(
    'title' => 'Reset password',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('MYMODULE_user_pass_reset', 2, 3, 4),
    'access callback' => TRUE,
    'type' => MENU_CALLBACK,
);

```

Because as you'll see below, the original `user_pass_reset` callback uses a drupal\_goto() and therefore I can't redirect as I would by hooking the form and using redirect (or by adding another submit handler)

```
  if ($account->login && $current - $timestamp > $timeout) {
    drupal_set_message(t('You have tried to use a one-time login link that has
expired. Please request a new one using the form below.'));
    drupal_goto('user/password');
  }

```

So I created an almost duplicate version of it, except for the edit to the above which now retrieves the last place the user tried to go, before resetting their password, from the db and supplying that in the drupal\_goto() parameters.

# Answer
You should implement hook\_menu\_alter to alter the data of menu items.

> This hook is invoked by menu\_router\_build(). The menu definitions are passed in by reference. Each element of the $items array is one item returned by a module from hook\_menu. Additional items may be added, or existing items altered.

code snippets

```
function custom_menu_alter(&$items) {

  $items['user/reset/%/%/%']['page arguments'] = array('MYMODULE_user_pass_reset', 2, 3, 4);
  $items['user/reset/%/%/%']['file'] = '';
}

```
> 1 votes

---
Tags: 7
---


# Question
Title: How to change "Add new node" button label?
I have created two content types "A" and "B".
I have included content type "B" in content type "A".
So when I am adding a content of type "A" that time it shows me a button "Add new node".
I want to change this label with another label.
Also when I click on this button it display form with fields of content type "B". This also shows a button with label "Create Node" and a title "ADD NEW NODE". I also want to replace with another string.
I have used `form_alter()` hook.

Can any one guide me how can do this?

# Answer
I suggest you take a small form\_alter sample module code and start changing in it. Pl also see this video.

You can also do it easily using String Overrides module.
> 0 votes

---
Tags: forms
---


title: Adding a custom path for node

text:
# Question
Title: Adding a custom path for node
I have enabled the path auto and workbench modules in my drupal installation. I have to set the url alias once only. Once a node is published and url alias is generated, the url alias should not be generated again if end user changes the title of the node. Also I have to generate the url alias only when node goes to published state.

I am trying something like this:

```
function hook_entity_presave($entity, $type) {
  //Do not create url alias of node unless its not published and if you create a Draft of a published node, the URL of the published node should not go away.
  if($entity->workbench_moderation['current']->state != 'published'  && !isset($entity->workbench_moderation['published']))
  {
    $entity->path['alias'] = '';
    $entity->path['old_alias'] = '';
    $entity->path['pathauto'] = 0;
  }
  else {
    $entity->path['pathauto'] = 1;
  }
  // if node is published, do not change the url alias if end user changes the title of the node.
  if(isset($entity->workbench_moderation['published'])) {
    $entity->path['alias'] = $entity->path['original']['alias'];
  }
}

```

and I am trying to accomplish this with hook

```
function hook_node_presave($node) {
  $node->path['alias'] = $node->path['original']['alias'];
  $node->path['pathauto'] = 0;
}

```

# Answer
> 0 votes
I have changed the logic in my custom module and hopping that will work.

```
/**
 * Implements hook_entity_presave().
 */
function my_module_entity_presave($entity, $type) {
  // the url alias should not be created as long as the node goes in published state
  if($entity->workbench_moderation['current']->state != 'published' && !isset($entity->workbench_moderation['published'])) {
    $entity->path['pathauto'] = 0;
  }
  else {
    $entity->path['pathauto'] = 1;
  }
  // if node is passed through a published state then node url should not be changed in any title edits.
  if(isset($entity->workbench_moderation['published']) && isset($entity->path['alias']) && !empty($entity->path['alias'])) {
    $entity->path['pathauto'] = 0;
  }
}

```

# Answer
> 0 votes
You can set that in the URL aliases configuration.

In http://example.com/admin/config/search/path/settings

In the section 'update action', check one of the two:

```
Do nothing. Leave the old alias intact.
Create a new alias. Leave the existing alias functioning.

```

The default is:

```
Create a new alias. Delete the old alias.

```

---
Tags: nodes, path-aliases
---


# Question
Title: url of custom theme not showing up with page.tpl
I've a custom theme. page.tpl has the html markup for my template. And I created some paths like 'about-us', 'terms' via my custom module.

Now, my problem is when I access the above defined paths. They are just showing up the contents defined in the callback function.

What I've to do if I want to show the contents in the content region of my page.tpl

Please help me.

----- THIS IS FIXED NOW :: THANKS FOR YOUR HELP -------

# Answer
> -1 votes
Thanks everyone for helping. I changed the contents of the callback function, print to return. It solved the problem.

---
Tags: 7, theming, uri
---


# Question
Title: How to include attributes of the MySQL table to hook_schema() schema in drupal 7?
I am creating a table using hook\_schema()

I am referring phpMyadmin to create a new table. In the phpMyadmin there is a
column `'Attributes'`

which has values as `'unsigned'` or `on update CURRENT_TIMESTAMP'` I have a row in a table which is of type '`timestamp`' and has attributes 'on update `CURRENT_TIMESTAMP'`.
How can I include this attribute `on update CURRENT_TIMESTAMP` in the `hook_schema()` ?

Also there is a default column in phpMyAdmin how can I add that in `hook_schema()` ?

the first time I created a `hook_module_name.install` a table was created as it was specified in the `hook_schema()`

Then I uninstalled that module but the table was not deleted ? Now I even removed the `.install` file cleared the cache , even after this a table is not created. What can be the solution to this problem.

What I have checked is that it is entering into `hook_schema` function but the table is not generated at the database. Any hints on this would be appreciated.

# Answer
> 3 votes
You can't use an `ON UPDATE` unfortunately - Drupal's schema API doesn't give you that sort of dbms-specific control.

You can use `unsigned` for unsigned and `default` for a default value though:

```
$schema['some_table'] = array(
  'fields' => array(
    'some_field' => array(
      'type' => 'int',
      'not null' => TRUE,
      'unsigned' => TRUE,
      'default' => 0,
    ),
  ),
);

```

See the Schema API docs for the full list of data types and usage.

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


# Question
Title: views to display list and related content on same page
I have created a veiws block which displays all the taxonomy terms of a particular type. This block is in left sidebar . Now what I want is ,"when i click on any of the term all nodes related to it should be shown on the same page in the content area " ( what normally happens is it shows all nodes listing correctly but not on the content area of same page but takes me to next page) . Can someone please help me with this and any good tutorials for views

# Answer
I got it solved myself! What I did is:

1. Create a views page to display all contents having these taxonomy terms. This page has path "views-page".
2. Create a block view of those taxonomy terms, now while enabling this block the setting for pages tab is under Show block on specific pages --\> select radio of "Only the listed pages" and the values for this should be :
> views-page
> views-page/\*

This way when you select a term all related posts appear on the page and taxonomy block is also there.
> 0 votes

---
Tags: views, 7
---


# Question
Title: How to create timestamp field? I get Undefined index: timestamp:normal in DatabaseSchema_mysql->processField()
I am getting the following error for the field within a hook\_schema()

> Notice: Undefined index: timestamp:normal in DatabaseSchema\_mysql-\>processField() (line 205 of /D7/../includes/database/mysql/schema.inc).

```
function hook_schema() {

$schema['abc'] = array(
  'description' => t('asdc'),
  'fields' => array(
    'rec_create_date' => array(
      'type' => 'timestamp',
      'not null' => FALSE,
      'default' => NULL,
  ),
 ),
)
}

```

# Answer
Looking at `DatabaseSchema_mysql::getFieldTypeMap` we can see that timestamp itself is not implemented:

```
$map = array(
    'varchar:normal' => 'VARCHAR',
    'char:normal' => 'CHAR',
    'text:tiny' => 'TINYTEXT',
    'text:small' => 'TINYTEXT',
    'text:medium' => 'MEDIUMTEXT',
    'text:big' => 'LONGTEXT',
    'text:normal' => 'TEXT',
    'serial:tiny' => 'TINYINT',
    'serial:small' => 'SMALLINT',
    'serial:medium' => 'MEDIUMINT',
    'serial:big' => 'BIGINT',
    'serial:normal' => 'INT',
    'int:tiny' => 'TINYINT',
    'int:small' => 'SMALLINT',
    'int:medium' => 'MEDIUMINT',
    'int:big' => 'BIGINT',
    'int:normal' => 'INT',
    'float:tiny' => 'FLOAT',
    'float:small' => 'FLOAT',
    'float:medium' => 'FLOAT',
    'float:big' => 'DOUBLE',
    'float:normal' => 'FLOAT',
    'numeric:normal' => 'DECIMAL',
    'blob:big' => 'LONGBLOB',
    'blob:normal' => 'BLOB',
  );

```

So, according to Schema API

> **'mysql\_type'**, **'pgsql\_type'**, **'sqlite\_type'**, etc.: If you need to use a record type not included in the officially supported list of types above, you can specify a type for each database backend. In this case, you can leave out the type parameter, but be advised that your schema will fail to load on backends that do not have a type specified. A possible solution can be to use the "text" type as a fallback.

In your specific case `"int"` makes more sense than `"text"` as fallback.

Or simply do as core modules, go with `"int"` for timestamps and calculate everything date-based in PHP code.
> 6 votes

---
Tags: database
---


# Question
Title: File is saved to /tmp directory, despite setting it permanent
I have a form, where I can upload a file:

```
function policies_edit_form($form, &$form_state, $data_array = NULL)
{
  ...
  $form['file'] = array(
        "#title" => "Document file",
        '#type' => 'file',
        '#size' => 22,
        );
  ...
}

function policies_edit_form_validate($form, &$form_state)
{
   $file = file_save_upload('file', array(
           'file_validate_extensions' => array('pdf doc docx'),
                                 ));
   if ($file) {
        // Save the file for use in the submit handler.
        $form_state['values']['file'] = $file;
    }
}

function policies_edit_form_submit($form, &$form_state)
{
  if($form_state['values']['file'] != '')
  {
    $form_state['values']['file']->status = FILE_STATUS_PERMANENT;
    $file = file_save($form_state['values']['file']);
  }
}

```

Despite I set the status to FILE\_STATUS\_PERMANENT, the file is uploaded to /tmp directory. After the upload is done, bash commands give this:

```
bash-4.2$ cd /tmp
bash-4.2$ ls -la 1_1.pdf
-rw-rw-r-- 1 apache apache 111531 Sep 16 16:06 1_1.pdf

```

And "temporary://" folder in the database:

```
mysql> SELECT * FROM file_managed;
+-----+-----+----------+---------------------+-----------------+----------+--------+------------+
| fid | uid | filename | uri                 | filemime        | filesize | status | timestamp  |
+-----+-----+----------+---------------------+-----------------+----------+--------+------------+
|   2 |   1 | 1.pdf    | temporary://1_1.pdf | application/pdf |   111531 |      1 | 1379333217 |
+-----+-----+----------+---------------------+-----------------+----------+--------+------------+

```

How can I upload it to public://policies/ folder? Should I manually set $form\_state\['values'\]\['file'\]-\>uri or there is another way?

# Answer
> 2 votes
Just use a managed file element, it's much easier:

```
$form['fid'] = array(
  "#title" => "Document file",
  '#type' => 'managed_file',
  '#size' => 22,
  '#upload_location' => 'public://',
  '#upload_validators' => array(
    'file_validate_extensions' => array('pdf doc docx'),
  ),
);

```

Then remove the validation handler and change you submit handler to:

```
$file = file_load($form_state['values']['fid']);
$file->status = FILE_STATUS_PERMANENT;
file_save($file);

```

And you're done; Drupal handles moving the temp file into the right place for you, as well as adding relevant records to the `file_managed`/`file_usage` tables.

---
Tags: 7, files
---


# Question
Title: What is the substitute for update_sql() in D7?
I am using update\_sql() in hook\_update of drupal .install file (D6) ?

Can **update\_sql()** be used for D7 ?

# Answer
> 0 votes
No, it does not exist any longer. You need to use Schema API function dedicated for what you need to be done. For example to rename field you should use `db_change_field`.

---
Tags: 7, updating
---


# Question
Title: Translate an SQL update query into Drupal language
I need to convert the following query that works against a database table

"UPDATE `MYTABLE` SET `field_temp`= %s", UNIX\_TIMESTAMP(`field`);

into Drupal language

```
db_update('MYTABLE')
      ->fields(array(
          'field_temp' => UNIX_TIMESTAMP('field'), //or strtotime()
         ))
        ->execute();

```

seems to be not working.

# UPDATE

```
db_update('MYTABLE')
        ->expression('field_temp',  "UNIX_TIMESTAMP('field')"),
        ->execute();

```

will run into:

```
PDOException: SQLSTATE[22007]: Invalid datetime format: 1292 Incorrect datetime value:

```

Some more details:

* 'field' is datetime format type, field\_type is 'int' format type
* I am running this script through a hook\_update\_N
* I am debugging it by running update.php

# Answer
> 2 votes
You need to add an `expression()`:

```
db_update('MYTABLE')
  ->expression('field_temp', "UNIX_TIMESTAMP(field)")
  ->execute();

```

---
Tags: database
---


# Question
Title: Is it safe to clone a EntityMetadataWrapper Object?
I want to clone an entity for multiple users, But some fields for each of them is different, Some fields are the same.

One way is to create the Entity for each:

```
// Doing in this in a loop for each user.
$e = entity_create('type', $info);
$e->{$same_field_for_all1}->set($value1);
$e->{$same_field_for_all2}->set($value2);
$e->{$same_field_for_all3}->set($value3);
$e->{$same_field_for_all4}->set($value4);
$e->{$fieldName}->set($this->getUserValue($user1, $fieldName));
// Set author and title for user here...
$e->save();

```

Another way is:

```
// Doing this only once
$e entity_create('type', $info);
$e->{$same_field_for_all1}->set($value1);
$e->{$same_field_for_all2}->set($value2);
$e->{$same_field_for_all3}->set($value3);
$e->{$same_field_for_all4}->set($value4);

// And doing this in a loop:
$clone = clone $e;
$clone->{$fieldName}->set($this->getUserValue($currntUser, $fieldName));
// Set author and title for user here...
$clone->save();

```

Is this sort of shallow cloning of EntityMetadataWrapper safe?

# Answer
> 0 votes
Well, It's not safe/ I don't know why yet, But, Sometimes it result in saving only last cloned entity.

It's not a good answer till it says why!

---
Tags: entities
---


# Question
Title: How to output just a page's contents in page.tpl.php in Drupal 7?
I am creating a page.tpl.php template in Drupal 7 in which I want to rearrange how certain elements of the page are laid out. Specifically I want the title of the page to appear before the tabs and messages section (which I have done) and have the content of the page appear after the tabs and messages section (this is where I run into issues). I can't find a way to just render the $page\['contents'\] without the title. Is there a way to achieve this in Drupal 7?

I know that the node.tpl.php template handles the node specific layout, but it doesn't allow me to layout the page like as described above.

Thanks.

# Answer
Somethings can be done in **page.tpl.php** & some in **node.tpl.php**

Like you said, you need to make title of the node appear before tabs. You can do this in your **page.tpl.php**. Find `$title` variable as well as `$tabs` & arrange accordingly in your **page.tpl.php**. Like --

```
<?php if ($title) : ?>
  <h1 class="title">
    <?php print $title; ?>
  </h1>
<?php endif; ?>
<?php if ($tabs): ?>
  <div class="tabs">
    <?php print render($tabs); ?>
  </div>
<?php endif; ?>

```

After this you will have `print render($page['content']);`, where **node.tpl.php** comes into the scene, so arranging other things like node content, comment, links you will have to go to your **node.tpl.php** & arrange accordingly. More modification such as in comment & other TPLs will come into the scene like **comment.tpl.php** etc..
> 1 votes

---
Tags: 7, theming
---


# Question
Title: Using db_select, how can I select all nodes with any of an array of taxonomy terms and order by the number of terms it is associated with?
I have this so far:

```
// for example, $tags = array(2, 8, 18);
$query = db_select('node', 'n')
  ->fields('n', array('nid'))
  ->condition('n.type', 'post')
  ->condition('n.status', 1);
$query->join('field_data_field_tags', 'tags', 'tags.entity_id = n.nid');
$query->condition('tags.field_tags_tid', $tags, 'IN');

```

I need to order these results by the number of "tags" associated with each node.

I've tried many things, using addExpression() with count() statements, then an orderBy(), etc, but I can't get it right. Any help would be greatly appreciated!

# Answer
> 2 votes
I was able to get this to work. Following is the code I used to generate the query:

```
// for example, $tags = array(2, 8, 18);
$query = db_select('node', 'n')
  ->fields('n', array('nid'))
  ->condition('n.type', 'post')
  ->condition('n.status', 1);
$query->join('field_data_field_tags', 'tags', 'tags.entity_id = n.nid');
$query->condition('tags.field_tags_tid', $tags, 'IN');
$query->addExpression('count(tags.entity_id)', 'num_tags');
$query->groupBy('nid');
$query->orderBy('num_tags', 'DESC');

```

# Answer
> 1 votes
You should put count as alias name in the count(\*) and then groupby clause can be used on that column.

```
$query = db_select('node', 'n')
      ->fields('n', array('nid'));
$query->addExpression('COUNT(n.nid)', 'count'); // addExpression
   $query->condition('n.type', 'post')
      ->condition('n.status', 1);
    $query->join('field_data_field_tags', 'tags', 'tags.entity_id = n.nid');
    $query->condition('tags.field_tags_tid', $tags, 'IN');
    $query->groupBy('count', 'DESC'); //count is column name given in the addExpression

```

---
Tags: database
---


title: Multiple Landing Pages Under Same Url

text:
# Question
Title: Multiple Landing Pages Under Same Url
I need some suggestions, I am not sure which direction to go to do this, but I need to do 4 different landing pages, with 4 different urls, example http://site.com/landingpage?blue=1, http://site.com/landingpage?blue=2.

Now everything is almost the same on the landing pages except for a banner thats going to be on the front and on 2 of the landing pages the layout will be different. I am using panels for the pages. Should I make 4 different panels for them or can panels allow me to change different elements on certain urls? How would I do that using panels? Or would you suggest a different module?

Any suggestions is appreciated, Thanks

# Answer
a way to do something like you are talking about is creating one panel page with panels variants and showing each one depending on selection rules.

Regards.
> 2 votes

# Answer
You can use View Mode Page to achieve this. Just create a new view mode per page, which if you want the same display, just clone it for each view mode and apply the styling with CSS for each view mode.
> 1 votes

---
Tags: 7
---


# Question
Title: Accessing Drupal database for read purposes
I'm interested in analyzing various aspects of the content in our Drupal site involving node meta data such as type, name, creation date, etc. I know I can create views to show some informaiton and I know I can dump out the database and analyze it separately, but I'd really like to query the database live (for read purposes only) from a remote machine so that I can use the software of my choice to do the analysis, reporting, etc.

Does Drupal have a remotely accessible API that I can use query its database?

(Note: I suspect the "db-api" tag is inappropriate for this question, but I couldn't figure out anything else to use.)

# Answer
> 1 votes
If

* you want to programatically work with data,
* reading them is enough,
* you don't have direct DB access (which is not such a good idea anyways, for security reasons - you'd have to set up SSL tunnels to access the DB), and
* you can dig all the data you need using Views (you can always create some custom module to dig data which Views wouldn't have direct support),

I would suggest using Services Views module. Services Views turns a View into REST service endpoint. You can then query LIVE data you need from an external application. For enhanced security the endpoint (and service authentication, etc.) should be wrapped in HTTPS.

# Answer
> 1 votes
If you want easily importable data, consider using Views data export:

> This module is designed to provide a way to export large amounts of data from views. It provides a display plugin that can rendered progressively in a batch. Style plugins are included that support exporting in the following types:
>
> * CSV
> * Microsoft XLS
> * Microsoft DOC
> * Basic TXT
> * XML

You can import CSV or XML to pretty much any data analysis tool you may need.

# Answer
> 0 votes
In the views UI settings, you can check an option in this url :

> admin/structure/views/settings
>
> check "Show the SQL query"

So, in the view's UI live preview, you can copy/paste and re-use theses queries in another code

It is maybe not the best way but it is one, and you do not have to write complex queries joins, views UI do it for you

Theses queries can be executed from anywhere (even directly in mysql), without the drupal boostrap

---
Tags: database
---


# Question
Title: I see all aliases besides the home page alias (At URL bar)
Why is that? I mean, why when I click the home page link at main menu, it is only the site's URL (www.example.com), and not the exact URL of the home page (www.example.com/Decorations-for-all-houses) that appears? how can I make the full URL appear at the home page?

It should be noted that this is the only page with this problem; in all other pages, the FULL URL is always displayed.

# Answer
If you set your site home page "Decorations-for-all-houses" (or perhaps lowercase would be less confusing) at admin/config/system/site-information, any home link provided by core, contrib modules, themes etc. will point to the right page.

You can edit any link of your main-menu including the home link at admin/structure/menu/manage/main-menu. The default link for home is \<front\> which will point to your assigned home page, but it can be any path, including "decorations-for-all-houses".

Themes typically implement their logo link so that it points to the home page without the path, so you would have to edit the theme.

The above (hopefully) covers any case where users already on your site click a home link or logo. But what about visitors clicking a link outside of your site, like Google, or typing the domain name? For redirecting them from www.example.com to www.example.com/decorations-for-all-houses something like the Global redirect module probably would be able to do that.

What people usually seem to want, is just the opposite, redirect from the long url to the root. It might be confusing to visitors if they never can't get to the www.example.com even if they want to. This is what visitors expect to see as the home page url.
> 3 votes

---
Tags: path-aliases
---


# Question
Title: self hosted video player/soution with fallback
I use drupal 6 and I am looking for a way to play my own videos (only one per product page). I use views to display content. Player should have ability to fallback to browser player for users with javascript disabled. Similar solution is implemented on zappos page for example here http://www.zappos.com/reef-fanning-brown-lux?zfcTest=fcl%3A0

If I click on video with javacsript disabled, I get a new window with video playing.

Can anybody recommend a solution? Thank you

# Answer
You could probably use:

https://drupal.org/project/jwplayermodule

> * Full support for JW Player for Flash and HTML5.
> * Manage multiple custom players.
> * Full skin and plugin support with easy to use plugin customization interface.
> * A powerful shortcode system for customizations at embed time.
> * CCK Field support.
> * Integration with the popular FileField module.
> * Integration with the Embedded Media Field module.
> 1 votes

---
Tags: 6, files
---


# Question
Title: Views formatting: liquid number of columns?
I have a Views page that creates a 3-column grid layout. These look just fine on a desktop browser.

On a mobile browser, each column is too thin to usefully read the text that's displayed, and it looks pretty awful, even if I use media queries to scale the text down. I'd like to go to a single-column layout on these sorts of screens. Is there a good way to do this? Ideally, a CSS-only approach would be best, since I've managed to get my layout fluid using only CSS thus far.

# Answer
You'll need to move away from using a table layout to one that uses divs instead, e.g an 'unformatted list' views style.

It's quite easy by piling a set of floated divs into a container.

If the container width changes, the number of items per 'row' also change.

e.g, something like this for the view items.

```
.views-row{
  float:left;
  margin:8px;
}

```
> 3 votes

---
Tags: views, theming
---


title: Drupal 7 video player for stream

text:
# Question
Title: Drupal 7 video player for stream
I'm using JW Player for playing video files and it's working great.

Is it possible to play video streams with this player?

I already have a rights to stream and link for a TV station. It's in this format: http://XX.XXX.XXX.XXX:9090/stream.flv

How can I set this link for stream?

If you know some alternative player with possibility of live streaming, please let me know.

# Answer
> 1 votes
JWPlayer does streaming.

http://www.longtailvideo.com/jw-player/hls-rtmp-live-streaming

I wasn't able to find a module that did this, but you can add this to your page, using the Full HTML text input:

```
<script type="text/javascript" src="/path/to/jwplayer/jwplayer.js" ></script>
<div id="home-video">Loading the player</div>
<script type="text/javascript">
    jwplayer("home-video").setup(
        {
            file: "http://XX.XXX.XXX.XXX:9090/stream.flv",
            height: 320,
            width: 640,
        }
    );
</script>

```

---
Tags: files
---


# Question
Title: Default value for the same field, different depending on content type
I am building a website and have 3 content-types.

```
Type A
Type B
Type C

```

I built these content types one after another, and `used existing field` when creating the content-type field `Field`.

My question is, how do I set a default value for `Field` for each of my content-types ? Right now when I set a default it is default for all my content-types.

I want to have

```
Type A -> Field = value 1
Type B -> Field = value 2
Type C -> Field = value 3

```

# Answer
You can easily achieve you goal with the rules module, as @pico34 wrote in his answer, but use the trigger `Before saving content` instead of `After saving new content`.

Alternativey, if you need to do that programmatically, you can define your default values in just a few lines of code using hook\_node\_presave()

**Example**

```
/**
 * Implements hook_node_presave().
 */
function YOUR_MODULE_node_presave($node) {
  // set the value of field "field_somefield" in case of node type: a, b or c.
  if (in_array($node->type, array('a', 'b', 'c')) && empty($node->field_somefield[$node->language][0]['value'])) {
    switch ($node->type) {
      case 'a' :
        $node->field_somefield[$node->language][0]['value'] = 'Default value for A';
        break;
      case 'b' :
        $node->field_somefield[$node->language][0]['value'] = 'Default value for B';
        break;
      case 'c' :
        $node->field_somefield[$node->language][0]['value'] = 'Default value for C';
        break;
    }
  }
}

```
> 1 votes

# Answer
You can use Rules module

For each content type, add a rule :

* The event trigger is : after saving new content
* Add a distinct condition on each: content is type 'foo'
* Add another condition : 'data value is empty' on your field
* Add an action : "Set a data value" and select your field and add your default value

OR pre-populate the field in the form

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

    switch ($form_id) {

      case 'typea_node_form':
        if (!$form['nid']['#value']) {// = add only
          $form['field_custom']['und'][0]['#default_value']['value'] = 'default_a';
        }
        break;

      case 'typeb_node_form':
      // the same...
        break;

    }
}

```
> 0 votes

---
Tags: entities, nodes
---


# Question
Title: How do I force my nodes to all show up at a given path, without adding them to a menu?
My site has a set of events, all with the content type "event". I don't want to have to add them to the main menu manually, because there's hundreds of them and they'll make the menu very cumbersome to manage. I'd like each event to show up with the same breadcrumb and secondary menu as the view that displays all events.

So I added a hook\_node\_view to try and force all event nodes to show up in the same place as the events listing:

```
function MYMODULE_node_view($node, $view_mode, $langcode) {
    $menu_name = variable_get('menu_secondary_links_source', 'main-menu');
    if ($view_mode == 'full' && $node->type == 'event') {
        menu_tree_set_path($menu_name, 'events'); // 'events' is the path to the view listing
    }

```

This only works when the nodes are already added to the main menu manually (i.e. it can be used to override the path, but won't do anything if the node isn't in the menu already).

Is there an easy way to force Drupal to always return my hardcoded path for a given content type?

# Answer
I actually found a good module at http://drupal.org/project/menu\_position. It adds an administrative UI for saying "all nodes of type blah should appear underneath this menu link". It seems to be adding "fake" menu items in the tree, and using those as handlers for rendering all items of the given content type.
> 0 votes

# Answer
There are two ways I know, and both are based on Menu block module.

1. Add all elements to the menu all right, but in the blocks that show menus, limit maximum depth so they are never shown to the end user in menu. Additional benefit is that you will have them properly placed in a tree for SEO modules like Site map or SiteMenu. And breadcrumbs will work out of the box.
2. Keep all nodes that should "appear" like they are in one menu in one path "directory", using Pathauto or similar solution. Add a Menu block set to show menu you need, and set it's display settings to only appear under the path you need and everywhere deeper. For breadcrumbs, you would need something like Breadcrumbs by path or Easy Breadcrumb \- both claim to provide breadcrumbs based on URL aliases, so they are menu independent.

Personally, I would go with first way.
> 2 votes

---
Tags: routes
---


# Question
Title: Make Apache Solr return results based on taxonomy term
I have Content Type A and Content Type B. They both use the same vocabulary. I want to achieve the following:

Let's say that **node1** of content type **A** is associated with the terms **term1** and **term2**. When a search returns node1 as a result (based on its body or other fields), I would also like to present to the user all nodes of Content Type B that are associated with term1 and term2.

Is that possible with the apachesolr module?

# Answer
> 2 votes
Apachesolr's "More like this" block, that you can display on your nodes, is similar, but not particularly configurable. It uses both terms and text to determine related nodes, so you can't just base it on a particular term reference field. Also, it appears on the actual nodes (in your example, it would appear only once a user has clicked on and is viewing node1), not on the search results page.

**OPTION 1** ----------

If you're looking to include this type of block on nodes, it'd be possible to do precisely what you want with just a view.

* Create a content view that filters out only the node types you want.
* Make sure it accepts a term id as a contextual filter to use (i.e. based on the currently viewed node and its terms, it will filter the list of nodes it displays to ones with precisely those terms). To accomplish this, add a contextual filter to your view that is "**Content: term\_reference\_field**"!
* Then, set the default value of this contextual filter to come from the current node if it's not in the URL: select '**Taxonomy term id from URL**' as the default value and then select '**Load default filter from node page**'. Under that, select the vocabulary that your term reference is based on. Also make sure you select how to handle multiple values (if the current node being viewed has multiple terms selected, do all terms have to match for a related node to be shown, or should just a single value match be enough?).
* That should be all you need! Test your view out by providing some sample inputs in the 'Preview' area and making sure that the resulting nodes match via their terms!

**OPTION 2** ----------

Now, if you're looking to do this on the **search results page**, that is a little trickier, because you have to look at multiple nodes (all the ones in the results) rather than just a single one.

Here's how I would do that:

* In your view, from above, make sure you expand the 'More' section at the bottom of the contextual filter, and check that it should be able to accept multiple parameters (if you want to base the 'Related nodes' view on all the nodes from the search result rather than just the top one
* Implement a hook\_preprocess\_search\_results() function in your custom theme - this should be placed in your template.php file.

```
  function YOURTHEME_preprocess_search_results(&$variables) {

  // Get nodeids from search results
  $node_ids = array();
  foreach ($variables['results'] as $result) {
    if (!is_object($result['node'])) {
      continue;
    }

    $node_ids[] = $result['node']->entity_id;
  }

  // Ensure node ids exist
  if (!count($node_ids)) {
    return;
  }

// Now that you have the nids of all the search results on the current page, call the above view with those nodes as parameters
// The second argument should be the display on your view you want to call, could be 'page', 'block' or whatever custom one you have
$view_output = views_embed_view('YOUR_VIEW_MACHINE_NAME', 'block', implode('+', $node_ids));
if ($view_output) {
  $variables['my_view_results'] = $view_output;
}
 }

```
* Finally, now that you've set the variable $my\_view\_results above (with nodes from the search results at view contextual filters!!!), you can call place that variable anywhere in your search\_results.tpl.php template file and place it anywhere: above, below or anywhere on your content

```
  <?php print $my_view_results; ?>

```

Sorry that Option #2 is kind of complicated. Someone may come up with a more straight-forward answer, but I can only think of using a view and providing it with the right parameters by hooking into hook\_preprocess\_search\_results() to grab the right node ids that are appearing on the search page. Good luck. Let us know if this works out!

---
Tags: taxonomy-terms, search
---


# Question
Title: How can I serve a "410 Gone" HTTP status AND redirect my removed content?
I have a load of content that is **gone** (don't ask). I would like to tell Google and other search engines that this resource is gone, please don't try to index it. This is what HTTP status code 410 looks good for.

This is great for search robots, but if it's a real person accessing the page, I'd rather they were redirected to the new content.

Luckily, all the gone URLs match a pattern.

Is it possible to have all those handled by issueing a 410, **and** a redirect of some sort?

(I worry that permanent redirects might affect SEO too?)

Put another way: what I want to say is "That content is gone, you should not link to it. There's new content here:..."

**\[EDIT: to express why this is Drupal related\]**

Drupal is my CMS. With any generic website I would find my own solution to present a page and the correct header. With Drupal there's usually "a module for that", sometimes an elegant way to solve a common problem, and sometimes a hideously inefficient way to square a circle known as "the Drupal Way" \[joke\].

Drupal has an in-built system for 404s that works great. You can set a page, and because it's got a url you can use the block module to put other useful stuff on it, e.g. a View.

So there's 2 questions:

1. Does Drupal (or a reliably contrib'ed module) have a way to issue 410s akin to the 404 system?
2. Does Drupal have a 302/301 redirect system that can work with path patterns (i.e. separate from node as these dead pages were from another module that has been removed)

# Answer
We just did a major redesign that include a new URL structure. We decided to to use the Redirect module as part of the plan.

One of its features is to go through the `{watchdog}` table, and look for Page Not Found errors (ie, 404s). It then provides a UI for adding a redirect to another URL. You also have the option for setting the status code. It will default to using a 301. From the definition:

> 10.3.2 301 Moved Permanently
>
> The requested resource has been assigned a new permanent URI and any future references to this resource SHOULD use one of the returned URIs. Clients with link editing capabilities ought to automatically re-link references to the Request-URI to one or more of the new references returned by the server, where possible. This response is cacheable unless indicated otherwise.

According to Google, a 301 is the proper code to use when you want the user to goto a new page:

> If you're moving that content to a new URL, you should 301 redirect the old URL to the new URL-that way when users come to the old URL looking for that content, they'll be automatically redirected to something relevant to what they were looking for.

and a 410 should be used for content that is gone forever:

> If you're getting rid of that content entirely and don't have anything on your site that would fill the same user need, then the old URL should return a 404 or 410. Currently Google treats 410s (Gone) the same as 404s (Not found).

The Redirect module does not handle 410 generation, though. Otherwise, it has been a good way to handle the new scheme w/o needing to manually generate Apache rules.
> 1 votes

# Answer
You can always output HTTP 410 header and redirect human users using JavaScript in a body:

```
var delay = 10000; //Your delay in milliseconds
setTimeout(function(){ window.location = URL; }, delay);

```

JavaScript from this answer.

Note that by rfc2616:

> The 4xx class of status code is intended for cases in which the client seems to have erred. Except when responding to a HEAD request, the server SHOULD include an entity containing an explanation of the error situation, and whether it is a temporary or permanent condition. These status codes are applicable to any request method. **User agents SHOULD display any included entity to the user.**

Emphasis mine. So, JavaScript outputted inside HTML body *should* work. But of course it is not *guaranteed* it will.

Your content is not nodes, so you probably have implemented `hook_menu`. If not, you can alter existing implementation with `hook_menu_alter`. What you need is to:

* Using `access callback` and/or `access arguments`, ensure user gets the access permission to deleted content. If not, he will see 403 or 404, as this is Drupal's default behaviour for unpublished / deleted data.
* In `page callback` test if content is valid, deleted or never existed.
    + If valid, default to the callback you are using now.
    + If deleted, use `drupal_add_http_header` to add "410 gone" header as appropriate. Output nice human readable page (optionally with JavaScript redirect, search box or anything appropriate).
    + If never existed, either default to what you were using already, or implement 404 the way you implemented 410 above.

---

Google says:

> We recommend that you always return a 404 (Not found) or a 410 (Gone) response code in response to a request for a non-existing page.
> 2 votes

# Answer
Here's a more Drupal-specific answer.

410 doesn't seem appropriate to me.

I would simply have the old URLs issue HTTP `301` redirects, which you could do with the Redirect module.

Google and other search engines would then remove the old addresses and pick up the new ones (eventually, depending on how often your site is indexed). You could even submit URL removal requests to Google for each old address if you want to try expediting the process.

If you don't want the new addresses to be indexed at all, then the new pages should use a robots 'noindex' `<meta>` tag, which you could do with the Metatag module.
> 1 votes

# Answer
I've thought a lot about using 410 (gone) for pages that we don't need. Remember backlinks are like money you never want to lose them. So only under extreme conditions should we use 410 response for gone pages.

If you want Google to not to index them and delete them all from their index exclude them in the Robots.txt( here).

So better redirect all of them using 301 to one common "Moved" page and let Google know about it( and not block using robots.txt etc). If search engines know about 301 moved then your backlink worth will be maintained.

410 response is too risky to use since once you've sent a 410 response to Google etc, if pathauto creates the same alias for another page then Google will simply ignore it. I don't think this type of error can be debugged using WMT.

I think this question is more suitable to webmasters.stackexchange.com
> 1 votes

---
Tags: redirection, 7
---


# Question
Title: How to add expose View filter for a derived field
I have a Drupal View looking at User profiles. One of the fields is derived, or calculated, which is done using Views PHP.

I'm trying to add an exposed filter for this View, but the expose option isn't visible.

Is there another module I use to add this?

# Answer
> 0 votes
Sadly I needed to filter the results myself in the Views alter hook.

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

Query Alter https://api.drupal.org/api/views/views.api.php/function/hook\_views\_query\_alter/7

---
Tags: views
---


# Question
Title: drupal could not index site using apache solr
I'm using windows 8,and have installed apache solr(version 4.4.0) using BitNami installer,I've install "search api" and "search api solr" modules on my drupal7 site,then I add solr server to module and the connection has made successfully, the problem is when I'm trying to index my site using the default "Default node index" index I get "Couldn't index items. Check the logs for details."

I've replace the files in "search\_api\_solr\solr-conf\4.x" folder of search api solr module into "C:\solr\apache-solr\solr\collection1\conf"

the drupal log message is :

> SearchApiException while indexing: "400" Status: Bad Request: Bad Request{"responseHeader":{"status":400,"QTime":1},"error":{"msg":"ERROR: \[doc=default\_node\_index-1\] unknown field 'index\_id'","code":400}} in `SearchApiSolrConnection->checkResponse()` (line 548 of C:\wamp1\www\testak\sites\all\modules\search\_api\_solr\includes\solr\_connection.inc).

and in my solr log I have :

org.apache.solr.common.SolrException: ERROR: \[doc=default\_node\_index-1\] unknown field 'index\_id'

i don't get what did i miss

this is my schema :

```
<?xml version="1.0" encoding="UTF-8" ?>

<!--
 This is the Solr schema file. This file should be named "schema.xml" and
 should be in the conf directory under the solr home
 (i.e. ./solr/conf/schema.xml by default)
 or located where the classloader for the Solr webapp can find it.

 For more information, on how to customize this file, please see
 http://wiki.apache.org/solr/SchemaXml
-->

<schema name="drupal-4.1-solr-4.x" version="1.3">

  <types>

    <fieldType name="string" class="solr.StrField" sortMissingLast="true" omitNorms="true"/>
    <fieldType name="boolean" class="solr.BoolField" sortMissingLast="true" omitNorms="true"/>
    <fieldtype name="binary" class="solr.BinaryField"/>
    <fieldType name="integer" class="solr.TrieIntField" precisionStep="0" omitNorms="true" positionIncrementGap="0"/>
    <fieldType name="float" class="solr.TrieFloatField" precisionStep="0" omitNorms="true" positionIncrementGap="0"/>
    <fieldType name="long" class="solr.TrieLongField" precisionStep="0" omitNorms="true" positionIncrementGap="0"/>
    <fieldType name="double" class="solr.TrieDoubleField" precisionStep="0" omitNorms="true" positionIncrementGap="0"/>
    <fieldType name="sint" class="solr.TrieIntField" sortMissingLast="true" omitNorms="true"/>
    <fieldType name="slong" class="solr.TrieFloatField" sortMissingLast="true" omitNorms="true"/>
    <fieldType name="sfloat" class="solr.TrieLongField" sortMissingLast="true" omitNorms="true"/>
    <fieldType name="sdouble" class="solr.TrieDoubleField" sortMissingLast="true" omitNorms="true"/>
    <fieldType name="tint" class="solr.TrieIntField" precisionStep="8" omitNorms="true" positionIncrementGap="0"/>
    <fieldType name="tfloat" class="solr.TrieFloatField" precisionStep="8" omitNorms="true" positionIncrementGap="0"/>
    <fieldType name="tlong" class="solr.TrieLongField" precisionStep="8" omitNorms="true" positionIncrementGap="0"/>
    <fieldType name="tdouble" class="solr.TrieDoubleField" precisionStep="8" omitNorms="true" positionIncrementGap="0"/>
    <fieldType name="pfloat" class="solr.FloatField" omitNorms="true"/>
    <fieldType name="file" keyField="id" defVal="1" stored="false" indexed="false" class="solr.ExternalFileField" valType="pfloat"/>
    <fieldType name="date" class="solr.DateField" sortMissingLast="true" omitNorms="true"/>
    <fieldType name="tdate" class="solr.TrieDateField" omitNorms="true" precisionStep="6" positionIncrementGap="0"/>
    <fieldType name="text_ws" class="solr.TextField" omitNorms="true" positionIncrementGap="100">
      <analyzer>
        <tokenizer class="solr.WhitespaceTokenizerFactory"/>
        <filter class="solr.LowerCaseFilterFactory"/>
      </analyzer>
    </fieldType>
    <fieldType name="text" class="solr.TextField" positionIncrementGap="100">
      <analyzer type="index">
        <charFilter class="solr.MappingCharFilterFactory" mapping="mapping-ISOLatin1Accent.txt"/>
        <tokenizer class="solr.WhitespaceTokenizerFactory"/>
        <filter class="solr.StopFilterFactory"
                ignoreCase="true"
                words="stopwords.txt"
                enablePositionIncrements="true"
                />
        <filter class="solr.WordDelimiterFilterFactory"
                protected="protwords.txt"
                generateWordParts="1"
                generateNumberParts="1"
                catenateWords="1"
                catenateNumbers="1"
                catenateAll="0"
                splitOnCaseChange="1"
                preserveOriginal="1"/>
        <filter class="solr.LengthFilterFactory" min="2" max="100" />
        <filter class="solr.LowerCaseFilterFactory"/>
        <filter class="solr.SnowballPorterFilterFactory" language="English" protected="protwords.txt"/>
        <filter class="solr.RemoveDuplicatesTokenFilterFactory"/>
      </analyzer>
      <analyzer type="query">
        <charFilter class="solr.MappingCharFilterFactory" mapping="mapping-ISOLatin1Accent.txt"/>
        <tokenizer class="solr.WhitespaceTokenizerFactory"/>
        <filter class="solr.SynonymFilterFactory" synonyms="synonyms.txt" ignoreCase="true" expand="true"/>
        <filter class="solr.StopFilterFactory"
                ignoreCase="true"
                words="stopwords.txt"
                enablePositionIncrements="true"
                />
        <filter class="solr.WordDelimiterFilterFactory"
                protected="protwords.txt"
                generateWordParts="1"
                generateNumberParts="1"
                catenateWords="0"
                catenateNumbers="0"
                catenateAll="0"
                splitOnCaseChange="1"
                preserveOriginal="1"/>
        <filter class="solr.LengthFilterFactory" min="2" max="100" />
        <filter class="solr.LowerCaseFilterFactory"/>
        <filter class="solr.SnowballPorterFilterFactory" language="English" protected="protwords.txt"/>
        <filter class="solr.RemoveDuplicatesTokenFilterFactory"/>
      </analyzer>
    </fieldType>
    <fieldType name="text_und" class="solr.TextField" positionIncrementGap="100">
      <analyzer type="index">
        <tokenizer class="solr.WhitespaceTokenizerFactory"/>
        <filter class="solr.StopFilterFactory" ignoreCase="true" words="stopwords.txt" enablePositionIncrements="true" />
        <filter class="solr.WordDelimiterFilterFactory"
                protected="protwords.txt"
                generateWordParts="1"
                generateNumberParts="1"
                catenateWords="1"
                catenateNumbers="1"
                catenateAll="0"
                splitOnCaseChange="0"/>
        <filter class="solr.LengthFilterFactory" min="2" max="100" />
        <filter class="solr.LowerCaseFilterFactory"/>
      </analyzer>
      <analyzer type="query">
        <tokenizer class="solr.WhitespaceTokenizerFactory"/>
        <filter class="solr.SynonymFilterFactory" synonyms="synonyms.txt" ignoreCase="true" expand="true"/>
        <filter class="solr.StopFilterFactory"
                ignoreCase="true"
                words="stopwords.txt"
                enablePositionIncrements="true"
                />
        <filter class="solr.WordDelimiterFilterFactory"
                protected="protwords.txt"
                generateWordParts="1"
                generateNumberParts="1"
                catenateWords="0"
                catenateNumbers="0"
                catenateAll="0"
                splitOnCaseChange="0"/>
        <filter class="solr.LengthFilterFactory" min="2" max="100" />
        <filter class="solr.LowerCaseFilterFactory"/>
      </analyzer>
    </fieldType>
    <fieldType name="edge_n2_kw_text" class="solr.TextField" omitNorms="true" positionIncrementGap="100">
      <analyzer type="index">
        <tokenizer class="solr.KeywordTokenizerFactory"/>
        <filter class="solr.LowerCaseFilterFactory"/>
        <filter class="solr.EdgeNGramFilterFactory" minGramSize="2" maxGramSize="25" />
      </analyzer>
      <analyzer type="query">
        <tokenizer class="solr.KeywordTokenizerFactory"/>
        <filter class="solr.LowerCaseFilterFactory"/>
      </analyzer>
    </fieldType>
    <fieldType name="textSpell" class="solr.TextField" positionIncrementGap="100">
      <analyzer>
        <tokenizer class="solr.StandardTokenizerFactory" />
        <filter class="solr.StopFilterFactory" ignoreCase="true" words="stopwords.txt"/>
        <filter class="solr.LengthFilterFactory" min="4" max="20" />
        <filter class="solr.LowerCaseFilterFactory" />
        <filter class="solr.RemoveDuplicatesTokenFilterFactory" />
      </analyzer>
    </fieldType>
    <fieldType name="sortString" class="solr.TextField" sortMissingLast="true" omitNorms="true">
      <analyzer>
        <tokenizer class="solr.KeywordTokenizerFactory"/>
        <filter class="solr.LowerCaseFilterFactory" />
        <filter class="solr.TrimFilterFactory" />
        -->
      </analyzer>
    </fieldType>
    <fieldType name="rand" class="solr.RandomSortField" indexed="true" />
    <fieldtype name="ignored" stored="false" indexed="false" class="solr.StrField" />
    <fieldType name="point" class="solr.PointType" dimension="2" subFieldType="tdouble"/>
    <fieldType name="location" class="solr.LatLonType" subFieldType="tdouble"/>
    <fieldtype name="geohash" class="solr.GeoHashField"/>
  </types>

  <xi:include href="schema_extra_types.xml" xmlns:xi="http://www.w3.org/2001/XInclude">
    <xi:fallback></xi:fallback>
  </xi:include>

  <fields>
    <field name="id" type="string" indexed="true" stored="true" required="true" />
    <field name="item_id"  type="string" indexed="true" stored="true" />
    <field name="index_id" type="string" indexed="true" stored="true" />
    <copyField source="item_id" dest="sort_search_api_id" />
    <field name="entity_id"  type="long" indexed="true" stored="true" />
    <field name="entity_type" type="string" indexed="true" stored="true" />
    <field name="bundle" type="string" indexed="true" stored="true"/>
    <field name="bundle_name" type="string" indexed="true" stored="true"/>
    <field name="site" type="string" indexed="true" stored="true"/>
    <field name="hash" type="string" indexed="true" stored="true"/>
    <field name="url" type="string" indexed="true" stored="true"/>
    <field name="label" type="text" indexed="true" stored="true" termVectors="true" omitNorms="true"/>
    <copyField source="label" dest="sort_label"/>

    <field name="content" type="text" indexed="true" stored="true" termVectors="true"/>
    <field name="teaser" type="text" indexed="false" stored="true"/>
    <field name="path" type="string" indexed="true" stored="true"/>
    <field name="path_alias" type="text" indexed="true" stored="true" termVectors="true" omitNorms="true"/>
    <field name="tid"  type="long" indexed="true" stored="true" multiValued="true"/>
    <field name="taxonomy_names" type="text" indexed="true" stored="false" termVectors="true" multiValued="true" omitNorms="true"/>
    <copyField source="tm_vid_*" dest="taxonomy_names"/>
    <field name="timestamp" type="tdate" indexed="true" stored="true" default="NOW" multiValued="false"/>
    <field name="spell" type="textSpell" indexed="true" stored="true" multiValued="true"/>
    <copyField source="label" dest="spell"/>
    <copyField source="content" dest="spell"/>

    <copyField source="ts_*" dest="spell"/>
    <copyField source="tm_*" dest="spell"/>
    <dynamicField name="tags_*" type="text"   indexed="true" stored="false" omitNorms="true"/>

    <dynamicField name="is_*"  type="long"    indexed="true"  stored="true" multiValued="false"/>
    <dynamicField name="im_*"  type="long"    indexed="true"  stored="true" multiValued="true"/>
    <dynamicField name="fs_*"  type="float"   indexed="true"  stored="true" multiValued="false"/>
    <dynamicField name="fm_*"  type="float"   indexed="true"  stored="true" multiValued="true"/>
    <dynamicField name="ps_*"  type="double"   indexed="true"  stored="true" multiValued="false"/>
    <dynamicField name="pm_*"  type="double"   indexed="true"  stored="true" multiValued="true"/>
    <dynamicField name="bm_*"  type="boolean" indexed="true"  stored="true" multiValued="true"/>
    <dynamicField name="bs_*"  type="boolean" indexed="true"  stored="true" multiValued="false"/>
    <dynamicField name="ss_*"  type="string"  indexed="true"  stored="true" multiValued="false"/>
    <dynamicField name="sm_*"  type="string"  indexed="true"  stored="true" multiValued="true"/>
    <dynamicField name="ts_*"  type="text"    indexed="true"  stored="true" multiValued="false" termVectors="true"/>
    <dynamicField name="tm_*"  type="text"    indexed="true"  stored="true" multiValued="true" termVectors="true"/>
    <dynamicField name="tus_*" type="text_und" indexed="true"  stored="true" multiValued="false" termVectors="true"/>
    <dynamicField name="tum_*" type="text_und" indexed="true"  stored="true" multiValued="true" termVectors="true"/>
    <dynamicField name="tos_*" type="text"    indexed="true"  stored="true" multiValued="false" termVectors="true" omitNorms="true"/>
    <dynamicField name="tom_*" type="text"    indexed="true"  stored="true" multiValued="true" termVectors="true" omitNorms="true"/>
    <dynamicField name="tes_*" type="edge_n2_kw_text" indexed="true" stored="true" multiValued="false" omitTermFreqAndPositions="true" />
    <dynamicField name="tem_*" type="edge_n2_kw_text" indexed="true" stored="true" multiValued="true" omitTermFreqAndPositions="true" />
    <dynamicField name="tws_*" type="text_ws" indexed="true" stored="true" multiValued="false"/>
    <dynamicField name="twm_*" type="text_ws" indexed="true" stored="true" multiValued="true"/>

    <dynamicField name="ds_*"  type="tdate"   indexed="true"  stored="true" multiValued="false"/>
    <dynamicField name="dm_*"  type="tdate"   indexed="true"  stored="true" multiValued="true"/>
    <dynamicField name="its_*" type="tlong"   indexed="true"  stored="true" multiValued="false"/>
    <dynamicField name="itm_*" type="tlong"   indexed="true"  stored="true" multiValued="true"/>
    <dynamicField name="fts_*" type="tfloat"  indexed="true"  stored="true" multiValued="false"/>
    <dynamicField name="ftm_*" type="tfloat"  indexed="true"  stored="true" multiValued="true"/>
    <dynamicField name="pts_*" type="tdouble" indexed="true"  stored="true" multiValued="false"/>
    <dynamicField name="ptm_*" type="tdouble" indexed="true"  stored="true" multiValued="true"/>

    <dynamicField name="xs_*"  type="binary"  indexed="false" stored="true" multiValued="false"/>
    <dynamicField name="xm_*"  type="binary"  indexed="false" stored="true" multiValued="true"/>
    <dynamicField name="dds_*" type="date"    indexed="true"  stored="true" multiValued="false"/>
    <dynamicField name="ddm_*" type="date"    indexed="true"  stored="true" multiValued="true"/>

    <dynamicField name="iss_*" type="slong"   indexed="true"  stored="true" multiValued="false"/>
    <dynamicField name="ism_*" type="slong"   indexed="true"  stored="true" multiValued="true"/>
    <dynamicField name="fss_*" type="sfloat"  indexed="true"  stored="true" multiValued="false"/>
    <dynamicField name="fsm_*" type="sfloat"  indexed="true"  stored="true" multiValued="true"/>
    <dynamicField name="pss_*" type="sdouble" indexed="true"  stored="true" multiValued="false"/>
    <dynamicField name="psm_*" type="sdouble" indexed="true"  stored="true" multiValued="true"/>
    <dynamicField name="hs_*" type="integer" indexed="true"  stored="true" multiValued="false"/>
    <dynamicField name="hm_*" type="integer" indexed="true"  stored="true" multiValued="true"/>
    <dynamicField name="hss_*" type="sint"   indexed="true"  stored="true" multiValued="false"/>
    <dynamicField name="hsm_*" type="sint"   indexed="true"  stored="true" multiValued="true"/>
    <dynamicField name="hts_*" type="tint"   indexed="true"  stored="true" multiValued="false"/>
    <dynamicField name="htm_*" type="tint"   indexed="true"  stored="true" multiValued="true"/>

    <dynamicField name="zs_*" type="string"   indexed="false"  stored="true" multiValued="false"/>
    <dynamicField name="zm_*" type="string"   indexed="false"  stored="true" multiValued="true"/>
    <dynamicField name="points_*" type="point" indexed="true"  stored="true" multiValued="false"/>
    <dynamicField name="pointm_*" type="point" indexed="true"  stored="true" multiValued="true"/>
    <dynamicField name="locs_*" type="location" indexed="true"  stored="true" multiValued="false"/>
    <dynamicField name="locm_*" type="location" indexed="true"  stored="true" multiValued="true"/>
    <dynamicField name="geos_*" type="geohash" indexed="true"  stored="true" multiValued="false"/>
    <dynamicField name="geom_*" type="geohash" indexed="true"  stored="true" multiValued="true"/>

    <dynamicField name="eff_*" type="file"/>

    <dynamicField name="sort_*" type="sortString" indexed="true" stored="false"/>
    <copyField source="ss_*" dest="sort_*"/>
    <dynamicField name="random_*" type="rand" indexed="true" stored="true"/>

  </fields>

  <xi:include href="schema_extra_fields.xml" xmlns:xi="http://www.w3.org/2001/XInclude">
    <xi:fallback></xi:fallback>
  </xi:include>

  <uniqueKey>id</uniqueKey>

  <defaultSearchField>content</defaultSearchField>

  <solrQueryParser defaultOperator="AND"/>

</schema>

```

# Answer
> 0 votes
Apache solr was configured properly, but the modules I've installed facing some problem though, I reinstalled the **Search api** and **Search api Solr** module and it solved the problem.

---
Tags: search
---


# Question
Title: Hide node and file paths in view when printing page
I have a views page that lists nodes that contain uploaded PDF and bibtex files (see here). Everything looks fine when you view the page, but when you go to print it in the browser, the node path (from the linked title) and the path to the uploaded files are displayed. The client would like to be able to print the page **without** those paths being shown. Is there a way to suppress these paths when printing from the browser? I suggested having a link to another print friendly page, but he just wants to be able to print from the browser.

# Answer
It sounds like a CSS issue. The most efficient way is to add a CSS to your theme whose `media` type is `print` (see below for example).

Assuming the part you want to hide is an element (`div`, `span`, etc) whose class is `mycustomclass`, inside that stylesheet you could add something like this.

```
.mycustomclass {
  display: none;
  visibility: hidden;
}

```

And this is the example mentioned above.

```
<link type="text/css" rel="stylesheet" href="http://www.example.com/sites/all/themes/mytheme/print.css" media="print" />

```
> 1 votes

---
Tags: views, files, navigation
---