# Question
Title: How do you get DRUPAL_ROOT when using it in a separate php file?
It has been covered many many times on several sites, explaining how to define DRUPAL\_ROOT and bootstrap the page (whatever that actually means). However no one has ever said how to use it in a separate PHP file.

I am trying to use a php file as my data layer in a custom module. However when I use define('DRUPAL\_ROOT', getcwd()) it comes back with the directory of the module (as expected). If I use $\_SERVER\['DOCUMENT\_ROOT'\] it comes back with the www HTML folder and not my drupal install folder.

If I add .base\_path() it doesnt know what the hell that is! I can't just had code it because it's going to another IT team and I have no idea what their file structure is like.

Please, can anyone help! I am going insane!!

Its just a standard php file with some db\_query's in. This really can't be as hard as I'm making it, can it?

# Answer
> 0 votes
Why not use **DRUPAL\_ROOT** instead of trying to define it in your php file?

**DRUPAL\_ROOT** is already available at this point and it contains the path to your Drupal installation.

For example:

> watchdog('testlog', DRUPAL\_ROOT . 'test');

# Answer
> 0 votes
You need to define the DRUPAL\_ROOT constant to point to the folder where your drupal installation is (in other words, on same folder where the index.php is located)

The bootstrap phase that you need load will depend on what do you need to do on your separated php script (db queries, session handling, multilanguage, ...).

On this answer you can see a small example on what I think you are looking to implement.

If you don't know where is going to be installed the Drupal site on other environments, you could use a relative path to define it, for example, if your script it's located in a module with this path:

```
sites/all/modules/custom/my_module

```

And your site has the same architecture on the other environments, you could set the DRUPAL\_ROOT like this:

```
$drupaldir = realpath('../../../../../');
define('DRUPAL_ROOT', $drupaldir);

```

It's not elegant but it should work on any environment no matter on which folder is the drupal site.

---
Tags: external-scripts
---


title: Help with Pagination

text:
# Question
Title: Help with Pagination
I used this code to get a pager.

```
   if (isset($_GET['tid'])) {
     $id=($_GET['tid']);
     $query = new EntityFieldQuery();
     $query->entityCondition('entity_type', 'node');
     $query->entityCondition('bundle', 'escorts_product');
     $query->pager(2,1);
     $query->propertyCondition('status', 1);
     $query->fieldCondition('field_product_sub_cat', 'tid', $id,'=');
     $result = $query->execute();
    //print "<pre>";print_r($result);
    }

```

When I used `print "<pre>";print_r($result)`, it gave me 2 results on y page, whereas I added more than 2; this is right.

How should I get links for next page and also previous, next? Is there any other way to get a pager?

# Answer
To get the links for the next/previous pages you need to use `theme('pager')`.

On this post you can find an example of that implementation.
> 0 votes

---
Tags: 7, database
---


# Question
Title: How to move a form field inside a container
I have a "Birthday" field and the "date" module automatically adds the countainer around it.

Now I'm adding another field "Show Birthday". How can I display that field within the container?

# Answer
The fieldset is added by the `theme_date_combo()` function, which is on the element itself, not the wrapper (i.e. `$form['field_birthday']`).

To get this to work you'll need to temporarily move the Show Birthday field into the `date_combo` field, like so:

```
function MYMODULE_form_article_node_form_alter(&$form, &$form_state, $form_id) {
  $form['field_birthday'][LANGUAGE_NONE][0]['field_show_birthday'] = $form['field_show_birthday'];
  unset($form['field_show_birthday']);

  $form['#validate'][] = 'MYMODULE_article_node_form_validate';
}

```

Importantly, you'll also need to move that field back to where it originally was when the node form is validated. You won't get any errors if you don't, but the `field_birthday` value simply won't be saved.

```
function MYMODULE_article_node_form_validate(&$form, &$form_state) {
  $form_state['values']['field_show_birthday'] = $form_state['values']['field_birthday'][LANGUAGE_NONE][0]['field_show_birthday'];
  unset($form_state['values']['field_birthday'][LANGUAGE_NONE][0]['field_show_birthday']);
}

```

The above assumes you're making changes to the Article node form, just replace `article` with the name of your content type in the code. If your fields are inside another fieldset you might need to dig a bit further into the form array to find out how to access the precise field, but the logic will remain the same.

This is the result I get with that code (using admin theme):

I've tested both add and edit node forms and they seem to work perfectly using this method.
> 8 votes

# Answer
Some vague memory tells me that Date module does something weird with fieldsets, but this would work in most circumstances.

Implement hook\_form\_alter in your module, then move your field into the birthday container, something like this:

```
/**
* Implements hook_form_alter().
*/
function mymodule_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id = 'yourform') {
    $field_to_move = 'fieldname';
    $form['birthday'][$fieldname] = $form[$fieldname];
    unset($form[$fieldname]);
  }
}

```

You'll need to use the correct field names of course - an easy way to figure them out is to use `dpm($form)` inside your 'if' to see the array keys and values in the form array.
> 0 votes

# Answer
```
$('#field-whatevet').appendTo('fieldset#whatever');

```

eh eh

I hope this helps you.
> 0 votes

# Answer
Check out the drupal form api.

As far as I know, those kind *customization* fit into the hook\_form\_FORM\_ID\_alter in a custom module (you have to create it, but a base module is really easy to do).

Then, as cam8001 suggested, you have to choose how to move the *show birthday* field where you want - I can suggest you to do a `var_dump($form);` to see the form array structure.

Simple example (replace \[yourmodulename\] and \[FORM\_ID\]!):

```
function [yourmodulename]_form_[FORM_ID]_alter(&$form, &$form_state){
    $form['#after_build'][] = '_choose_a_custom_function_name';
}

function _choose_a_custom_function_name($form, $form_state)
{
    // var_dump($form); // need to see the form structure?
    // lets move the title and body fields in a group
    $form['group_whatever']['title'] = $form['title'];
    $form['group_whatever']['body_field'] = $form['body_field'];
    // delete the original
    unset($form['title']);
    unset($form['body_field']);
    // remember to return the form!
    return $form;
}

```

I can't give you more specific help because I don't know exactly the field structure used by the date module, so give out a dump and see.

Also, moving a key usually means to duplicate it - remember to unset the original one.
> 0 votes

# Answer
```
var $date_field = $('#edit-field-deadline');

$date_field.find('label').first().html($date_field.find('.fieldset-legend').html());
$date_field.find('.date-padding').appendTo($date_field);
$date_field.find('fieldset').hide();

```
> 0 votes

---
Tags: 7, forms
---


# Question
Title: How to migrate users from one website to another website?
I created a Drupal Kickstart site and when updating I created another test site. During the updating process my older site has new members and orders how do I transfer the new database tables to reflect the new changes (members and orders) from the older site?

# Answer
> 0 votes
Users Export to export the user from your Kickstart and User Import to your new website.

For the future you should use consider using something similar to Deploy or Configuration Management so you can keep track from your changes.

---
Tags: users
---


# Question
Title: The clean URL test failed. (ubuntu14.04 lts + virtualmin + Apache/2.4.7)
i can't enable clean url. Mod\_rewrite is already enabled. Anything i'm missing? here is the conf

my apache is running user mode, the document root is in /home/drupal/public\_html

/etc/apache2/sites-available/drupal.domain.local.conf

```
<VirtualHost *:80>
SuexecUserGroup "#1008" "#1008"
ServerName drupal.domain.local
ServerAlias www.drupal.domain.local
ServerAlias webmail.drupal.domain.local
ServerAlias admin.drupal.domain.local
DocumentRoot /home/drupal/public_html
ErrorLog /var/log/virtualmin/drupal.domain.local_error_log
CustomLog /var/log/virtualmin/drupal.domain.local_access_log combined
ScriptAlias /cgi-bin/ /home/drupal/cgi-bin/
ScriptAlias /awstats/ /home/drupal/cgi-bin/
DirectoryIndex index.html index.htm index.php index.php4 index.php5
<Directory /home/drupal/public_html>
Options -Indexes +IncludesNOEXEC +SymLinksIfOwnerMatch +ExecCGI
allow from all
AllowOverride All
#Options=ExecCGI,Includes,IncludesNOEXEC,Indexes,MultiViews,SymLinksIfOwnerMatch
Require all granted
AddHandler fcgid-script .php
AddHandler fcgid-script .php5
FCGIWrapper /home/drupal/fcgi-bin/php5.fcgi .php
FCGIWrapper /home/drupal/fcgi-bin/php5.fcgi .php5
</Directory>
<Directory /home/drupal/cgi-bin>
allow from all
AllowOverride All Options=ExecCGI,Includes,IncludesNOEXEC,Indexes,MultiViews,SymLinksIfOwnerMatch
</Directory>
RewriteEngine on
RewriteCond %{HTTP_HOST} =webmail.drupal.domain.local
RewriteRule ^(.*) https://drupal.domain.local:20000/ [R]
RewriteCond %{HTTP_HOST} =admin.drupal.domain.local
RewriteRule ^(.*) https://drupal.domain.local:10000/ [R]
RemoveHandler .php
RemoveHandler .php5
php_admin_value engine Off
IPCCommTimeout 7200
FcgidMaxRequestLen 2073741824
<Files awstats.pl>
AuthName "drupal.domain.local statistics"
AuthType Basic
AuthUserFile /home/drupal/.awstats-htpasswd
require valid-user
</Files>
</VirtualHost>
<VirtualHost *:443>
SuexecUserGroup "#1008" "#1008"
ServerName drupal.domain.local
ServerAlias www.drupal.domain.local
ServerAlias webmail.drupal.domain.local
ServerAlias admin.drupal.domain.local
DocumentRoot /home/drupal/public_html
ErrorLog /var/log/virtualmin/drupal.domain.local_error_log
CustomLog /var/log/virtualmin/drupal.domain.local_access_log combined
ScriptAlias /cgi-bin/ /home/drupal/cgi-bin/
ScriptAlias /awstats/ /home/drupal/cgi-bin/
DirectoryIndex index.html index.htm index.php index.php4 index.php5
<Directory /home/drupal/public_html>
Options -Indexes +IncludesNOEXEC +SymLinksIfOwnerMatch +ExecCGI
allow from all
AllowOverride All Options=ExecCGI,Includes,IncludesNOEXEC,Indexes,MultiViews,SymLinksIfOwnerMatch
Require all granted
AddHandler fcgid-script .php
AddHandler fcgid-script .php5
FCGIWrapper /home/drupal/fcgi-bin/php5.fcgi .php
FCGIWrapper /home/drupal/fcgi-bin/php5.fcgi .php5
</Directory>
<Directory /home/drupal/cgi-bin>
allow from all
AllowOverride All Options=ExecCGI,Includes,IncludesNOEXEC,Indexes,MultiViews,SymLinksIfOwnerMatch
</Directory>
RewriteEngine on
RewriteCond %{HTTP_HOST} =webmail.drupal.domain.local
RewriteRule ^(.*) https://drupal.domain.local:20000/ [R]
RewriteCond %{HTTP_HOST} =admin.drupal.domain.local
RewriteRule ^(.*) https://drupal.domain.local:10000/ [R]
RemoveHandler .php
RemoveHandler .php5
php_admin_value engine Off
IPCCommTimeout 31
FcgidMaxRequestLen 1073741824
SSLEngine on
SSLCertificateFile /home/drupal/ssl.cert
SSLCertificateKeyFile /home/drupal/ssl.key
<Files awstats.pl>
AuthName "drupal.domin.local statistics"
AuthType Basic
AuthUserFile /home/drupal/.awstats-htpasswd
require valid-user
</Files>
</VirtualHost>

```

.htaccess

```
   #
    # Apache/PHP/Drupal settings:
    #
    # Protect files and directories from prying eyes.
    <FilesMatch "\.(engine|inc|info|install|make|module|profile|test|po|sh|.*sql|theme|tpl(\.php)?|xtmpl)(~|\.sw[op]|\.bak|\.orig|\.save)?$|^(\..*|Entries.*|Repository|Root|Tag|Template)$|^#.*#$|\.php(~|\.sw[op]|\.bak|\.orig\.save)$">
      Order allow,deny
    </FilesMatch>

    # Don't show directory listings for URLs which map to a directory.
    # Options -Indexes

    # Follow symbolic links in this directory.
    # Options +FollowSymLinks

    # Make Drupal handle any 404 errors.
    ErrorDocument 404 /index.php

    # Set the default handler.
    DirectoryIndex index.php index.html index.htm

    # Override PHP settings that cannot be changed at runtime. See
    # sites/default/default.settings.php and drupal_environment_initialize() in
    # includes/bootstrap.inc for settings that can be changed at runtime.

    # PHP 5, Apache 1 and 2.
    <IfModule mod_php5.c>
      php_flag magic_quotes_gpc                 off
      php_flag magic_quotes_sybase              off
      php_flag register_globals                 off
      php_flag session.auto_start               off
      php_value mbstring.http_input             pass
      php_value mbstring.http_output            pass
      php_flag mbstring.encoding_translation    off
    </IfModule>

    # Requires mod_expires to be enabled.
    <IfModule mod_expires.c>
      # Enable expirations.
      ExpiresActive On

      # Cache all files for 2 weeks after access (A).
      ExpiresDefault A1209600

      <FilesMatch \.php$>
        # Do not allow PHP scripts to be cached unless they explicitly send cache
        # headers themselves. Otherwise all scripts would have to overwrite the
        # headers set by mod_expires if they want another caching behavior. This may
        # fail if an error occurs early in the bootstrap process, and it may cause
        # problems if a non-Drupal PHP file is installed in a subdirectory.
        ExpiresActive Off
      </FilesMatch>
    </IfModule>

    # Various rewrite rules.
    <IfModule

mod_rewrite.c>
  RewriteEngine on

  # Set "protossl" to "s" if we were accessed via https://.  This is used later
  # if you enable "www." stripping or enforcement, in order to ensure that
  # you don't bounce between http and https.
  RewriteRule ^ - [E=protossl]
  RewriteCond %{HTTPS} on
  RewriteRule ^ - [E=protossl:s]

  # Make sure Authorization HTTP header is available to PHP
  # even when running as CGI or FastCGI.
  RewriteRule ^ - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]

  # Block access to "hidden" directories whose names begin with a period. This
  # includes directories used by version control systems such as Subversion or
  # Git to store control files. Files whose names begin with a period, as well
  # as the control files used by CVS, are protected by the FilesMatch directive
  # above.
  #
  # NOTE: This only works when mod_rewrite is loaded. Without mod_rewrite, it is
  # not possible to block access to entire directories from .htaccess, because
  # <DirectoryMatch> is not allowed here.
  #
  # If you do not have mod_rewrite installed, you should remove these
  # directories from your webroot or otherwise protect them from being
  # downloaded.
  RewriteRule "(^|/)\." - [F]

  # If your site can be accessed both with and without the 'www.' prefix, you
  # can use one of the following settings to redirect users to your preferred
  # URL, either WITH or WITHOUT the 'www.' prefix. Choose ONLY one option:
  #
  # To redirect all users to access the site WITH the 'www.' prefix,
  # (http://example.com/... will be redirected to http://www.example.com/...)
  # uncomment the following:
  # RewriteCond %{HTTP_HOST} .
  # RewriteCond %{HTTP_HOST} !^www\. [NC]
  # RewriteRule ^ http%{ENV:protossl}://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
  #
  # To redirect all users to access the site WITHOUT the 'www.' prefix,
  # (http://www.example.com/... will be redirected to http://example.com/...)
  # uncomment the following:
  # RewriteCond %{HTTP_HOST} ^www\.(.+)$ [NC]
  # RewriteRule ^ http%{ENV:protossl}://%1%{REQUEST_URI} [L,R=301]

  # Modify the RewriteBase if you are using Drupal in a subdirectory or in a
  # VirtualDocumentRoot and the rewrite rules are not working properly.
  # For example if your site is at http://example.com/drupal uncomment and
  # modify the following line:
  # RewriteBase /drupal
  #
  # If your site is running in a VirtualDocumentRoot at http://example.com/,
  # uncomment the following line:
  RewriteBase /

  # Pass all requests not referring directly to files in the filesystem to
  # index.php. Clean URLs are handled in drupal_environment_initialize().
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteCond %{REQUEST_URI} !=/favicon.ico
  RewriteRule ^ index.php [L]

  # Rules to correctly serve gzip compressed CSS and JS files.
  # Requires both mod_rewrite and mod_headers to be enabled.
  <IfModule mod_headers.c>
    # Serve gzip compressed CSS files if they exist and the client accepts gzip.
    RewriteCond %{HTTP:Accept-encoding} gzip
    RewriteCond %{REQUEST_FILENAME}\.gz -s
    RewriteRule ^(.*)\.css $1\.css\.gz [QSA]

    # Serve gzip compressed JS files if they exist and the client accepts gzip.
    RewriteCond %{HTTP:Accept-encoding} gzip
    RewriteCond %{REQUEST_FILENAME}\.gz -s
    RewriteRule ^(.*)\.js $1\.js\.gz [QSA]

    # Serve correct content types, and prevent mod_deflate double gzip.
    RewriteRule \.css\.gz$ - [T=text/css,E=no-gzip:1]
    RewriteRule \.js\.gz$ - [T=text/javascript,E=no-gzip:1]

    <FilesMatch "(\.js\.gz|\.css\.gz)$">
      # Serve correct encoding type.
      Header set Content-Encoding gzip
      # Force proxies to cache gzipped & non-gzipped css/js files separately.
      Header append Vary Accept-Encoding
    </FilesMatch>
  </IfModule>
</IfModule>

```

/etc/apache2/mods-available/userdir.conf

```
<IfModule mod_userdir.c>
    UserDir public_html
    UserDir disabled root
    <Directory /home/*/public_html>
                AllowOverride All
        #AllowOverride FileInfo AuthConfig Limit Indexes
                Options Indexes
        #Options MultiViews Indexes SymLinksIfOwnerMatch IncludesNoExec
        <Limit GET POST OPTIONS>
            Require all granted
        </Limit>
        <LimitExcept GET POST OPTIONS>
            Require all denied
        </LimitExcept>
    </Directory>
</IfModule>

```

# Answer
In my case, changing `Options +FollowSymLinks` in Drupal's .htaccess file worked:

```
Options +SymLinksIfOwnerMatch

```

It looks like it is more secure too: http://drupal.org/node/1269780
> 0 votes

---
Tags: .htaccess
---


title: CiviCRM report by address

text:
# Question
Title: CiviCRM report by address
Is there a way to pull a CiviCRM report that compiles all donations from matching addresses?

Whether or not the people at the matching addresses are formally part of a household -- kind of like the mailing option that merges matching addresses for a mailing export to prevent double mailings.

# Answer
If I understand you correctly the Aggregate Household Contribution Report is what you are looking for. If that is not sufficient, it may provide a good basis for a custom report.
> 4 votes

# Answer
This Display Related Contributions extension might also be of interest.
> 2 votes

---
Tags: 7, civicrm
---


title: How To Add Field In Registration Page

text:
# Question
Title: How To Add Field In Registration Page
In user page, I want to add more field like username, contact number and address. What is the common way to do it?

# Answer
> 1 votes
You can either use Profile2, or you can add your fields in /admin/config/people/accounts/fields.

From Profile2 project page:

> Designed to be the successor of the core profile module, which is deprecated for Drupal 7. In contrast to the deprecated module this module provides a new, fieldable 'profile' entity - leverage the power of fields!

You can find out how to create profiles in Profile2 documentation

---
Tags: users
---


title: drupal 7 pagination

text:
# Question
Title: drupal 7 pagination
I used the below code but it gives me error. Below is my code:
`if(isset($_GET['tid']))
 {
 $id=($_GET['tid']);
 $query = new EntityFieldQuery();
 $query->entityCondition('entity_type', 'node');
 $query->entityCondition('bundle', 'escorts_product');
 $query->propertyCondition('status', 1);
 $query->fieldCondition('field_product_sub_cat', 'tid', $id,'=');
 $result = $query->execute();
 $total=count($result);
function pager_default_initialize($total, $limit = 2, $element = 0)
 {
 global $pager_page_array, $pager_total, $pager_total_items;
 $page = pager_find_page($element);
 $pager_total_items[$element] = $total;//total items
 $pager_total[$element] = ceil($pager_total_items[$element] / $limit);
 $pager_page_array[$element] = max(0, min($page, ((int) $pager_total[$element]) -1));
 $pager_limits[$element] = $limit;
 return $pager_page_array[$element];
 //print "<pre>";print_r($pager_page_array[$element]);
 }
 print theme('pager', array('quantity',count($result)));`
error on this line
`function pager_default_initialize($total, $limit = 2, $element = 0)`,can anyone please guide me?

# Answer
> 1 votes
You have missed a parenthesis } before the line: function pager\_default\_initialize($total, $limit = 2, $element = 0).

Please put it and check the result.

---
Tags: 7, paging
---


# Question
Title: Expose the required fields in listing view
I have created a content type say "Form" which have one of a field named as "gender" set as a radio buttons. This radio button I want to expose or make it visible with its functionality when I am displaying it in a View which can be called as "Form display" on a listing page. I hope my question was clear,if not then please ask me in comments.

# Answer
Use hook\_form\_alter() on the views\_exposed\_form. You can then change the type from select to radios or checkboxes.
> 0 votes

---
Tags: forms
---


# Question
Title: Disable plugin ckeditor per content type
I am using the ckeditor module. I have 2 content types. Both content types use the same ckeditor profile on their body field.

Is it possible, without creating another profile, to disable a certain plugin (e.g. image plugin) on that ckeditor profile for only one content type?

# Answer
You need create different "body field" in one of your content type. I.e. For first content type use the same "body field" and use first ckeditor profile. For next content type create a new "body field" - like a "content\_type\_name\_body" and use last ckeditor profile.
> 2 votes

# Answer
I was having a same issue and did it using Better Formats module.

1. I created a new Input Format (for example "my input format")
2. Disabled WYSIWYG in that format
3. In the Content type settings, under "Input format settings", select that new profile as default
> 2 votes

# Answer
In a custom module, have some code similar to this:

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

  if ($form_id == 'profile_node_form') { //change profile to be your content type
      $form['body'][LANGUAGE_NONE][0]['#wysiwyg'] = FALSE;
  }
}

```

body is the field name, you might need to change it if you're using a different / more fields.

It is probably best to name your module with something in the alphabet later than 'ckeditor' or use the moduleweights module to ensure your hook runs after ckeditor... I say probably because I haven't tested to see if this is an issue or not.
> 0 votes

---
Tags: wysiwyg
---


# Question
Title: Problem with session ID and Drupal cookies when trying to establish a connection
I tried to established a connection between my app and Drupal services. When I try to login to remote Drupal site using Mozilla add-on Poster everything is working... POST request return OK 200 and I'm logged into the site.

When I make the POST request from my app, I always get 200 repose OK, but when I visit the site in browser I'm not logged in. I suppose that Cookie header is not correctly structured in POST request...but I don't know how to fix it.

Does anyone have idea how can I solve this?

# Answer
> 1 votes
I had the same problem in Drupal 8. The AJAX POST isn't retrieving the cookie from `user/login` as Drupal does a redirect right away to another page (`user` usually) which is where you get your 200. And there is nothing (*nothing*) you can do to interrupt that redirect as its wired into the browser. Postman in Chrome (and I presume Poster in Firefox) don't have those restrictions.

In Drupal 7 the Services module provides a login endpoint. After that you can retrieve the session ID and create the cookie by hand. See https://groups.drupal.org/node/358308

In Drupal 8 that endpoint doesn't exist (and there is debate as to whether it should). What I do is:

1. In the app I create a regular login form with a return destination to my app `<form action="/user/login?destination=/app">`
2. Once that's done I retrieve a CSRF token as by then the cookie is set. In Drupal 8 you get that at `rest/session/token`. With Drupal 7 and the Services module you retrieve it at a different path based on your end point.
3. After that every request goes back with the *X-CSRF-Token* header and the cookie isn't used anymore.

---
Tags: services, 8
---


# Question
Title: How can I show parent and child terms in facet search filter block for a taxonomy field having simple hierarchial select as widget type
I am using facet filter to filter views values . I have a taxonomy term using widget type `[Simple Hierarchial Select][1]` . I want to be able to filter parent and child terms both in facet filter block

Tax A
-- Tax A child
---- Tax A child of child

I want to use each one of the above as a filter in the facet filter block

How Can I achieve it?
I have ticked 'index hierarchy ' but it just shows the deepest term e.g. "Tax A child of child"

```
http://example.com/admin/config/search/search_api/index/*server name*/workflow

```

# Answer
> 6 votes
I'm presuming you are using FacetAPI and Search API Solr.

You need to add some settings to the facet itself at Search API \> Index \> Facets \> \[Taxonomy name\]: `http://example.com/admin/config/search/facetapi/[indexname]/block/field_[taxonomyname]/edit`

You'll need to

1. Expand the hierarchy
2. Treat parent items as individual facet items
3. Don't flatten hierarchy
4. and minimum count zero (ie: show even when empty)

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


# Question
Title: Filters and relationships data from a display to another within the same view
Hi everybody,

I've been freshly introduced to Drupal and I'm having my first "serious" issue with contextual filters and relationships. Here is the context :

* I have a "process" content type and several contents (processes)based on it
* Some processes (contents) have an field, called "sub-process", which is an entity reference to processes
* I made a grid page view showing every process and a bloxk view showing every "sub-process"
* In every cell of the grid, there is one process and I want to display the sub-processes attached to it.
* I can display the name of every process's sub-process through the "sub-process" field, but I would like to display other properties of these subprocesses.
* To do so, I used the Views Field View module and a Global : view field. The problem is that it shoes all the subprocesses in all the cells of the gris except the right ones.

Any idea how to proceed ?

# Answer
On your "subprocess" display, you need to add a relationship to the process that is referencing that subprocess. Then add a contextual filter of the process id using the relationship you created. Finally, add a field "Id" in the "process" display and pass the process id as contextual filter in the global view field (check the replacing patterns).
> 2 votes

# Answer
Sounds like you should consider https://www.drupal.org/project/views\_field\_view . It is basically a subquery. make sure you have views caching enabled as these can get complex quickly.
> 0 votes

---
Tags: blocks, views
---


# Question
Title: How to Wrap the text in Source View of CKeditor
I am using CKeditor version 7.x-1.16 with Drupal 7.34. How can I force the text to wrap in source view of the editor. I don't want the horizontal scroll bar to appear.

I managed to do that in WYSIWYG view. Pressing the 'Enter key' in 'source view' will not solve it, since it gets overruled at the next switch between views.

See the images for differences. This is the same text as it appears when I switch between '*Source view*' and '*WYSIWYG view*'

This seems to be a Firefox problem, since in Google Chrome browser it is not an issue.

# Answer
> 10 votes
I found the solution to this: This is a Firefox browser issue only (FF version \>= 36). This behavior is not affected in other major browsers (Safari, IE and Chrome). Here is the fix. Add the following code to you theme's CSS file:

`.cke_source {
 white-space: pre-wrap !important;
}`

Basically, you are overwriting the 'white-space' property of the "cke\_source" selector in the "editor\_gecko.css" file of the CKEditor module. This file is located at: *\sites\all\libraries\ckeditor\skins\moono\editor\_gecko.css*

References:

https://stackoverflow.com/questions/29038262/source-code-not-wrapping-in-ckeditor-on-firefox

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

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

# Answer
> 0 votes
You should probably use the WYSIWYG module (the latest dev version) and get CKeditor directly from their site (the 4.x version) and use the Code Mirror plugin. You'll have better luck keeping current.

---
Tags: wysiwyg
---


# Question
Title: First four free - changing product pricing based on cart quantity in Commerce using Rules
**Brief:**

* Product with SKU "sample" has a unit price of £0.00
* Once quantity \> 4, product unit price is £2.50
* First four remain free. E.g if five in cart = (4 x £0.00) + (1 x £2.50).

Currently I have the first two requirements working, I can change the price of a particular product once there are more than 4 items, my current problem is that because the unit price changes, it counts for the four "free". So currently 5 samples bill at £12.50, instead of £2.50.

You can see my rules set up here:

The easiest solution would be to apply a discount of £10.00 to the cart, but I can only see options to alter a unit price of a line item, rather than applying a discount to the order.

How should I do this?

**Possible solution avenue**

I added a second action "Add line item to cart" and created a product with value of -£10.00. The problem here is that when the quantity is reduced to 4 or below, the line item remains. I cannot see a rule option to then remove that line item.

# Answer
> 0 votes
You can add a custom rules condition for line item which will check next:

* if the amount of items in cart is more than 4
* if the current line item position is greater that 4 (load cart, sort cart line items by created date)

Use the custom condition in pricing rules for line item.

---
Tags: 7, commerce, rules
---


title: Store mysqli-connection object in cache

text:
# Question
Title: Store mysqli-connection object in cache
I have some code in a drupal 7 site that makes repeated requests to an external database using mysqli. To speed up the code, I was hoping that I could store the mysqli-connection object in the cache, like this:

```
// Check if DB-connection already loaded
$external_db = &drupal_static(__FUNCTION__);

if ( !isset($external_db) ){
    // Check if DB-connection in cache
    if( $cached_db = cache_get('external_db', 'cache') ) {
           $external_db = $cached_db->data;
        }

    // Else make a new connection
    else {
        $external_db = mysqli_connect('someip', 'someuser', 'somepass', 'somedb');
        cache_set('external_db', $external_db, 'cache');
    }
}

```

However, something spooky happens to the connection object when I fetch it from out of the cache: it seems to have lost most of its properties. For example, the properties `client_info` and `host_info`are being unset.

Any idea what causes this? Does Drupal delete those properties, or is it something built in to mysqli? Are there alternatives to mysqli that are cacheable?

Thanks a lot you guys!

# Answer
> 1 votes
> To speed up the code, I was hoping that I could store the mysqli-connection object in the cache

It doesn't work like that. For one thing a database connection cannot be serialised (not in any meaningful way at least, as you've discovered). Once the page request is done with, the connection is closed. You can't force it to stay open by maintaining a reference to it, as that physically won't work when you come to accessing the network.

Separately, you should never have any cause to use `mysql_connect()` in Drupal (or *ever* if you want to be technical - it was deprecated a long time ago). Drupal's database connection is as optimised as you'll need such a thing to be, so you should just use that.

---
Tags: caching, database
---


# Question
Title: What is the front page path of the Recruiter Distribution?
I am using the Recruiter distribution and I want to find the path of the front page so as to add it to the 404 redirect settings of the site. However,there is no panel page as homepage.There is only used the context module that says if path=\< front \> then etc.Also I tried the path /node with no luck.

So how can I find the path of the homepage?

# Answer
Recruiter Distribution, does not have a path where you can modify everything.

Everything is base on blocks and they are using the the Context module to display it.

1. **Menu** that it can be modify at `admin/structure/menu/manage/user-menu/`
2. **Block** The name of the region is called Banner. On the recruiter installation this block is blank.
3. **Views block.** If you wish to modify search you can go to `admin/structure/views/view/job_search/edit/search_page` to modify the location you can go to the context module.
4. **Block** That is blank on the Recruiter installation but is also a block and it can be modify at the context.
5. **Views Block** the views can be modify at `admin/structure/views/view/front_page_job_search` and the location at the context module.
6. **Block** That is blank on the Recruiter installation but is also a block and it can be modify at the context.
7. **Facets** To modify the location you need to the context page and to modify the look you would need to used the Facet Api module.

The rest of the footer it suppose to be at context module and they are many blocks.

**If you wish to have it on a path.** You probably would need to uninstall the `recruiter_front` module and then you need to make sure that any of the blocks that are pointing the the front page are gone. At this post you should have an empty page. After that is going a default Drupal configuration. You can go to `/admin/config/system/site-information` and set a path that you wish.
> 1 votes

# Answer
You can define it at `/admin/config/system/site-information`. This is the value the `<front>` path uses.

**UPDATE**: The default frontpage after a fresh install appears to be `/node` as defined per `/admin/config/system/site-information`
> 1 votes

# Answer
what is your problem with this code

```
<?php
    global $base_url;
    print $base_url;
 ?>

```

No matters what configuration is in system setting, it returns the address of front page.
> 1 votes

---
Tags: panels
---


# Question
Title: Quick tabs: Passing current nid to a view
I have a content type called products. The url is products/\[node:title\], i.e. /products/pear, products/banana, etc.

On the node page itself many of the fields of that node are hidden, because I want them displayed in tabs, along with content from associated nodes (via Entity References). So I am using Quicktabs and views to display this content. However, I can't work out how to pass the NID to a view if it doesn't appear in the URL. Since I just want to pass the NID of the page I am on, this seems like it should be a simple issue, but I can't work it out.

# Answer
Ok I've worked it out. The URL that QuickTabs references is the **System** URL, so the NID is there and can be referenced just by %1.

I knew there would be a simple answer! Hopefully this will help someone else.
> 3 votes

# Answer
You need to use contextual filters on your view.

1. Under view settings -\> Advanced -\> contextual filters -\> Add 'Content: Nid'
2. Under 'When the filter value is not available' -\> provide default value -\> Content ID from URL

Then save the filter / view and it should be set up to pull the nid from whatever page it is displayed on.
> 0 votes

---
Tags: views, blocks
---


title: Tableselect with dropdown per row

text:
# Question
Title: Tableselect with dropdown per row
I use a tableselect to output a list of terms and per row I want a drop down (select):

```
$header = array(
      'name' => array('data' => t('Name')),
      'weight' => array('data' => t('Weight')),
    );

    $options = array();

    foreach ($terms as $term) {
      $options[$term->tid] = array(
        'name' => array(
          'data' => array(
            '#title' => $term->name,
            '#type' => 'link',
            '#href' => sprintf('/taxonomy/term/%d', $term->tid),
          ),
        ),
        'weight' => array(
          'data' => array(
            '#type' => 'select',
            '#options' => range(1,25),
          ),
        ),
      );
    }

    $form['term_list']['list'] = array(
      '#type' => 'tableselect',
      '#header' => $header,
      '#options' => $options,
    );

```

My problem is that I do not see the value of the drop down (select) when I debug.

```
function example_block_save($delta = '', $edit = array()) {
  debug($edit, null, true);
}

```

Here is what I get:

```
[term_list] => Array
        (
            [list] => Array
                (
                    [5] => 5
                    [4] => 0
                    [6] => 0
                )

        )

```

When I check the code I can see that the select has no name, I'm guessing that's why I don't see it in the debug.

# Answer
Thanks to this post on Hexblot, I think I've found a solution that works, in case anyone else is still out there trying to get this working.

The trick is to add an extra form field to contain your values from the select input.

```
$form['weight'] = array(
  '#type' => 'value'
);
$form['term_list']['list'] = array(
  '#type' => 'tableselect',
  // etc...
);

```

Then add your select input to each row.

```
  'weight' => array(
    'data' => array(
      '#title' => 'Weight',
      '#title_display' => 'invisible',
      '#name' => 'weight['.$tid.']',
      '#type' => 'select',
      '#options' => range(1,25),
    ),
  ),

```

The important part is the use of the '#name' attribute to create an array of select inputs. Oddly enough it seems to work fine whether I use \['data'\]\['#name'\] or \['data'\]\['#attributes'\]\['name'\]. Basically, you're leveraging PHP's own internal POST data -\> array conversion handling instead of relying on Drupal to parse it all for you. Then I guess Drupal picks it up on the other side. Doesn't feel super clean, but it works.

Just in case anyone needs it, I also struggled a bit using default or placeholder values in a select embedded in a tableselect, so I'll also add that if you need that functionality, you need to use '#value' instead of '#default\_value'. '#empty\_option' also didn't work, so I ended up having to implement it like this:

```
    'data' => array(
      '#title' => 'My Select',
      '#title_display' => 'invisible',
      '#type' => 'select',
      '#options' => array('' => '- None -') + range(1,25),
      '#value' => $default_value,
      '#empty_value' => '',
      '#name' => 'my-select['.$tid.']',
    ),

```
> 1 votes

# Answer
give default value property to select element e.g select form element returns value if select has been checked

add this attribute

```
'#default_value'= 1;

```

to every select list and your data to select list must be an array with key and value

```
$element=array(
'#type'=>'select',
'#default_value'=>1,
'#options'=>array(
         0 => t('No'),
         1 => t('Yes'),
    )

);

```

maybe then you have to render this element array with theme\_form\_element to your data variable. sorry but i havent enough time to test this solution
> 0 votes

# Answer
What you're looking for is this:

```
'weight' => array(
  'data' => array(
    '#type' => 'select',
    '#title' => 'Weight',
    '#options' => drupal_map_assoc(range(1, 25)),
    '#title_display' => 'invisible',
    '#attributes' => array(
      'name' => 'term-weight[' . $term->tid . ']',
    ),
  ),
),

```

The `#title_display` set to invisible makes sure the "Weight" label doesn't appear in every row.

Typically if you're creating a weight select you'd use:

```
'weight' => array(
  '#type' => 'weight',
  '#title' => 'Weight',
  '#delta' => 100,
  '#default_value' => 0,
),

```

But for some reason that doesn't work in a `tableselect`.

Also, be sure to use `drupal_map_assoc()` if you're going to use a range like that since the option keys will be automatically assigned and they always start with 0.

There is no `#name` attribute for select fields but you will need to give the select a name by using #attributes. That is the only way you'll get the values to come through your validation and submission handlers.

However, they do not come through to `$form_state['values']`. Instead you'll have to get them from `$form_state['input']`. So if you use the name I gave the field in my example you'd loop through `$form_state['input']['term-weight']` to get the values. You can add the values to your `$form_state['values']` using a form validator like this:

```
function my_tableselect_form_with_weight_field_validate($form, &$form_state){
  foreach($form_state['input']['term-weight'] as $tid => $weight){
    $form_state['values']['term-weight'][$tid] = $weight;
  }
}

```

I don't know what the equivalent would be for the block hooks. I found this question when trying to find a solution for adding a table drag to a tableselect and the code I provided works for what I'm trying to do. I'm hoping this will help anyone else who may have a similar issue.
> 0 votes

# Answer
I had the similar problem. I tried with the following element added to the array.

```
'#name' => 'status',

```

It should be like...

```
   'weight' => array(
      'data' => array(
        '#name' => 'weight',
        '#type' => 'select',
        '#options' => range(1,25),
      ),
    ),

```
> -1 votes

---
Tags: 7, forms
---


# Question
Title: Add A Redirect Link In Webform Submit Button
I want to add a redirect link on Webform submission button when a user submit a webform I want to redirect them in different page.

How can I redirect a user after they submit the webform ?

# Answer
> 1 votes
This is duplicated question.

**But here is the answer** If i had to redirect the users after submission than i would go to the already created webfrom, click on

* **Webform**(on top of the form)-\>**Form settings**

After scrolling down a bit you will see **Redirection location**

Choose **Custom URL** and enter your Internal URL ***www.mysite.com/foo***

Thats it you are done.

---
Tags: webforms
---


title: Hide a field based on checkbox

text:
# Question
Title: Hide a field based on checkbox
I want to hide the price for specific products in a product display. I have added a checkbox to the product display type and when it is checked I want to hide the price.

I have figured out that I can hide the field with hide($build\['product:commerce\_price'\]) in hook\_node\_view\_alter but the problem is I don't know how to get the value of the checkbox. var\_dump($build\["field\_hide\_price"\]) outputs null;

# Answer
> 1 votes
The conditional field module will do this for you. In this module when certain fields are selected, get value, ... other operations (hiding,removing,make it required,...) may happen

# Answer
> 0 votes
I believe you want to use the form API states, this will allow you to use Drupal's built in jQuery to hide and show the price based on the state of the checkbox.

Example syntax:

```
'#states' => array(
  'action_to_take_on_this_form_element' => array(
    'jquery_selector_for_another_element' => array(
      'condition_type' => value,
    ),
  ),
)

```

---
Tags: commerce
---


# Question
Title: Drush @sites alias does not work in a multisite installation
I have 3 Drupal sites installed and I've developed a simple "hello-world" command that just does the following:

```
drush_log(getmypid() . ' Hello world!', 'ok');

```

When I run `drush @sites hello-world` I get the following error message:

> Could not find a Drupal settings.php file at sites/default/settings.php

Please note that the command is working fine when run for a specific site.

```
drush -l test1 hello-world

```

I was under the assumption that Drush @sites alias should be available by default. Is it not?

# Answer
> 1 votes
I just tested this on HEAD of today's master branch of drush, and `drush @sites status` worked fine for me with no `sites/default` folder. Try upgrading to drush 7.0-alpha9.

# Answer
> 0 votes
Do you have a site at `sites/default` or do you only have 3 subsites that are in 3 other folders?

`@sites` (i believe) makes certain assumptions. Such as "there is a default site directory" and others ... If your site folders are structured otherwise then you need to something like:

`drush @test1 hello-world`

Also note that aliases are defined in Drush Site Alias files. So for example my `@test1` alias would need to be defined previously for drush.

---
Tags: drush, multi-sites
---


# Question
Title: How to specify in a form field's #ajax setting that the entire form should be rebuilt
I have a form with 3 sequential selects at the top, each populated as a result of the selection in the one prior.

After the third select is choice is made, a large number of fields segregated into two vertical tabs should be populated.

1. In the form, I set the default value of each of the fields to an associative array element, which is empty when the form is first built.
2. When the third select choice is made, its callback a. obtains an associative array of the values needed for the form b. stores them in $form\_state\['storage'\]\['mykey'\] c. sets $form\['rebuild'\] to true (for good measure) d. returns $form
3. In the form function, prior to the field definitions, I set the associative array used for the default values to $form\_state\['storage'\]\['mykey'\]

I can see in xdebug that $form\_state has the data in the correct place prior to returning, but when execution returns to the form function, $form\_state no longer has a \['storage'\] key.

AJAX CALLBACK

```
function my_ajax_callback($form, &$form_state) {
  $form_state['storage']['draft'] = my_mysql_get($form_state['values']['id']);
  return $form;
}

```

FIRST LINE OF FORM FUNCTION (most fields use $r for default\_value)

```
  $r =  !isset($form_state['storage']['draft']) ?  array() : $form_state['storage']['draft'];

```

A breakpoint at the callback reveals that it is reached, and that $form\_state\['storage'\]\['draft'\] is populated at the point of returning.

A breakpoint at the equate reveals that \['storage'\] is no longer in $form\_state, but this is only reached (in the form function) if I return only a field from the callback, not the entire form. I really need the entire form, because 17 of 20 fields on the form need to be rebuilt at that point, to get the default value into them.

FORM FIELD WITH AJAX CALLBACK

```
  $form['info'] = array(
    '#type' => 'select',
    '#title' => 'Player',
    '#prefix' => '<div id="info_select">',
    '#suffix' => '</div>',
    '#options' => info_options($form_state['values']['key1'], $form_state['values']['key2']),

    // ajax to bind this select to the players select
    '#ajax' => array(
      'event' => 'change',
      'callback' => 'my_ajax_callback',
      'wrapper' => 'my_form_id',
    ),

```

# Answer
> 1 votes
The workflow in an AJAX callback with a non button element is:

* Submit data is received, form is constructed and validated.
* If no validation errors are detected form is rebuilt. This means that the form function is called again (the form that returns the form structure).
* AJAX callback function is called. The task of this function is only to return the data to the browser. No persistent calculations should be done here.

You have to detect if tou are in an AJAX form request in your form function. If yes, calculate your date. Then, construct your form accordingly. Last, return the right form fragment (or the whole form) in your AJAX callback function.

Form function:

```
 $form['info'] = array(
    '#type' => 'select',
    '#title' => 'Player',
    '#prefix' => '<div id="info_select">',
    '#suffix' => '</div>',
    '#options' => info_options($form_state['values']['key1'], $form_state['values']['key2']),

    // ajax to bind this select to the players select
    '#ajax' => array(
      'event' => 'change',
      'callback' => 'my_ajax_callback',
      'wrapper' => 'my_form_id',
    ),

// If all selects have values get data to populate elements in vertical tabs.
if (all_select_have_values()) {
  $form_state['storage']['draft'] = my_mysql_get($form_state['values']['id']);
}

// Then add the rest of form elements.
$r =  !isset($form_state['storage']['draft']) ?  array() : $form_state['storage']['draft'];
...

```

In callback just return your form:

```
function my_ajax_callback($form, &$form_state) {
  return $form;
}

```

You are losing the values in $form\_state because you are adding data to the $form\_state in the callback function. AJAX calls are procesed by ajax\_form\_callback(). This function first calls drupal\_process\_form(), and then the AJAX callback function. $form\_state is saved (when condition apply) at the end of drupal\_process\_form function.

---
Tags: 7, forms, ajax
---


title: Drupal integration for streaming video

text:
# Question
Title: Drupal integration for streaming video
I am working with an STI product for wowza media server to allow streaming video on our website made in drupal 7. I am using panels for the profile pages which will have 8 guest camera docks which is simple enough. it will also have a text chat as well as a main video dock for the person who owns that profile. Anyone know how I might be able to set a flashvar to the userid of the profile by variable so i do not have to custom code each profile as people sign up? I want it so when a user signs up they have a profile with all the features and those features are specific to that user so that when one person goes to broadcast it doesnt broadcast to every profile.

# Answer
Based on your comments and the fact you will be writing some custom code for the video player in your site. You can easily include the Drupal user id into flash variables.

In order to do this, you will load the Drupal user object of the currently logged in user. This is quite easy to do.

```
<?php

$global $user;
$drupaluserid = $user->uid

?>

```
> 0 votes

---
Tags: panels
---


title: Custom space types in Open Atrium

text:
# Question
Title: Custom space types in Open Atrium
I have seen the OA webinar on extending Open Atrium that documented how to make custom content types for sections and have them be recognized and tie in to the OA hierarchy. I would like to do the same but with spaces.

I can clone the space content type to get different ones like "department" or "project" with different custom fields but I want them treated separately in the navbar/breadcrumb. In other words, the label "space" isn't useful - can't sell that to my client. Having departments and projects all lumped together as spaces is awkward and too generic.

As far as I can see spaces are OG groups and you can make custom OG groups, but OA builds a complex hierarchy with permissions inheritances and such so not sure if it's possible.

The label "space" and such are hardcoded into the oa breadcrumb module so it appears there's no flexibility and this may require substantial rejiggering of the architecture.

Is there a way to override the default breadcrumb toolbar using the Panels Breadcrumb module (part of the OA distro)? Can I just roll my own navbar and disable the oa specific module?

# Answer
> 0 votes
This has been addressed here: https://www.drupal.org/node/2295541

Short answer: You can't create your own space content types because it breaks the architecture set up by organic groups. Better to use the stock space content type and add a term reference field where the terms delineate different space "types", or make use of the standard "space type" term reference field.

---
Tags: distributions
---


# Question
Title: Getting the number of Flood events within threshold?
The `FloodInterface` has 4 methods:

* `register` \- which adds an event
* `clear` \- which clears an event
* `isAllowed` \- which checks to see if the number of logged events is greater than the threshold
* `garbageCollection` \- removes expired events

I'm creating an `EntityForm` and need to use the number of flood events to conditionally set certain form elements, does anyone know if there is a way to do this?

# Answer
> 1 votes
The only way to do that with the default FloodInterface would be to use the isAllowed method and adjust the threshold to the number of allowed attempts.

From a hook\_form\_alter() you could do something similar to this, where 'my\_trigger' is the name of the event that is registered, such as 'contact' for the contact form or 'user.failed\_login\_ip' and 'user.failed\_login\_user' for user login. 5 would be the maximum number of times the event could have been registered in 3600 seconds.

```
<?php

function hook_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
  // Hide element if over the number of allowed attempts
  if (!\Drupal::flood()->isAllowed('my_trigger', 5, 3600)) {
    $form['my_element']['#access'] = FALSE;
  }
}

```

---
Tags: 8, entities
---


# Question
Title: db_query with where clause not returning anything
I ran following query on DB through PHPmyAdmin

```
SELECT * FROM field_data_field_country_feed WHERE entity_id=40848

```

And it worked and returned me the single row But when I try to implement that in my custom services it is not returning anything.

```
$result1 = db_query("SELECT * FROM field_data_field_country_feed WHERE entity_id=40848")->fetchAll();
        var_dump($result1);

```

Please help

# Answer
> 2 votes
Try:

```
$taxonomy_term = taxonomy_term_load(40848); // the 40848 is the term id
$field_items = field_get_items('taxonomy', $taxonomy_term, 'field_data_field_country_feed');

```

---
Tags: database
---


title: How to upgrade the WebForm module?

text:
# Question
Title: How to upgrade the WebForm module?
I'm planning on upgrading the WebForm module in my Drupal 7 site. The current WebForm version is 7.x-3.19 and I'm upgrading to 7.x-4.2.

Question: Is it as simple as uploading the new version? Do I need to run `update.php` afterwards?

Somehow I seem to remember that updating the WebForm module is not as simple as other modules and can cause existing webforms to break.

# Answer
> 2 votes
You should be fine with the upgrade. Back up your DB, of course. If you are uploading the module instead of installing through the UI, then yes, you need to run /update.php.

---
Tags: 7, webforms
---


# Question
Title: WSOD with error when login as administration
I was working on website and suddenly noticed that a particular page had a error message and lost a lot of css styles.

When I went back to the back-end I saw a white page with following message and nothing else (no administration menu, no content overview, ...

**Error message**

Additional uncaught exception thrown while handling exception.

Original

```
PDOException: SQLSTATE[HY000]: General error: 2006 MySQL server has gone away: SELECT s.uid, c.updated FROM {ctools_object_cache} c INNER JOIN {sessions} s ON c.sid = s.sid WHERE s.sid <> :session_id AND c.obj = :obj AND c.name = :name ORDER BY c.updated ASC; Array ( [:session_id] => HWv-9jPhNMHqjMdxRprJh-YmmBQc2y0jWXrbR_68TeA [:obj] => view [:name] => article_4pc ) in ctools_object_cache_test() (line 145 of /home/admin/domains/peace-in-the-city.be/public_html/sites/all/modules/ctools/includes/object-cache.inc).

```

Additional

```
PDOException: SQLSTATE[HY000]: General error: 2006 MySQL server has gone away: INSERT INTO {watchdog} (uid, type, message, variables, severity, link, location, referer, hostname, timestamp) VALUES (:db_insert_placeholder_0, :db_insert_placeholder_1, :db_insert_placeholder_2, :db_insert_placeholder_3, :db_insert_placeholder_4, :db_insert_placeholder_5, :db_insert_placeholder_6, :db_insert_placeholder_7, :db_insert_placeholder_8, :db_insert_placeholder_9); Array ( [:db_insert_placeholder_0] => 1 [:db_insert_placeholder_1] => php [:db_insert_placeholder_2] => %type: !message in %function (line %line of %file). [:db_insert_placeholder_3] => a:6:{s:5:"%type";s:12:"PDOException";s:8:"!message";s:382:"SQLSTATE[HY000]: General error: 2006 MySQL server has gone away: SELECT s.uid, c.updated FROM {ctools_object_cache} c INNER JOIN {sessions} s ON c.sid = s.sid WHERE s.sid &lt;&gt; :session_id AND c.obj = :obj AND c.name = :name ORDER BY c.updated ASC; Array ( [:session_id] =&gt; HWv-9jPhNMHqjMdxRprJh-YmmBQc2y0jWXrbR_68TeA [:obj] =&gt; view [:name] =&gt; article_4pc ) ";s:9:"%function";s:26:"ctools_object_cache_test()";s:5:"%file";s:103:"/home/admin/domains/peace-in-the-city.be/public_html/sites/all/modules/ctools/includes/object-cache.inc";s:5:"%line";i:145;s:14:"severity_level";i:3;} [:db_insert_placeholder_4] => 3 [:db_insert_placeholder_5] => [:db_insert_placeholder_6] => http://peace-in-the-city.be/admin [:db_insert_placeholder_7] => [:db_insert_placeholder_8] => 178.118.99.54 [:db_insert_placeholder_9] => 1426611072 ) in dblog_watchdog() (line 160 of /home/admin/domains/peace-in-the-city.be/public_html/modules/dblog/dblog.module).

```

Uncaught exception thrown in session handler.

```
PDOException: SQLSTATE[HY000]: General error: 2006 MySQL server has gone away: SELECT 1 AS expression FROM {sessions} sessions WHERE ( (sid = :db_condition_placeholder_0) AND (ssid = :db_condition_placeholder_1) ); Array ( [:db_condition_placeholder_0] => HWv-9jPhNMHqjMdxRprJh-YmmBQc2y0jWXrbR_68TeA [:db_condition_placeholder_1] => ) in _drupal_session_write() (line 209 of /home/admin/domains/peace-in-the-city.be/public_html/includes/session.inc).

```

---

I was able to login as another users without any problems. I flush caches and run cron and this have not solve my issue.

How can I troubleshoot this problem ?

You can find the website here.

# Answer
To troubleshoot, add these lines to your settings.php:

```
error_reporting(E_ALL);
ini_set('display_errors', TRUE);
ini_set('display_startup_errors', TRUE);

```

Once you add these, you should see some error output.
> 1 votes

---
Tags: database, debugging, users
---


# Question
Title: How do I create and delete a forum via POST to taxonomy_term?
I'd like to be able to programmatically create and delete Forums on a Drupal 7 install, via the Services module. I want to send in HTTP requests and have those things happen.

I know how to create a node (page, article, or forum topic). I know how to delete a node.

How can I create a forum? I think Forums is a taxonomy\_vocabulary. I think creating and removing forums is equivalent to adding and removing terms to the vocabulary. But I would like to see an example.

Any help?

# Answer
**Part one: How to delete a forum.**

```
curl -i -X DELETE \
  -H Cookie:SESSe6abeefcafe=ovQpO6ahoQYUUREX23bre_2Q1onya55i9fbmzq7TWEE \
  -H X-CSRF-Token:v6j7r9Rbase62tokenHere-m9YYZA \
  -H Accept:application/json \
  http://myserver/rest/taxonomy_term/7

```

Some notes:

* to construct the URL, you need to use the Term ID of the particular forum you would like to delete
* You need to use the Cookie obtained from the prior call to /user/login
* You need to use the CSRF token obtained from that same call

---

**Where does the term ID come from?**

The term id in my case, is something I retrieved from a combination of two other calls: one to retrieve the taxonomy id for the forums, then another to retrieve the terms under that taxonomy. Like this:

```
curl -i -X GET \
  -H Cookie:SESSe6abeefcafe=ovQpO6ahoQYUUREX23bre_2Q1onya55i9fbmzq7TWEE \
 'http://myserver/rest/taxonomy_vocabulary?parameters\[machine_name\]=forums'

```

The response is like this:

```
[{
  "vid": "1",
  "name": "Forums",
  "machine_name": "forums",
  "description": "Forum navigation vocabulary",
  "hierarchy": "0",
  "module": "forum",
  "weight": "-10",
  "uri": "http://myserver/rest/taxonomy_vocabulary/1"
}]

```

And then, with the taxonomy ID returned there, I can retrieve the *terms*, which correspond to actual forums, like this:

```
curl -i -X GET \
 -H Cookie:SESSe6abeefcafe=ovQpO6ahoQYUUREX23bre_2Q1onya55i9fbmzq7TWEE \
 -H Accept:application/json \
 'http://myserver/rest/taxonomy_term?parameters\[vid\]=1'

```

The response is an array of JSON items, each of which has a term id. You can then choose one of those term id's to delete, as above.

**Part two: How to create a forum.**

To create a forum, do the converse; add a new term in the same "forums" vocabulary. like this.

```
curl -i -X POST \
  -H Cookie:SESSe6abeefcafe=ovQpO6ahoQYUUREX23bre_2Q1onya55i9fbmzq7TWEE \
  -H X-CSRF-Token:v6j7r9Rbase62tokenHere-m9YYZA \
  -H Accept:application/json \
  -H content-type:application/json \
  http://myserver/rest/taxonomy_term \
  -d '{
    "vid": "1",
    "name": "Another Forum on the site",
    "description": "",
    "format": null,
    "weight": "10"
  }'

```

The vid property needs to be the "vocabulary id" of the forums vocabulary. The uuid and the tid of the newly-created term will be generated for you. Unfortunately, the tid will not be returned for you to reference. You need to query again to find it.

```
curl -i -X GET \
  -H Cookie:SESSe6abeefcafe=ovQpO6ahoQYUUREX23bre_2Q1onya55i9fbmzq7TWEE \
  -H Accept:application/json \
  'http://myserver/rest/taxonomy_term?parameters\[name\]=Another+Forum+on+the+site'

```

Response:

```
[{
  "tid": "36",
  "vid": "1",
  "name": "Another Forum on the site",
  "description": "",
  "format": null,
  "weight": "10",
  "uuid": "dcbe0118-c160-4556-b0b6-1813241bb851",
  "uri": "http://myserver/rest/taxonomy_term/36"
}]

```

Therefore, make sure you use unique names for these "terms".
> 0 votes

---
Tags: 7, taxonomy-terms, services
---


title: user/login page - no access to it

text:
# Question
Title: user/login page - no access to it
I want to add a Login link in the user menu. When I give it the path 'user/login', I get the message: The path 'user/login' is either invalid or you do not have access to it.

If I give it a path of 'user', it works. However, that's not the path I want, because it will still be visible to the logged-in user.

If I give it a full path, http://mysite.com/user/login, it works BUT isn't hidden from the logged-in user. Puzzling.

Any ideas? I am pretty sure I could use a module to handle this, but it seems like overkill.

# Answer
> 7 votes
If you are using the Sub-pathauto module simply:

1. Disable the subpathauto module.
2. Add your menu item(s) for user/login.
3. Re-enable the subpathauto module.

# Answer
> 2 votes
Thank you to everyone who answered. I was not asking about whether or not the login link was visible, but was instead asking how to enter the user/login path on the user menu or in the URL aliases without getting an error.

I solved it by using the path user/login? instead of user/login. So simple, so much time wasted.

# Answer
> 1 votes
How about wrapping it in a conditions like these?

```
if (user_is_logged_in()) {
  // Do something.
}

```

or

```
if (user_is_anonymous()) {
  // Do something.
}

```

A useful link - https://api.drupal.org/api/drupal/modules%21user%21user.module/function/user\_menu\_site\_status\_alter/7

# Answer
> 1 votes
That error message is show from the form validation handler used by the form that allows you to add a menu item, or edit it; it calls drupal\_valid\_path(), which contains the following code.

```
return $item && $item['access'];

```

As @Nikhil M said in his comment, logged-in users don't have access to that menu item, which means `$item['access']` is `FALSE`.

The only way I found to add that link was first creating a path alias (e.g. user-login) to /user/login, and then using the path alias when creating the menu item.

Apparently it works.

Once logged in, the menu item doesn't appear.

I have also tried with a different menu (e.g. the Main menu) and it works.

At first, it seemed not to work, since the link was not shown when I logged out. To see the login link, I had to clean the Drupal cache, and refresh the page from Firefox after logging out.

# Answer
> 0 votes
One of my colleagues came up with a simple solution that I'm sharing in case it helps others. "Basically, you can't edit an existing menu item that links to user/login, you have to create a whole new one. I did that and it's working now!"

So you can create a menu item with the path in question (user/login), but you'll never be able to edit it. If you want to change the text down the road,create a new menu item and delete the old.

---
Tags: 7, users
---


title: My .js file is not included in my site

text:
# Question
Title: My .js file is not included in my site
I am working on Recruiter distribution which uses a Cloudy theme.

I have tried 2 ways to add custom javascript to my site:

> 1)Adding jquery code to the `.info` file of Cloudy theme(default theme) called `cloudy.js`.
>
> 2)Adding a new `.js` file under `js/myjs.js` and added this to the `.info` file of Cloudy theme `scripts[] = js/myjs.js`

However,when I view the source code of my frontpage, neither `cloudy.js` nor `myjs.js` is loaded and as a result the jquery code doesn't work.

What am I missing? Has anything to do that it is a distribution and not a drupal site? thanks

# Answer
In order to allow Drupal Core to handle the JS for you. You need to use drupal\_add\_js() function to load the JS. This has many important aspects to loading JS into a Drupal site. If you do not use drupal\_add\_js() performance features in Drupal such as aggregating JS files will not work. If you are not using the aggregate feature on a production website you are missing out on one very important feature of Drupal 7.

This code goes into your template.php file within your theme. You can also use the same exact code in a custom module. You only have to change the path function and hook names.

```
/**
* Implements hook_preprocess_html().
*/

function yourthemename_preprocess_html(&$variables, $hook) {
   $path = drupal_get_path('theme','yourthemename') . 'any/extra/path/needed/myjs.js';
   drupal_add_js($path);
}

```
> 1 votes

# Answer
\***EDITED\****

How about if you add the js into the HEAD tag .

This goes into your default Theme that is being used and you need to add this hook to the template.php file ; if it doesn't already exist. Remember to Clear you cache afterwards also.

```
/**
* hook_preprocess_html
*/

function yourtheme_preprocess_html(&$variables, $hook) {

   drupal_add_js(drupal_get_path('theme', 'yourtheme') . '/js/common.js');

```

}
> 1 votes

# Answer
The answers is already been provide. This is another solution if you wish to add JS from a Drupal module.

You can used the JS injector.
> 0 votes

---
Tags: javascript
---


# Question
Title: different "no content" message based on taxonomy vocabulary/term
how would I change the message: "There is currently no content classified with this term" when viewing a term that doesn't have conent asscociated with it?

I see the message is in taxonomy.pages.inc and that I could just edit that line, but that would change it for ALL terms, whereas I'd like to have a custom message based on the taxonomy vocabulary.

Lets' say I have vocabularies: "countries" message \> Sorry no event listed in \[country-name\] "sports" message \> Sorry no games of \[sport-name\]

Please keep in mind I am not a coder.

Thank you

# Answer
> 0 votes
Drupal 7 has a default Taxonomy Views display you can use to override the default pages. Here are the steps:

1. Install Views, if you haven't already.
2. Go to Structure -\> Views and look for the **Taxonomy term** view.
3. In the little button that says "Enable", drop it down and select "Clone", and create a new name for the view (it defaults to "Clone of Taxonomy term"). This will make a copy of the Taxonomy view.
4. Edit the view, and drop down the Advanced tab. Add a NO RESULTS BEHAVIOR.
5. Select Global: Text area.
6. Enter the text you want to display for no results.

Let me know if you need help beyond this.

---
Tags: taxonomy-terms
---


title: How to stop spam in comments

text:
# Question
Title: How to stop spam in comments
I've installed reCAPTCHA module but spam still bypass my security and leave nasty comments. What should I do? How to block them?

# Answer
I had a good experience with the Mollom module, but a free registration is required for your site. Unfortunately, Mollom has announced the end-of-life for their service. Acquia support and maintenance for Mollom ended as of April 2, 2018.

I really like the Antibot module: It's lightweight and pretty effective.
> 9 votes

# Answer
Mollom is a very useful tool for preventing spam and integrates well with Drupal and is an essential module for running a Drupal site which can get reasonable traffic.

AntiSpam is also another spam prevention module for Drupal based on Akismet of Wordpress, but you need to have an Akismet account for it to work.

You could also try the following suggestions to bring in an additional level of spam protection.

If you are running memcache and if you are not worried about regular users posting to your site now and then, you can use the following trick.

You can add PHP code in your settings.php file to filter out anonymous users who are trying to use 'POST' to paste comments within a period of say '5' seconds from the same IP address and preventing them from posting again. Very useful against bots.

```
if ($_SERVER["REQUEST_METHOD"] == 'POST' && !isset($_COOKIE['DRUPAL_UID'])) {
  $m = new Memcached();
  $m->addServer('localhost', 11211);
  $key = 'anon_'. $_SERVER['REMOTE_ADDR'];
  if (!$m->get($key)) {
    $m->set($key, 1, 5);
  }
  else {
    $m->set($key, 1, 5);
    echo ("We are sorry, there was an error processing your submission. Please try after some time");
    exit;
  }
}

```

The code creates a key in memcache which will act as a decaying flag for finding out whether a user has been posting comment to the site in the last 5 seconds.

For more details check out this article.

Another strategy would be to detect non english spam comments with more than 3 links. You can use the PEAR language detection library to filter out comments that are not in English or have more than 3 links which are typical of spam comments. This one requires a bit of coding skills and you need to write a custom module. For more details check out the article by the forementioned link.
> 7 votes

# Answer
Another module that does a pretty good job with spam comments (depending on your site) is Honeypot, a project I created, for which I am one of the maintainers and the project owner.
It will also help prevent user registration and form spam.

The module has releases for Drupal 7, Drupal 8, Drupal 9, and Drupal 10. Out of the alternative modules suggested in its project page, this is the only module that declares to be compatible with Drupal 10.
> 5 votes

# Answer
Try to use the ASCII art CAPTCHA the CAPTCHA Pack module makes available. It helped me in bad times.
> 3 votes

# Answer
Here's a quick and easy method that has pretty much gotten rid of all my spam comments. It stops comments with embedded links from being posted by anonymous users.

```
// hook comment creation
function THEME_OR_MODULE_NAME_form_comment_form_alter(&$form, &$form_state, $form_id) {
  $form['#validate'][] = 'THEME_OR_MODULE_NAME_comment_exclude_spam_with_link';
}

// function to weed out spam comments with links submitted by anonymous users
function THEME_OR_MODULE_NAME_comment_exclude_spam_with_link($form, &$form_state) {
  $comment_body = $form_state['values']['comment_body'][LANGUAGE_NONE][0];
  if (isset($comment_body['format'])) {
    $comment_text = check_markup($comment_body['value'],$comment_body['format']);
  }
  else {
    $comment_text = check_plain($comment_body['value']);
  }
  if(preg_match("/href=/i",$comment_text)) {
    if(isset($_SERVER['REMOTE_ADDR'])) {
      $user_ip = $_SERVER['REMOTE_ADDR'];
      if(!user_is_logged_in()) {
        $watchdog_message = "Attempted anonymous link, IP: " . $user_ip;
        watchdog("content",$watchdog_message,NULL,WATCHDOG_ERROR);
        form_set_error('comment_body', t('Embedded links are not allowed for anonymous users'));
      }
    }
  }
}

```

There is a watchdog message that you can use to ban the IP address if you wish. This code goes in a custom module or the template.php file for your theme. I'm using a module as this is functionality only. Replace THEME\_OR\_MODULE\_NAME with the name of your theme or module.
> 1 votes

---
Tags: advertising
---


# Question
Title: Create a module to access a 3rd party API and store the keys in the database
I am new to Drupal module development, and have searched but haven't found any tutorials or guides on how to create a module to do the following:

1. Access a 3rd party API via a form
2. Store the user API key in the database
3. Access the API key when the user uses the 3rd party API via a form submission

Can someone show me how or point me in the right direction for at least steps 2 and 3?

# Answer
You can handle the storage and retrieval of the API keys in the database via the Drupal API functions: variable\_set and variable\_get.

To store the key (step 2):

```
variable_set('mymodule_api_key', $api_key);

```

To access the key (step 3):

```
$api_key = variable_get('mymodule_api_key', t('-key not set-'));

```

Where "mymodule" is the short name of your custom module.

As for a comprehensive example: There are many bridge modules in the Drupal.org repos that connects to an external service using an API and authenticates using API keys. One example of this is Mollom.
> 1 votes

---
Tags: 7, forms, database
---


# Question
Title: Create a view to show comments on a user ONLY from that user
Am using comment as reviews for a content type. Now am trying to create a block in views that will appear on the user profile page. I want to show ONLY comments (reviews) that are from the specific users page i'm on. If the user has no comments made, then the block would be hidden. What settings in views would allow this to happen?

I've tried using content filters and relationship filters but I haven't been able get the right settings. Example: Am on User A's Profile page, I want to display all comments from User A on his profile page.

EDIT: Since my answer really didnt receive anything that can help. I will try to better word the question. I just need to create a block with comments from a specific content type in context to the user profile I'm on. I've created my view and added a contextual filter base off the author uid. But it still shows all the comments not just the ones from the current profile user.

# Answer
You should indeed use a contextual filter, selecting "When the filter value is NOT available", then "provide default value", and choose "user ID from loggued user".

That should work.
> 0 votes

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


# Question
Title: Exclude Views field from displaying and just print it in field template?
I have a field (title) in my View that I want to print in another views field template, using:

```
print ($fields["title"]->content);

```

However, when I use the above code, the field now prints twice. So I tried to Exclude it from the display in Views, but then my above print stopped working. How can I exclude the field, but still print it somewhere else??

Thanks for the help

P.S. I am referring to Views fields, not Content Type fields.

# Answer
Excluding the field from display empties the `$field['name']->content`, so that when the renderer gets to the default field template, there's nothing to print.

If you absolutely cannot achieve your intended result using tokens and **Rewrite Output** then I suggest you:

* Do as you have already done to print the title in a different field's template
* Create a field template for title that is empty
> 0 votes

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


# Question
Title: how to make term reference field choose term from a multi level taxonomy vocabulary
I have a taxonomy voc 'area' that has three levels, region \> province \> town and city.

I then have a content type 'members' which has these three term reference fields that retrieve region, province and town and city respectively from the area vocabulary.

I used feeds to transfer a csv file of members with one member per row, each with region / province / town city. The result after the feed upload looks great.

Using views to make a block and page I have contextual filters show those same terms and they expand quite nicely via a block from region to a province page, each showing how many 'members' there are per page in parenthesis, drilling down to a town and city page. It's all very nice.

However when I try to manually enter a Member I need to enter region, province and town city using a a select field each time. Using hierarchical select doesn't work because I think it doesn't know which level to choose a term from. The result always skews the view, because for example, province field is choosing a town city, or vice versa, or a region. I do not know how to make it choose the level in the select field i want.

I am clueless. I do not even know if I am asking the correct question because I do not know if my error lies elsewhere.

# Answer
Try Simple Hierarchical Select, it is less buggy than the more complex one.
> 0 votes

---
Tags: views, feeds, taxonomy-terms
---


# Question
Title: Private Files System - Media upload works, but image is not displayed
I have set default download method in D7 to private. When uploading images, they are stored in the private folder (OS level). But when having a look to content-media, only a placeholder is visible. The image cant be displayed. Any ideas ?

Thanks

Martin

# Answer
> 1 votes
For the image to be displayed, you would have to have access to the private folder, but since you're an anonymous user to the webserver, it won't display.

Images being served on your website should be in a public folder. Downloads could come from a private folder if the webserver/Drupal moves them to a temp directory before downloading them.

# Answer
> 0 votes
Check fast 404 settings in your settings file...

---
Tags: media
---


# Question
Title: Menu does not appear while opening my site
management menu such as add content type,module ,configuration does not appear in my site. So how can I solve it.

# Answer
> 0 votes
Please login through admin credentials. Check module permissions for Toolbar for authenticated users. Check that if it is unchecked. Try flushing drupal cache.

Once you see the toolbar. You can install admin\_menu for better administration menu.

https://www.drupal.org/project/admin\_menu

---
Tags: routes
---


# Question
Title: Content type creation with table of fields
I want to be able to create a content type with a number of fields (naturally). One section of the content type needs to be like the attached image with the ability to:
\- group items together (e.g. an 'ingredient' in a recipe' - "2 cups flour, sifted"
\- link (via autocomplete) to existing nodes \[INGREDIENT NAME field below\]
\- add multiple items with a "more" button

Below is a screenshot from the 'Recipe' module. Is it possible to create this structure with CCK and can this be then added in a feature?

# Answer
Use field collection to make a group of fields, then set that group to unlimited entries, simple.
> 3 votes

---
Tags: entities, features
---


# Question
Title: Custom search box to be included in a view
I am using the search box provided from the Custom Search module. It works great. I want to know if there is any way by which i can include the search box in a view which i have created. Regards

PS: I tried this but no effect:

```
<?php
  $block = module_invoke('custom_search', 'block_view', 'custom_search');
  print render($block);
?>

```

It displays nothing

Based on below comments i tried doing this:

```
<?php
$block = module_invoke('custom_search', 'block', 'view', 0);
print $block['content'];
  ?>

```

# Answer
If you are trying to filter views result, then adding **Custom Search** block will not work. To get this work you need to add **Global: Combine fields filter** under Add filter criteria, then select fields on which you want to filter the result from **Choose fields to combine for filtering**. Expose this field to display a search text field. Please check screenshot below:
> 4 votes

# Answer
You can not include search box generated by custom search module into views, but you can add exposed filter into views to implement search functionality in the views.

To implement search functionality in the views

* Add "field" in the filter and choose "Contains" from the operator list
* Exposed field in the filer

It will display a search box for that field in the views and work nicely for searching.
> 1 votes

# Answer
You may just try to expose the "Custom Search 1"-block found in the block-list under `admin/structure/block`. In the configuration settings for the block `admin/structure/block/manage/custom_search_blocks/1/configure` you can set the visibility settings for the block to your views-page by inserting your path to the view page.
> 0 votes

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


# Question
Title: Manually enter cck field data into database
I have 1 **content type** and one cck text field. if i create node and enter **title** and **text field** data and click to save save button its create node and enter data into **node and content\_field\_table** perfectly, but if i update cck field data manually into database its not shows update node data.

# Answer
> 2 votes
I can't say I'd advise manually inserting data into the database (there are a lot of API functions for CCK that will help you to do this), but that's for another question.

To make sure the node is reloaded from the database after you've inserted your record(s) just run this code:

```
$node = node_load($node->nid, NULL, TRUE);

```

The third argument to the function is `$reset`, which if `TRUE` will force the node to be built again from the database, not from the static cache.

# Answer
> 0 votes
Have you tried clearing the cache? A lot of things in drupal are being cached, so editing/removing them from their database table might give a conflict with what's in the cache.

# Answer
> 0 votes
I needed to do the same thing in Drupal 6, but ran into issues with the CCK Cache not clearing. I dug into the CCK Module code, and found the method they used:

```
cache_clear_all('content:'. $node->nid .':'. $node->vid, content_cache_tablename());

```

You can find details on cache\_clear\_all() here.

If you use this method, then your manual update code should look like this:

```
db_query("UPDATE `content_type_$type` SET field_$type_$fieldname_value='%s' WHERE nid=%d AND vid=%d",$node->fieldname[0]['value'], $node->nid, $node->vid);
cache_clear_all('content:'. $node->nid .':'. $node->vid, content_cache_tablename());

```

---
Tags: entities, nodes, database
---


title: Charset issue in a webform

text:
# Question
Title: Charset issue in a webform
We have got a multisite structure with several sites. One of the sites has got a webform, from which client needs to download submissions from time to time. However, when we choose to export to Excel using the default values (delimited text and \t as delimiter format), Turkish characters get corrupted on a Windows. I have got no trouble on Linux, but client uses Windows. I must also mention that this behaviour doesn't occur on another site in the same multisite structure. What could I be missing?

EDIT: We are running Drupal 7.34, Webform 7.x-3.21, PHP 5.2.17, and we are using MS Office 2007. I export to Excel using /node/%nid/webform-results/download. I have also tried exporting the Webform to another site on the same multisite structure (hence the same PHP version) and verified it works fine there.
Regards,

# Answer
> 0 votes
After 3 months of dabbling, I managed to solve this by adding some PHP to includes/webform.export.inc:

```
<?php

 if (function_exists('mb_convert_encoding')) {
      $user_agent = strstr($_SERVER['HTTP_USER_AGENT'], 'Windows');
      if ($user_agent) {
        $row = mb_convert_encoding($row, 'UTF-16LE', 'ISO-8859-9');
      }
      else {
        $row = mb_convert_encoding($row, 'UTF-16LE', 'UTF-8');
      }
    }
?>

```

Not sure how to do it for Mac.

# Answer
> 1 votes
This might be a fix for your problem, perhaps you should try this on your test environment: https://www.drupal.org/node/2060519

---
Tags: webforms
---


title: Can't find html.tpl.php

text:
# Question
Title: Can't find html.tpl.php
I'm editing a template of the Seven theme in Drupal 7. I want to change something in the html.tpl.php file, but I can't find where it is located.

Where is it the html.tpl.php file used by the Seven theme? Does the Seven theme have a html.tpl.php file?

# Answer
There is none. To override it, copy `modules/system/html.tpl.php` into your Seven subtheme and change that. Remember to clear cache to make your changes visible.

(Don't hack Seven directly, next core update will overwrite your changes.)
> 4 votes

# Answer
If it is not in your custom theme you can copy from modules/system/ html.tpl.php and change it
> 0 votes

---
Tags: 7, theming
---


# Question
Title: The Facebook Autopost module "user hasn't authorized the application"
I have a problem with the Facebook Autopost module for Drupal 7.28): After publishing a node, I get an authorization error.

> Facebook SDK threw an error: OAuthException: (#200) The user hasn't authorized the application to perform this action

I have checked permissions "*Publish Actions*", "*Publish Stream*", "*Manage Pages*" for Administrator role in *fbpermissions* module.

Also, I have submitted "manage\_pages" in my app but cannot submit "publish\_actions" because of this:

> It looks like you haven't made any API requests to access content with the publish\_actions permission in the last 30 days.

Don't know what to do now. Have no idea why it's not working and what Facebook app permissions are missing. Was googling it for an about 2 hours. Checked all found solutions... none of them worked...

# Answer
This happens when you add any user to roles section and if the user haven't accepted the role and you are trying to post something on his behalf. first accept the role in developers page of Facebook.
> 0 votes

---
Tags: social-network
---


# Question
Title: I get 404 when uploading private *image* files in D7
I have this Drupal 7.15 site (it needs an upgrade, I know).

I have some public and private files in there (all according to my settings). I have a public file field and a private file field.

So, using my private field, I can upload some files that are set to private (I've set the allowed extensions as: .zip, .pdf, .jpg, .png, .gif, and some more). I'm the only user allowed to use the private field.

**When I upload an image file (png, jpg or gif), it does get uploaded ok, but when trying to click on the link I get a "404 error". When there's any other file type uploaded, everything works just fine.**

The private files field is inside a content type that is set as a "group content type".

All files get uploaded ok and they do appear at the list of uploaded files in the normal way.

## Some configuration information

* My Apache file handler is mode\_php (aka DSO).
* Permissions and file owner of all files (images or not) are the very same: rw-rw-r-- (664)
* Group and owner are the same too (images or not): nobody and nobody
* All files are being uploaded to the same folder: ../files/private/filename.ext
* All files get the same symlink: ../system/files/filename.ext

**But only the pdf file is accessible to users (with perms to view the node). Even as an admin I get the 404 error when trying to access the image files.**

What's wrong?

# Answer
> 0 votes
First, have you already checked the status report (/admin/reports/status)?

If that's all green then do you can dig around the content type field settings and also the content type view fields settings to see if you're using any image styles on the images. If you are you need to make sure the folder sites/default/files/styles has proper access perms.

---
Tags: media, files
---


title: Search inside title and body

text:
# Question
Title: Search inside title and body
```
<div class="views-row views-row-1 views-row-odd views-row-first">

  <div class="views-field views-field-name">
  <span class="field-content"><a href="/committees-groups/test-committee1">Test Committee 1</a></span>
  </div>
  <div class="views-field views-field-description"> <div class="field-content"><p>Test Committee one description</p></div>  </div>

  </div>
  <div class="views-row views-row-2 views-row-even views-row-first">

  <div class="views-field views-field-name">
  <span class="field-content"><a href="/committees-groups/test-committee2">Test Committee 2</a></span>
  </div>
  <div class="views-field views-field-description"> <div class="field-content"><p>Test Committee 2 description</p></div>  </div>

  </div>

```

This is the array string i got when i do a print\_r($header); in my template.

```
<?php
                    $doc = new DOMDocument();
                    $doc->loadHTML($header);
                    $links = array();
                    $arr = $doc->getElementsByTagName("a");
                    foreach($arr as $item) {
                    $href =  $item->getAttribute("href");
                    $text = trim(preg_replace("/[\r\n]+/", " ", $item->nodeValue));
                    $links[$text] = $href;
                    }
                    $serch = $_GET['combine'];
                    $arr = array();
                    $arr =  explode(" ", $serch);
                    foreach($links as $key => $value) { ?>
                    <?php if ( stripos( $value, $arr[0] ) !== false ) {?>
                    <div class="views-row"><a href="<?php echo $value; ?>"><?php echo $key; ?></a></div>
                    <?php } }
            ?>

```

This is my code to print the result and search the link title in the array. I need to add the body field (*views-field-description*) to result display and need to search the keyword (`$serch = $_GET['combine'];`) inside the body (*views-field-description*) content.

The title search works fine for me. How can i add it.

# Answer
> 0 votes
It is much more easier to implement this using `views` module. In this tutorial, you can ask user an input, and search on any field in the content type.

---
Tags: search
---


# Question
Title: Views Conditional Fields According to Devices
Does views allows to render fields according to device. For example is there a possibility to load field a if website is loading on iphone, load field b if device is loading on android.

or

load field 1 if website is loading on smart phones, load field 2 if tab and load field 3 if desktop.

# Answer
> 0 votes
As of now, I don't think views supports this. But you can use the Mobile Detect module to achieve this. Note: you need to download the mobile detect library as well and place it in the module folder as specified in ReadMe.txt Then you can use either of the below preprocess functions to detect the device and then return your output to the views template.

- template\_preprocess\_views\_view
- template\_preprocess\_views\_view\_fields

Hope this helps.

# Answer
> 0 votes
You can also create different views and in your template file use a code like this:

```
switch($device){
      case "device1":
           print views_embed_view("VIEW_NAME","PAGE_1");
           break;
      case "device2":
           print views_embed_view("VIEW_NAME","PAGE_2");
           break;
      case "device3":
           print views_embed_view("VIEW_NAME","PAGE_3");
           break;
      case "device4":
           print views_embed_view("VIEW_NAME","PAGE_4");
           break;
}

```

---
Tags: 7, views
---


title: Building a link with l() and t()

text:
# Question
Title: Building a link with l() and t()
I'm trying to build this:

```
<a href="/en/webform?edit[submitted][nameofthepet_webform_fieldset][webform_nume_animal_comp]=NAME-OF-PET" class="btn btn-primary btn-xs">Adopt NAME-OF-PET</a>

```

the code I'm using:

```
$adopt_me_link_male = l(t("Adopt !name",
 array('!name' => $node->field_pet_name['und'][0]['safe_value']), array('context' => 'Male pet name')), 'node/163', array('query' => array('edit[submitted][nameofthepet_webform_fieldset][webform_nume_animal_comp]=' => $node->field_pet_name['und'][0]['safe_value'])), array('attributes' => array('class' => array('btn', 'btn-primary', 'btn-xs'),),) );

```

The above code generates the link but I have two problems:

1. the link looks like this:

Adopt NAME-OF-PET
2. there's no css class applied to the anchor

Why the classes are not applied and the link looks so messy?

Thank you!

# Answer
There is a bug in your URL snippet (syntax error), so I'm writing the code.

```
<?php
$adopt_me_link_male = l(
  t('Adopt @name',
    array('@name' => $node->field_pet_name['und'][0]['safe_value']), //t() function replacements array
    array('context' => 'Male pet name') //t() function options array. Not necessary in this case though.
    ),
  'node/163', // l() function - URL
  array(
    'query' => array(
      'edit[submitted][nameofthepet_webform_fieldset][webform_nume_animal_comp]' => $node->field_pet_name['und'][0]['safe_value'],
    ),
    'attributes' => array(
      'class' => array('btn', 'btn-primary', 'btn-xs'),
    ),
  )
);

?>

```

In this example, I changed `!name` to `@name` for the security (Read `t()` function documentation). Also, if you want to use HTML inside the anchor (say, an image), you have to pass `'html' => TRUE` the last parameter array in the `l()` function (add it along with the `attributes` and `query` array keys).
> 2 votes

---
Tags: navigation
---


# Question
Title: with limit(20) it runs only the first 20 values of DB
In this lines of code it selects only the first 0-20 but i want the first time select the first 0-20 and then the other(20-40) and other(40-60) and so on. How I can solve this problem?

```
 function something_cron()
      $query = db_select('watchdog', 'wa')
        ->extend('PagerDefault')
        ->orderBy('wid')
        ->fields('wa', array('variables', 'type', 'severity',
      'message', 'wid', 'timestamp'))
        ->limit(20);
      $result = $query->execute();

      // Loop through each item and add to $row.
      foreach ($result as $row) {
        someother();
      }

```

# Answer
The common pattern is to store the last ID processed in a variable, using variable\_set(). Then you can retrieve it using variable\_get() with a default of 0 before running your query, and add a condition to the query for wid being greater:

```
$last_id = variable_get('mymodule_last_id', 0);
...
->condition('wid', $last_id, '>')

...
$last_id = value from row
variable_set('mymodule_last_id', $last_id);

```
> 1 votes

---
Tags: 7, database
---


# Question
Title: Views: How can I show a list of users who have a taxonomy term attached via a term reference field?
I'm using the views module's built-in "Taxonomy term" view which overrides the way Drupal displays taxonomy by default and makes it accessible to views. However, this only works for content, not users.

I tried creating a new view that lists users but there is no contextual filter like "User: has taxonomy term", just "Content: has taxonomy term." In my case, however, some of the fields I want to display are term references stored on the user profile; they don't exist on any content.

Ideally, this is what I want: if a user visits the page taxonomy/term/oranges, it will show all users who have "oranges" in a taxonomy reference field. How can I do this?

# Answer
> 2 votes
I ended up implementing this by overriding the taxonomy page with panels instead of views. I then made the old view taxonomy term override into a content pane. Then, to get the "User: has taxonomy term" effect, I made a view (content pane) for each vocabulary with a "Term ID" contextual filter (supplied as a panel argument) and a relationship of "Taxonomy term: User using MY TERM". I then added these views as content panes to the taxonomy override in panels.

I had to do this for each vocabulary, but it works.

# Answer
> 0 votes
I found a different solution by using EVA.

In my case, I have a dentistry website that has a taxonomy vocabulary named as "Expertise" and terms named as "Endodontics, Pedodontology" etc.

Dentist members can choose their area of expertises from this vocabulary on their profile2 pages ("Field: Expertise" as a term referenced field, profile2 is not neccessary at all).

I was trying to show term related dentists on taxonomy term archive pages. So I did this:

1. I created a Profiles block View that displays fields (You can create Users block if you don't use Profile2)
2. Added a Relationship -\> Profile:Expertise
3. Added a Contexual filter -\> (term from field\_expertise) Taxonomy term: Term ID
4. Added an EVA Field
5. Selected Entity Type: Taxonomy Term
6. Selected Budles: Expertise
7. Selected Arguments: id
8. Set up EVA field "Visible" from "Expertise" vocabulary display (admin/structure/taxonomy/EXPERTISE/display

---
Tags: 7, views, taxonomy-terms
---


# Question
Title: Create user in Drupal 8 but password not working
I tried to create user in Drupal8 using entity\_create. The user is created just fine, but I can't login with the password unless I change it from the admin page.

```
$authData['name'] = 'testuser';
$authData['pass'] = 'testpass';
$authData['mail'] = 'sss@test.com';
$authData['status'] = 1;
$account = entity_create('user', $authData);

```

I also tried, the following code (obtained from drush)

```
$account->pass = 'testpass';
$account->save();

```

and also `$account->setPassword`

none of above works.

# Answer
I try with you code, I not see any problem and work for me (drupal 8 beta7).

```
$authData['name'] = 'testuser';
$authData['pass'] = 'testpass';
$authData['mail'] = 'sss@test.com';
$authData['status'] = 1;
$account = entity_create('user', $authData);
$account->save();

```

Note that user and pass are different when you try to log in

user: testuser

pass: testpass

That drupal 8 version are you using?
> 1 votes

# Answer
I am using the following code:

```
$values = array(
'name' => 'test',
'mail' => 'test@example.com',
'roles' => array(),
'pass' => 'password',
'status' => 1,
);
$account = entity_create('user', $values);
$account->save();

```
> 1 votes

---
Tags: entities, 8
---