# Question
Title: These lines of code gets me out this error and i cannot understand it
```
$number_to_keep = db_select('variable', 'va')
    ->fields('va.value')
    ->condition('va.name', 'dblog_row_limit', '=')
    ->execute();

```

And it gets me out that errors:

Notice: Undefined index: table in SelectQuery-\>preExecute() (line 1245 of /var/www/html/drupal/includes/database/select.inc). Notice: Undefined index: table in SelectQuery-\>compile() (line 1079 of /var/www/html/drupal/includes/database/select.inc). Notice: Undefined index: table in SelectQuery-\>compiled() (line 1097 of /var/www/html/drupal/includes/database/select.inc). Notice: Undefined index: arguments in SelectQuery-\>arguments() (line 1024 of /var/www/html/drupal/includes/database/select.inc). Notice: Undefined index: table in SelectQuery-\>arguments() (line 1028 of /var/www/html/drupal/includes/database/select.inc). Notice: Undefined index: table in SelectQuery-\>compiled() (line 1097 of /var/www/html/drupal/includes/database/select.inc). Notice: Undefined index: table in SelectQuery-\>\__toString() (line 1531 of /var/www/html/drupal/includes/database/select.inc). Notice: Undefined index: table in SelectQuery-\>\__toString() (line 1538 of /var/www/html/drupal/includes/database/select.inc). Notice: Undefined index: alias in SelectQuery-\>\__toString() (line 1543 of /var/www/html/drupal/includes/database/select.inc).

# Answer
The signature for `SelectQuery::fields()` is:

```
public SelectQuery::fields($table_alias, array $fields = array())

```

So you need:

```
$number_to_keep = db_select('variable', 'va')
  ->fields('va', array('value'))
  ->condition('va.name', 'dblog_row_limit', '=')
  ->execute();

```
> 2 votes

---
Tags: 7, database
---


title: WYSIWYG Editor for node titles?

text:
# Question
Title: WYSIWYG Editor for node titles?
Is it possible to use a WYSIWYG Editor such as a CKEditor for node titles in the node creation form?

Update: Okay, so let's suppouse that I am developing a newspaper, and I want the journalists to be able to set the size of the title (i.e. if it is a very important news, they will select big font size for the title, otherwise, if it's a regular news, the title size will be medium).

Is the correct way to achieve this through Display Suite Extras, and some CSS classes?

# Answer
> 1 votes
I think there is a module for that --\> https://www.drupal.org/project/html\_title

An other way is probably to use the Body field (or any other) instead of the title and leave the title field as is. You could for example use the Display Suite module for this or alter your content type displays where you need it.

# Answer
> 0 votes
It's possible as @lance mentions, but it is not advisable. The node title is designed to be plain text to be used it several parts of the site including the `<title>` tag in the `<head>`

If you want better control over the `<h1>` tag in your theme I suggest installing Display Suite as there is a setting in the bundled Display Suite Extras module: Page title options - Hide or manually set the page title of the "Full content" view mode.

---
Tags: wysiwyg, nodes
---


# Question
Title: Cron function set to run once per month not completing
I have a cron function that is being triggered but not completing. The function is supposed to run only once on the first of every month. The function runs but, I think, gets as far as comparing the $summary\_sent variable and then stops. Cron is running once every 3 hours.

By changing the $day\_of\_month\_to\_run to the current day and resetting the $summary\_sent variable I can successfully run the full function using cron but, when left to run automatically on the first of the month it fails.

```
variable_set('summary_email_recipients', 'me@example.com');

function appointments_cron() {
    send_monthly_summary();
}

function send_monthly_summary() {
    $recipients = variable_get(summary_email_recipients);
    // run on first of the month
    $day_of_month_to_run = 01;
    $date_string = date('Y-m-'.$day_of_month_to_run);
    // only run on the correct day of the month
    if ( date('Y-m-d') == $date_string ) {
        // check if the process was last run today
        // prevents process being run multiple times on the same day
        $summary_sent = variable_get( 'appointment_summary_sent' );
        if ($summary_sent != $date_string) {
            // do stuff
            // set a record of this process
            variable_set( 'appointment_summary_sent', $date_string );
        }
    }
}

```

Why isn't this running once on the 1st of every month as expected?

# Answer
> 1 votes
I always struggled to get cron jobs running at the right time until I found Elysia Cron. Inside the configuration screen of Elysia Cron you can specify which cron hooks run when, so the standard hooks can be set to run each hour, others each day, each week, each month, etc. and you don't need to worry about coding the date as you've done.

EDIT: I just ran the following code:

```
$day_of_month_to_run = 01;
$date_string = date('Y-m-'.$day_of_month_to_run);
dpm($date_string);
dpm(date('Y-m-d'));

```

The results were 2015-04-1 & 2015-04-15 your 01 is being collapsed to 1, you need to change it to '01'

---
Tags: cron
---


# Question
Title: Why this code cannot delete the rows that i want?
i want keep the 100 rows that has the biggest timestamp and delete all the other rows... Here follow the code that i have create :

```
$values_to_delete = db_delete('table1', 't');
  $values_to_delete->orderBy('t.timestamp');
  $values_to_delete->range(101, 99999999);
  $values_to_delete->execute();

```

# Answer
> 3 votes
The DeleteQuery class doesn't have orderBy or range functions, so I would imagine you would need to write your own DELETE with SELECT subquery. An example from Stack Overflow

---
Tags: 7, database
---


title: Integrate print styles in Omega 4

text:
# Question
Title: Integrate print styles in Omega 4
What is the right or omega way of integrating print styles in omega 4?

I've found no references in the docs.

# Answer
Omega 4 layout styles are loaded last, even after print styles added via the theme's .info file. The only catch-all solution that I'm aware of is to an `@media` rule to your styles. If you need to override a layout's styles you'll need to add an `@media` rule there too.

If you're not using Omega 4 layouts then adding your print styles via the theme's .info file will work - just be aware that this will add an additional stylesheet request and so isn't the most performant option, especially considering how minimal print styles can often be. The `@media` solution wins on all fronts here IMHO.
> 1 votes

# Answer
Like for any css file, add it into the theme's info file, but rather than 'all', just specify it to be only for print.

```
stylesheets[all][] = css/everytime.css
stylesheets[screen][] = css/screen-only.css
stylesheets[print][] = css/print-only.css

```
> 1 votes

# Answer
Just add this to the OMEGASUBTHEME.hacks.scss

```
@media print {

}

```
> 0 votes

---
Tags: 7, theming
---


# Question
Title: Rules condition to check if user is a member of a specific group type?
I'm trying to create a rule where the condition is that the currently logged in user is a member of a specific type of group. Can anyone offer assistance on the proper data selectors to use to build this condition?

For example, we have three types of groups:

Group Type 1 Group Type 2 Group Type 3

The condition, upon login, should be to check if the logged in user is an active member of Group Type 2.

Thanks in advance.

# Answer
> 0 votes
The is a rule action "Rules has role" this should do it.

---
Tags: rules
---


# Question
Title: Date filter using $row data doesn't return any result
I am trying to filter my view by using a date range so that it shows all the activities for an event for which `Activity Start >= Event End & Activity End <= Event Start`.

To do this I have set up a view to show all the activities with a contextual filter to allow the event dates to be accessed.

I added the 4 fields to my table: Activity Start, Activity End, Event Start, and Event End.

My `$Row` data when adding a Global:PHP filter criteria now has the four variables accessible to carry out the comparison above.

* Activity Start: $Row-\>field\_start\_date\_and\_time
* Activity End: $Row-\>field\_start\_date\_and\_time\_1
* Event Start: $Row-\>field\_start\_date\_and\_time\_2
* Event End: $Row-\>field\_start\_date\_and\_time\_3

I am using views\_php 7.x-2.x-dev, which fixed the issue of `$row` not populating.

I am trying to write the above comparison in PHP and I am not getting what I expected. (I thought this would be the easy bit; I have spent a long time getting this far.)

However, it appears that the date format is not being read correctly as it is not returning any result. I have done some research which would indicate it might need to be in Unix timecode to do the comparison accurately.

Is this correct? What does the code look like to do it?

# Answer
You really shouldn't use PHP in Views have you seen the warning on the module page:

> While this module allows you to directly use PHP inside views which may be useful for quick and easy solutions, it is highly advisable to use regular handlers and plugins when available (or even to create one yourself). Take note that filtering and sorting a view using PHP always has a considerable performance impact.

Also this post has instructions how to write a Views handler or Plugin.

You should be able to achieve what you're trying to do with a combination of contextual filters, normal filters and relationships.
> 0 votes

---
Tags: views
---


# Question
Title: Best approach to move content between different instances/installations
As most of us are, I am involved on a project where we have different environments. I have created a profile for the initial installation and we are working with Features to maintain all environments with the same Content Types definition, views, rules, ... When we need to do a change, then we recreate the feature and put in the other environment.

Sometimes I have found I can't do a revert of one feature due to existing data, so I feel interesting and needed to have a very strong mechanism to extract, delete and put again into the site created content.

Also, in the case the customer will use the preproduction environment to start using the application, they will want these contents will be placed into the production environment without the need to create them again.

So I am looking for a strong solution to keep all the contents of the site, easy to backup and move between environments.

I have been playing with: \- node\_export \- node export dependency \- field\_collection\_deploy \- bulk\_copy

But I can't achieve to have a strong copy of the content. One of the content types has Taxonomy references and field collections those are not exported/imported, and at the end of the import I have several Notices as:

```
Notice : Trying to get property of non-object dans field_collection_field_get_entity() (ligne 1679 dans /users/cve00/web/html/sites/all/modules/contrib/field_collection/field_collection.module).

```

Please, I'll appreciate if anybody could point me to the best procedure to accomplish this common need or guide me to do it with these modules if I am missing some operation.

Thanks in advance.

PS.- Even if someone will remove this sentence by editing the post, I feel grateful for your reading :)

# Answer
> 0 votes
After discussion on freenode #drupal, I have had the advice to avoid as much as possible migration or copy-content, so I am going to use a dump from preprod environment to install the production one, what I thought it wasn't the best solution, it seems in this case it will be the simplest and valid.

I'll still appreciate all kind of thoughts of this issue.

---
Tags: importing-exporting
---


# Question
Title: How to assign user with civicrm membership to specific role?
I'm using D7 CiviCRM 4.4.6.

There are two roles in my site: authenticated user, member.

Those who registered in my site is authenticated user. Only users who have active civicrm membership will assigned to both user and member role.

How can I configure the system so that when it run cron, those who have civicrm membership will be added "member" role?

# Answer
> 2 votes
Can't think of any better way to say this than the docs: http://wiki.civicrm.org/confluence/display/CRMDOC/CiviMember+Roles+Sync

makes it really simple and straightforward.

Good luck :)

# Answer
> 1 votes
The way that I have resolved this issue is using CiviMember Roles Sync to tie a membership to a Drupal role.

You can also do similar if the member is an organisation, by creating a smart group out of those that have a certain relationship and then use a similar Civi Groups sync to match it up to a Drupal role.

---
Tags: 7, civicrm
---


# Question
Title: Leaflet library not avaliable even though it's in sites/all/libraries
I've seen people talking about hook\_library() etc., but I'm not creating a custom module, I'm trying to use Leaflet. In the browser I get the error message:

```
L is not defined

```

From leaflet.drupal.js in my sites/all/modules folder. I've got the Leaflet and Libraries modules installed and enabled, and the Leaflet files are extracted under sites/all/libraries/leaflet.

Anyone have any idea what I'm doing wrong?

# Answer
Looks to me like the library hasn't been installed correctly, the path should be `sites/all/libraries/leaflet/leaflet.js` you should be able to append this to your sites URL to load the file.

Have you looked through https://www.drupal.org/node/1954942 to see whether anything helps?
> 0 votes

---
Tags: javascript
---


title: How I can force enable clean url d7

text:
# Question
Title: How I can force enable clean url d7
Today i have transferred my d7 site to a new ubuntu vps, then in the Apache config files i made this change: `AllowOverride None` to `AllowOverride All` and now d7 site is working under clean url.

While transferring the website i have disabled the clean url option from the `admin/config/search/clean-urls`, but here is the difficulty. Now clean url works but in order to enable clean url when i click on the "Run the clean URL test" button then it shows "The clean URL test failed." though it is working :/

I have cleared all the cache data with no luck.

Now what are alternative ways to enable clean url manually in d7?

# Answer
> 6 votes
Clean URL state is managed through the Drupal variable clean\_url.

* clean url disabled: clean\_url is 0
* clean url enabled: clean\_url is 1

You can force this value by:

* Using drush

```
drush vset clean_url 1

```
* Using a direct SQL query

```
UPDATE variable SET value=1 WHERE name='clean_url';

```
* Force a value in settings.php

```
$conf['clean_url'] = 1;

```

# Answer
> 1 votes
Here is a non Drush solution:

The trick,if the clean url test fails on drupal 7 (but you think it should be working) is to edit the url.

Your current url at the clean url page should be; http://www.your-site.com/?q=admin/config/search/clean-urls

So edit it and change it to; http://www.your-site.com/admin/config/search/clean-urls

You should now be able to see the box to enable clean URLs. Enable the clean urls and visit some of the sites inner pages to check that it is working. If you have any problems you can turn them off again here: http://www.your-site.com/?q=admin/config/search/clean-urls

# Answer
> 0 votes
Setting

```
$GLOBALS['conf']['clean_url'] = 1;

```

line 587 in settings.php always work for me.

---
Tags: 7, uri
---


# Question
Title: Comment not respecting line breaks (Drupal 7)
All of my comments for all of my content types do not respect show line breaks. I have tried to dig pretty deep into this issue but I now feel quite stuck.

This is what I discovered.

* The problem is not related to the text formats. (I have verified that *Convert line breaks into HTML* is checked.)
* The problem may have to do with *safe\_value*. I used `dsm()` to show content of the `$vars` variable inside the `hook_preprocess_field()` implementation of the theme, which shows the value of the comment body has line breaks, but *save\_value* doesn't.
* The issue is not related to the format. With `dsm()` I have verified that the comment body is using the *Filtered HTML* input format, which I believe is correct.

This is what `dsm()` outputs for the comment body.

>

# Answer
When I found this problem it was because the results of the filter were being stripped by another filter.

Go to **/admin/config/content/formats** and check your filter processing order. The 'Convert line breaks into HTML' should be the last one.
> 3 votes

# Answer
I came across the same problem and I solved it by visiting `/admin/structure/types/manage/<content-type>/{fields,comment}/display` and changing the format to *Default*. Then, I played with the input formats accordingly.
> 0 votes

---
Tags: 7, entities, comments
---


# Question
Title: How to allow anonymous user register Civicrm event without create drupal account
I'm using D7 CiviCRM 4.4.6.

I had a civicrm event with profile fields for user to fill in.

Anonymous users are allowed to register the event and create civicrm profile.

But there is a "Username" field, which force anonymous user to create a drupal user account when registering the event.

Is there anyway which anonymous user can register in my event, creating profile, without create a drupal user account?

# Answer
Edit the profile that you are using for the event registration and under advanced settings (at the bottom)

select "No account create option" radio and "save"

Good luck!
> 4 votes

---
Tags: 7, civicrm
---


# Question
Title: Printing fields in a View template file (Devel / Krumo)
My "Article" node type has a field image. I can print this field in a node template with

```
<?php print render ($content['field_image']); ?>

```

I have a simple View which lists Articles here. The default Views template /modules/views/theme/views-view.tpl.php prints the content with `<?php print $rows; ?>` (line 58 here).

I want to use my own Views template which will specify the various elements of the node ie print title, print image, print body etc instead of `<?php print $rows; ?>`

I don't think...

```
<?php print render ($content['field_image']); ?>

```

...will work in a Views template so what syntax do I need?

In case it helps I have the devel / krumo output on the page.

I am aiming to use the Views template to control the layout of the Articles in the View, for example I might want the View to look like this:

So I think the default Views template's `<?php print $rows; ?>` is no good for this and I need to isolate the various elements of the View's output (image field etc)

Thanks...

# Answer
> 1 votes
You not using the correct Views template, `views-view.tpl.php` is the base template. You need to use `views-view-field.tpl.php` but you need to use template overrides in your theme.

Firstly, copy `views-view-field.tpl.php` from the Views module into your theme, make a copy of `views-view-field.tpl.php` calling it `views-view-field--field_image.tpl.php` and make your adjustments, remember to clear your template cache so Drupal picks up these files.

# Answer
> 1 votes
you should read this for more info about views templates.

---
Tags: views, theming, debugging
---


# Question
Title: How to recover content/configuration from a hacked site
I have a situation where I am faced with two sites which were vulnerable to the Drupageddon SQL injection exploit. I am looking at what is the best strategy for recovering these websites. Given that the sites were not patched within the alloted window of time, I am forced to assume they have been compromised.

There is a lot of information on what to do after one's Drupal site has been hacked; but one question that is not really addressed is the workflow for recovering content from the compromised site.

In the case of one site, no pre-exploit database backup is available. For the other website, there is a pre-exploit database backup; however, there is a large amount of post exploit content which has been created/updated.

What would be the workflow for recovering content (other than recreating everything by hand). Issues I can think of are:

* How to clean up existing content?
* What tools to use to achieve this?
* How to get the content out of the old site and into the rebuilt one?
* If site is being rebuild from previous DB backup does it make sense to try to only import content which has changed or been added since previous backup? or does it make more sense just to re-import everything?
* How to recover site configuration? Would it be possible to create features and then 'clean' them before installing into rebuilt site?

# Answer
I have never used this module, but it might be worth researching and using on a COPY of your site - Drupalgeddon module.

The first step to recovering from a hacked site is to do an audit of the activity that has taken place. If you have HTTP server logs (apache access logs, etc) you can review the various attack vectors (e.g. POST /node/add, POST /node/3/edit) to identify areas that were compromised. Based on this activity you can formulate a time window when the attacks occurred and search for content edits within that (e.g. checking the "changed" date on the node table). I do know Drupalgeddon does modify records in the users table, so definitely check that.

Either way I think a full audit of the entire database and file-system (pretty sure Drupalgeddon does write to your docroot; hope you have version control to see changes?).
> 2 votes

# Answer
Base on what I have read about "Drupalgeddon SQL injection exploit" the best way to be 100% sure that your website is not vulnerable is to go a old back which you are sure that is not been hack. Ideally it would be anytime before the 7.34 release.
> 1 votes

# Answer
* Start a new site
* Use a new clean drupal and download all needed modules which are used in the old site.
* Setup feeds for every cType from old site to new site. Depending on volume add a manual check of every batch of XX pieces. Check all content after the exploit.
* Re-import everything is the safest way.
* check the roles of all acccounts manually. If they are oke the are within the your wanted restrictions.
* Personally i would do the site configuration by hand but that's depending on how big/small the site is. It is the safest way.

I also used the module Hacked. It gives a indication not more.
> 1 votes

# Answer
First of all, keep in mind that the sql injection vulnerability does not only involve possible compromised content; for example an attacker may have benefit from this exploit in order to log in as user with uid 1 (or create a new user with advanced privileges), thus gaining the possibility to alter content, structure (views, menus, taxonomies, panels e.t.c) and even upload/inject malicious php code (and of course execute it). It is good that you assume the worst case scenario of your sites being compromised, but I would first advice you to actually check/look for confirmation (possible compromisations and their extent) before acting.

How? Unfortunately, mainly manually. Here is a list of some things you should check out first. Then I would personally check the server access logs (using log analyzer software depending on your web server) and Drupal logs (watchdog) for suspicious actions of any kind (e.g. user creation/edits, content deletions/edits, structure alterations in views/panels/CTs). Then, Hacked module, will help you identify any code changes. You might want to skip this step, but answers to these questions and acquiring a general overview of the server/site status will affect the decision/strategy on how to rebuild/clean up your sites:

You are talking about re-building your sites. In the first case you will use the available pre-exploit database backup. OK, this will make sure that content/configurations/structural elements are reverted back to their original state. What about the code? Drupal core, contributed/custom modules? You will use the current live one(s)? Are you sure they are 'clean' and malicious-code-free? What if they are compromised as well? This is why the damage assessment step is highly important. Only after ensuring that your 're-built' (up to the restore point) is safe then you should worry about the additional content missing from the backup. And this gets even harder for the second case - the second website for which no backup is available.

The reason that documentation is missing a data restore/clean up plan, is that simply there is not an optimal plan/solution for all usecases. And the complexity increases if you think the endless ways an attacker might have compromised a site; for a news site for example an attacker (having gained access to a user's account) may have edited an article and changed the original author's opinion or the presented facts (looks like a legitimate edit, no spamming or weird markup, thus it is very difficult to spot). However, there are plenty of tools, modules and processes that can be used to address similar situations/problems.

I would be more than happy to help you compile a recovery strategy, but I need more feedback:

* Were you involved in the development phase of those sites? (as manual checks might be needed, it is preferable if you have a general idea on how the sites are supposed to operate by design and prior to any possible alterations)
* How big/small your sites are? How many CTs? How many fields each? How many instances/nodes in total? Taxonomies? Views? Panels? Webforms?
* Have you been using Features when building those?
* Is code versioned (e.g. git, subversion)?
* Do you have development environments set up for those sites/projects? Are those up to date/synced with their current production versions?
* During the sites' lifecycles, if any additional structural changes were necessary (e.g. change the configuration of a view, add an extra field to a CT), how those were performed? Directly in the live site? Or they were performed/tested in a staging/development environment first?
* Have you created/implemented any custom modules for those sites? Custom themes?
> 1 votes

---
Tags: importing-exporting, nodes, security
---


# Question
Title: When does Views check node_access permissions?
I'm using the book\_access module (https://www.drupal.org/project/book\_access) and I'm finding that it has a good deal of bugs in it.

One thing I've found is in views 3.x, when I'm using a relationship to add the data for the top-level book in a view, and grouping the view results by the top level book, every node that isn't currently in a book doesn't show up since it seems that views isn't getting access permissions for anonymous users.

Though, when book\_access is disabled, or if node\_access permissions are bypassed, these items nodes show up in the view for anonymous users without any issue.

I'm trying to troubleshoot this, and I'm wondering if anyone knows the exact point at which Views 3.x takes node\_access permissions into account so I can muck with some debug statements, etc. Can any one help out?

# Answer
> 2 votes
Views adds the `node_access` tag to it's queries, which allows the implementation of `hook_query_TAG_alter` in the node module to intercept the query and the joins needed to respect node access grants.

The "Disable SQL re-writing" checkbox in the Query options under the advanced settings for the view can disable this behaviour.

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


# Question
Title: Should I make a SOAP or a REST service to receive files from a .Net WCF Service?
I need to implement a web service client in drupal 7 using the Web Service Client module, which receives files from a .Net WCF Service.

Should I make a SOAP Service or REST service using WCF such that the web service client can easily implement the file receiving logic in Drupal/PHP?

# Answer
I have implemented SOAP based web service. And for file transfer I have sent the file contents as an array of bytes and it was successfully received in PHP.
> 1 votes

---
Tags: 7, services
---


title: How to delete a user via REST

text:
# Question
Title: How to delete a user via REST
I'm trying to delete user account via REST API.

Here is my code:

```
// .xml asks for xml data in response.
$service_url = 'http://www.example.com/rest/user/login';

$post_data = [
  'username' => 'test',
  'password' => 'pass',
];

// Format post data as application/x-www-form-urlencoded.
$post_data = http_build_query($post_data, '', '&');

// Set up the request.
$curl = curl_init($service_url);

// Have curl_exec return a string.
curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
// Do a POST.
curl_setopt($curl, CURLOPT_POST, TRUE);
// POST this data.
curl_setopt($curl, CURLOPT_POSTFIELDS, $post_data);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
// Output to command line
curl_setopt($curl, CURLOPT_VERBOSE, TRUE);

// Make the request.
$response = curl_exec($curl);
$http_code = curl_getinfo($curl, CURLINFO_HTTP_CODE);
curl_close($curl);

$xml = new SimpleXMLElement($response);
$session_cookie = $xml->session_name . '=' . $xml->sessid;

// Get token.
$curl_get = curl_init();
curl_setopt_array($curl_get, [
  CURLOPT_RETURNTRANSFER => 1,
  CURLOPT_URL            => 'http://www.example.com/services/session/token',
]);
$csrf_token = curl_exec($curl_get);
curl_close($curl_get);

// A user ID.
$id = 1500;
// The token.
$token = $csrf_token;

// Set up the curl resource
$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, "http://www.example.com/rest/user/$id?access_token=$token");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "DELETE");

$response = curl_exec($ch);

// Close curl resource to free up system resources.
curl_close($ch);

```

It returns:

> Access denied for user anonymous

How do I need to write the code to delete a user?

# Answer
First you need to login:

```
$loginData = ['username' => 'yourusername', 'password' => 'yourpassword'];

$ch = curl_init("http://pathtodrupal.com/endpoint/user/login.json");

curl_setopt_array($ch, [
  CURL_OPT              => TRUE,
  CURLOPTRETURNTRANSFER => TRUE,
  CURLOPT_HTTPHEADER    => ['Content-Type: application/json'],
  CURLOPT_POSTFIELDS    => json_encode($loginData),
]);

$response = curl_exec($ch);

$responseData = json_decode($response, TRUE);

```

Once you send a POST request to login you get the following response back:

> {u'session\_name': u'SESScxx45656f30', u'sessid': u'mOE9NdG6Bk3EADSvKJHGGy8jgkQ', u'token': u'-HVkXhARIynpmJxow5NUIYTRXSc', u'user': {u'status': u'1', u'picture': u'0', u'uuid': u'514c987e7-15f0-43cc-9c6f-53279c216f30', u'uid': u'1', u'language': u'', u'created': u'1310006971', u'init': u'morinfo@dbasepu.com', u'timezone': u'America/New\_York', u'access': u'1429109927', u'theme': u'', u'roles': {u'2': u'authenticated user'}, u'signature': u'', u'signature\_format': u'1', u'mail': u'mor@morinfo.com', u'login': 1429111638, u'data': {u'ckeditor\_width': u'100%', u'form\_build\_id': u'form-60703ffc3';lk6c0fe03cebe9', u'ckeditor\_lang': u'en', u'ckeditor\_show\_toggle': u't', u'last\_category\_id': 1, u'ckeditor\_auto\_lang': u't', u'ckeditor\_default': u't', u'site\_access': {u'1': u'1'}, u'last\_site\_id': 1}, u'name': u'bewmrn'}}

In your subsequent requests you want set the the set in the header the X-CSRF-Token to `$response['token']` and Cookie to `$response['session_name'].=.$response['sessid']`. This should work.
> 1 votes

---
Tags: 7, users, services
---


# Question
Title: How could i configure drush to be always affirmative and verbose in a drush.ini-file?
Could I configure *drush* for non-interacive usage from *bash*-scripts to be always affirmative as I would pass the `--yes` and `-v`-option in `/etc/drush/drush.ini`? I'm aware that I could set a bash-*alias* and that I could set it in `/etc/drush/drushrc.php`. But for reasons of clarity I'd like to use the ini-style-configuration.

# Answer
> 2 votes
Drush will not read options from php.ini / drush.ini by default. Your best option would be to use a bash alias, or set `$options['yes'] = TRUE;` in a drushrc.php file.

If you *really really have to* set an option in drush.ini, you could hack this functionality by writing a policy file. It would look something like this:

```
function policy_init() {
  if (ini_get('drush_yes')) {
    drush_set_option('yes', TRUE);
    // Drush does not expect a globla option to change
    // at this time, so you need to re-call _drush_preflight_global_options().
    // This is not a public API, so the name may change, etc.
    _drush_preflight_global_options();
  }
}

```

The only motivation I can see for doing this is if you already have some fancy mechanism for selecting your php.ini based on context. If you wanted to do that, then put policy.drush.inc in ~/.drush, or some other location where Drush searches for commandfiles.

I have not tested this; post a follow-up comment if you really want to do this and have trouble with it.

---
Tags: drush
---


# Question
Title: Is there any way to connect Acquia Cloud intance with issue tracker?
As in question, I'm looking for a way to connect any issue tracker with a development site hosted by Acquia Cloud.

I want to have a connection between git commits and issues.

Is this possible in Acquia?

# Answer
> 1 votes
I use the combo of BitBucket/JIRA. There are many people that like GitHub's issue tracker too. Acquia has tutorial on setting up either service as a 2nd remote repo. Either service will give you a way to track issues against your commits.

---
Tags: version-control, acquia-cloud
---


# Question
Title: SHS field is not showing in drupal 7 MEFIBS
I am using Drupal 7 MEFIBS module, it will help to add more exposed filter blocks.

But, in this case, SHS filed not showing.

Needs to configure anything in that?

# Answer
> 0 votes
I try using MEFIBS Module and i think This module is not compatible with SHS Module.

BUT Here is another solution of your problem.

if you need multiple instances of "views exposed filter blocks" or any other block then I suggest you to use multiblock Module

following is the method for configuring multiple block instances.

1) install module multiblock Module.

2) Go to Structure-\>Blocks, on the Blocks page there will be an INSTANCES Tab click on it.

3) Give a title to your new instance Block and then select the block you want to create another instance of, from the "Block type" list box.

4) Click on Save

5) Now go to blocks page and find your newly created block instance in the "Disabled blocks" list and configure it in any region, any page you want.

---
Tags: views
---


# Question
Title: Lists the organic groups current user is not a member
I want to create a view that lists the groups user is not a member of. Tried to add the filter criteria -:(author)user:current(no),but it displays the groups user is a member & only filters the groups manage(created) by user. Views-:7.x-3.7 og-:7.x-2.3

# Answer
> 1 votes
You can create a view that lists all groups the current user is *not* a member of, but you need to develop your own custom Drupal module for it (if anybody knows of a simpler way, please share your knowledge).

The general idea is as follows: Create a view that lists *all* groups. In your custom module, implement the hook hook\_views\_query\_alter. There, add a condition to the view's query that checks whether the current user is or isn't a member of a group.

You can create the view that lists *all* groups via the website, or implement it in your custom module as well. For the latter, you can get a rough idea from tutorials like this.

In the database, the memberships are stored in the table `og_membership`. The field `gid` refers to the group's node id in the `node` table. The user who is member of the group is referred as an "Entity". So for each membership, the field `entity_type` is "user", and `etid` is the user id. So, a user is a member of a group if there *exists* a record in `og_membership` with the user's id in `etid`, "user" as `entity_type` and the group's id as `gid`. The other way around, if a user is not member in a group, such a membership record *doesn't exist*. In plain SQL, you could say something like (for user id 123)

```
SELECT n.nid, n.title
FROM node AS n
WHERE NOT EXISTS (
  SELECT *
  FROM og_membership AS m
  WHERE n.id=m.gid AND m.entity_type = "user" AND m.etid = 123
);

```

In your custom module, you need to add this `NOT EXISTS`-Condition to the view's query. To do that, you implement the hook hook\_views\_query\_alter. The following is a rough idea of what the implementation should look like:

```
// the parameters are a reference to the view and the query, respectively
function MY_CUSTOM_MODULE_views_query_alter(&$view, &$query) {

  // get the current user's info from the global scope
  global $user;

  // alter only the query for the correct view, not for every view on the site
  if($view->name == "MY_VIEWS_NAME" && $view->current_display == "MY_CURRENT_DISPLAY") {
    // the subquery to check for memberships
    $member_query = "SELECT * FROM {og_membership} AS m WHERE m.entity_type = 'user' AND m.etid = :uid AND m.gid = node.id";
    // add a new expression to the WHERE part of your view's query
    $query->add_where_expression("AND", "NOT EXISTS (" . $member_query . ")", array(":uid" => $user->uid));
  }
}

```

# Answer
> 0 votes
Try this in your View, using Drupal 7:

**RELATIONSHIPS**

```
OG membership: OG membership from Node group

(OG membership from node group) OG membership: User from OG membership

```

**FILTER CRITERIA**

```
(user from OG membership) User: Current (No)

```

---
Tags: views, organic-groups
---


title: drupal views with contextual filter

text:
# Question
Title: drupal views with contextual filter
I have created a content type page named events where several fields are there. also I have created a view page where list comes of events(title,body and read more). when we click on read more it takes me to the content display page

what I want to do is on display content page i want some sidebar links so that other fields should comes related to that particular node.

# Answer
> 0 votes
is the view page of events when we click on read more its takes me to the content display page (the second image) like there are sponsers block is there of individual node above that i need page links to show other fields which i use to save during creating the node like speakers and other thingd\]

---
Tags: nodes, views
---


# Question
Title: how to remove module-created links from menus?
I've ended up with two basic pages in the navigation menu and there seems no way to get them off.

The pages are just plain ol' pages; the pages are not created by a module. I am using the Drupal 7 core Book Module. One of the pages in question is a book; the other is a child page of the book. The book has other child pages which are not listed in the navigation menu. The Book navigation menu works fine.

* **admin/structure/menu/manage/navigation** has no "Delete" Links by the pages.
* editing the page, there is **no** "add page to menu" specified. I've even tried turning that on, creating a menu item, then turning it off again. The pages still list in Navigation.
* I've tried `drush cc all`

I have the option to disable these pages, but clearly that's just wrong. Can anyone help?

# Answer
> 2 votes
Ok, just in case anyone else finds this useful: I got in this pickle because I installed a module (nodehierarchy) which generated menu items. Menu items created by modules are not deletable in the normal admin UI. When I removed the module it did not clean up after itself, leaving orphaned entries that drupal thought belong to a module that doesn't exist.

I don't know why `drush cc menu` didn't clean them out, perhaps a policy of not deleting data just in case.

To fix: start a mysql client on your drupal db and inspect the contents of menu\_links, find the rows and delete. e.g.

```
mysql> delete from menu_links where module='nodehierarchy';

```

Then clear caches and fixed.

# Answer
> 1 votes
In my case I have two modules which have the ability to add links (that I know of...):

1. Views (/admin/structure/views -\> Edit a View -\> Page Settings -\> Menu)
2. Pages (/admin/structure/pages -\> Edit a Custom Page -\> Click on Menu)

In order to remove the menu links I had to do the following:

1. In the module that creates the menu item (Views, Pages, etc.) set the Menu option to "No Menu".
2. In the menu config (/admin/structure/menu/manage/), go to the menu item and click on "reset" to remove it from the menu.
3. Disable the Custom Page or View (the individual view or page, not the entire module)
4. Re-enable the Custom Page or View
5. The menu item should no longer be present in the menu\_links table.

My issue was related to what seems to be a core problem (see: https://www.drupal.org/node/1058672 OR https://www.drupal.org/node/1029022) which is that if a menu item is created and then removed, it can leave behind a stale record in the menu\_links DB table. Disabling the affected Custom Page or View is what actually removed it from the DB for me.

# Answer
> 0 votes
my problem was very close to the previous one, with some differences;

after an upgrade from D6 to D7, i suppressed some type of contents (better to do it before !!!);

but navigation links stayed under "create content";

i reinitialized every suppressed type of content link (which is not the right way), and it created each time a new "add content" line in the menu;

i went in menu\_links, and suppressed each line with add/content (found in link\_path and router\_path) one (except one)

---
Tags: 7, routes
---


title: Delete system menu links

text:
# Question
Title: Delete system menu links
I'd like to know the best way to delete system menu links. I can't delete them through the UI because they have somehow become stray links (there is no "delete" link next to them).

I've looked at menu\_link\_delete, which calls \_menu\_delete\_item, but that won't hit if `$item['module'] == 'system'` unless I force it which is discouraged.

So... if I can't do it through the Drupal API, do I need to do a DB query? If so, which tables should be involved in the delete? Can I get away with just removing records from the `menu_links` table? It looks like the has\_children value may also need to be altered?

Are there other options besides a DB query which I'm not seeing?

I've also seen this answer, but he just moved the stray links to another menu, which I don't want to do.

# Answer
> 2 votes
Rather than deleting the menu items myself through the DB (see here for possible explanation on how), I decided to try to find the underlying issue, and this is what I found:

In my case I have two modules which have the ability to add links to the menu(that I know of...):

1. Views (/admin/structure/views -\> Edit a View -\> Page Settings -\> Menu)
2. Pages (/admin/structure/pages -\> Edit a Custom Page -\> Click on Menu)

The above modules were adding menu items to the menu which cannot be deleted from the menu system unless you go to the modules and remove them first.

In order to remove the menu links I had to do the following:

1. In the module that creates the menu item (Views, Pages, etc.) set the Menu option to "No Menu".
2. In the menu config (/admin/structure/menu/manage/), go to the menu item and click on "reset" to remove it from the menu.
3. Disable the Custom Page or View (the individual view or page, not the entire module)
4. Re-enable the Custom Page or View
5. The menu item should no longer be present in the menu\_links table.

My issue was related to what seems to be a core problem (see: https://www.drupal.org/node/1058672 OR https://www.drupal.org/node/1029022) which is that if a menu item is created and then removed, it can leave behind a stale record in the menu\_links DB table. Disabling the affected Custom Page or View is what actually removed it from the DB for me.

# Answer
> 1 votes
As shown in the example you linked to, you can not only move the menu items to another menu using `hook_menu_alter()` but also unset them. There is no point in deleting menu links in the database that are defined by enabled modules via `hook_menu()`. They'll simply repopulate the menu\_links table when the menu cache is cleared. Module-defined menu links can be disabled, however.

---
Tags: routes
---


# Question
Title: Looking for a Module to allow presentation of data like a Microsoft Access Table
A client that is currently using Microsoft Access to manage some reporting tasks would like us to extend a custom module to allow them the same (or similar) functionality on their website.

I was looking at Data Tables which has a Drupal module and that would get us most of the way there however I wanted to reach out to the experts out there to see if there are any better solutions.

Their website is currently Drupal 6 but we may be rebuilding it in Drupal 7 so I will need solutions for both versions.

**EDIT** I'm interested in displaying data tabularly, but also need to have the filtering and sorting options on the columns. Data Tables has the sorting down but I don't see how it can filter.

Thanks in advance!

# Answer
So I think Data Tables are the answer in this case. I looked at the site more and they do have everything I need on the extras page

I'm not sure if the module supports add-ons so maybe I will have to update it a little.
> 0 votes

# Answer
Take a look at Node Table module.

* Generates sticky headers automatically
* Supports flexible column sorting on none, one, or multiple columns
* Supports a default sort column with asc / desc option
* Supports add, delete, edit of rows and columns
* Supports drag and drop reordering of rows and columns (row reordering works only when no column sorts are enabled)

> NodeTable module is a versatile module for handling HTML tables on Drupal sites. The module provides functionality for creating, uploading, editing, and presenting HTML tables within nodes or as nodes.
> 1 votes

# Answer
Not sure if this is going to be of any help, but did you consider the possibility of using: Views: format as table and Better exposed filters.

Regards
> 1 votes

# Answer
Another great module for filtering and doing things to nodes (or comments or users) is Views Bulk Operations. You can do all the exposed filtering you want and then it lets you apply a wide variety of commands to the selected rows.
> 1 votes

# Answer
Attempt to answer this part of the question:

> I'm interested in displaying data tabularly, but also need to have the filtering and sorting options on the columns. Data Tables has the sorting down but I don't see how it can filter.

1. If it's only a matter of **displaying the tabular data**, I usually just use the datatables module for that. It seems to work like a charm to me. Here are a few online samples to see that module at work (a rather basic views display, using the dataTables views style):

* AbitMORE-scm.com: experiment with the search box in the upper right, eg first type "without" in it, see what happens, and then continue typing so that it becomes "without packages". Doing so you'll only get the rows displayed the contain both keywords somewhere in any of the columns (= 'and' operation), in this sample "without" in 1st column and "packages" in 2nd column.
    * Dr.Chgman.com: similar suggestion for the search box, like "zmf z- 1.2" (pause a few secs before typing the spaces in between).

The sorting of the tables for both samples is obvious of course (I think / hope). Just using the tiny triangles of any column you want, either ascending, or descending. Obvious, these samples are views displays. From the OP I am not sure if it is about a views display or not however. Maybe enhance the question to clarify that a bit?
2. If the question is also to **retrieve the data from an external (to Drupal) database**, and/or **if we're not talking about some view here**, then I use the Forena module (and not the datatables module). In that case I can still use the datatables plugin (not the module), because for that I just need to specify so in the "skin" that I want Forena to use for my report. Skins in Forena are used for theming reports created by forena, to add just any CSS and/or JS. If relevant for this question (the MS Access makes me doubt if yes or no), I'd be happy to enhance this answer with a few more details on forena and/or its skins.
> 0 votes

---
Tags: 7
---


# Question
Title: Changing filter plugin settings before they are saved
(This is for D8, although parts of this filter settings API were already in D7.)

As far as I understand, a filter plugin exposes its settings solely with `FilterBase::settingsForm()` \- the central architecture then automatically stores the submitted form values and loads them when creating the plugin instance, so that a filter plugin can find them in `$this->settings`.

I'd like to reorganize and clean up the submitted form values before they're stored, but I'm not sure where to intercept the form. Should I attach a #validate or a #submit? If the latter, how do I ensure that my #submit runs before `FilterFormatInterface::submitForm()`?

# Answer
My new approach reverses the situation. Apparently I can't alter the structure of the values after the form is built - but I *can* change how the form is presented.

So instead of building the form in the user-friendly structure A and then failing to convert the values to developer-friendly structure B, I'll build a form as B and use a #theme hook to render it as A.
> 0 votes

# Answer
It looks like your only options right now are relying on generic form API features, like #process and #value\_callback. FilterFormatFormBase doesn't call into the plugins for validate/submit, like we do for example for block plugins.
> 0 votes

---
Tags: forms, 8, input-formats
---


# Question
Title: Allow authenticated users to create taxonomy terms
Currently I categorize content using nodes as categories, because authenticated users cannot create taxonomy terms.

What would be the way(s) to accomplish a term/add page for authenticated users?

# Answer
Taxonomy Access Control provides finer control of taxonomy permissions, that sounds like what you need.
> 1 votes

---
Tags: taxonomy-terms, users
---


# Question
Title: How to subtract two columns with db_select()?
I have a db\_select query that outputs two columns. I want to find the difference between these columns, output to another column, and then put a condition on this third column.

Here is a mysql query that I want to convert into db-select:

```
"SELECT *, `column1value`-`column2value` AS `difference` FROM `mytable` WHERE `difference` > 55"

```

# Answer
> 1 votes
You're looking for MySQL's `HAVING`, which permits `SELECT` level aliases.

So this:

```
SELECT *, `column1value`-`column2value` AS `difference`
FROM `mytable`
WHERE `difference` > 55

```

Becomes this:

```
SELECT *, `column1value`-`column2value` AS `difference`
FROM `mytable`
HAVING `difference` > 55

```

Which in Drupal-ese is:

```
$query = db_select('mytable')
  ->fields('mytable')
  ->having('difference > :floor', array(':floor' => 55));

$query->addExpression('column1value - column2value', 'difference');

```

For a simple calculation like this example performance would be better using the expression directly in a `WHERE` clause. In the example you've given in your answer, I suspect `HAVING` would be quicker (although MySQL's pretty smart, it may be able to cache that calculation)

# Answer
> 0 votes
It turns out that you can't use an MySQL expression in a conditional: the above MySQL doesn't work.

Here is an example db\_select() query that I came up with, that finds the difference between two flagging timestamps, and then makes sure that it's between two thresholds. I'm concerned that it's calculating the difference 3 times, but there doesn't seem to be a way around it, since the "duration" alias can't be used anywhere else, not even with raw MySQL.

```
$query = db_select('node', 'n');
$query->leftJoin('flagging', 'fass', 'fass.entity_id = n.nid AND fass.fid = :assigned', array(':assigned' => $task_assigned_fid));
$query->leftJoin('flagging', 'fcom', 'fcom.entity_id = n.nid AND fcom.fid = :completed', array(':completed' => $task_completed_fid));
$query->condition('fcom.timestamp', $this->date_endpoint0, '<');
$query->condition('fcom.timestamp', $this->date_endpoint1, '>=');
$query->condition('n.type', 'task', '=');
$query->isNotNull('fass.uid');
$query->isNotNull('fcom.uid');
$query->fields('n', array('nid'));
$query->fields('fass', array('timestamp'));
$query->fields('fcom', array('timestamp'));

// Note that we are calculating the difference three times.  I'd prefer to do it once.
$query->addExpression('fcom.timestamp - fass.timestamp', 'duration');
$query->where('(CAST(fcom.timestamp as SIGNED) - CAST(fass.timestamp as SIGNED)) < :threshold0', array(':threshold0' => $threshold0));
$query->where('(CAST(fcom.timestamp as SIGNED) - CAST(fass.timestamp as SIGNED)) > :threshold1', array(':threshold1' => $threshold1));

```

---
Tags: database
---


# Question
Title: How to modify account page adding possibility for a user to chose one of 2 roles
I have Drupal 7 installed on my WAMP localhost. I need to add a widget to the account page to allow users to chose 1 of 2 roles (recruiter or applicant). Having chosen one role the user cannot switch back to the other again. For particular reasons I do not consider possibility to chose role DURING registration.

I have read and searched a lot on this subject recently but have not yet found the solution. I understand it can be done with the help of hook\_form\_alter() in a module? Then I need to update the users\_roles table

Could you please guide me a bit through the code or tell me where I can find some examples.

Thank you.

---

Meanwhile I moved on - I have created the module with hook\_form\_alter(). The 2 radiobattons show up on non admin user's page (see attached screenshot).

The code is missing saving to the database and probably validation is also required - I dont know where to go yet. Looking forward to your comments/corrections of the below code which is far from being professional.

```
<?php
/*
 * Implements hook_form_alter().
 */
global $user;
if($user->uid !== 1) {
function testpwd_form_alter(&$form, &$form_state, $form_id) {
#   krumo($form_id);

    switch ($form_id) {
        case 'user_profile_form' :

// Adding radiobuttons
            $form['account']['roles']['#type'] = 'radios';
            $form['account']['roles']['#title'] = 'Role';
            $form['account']['roles']['#weight'] = -20;
            $form['account']['roles']['#access'] = true;
            $form['account']['roles']['#default_value'] = '';
            $form['account']['#access'] = true; /*without this Roles do not show up on autheticated
            user's profile page. I think after setting it to TRUE access for the nested elements has also
            changed to TRUE. I need to check what changed and set access to False for some nested elements.  */

            $form['account']['current_pass']['#access'] = false; /*see comment 1 line above.
            Not needed on this page as for changing passwords users are directed to Master site
            (2 sites joined with Bakery sso module).*/

            $form['account']['roles']['#options'][115362423] = 'applicant';
            $form['account']['roles']['#options'][100482362] = 'recruiter';

//To hide Roles options appeared. Where hide() does not work I used unset()
            unset($form['account']['roles']['#options'][30037204]); // admin
            hide($form['account']['roles'][2]); //auth users
            unset($form['account']['roles']['#options'][139881272]);
            unset($form['account']['roles']['#options'][29617163]); //content admin

            krumo($form);

//nice print of arrays
            echo '<pre>', print_r($form, true), '</pre>';
        break;

    }
  }
}

```

# Answer
The drupal module Auto Assign Role allows you to do this (users can select during registration, not afterwards).

The module name is a little misleading because although one of its features is allowing for automatically assigning roles to users, another of its features is to allow users to select a role for themselves.
> 0 votes

---
Tags: users
---


# Question
Title: Using jquery-match-height to set two blocks to equal height
I'm new to jquery and adding it to Drupal. I'm trying however to add this library to my Drupal site so I can set two of the blocks on my home page to equal heights. But it's not working and I'm not sure why.

Here's the library:

https://github.com/liabru/jquery-match-height

The items on the home page to make equal are in two different regions in the zen subtheme. They are separated by a third region in the middle. Here's how the regions look in the tpl:

```
  <?php print render($page['featured_resource']); ?>
  <?php print render($page['hp_video']); ?>
  <?php print render($page['whats_new']); ?>

```

Note: because I'm using Zen I've used Zen grids to make all these items be on the same 'row' (the same zen\_clear()). Not sure if this might cause problems with the way the jquery is coded.

I want to set the blocks within the 'featured\_resource' and 'whats\_new' to the same height. The blocks contained within those regions I've given the same class as each other: 'feat-res'.

I've added my jquery library and code file to my pages using drupal\_add\_js in my template file like so:

```
function mytheme_preprocess_page(&$vars) {
    drupal_add_js(drupal_get_path('theme', 'my_theme') . '/js/jquery.matchHeight.js');
    drupal_add_js(drupal_get_path('theme', 'my_theme') . '/js/matchHeightHP.js');
}

```

I think it's calling it correctly because when I firebug the page those .js files are showing up in tags.

The code I've put in the file matchHeightHP is simply this:

```
(function() {
    $('.feat-res').matchHeight();
})();

```

So that's where I get especially unsure. I tried to model it after the examples given on the link I referenced at the top, but as a jQuery newbie I really don't know if this is correct or not. Any help would be appreciated.

The blocks on my home page continue to look very uneven as the content on one is much great than the content on the other. I want them to both be equal to the height of the block that has more content.

# Answer
Have you already tried out the Equal Heights jQuery module? This module does exactly what you want, without having to create custom code and works fine with Zen.
> 1 votes

---
Tags: theming, javascript
---


# Question
Title: No menu link is working after the website is deployed on hosting server
I developed a website in the drupal and I have been accessing it in the development environment using the url like this "http://localhost/foldername"...

Now I have deployed the website (the folder "foldername" and database) to my Linux based hosting server.

I have to access it for testing using a URL like this "http://HostingServerIpAddress/~HostingServerUserName/foldername".

To my surprise, no menu link is working over there :( the paths are correct. The menu links which were opening in my local environment, are giving 404 error when opened using hosting urls... :(

Please guide me at your earliest.

# Answer
When I move a site to the production environment and can only access it using an URL as you describe, I have to disable Drupal's 'Clean URLs' functionality (`admin/config/search/clean-urls`) in order for menu links to work properly (and probably clear the caches afterwards).

**Edit:**

In the documentation on configuring clean URLs, I found that changing the RewriteBase setting in the .htaccess file is the solution for me to have clean URLs once again.

So, in your case it probably should be: `RewriteBase /~HostingServerUserName/foldername`
> 1 votes

---
Tags: migrations
---


title: Landing Page Based on Role?

text:
# Question
Title: Landing Page Based on Role?
Use Case - I've got several Dashboards (some custom View pages) in the site. Depending on the Role associated with a User, I want to direct them to thier respective Dashboard.

So an Editor would go to the Editor Dashboard, a Contributor would go to a Contributor Dashboard, etc. after they login.

(I'm using the OpenPublic distro)

# Answer
> 2 votes
You can redirect user after checking their role(by using below PHP snippet)

```
<?php $GLOBALS['user']->roles; ?>

```

Your code will look something like this:

```
<?php
if($GLOBALS['user']->roles == 'editor') {
  drupal_goto("dashboard_editor"));
}
?>

```

Note: this will work only when a user has single role associated with him.

# Answer
> 2 votes
You can use a panels for the dashboard and then create different variants based on roles using the Access rules.

# Answer
> 1 votes
Checkout the login destination module. Simple as that.

https://www.drupal.org/project/login\_destination

# Answer
> 0 votes
Few methods you could do this:

1) `hook_init()` \- check user's role and redirect to the correct address.

2) With the Pages module, you can set each panel's (=view's) display rule as having a certain role. With this you can stay at the same address (say, `/dashboard`)

---
Tags: users
---


# Question
Title: how to filter blog posts by taxonomy and by year
I have been trying to build a filter fuctionality for blog posts. I would want to filter by taxonomy terms and by the year the post was published. So basically in the content I want to list all blog posts – on sidebar I would have all used taxonomy terms listed and also a list of all years/months when post have been published.

Additionally I want the filter to be reflected by the URL structure:

* For a URL like `domain.com/blog/2014` all posts from 2014 would be listed.
* For a URL like `domain.com/blog/cars` only posts tagged with 'car' would be listed.

Is there a module to do this – or should this be done with views? I have been trying to do this with views now but with not much luck. Especially with the url I don't understand how i can do that. Or if there is some tutorials on somewhere – that would help also.

# Answer
You're on the right track. Views is good way to solve this with Contextual Filters. You need to create a page view with the path **blog**. That will create a page **example.com/blog** that shows all blog posts.

Adding a `Content: Created year` contextual filter will set up a filter rule so that **example.com/blog/XXXX** filter the view by posts created on year **XXXX**.

For your last need, tag filtering, you're going to need to add another page view since a page view can't do a mixed contextual filtering; views doesn't know how to treat **XXXX** in **example.com/blog/XXXX** as both a year or tag.

See this post on how to set up a filter `Content: Has taxonomy term ID` filter that will you create something like **example.com/tags/YYYY** where **YYYY** is the name of your tag.
> 0 votes

---
Tags: taxonomy-terms, views, nodes
---


# Question
Title: Prevent users of role from being flagged?
The Flag module is pretty robust, so maybe I am missing something. It has a lot of access features as to who can flag/unflag but I can't seem to find a way to prevent a user/role from being flagged.

Scenario: Creating a flag where all administrators posts should not be able to be flagged but "authenticated users" should be able to flag other content for other roles. All roles content should be flaggable except for administrators (or "premium users")

There doesn't seem to be a "if user is of role X, disable the ability to flag/unflag using FLAG NAME" permission or setting.

# Answer
Here is a sample code you could use for your custom template.

```
// Load the currently logged in user.
global $user;

// Check if the user has the 'standard' role.
if (in_array('standard', $user->roles)) {
  // enter the code to print your flag
}

```
> 2 votes

---
Tags: 7, flags
---


# Question
Title: Pager should start from last page instead of first one
I have a block view including pager and shown on front page. when I go to front page I see the pager under block shown in normal way(ie start from first page). But I want that pager start from last page instead of first one.

**Result of My View:**

**Result that I want:**

I want that when I visit my view, it's pager should look like this

# Answer
At the view, you can use SORT CRITERIA. It can help you arrange in post date, title page or even content field.
> 0 votes

---
Tags: views, paging
---


title: Path alias tokens and node references

text:
# Question
Title: Path alias tokens and node references
I'm trying to figure out if path aliases are even capable of what I'm trying to do, or if I need some other sort of module.

I have a content type "project" and a content type "mockup". A "project" references a User. A "mockup" references a "project". I'd like the path pattern for a mockup to look something like (I'm making up the token names, but you get the idea)

`[referenced_project's_reference_user]/[referenced_project's_title]/[node:title]`

Now another thing is that the project path already looks like the first part of the mockup's path:

`[project's_referenced_user]/[node:title]`

So I'm wondering if there's a way for a token to get the url of the referenced node or something? I was hoping you could stack tokens something like: `[[related_project]:url]` but that doesn't work.

If you can't tell, I'm using the "references" module.

# Answer
> 10 votes
You certainly can.

You need Entity and Entity Token (comes with Entity module) modules.

Clear cache after enabling them. The referencing node info will be available to you.

For the 'referencing' functionality, I use Entity Reference instead of Node Reference which will most probably be deprecated in the near future in favor of Entity Reference. (but I remember node reference info is also available in Pathauto pattern, you may try yourself)

# Answer
> 2 votes
If you have a parent-child tree hierarchy created using entity reference fields you can use:

\[node:entity-reference-field:url:path\]/\[node:title\]

You need the modules referenced in gilzero's answer above installed

# Answer
> 0 votes
Also note that you only get values \[node:fild-entityref:title\] IF your entityreference field "number of values" is set to 1.

If you use 'unlimited' or more than 1, tokens are changed to \[node:fild-entityref:(0,1,2,3...):title\]

In my case using the unlimited and then picking up the right item from the list(0), broke the token and the result was empty. Tried with multiple variations to get it to work but without success.

---
Tags: 7, uri, path-aliases, tokens
---


# Question
Title: Add content -> taxonomy autocomplete input field size
My content type has a taxonomy auto-complete field. My problem is that some content requires like 10-20 taxonomy terms where my input field for it is way to small.

I don't see in my 'manage fields' settings where I can define this length.

# Answer
> 1 votes
You can use the Entity Reference module; it allows the size of the autocomplete input field to be changed.

# Answer
> 0 votes
Just saw in a similar question this info : https://www.drupal.org/project/autocomplete\_deluxe "This is an enhanced autocomplete element, that uses the JQuery UI autocomplete. It will also implement a widget for taxonomy."

---
Tags: 7, taxonomy-terms, ajax
---


# Question
Title: duplicate entry on using commerce_product_ui_product_type_save()?
Reference to the code https://www.drupal.org/node/1059624#comment-4083864

```
 $product_type = commerce_product_ui_product_type_new();

  $product_type['type'] = 'prestation';
  $product_type['name'] = t('Prestation');
  $product_type['description'] = t('A basic prestation.');
  $product_type['is_new'] = TRUE;

  commerce_product_ui_product_type_save($product_type, FALSE);

```

When I execute the folllowing code given above I get a

> PDOException: SQLSTATE\[23000\]: Integrity constraint violation: 1062 Duplicate entry 'prestation' for key 'PRIMARY': INSERT INTO {commerce\_product\_type} (type, name, description, help, revision) VALUES (:db\_insert\_placeholder\_0, :db\_insert\_placeholder\_1, :db\_insert\_placeholder\_2, :db\_insert\_placeholder\_3, :db\_insert\_placeholder\_4); Array ( \[:db\_insert\_placeholder\_0\] =\> abcs\_new15 \[:db\_insert\_placeholder\_1\] =\> abcs new15 \[:db\_insert\_placeholder\_2\] =\> abcs new15 \[:db\_insert\_placeholder\_3\] =\> \[:db\_insert\_placeholder\_4\] =\> 1 ) in drupal\_write\_record() (line 7239 of

# Answer
You are getting the error because you are setting `$product_type['is_new']` to `TRUE`, which is saying to the module the product type is new, but that evidently is not true. That is what the error is telling you.

Set `$product_type['is_new']` to `FALSE`, or don't set it at all, and you will not get any error.

If you are programmatically creating new product types, be sure you give to `$product_type['type']` a unique value for each of the product types you create.

### Reference
> 1 votes

---
Tags: commerce
---


# Question
Title: Can we return 2 table themed arrays in function
I have 2 arrays, but the 2 have different key values you can see in foreach for one it is src, where as for another it is source. I would like to show the both both tables on one hook. But this seems not working.

# Answer
The issue is you're passing elements that a render array would use, such as the "#rows", "#sticky", etc, but Form API will ignore them, because anything prefixed with a "#" will be treated as a property of the form element.

Clive gives here (https://drupal.stackexchange.com/a/27269/28556) a very concise explanation and solution for that, which consists in creating your own theme function to render a particular element.

Additionally, I think you could, as well, use the existing theme('table', ...) function to render the table from that same function, but returning the results as direct markup instead.
> 1 votes

---
Tags: 7, forms
---


# Question
Title: Saving a particular field of a related entities with Entity Reference
Using Drupal 7, using entity and entity reference i have created 2 entities: --\*Aircraft reservation (date, user, aircraft categorie) \*Aircraft categories (name)

I have created a view (entity reference view) to list all aircraft categories.

Aircraft reservation reference aircraft categories. In the form subbmission of Aircraft reservation i can see the list of the categories. The reference link with the view work great.

But when i submit the form, instead of having the categorie of the aircraft which i has selected saved, i have the details of the entity that present the categorie which i had selected.

With other words, Instead of saving the value of the field name of the categorie, drupal save the details of the entity.

How can i fix that ? Thanks for all !

# Answer
I think the content is saved correctly but displayed wrong. Try to change your View which displays the results (the table). On the field for the entity reference, you should have an option to change the **Formatter** of the displayed entity. I think you have currently "Rendered entity" selected. Try to change to **Label** to only show the title of the referenced entity.

You could also display a different **View mode** for the rendered entity to show more/different fields. Check the Display Suite Module for this.
> 0 votes

---
Tags: views, entities
---


title: Change format of product attribute

text:
# Question
Title: Change format of product attribute
I have products with a few options.

* Option 1: Same price.
* Option 2: -50 cent ($9.50).
* Option 3: -$1 ($9).

Can I change the display so that it looks like this?

* Option 1:
* Option 2: ($0.50 off)
* Option 2: ($1.00 off)

# Answer
> 1 votes
In uc\_attribute.module file comment out from line number 1360 (starts at if ($adjustment != 0) {) to 1363 and add the bellow code

```
if ($adjustment != 0) {
    //$display_price = $adjustment > 0 ? '+' : '-';

    //this variable is used to flag your custom discount on minus values
    $set_discount = false;

    if($adjustment > 0){
        $display_price = '+';
    }else{
        $display_price = '(';
        $set_discount = true;
    }
    if($set_discount){
        $display_price .= uc_currency_format(abs($adjustment)). ' off)';
    }else{
        $display_price .= uc_currency_format(abs($adjustment));
    }
}

```

---
Tags: ubercart
---


# Question
Title: Delete old columns from table using hook update
I need to delete some old columns of existing table. How to do it using `hook_update` or Is there some other way to delete old columns in `.install` file .

Thanks

# Answer
> 5 votes
You can use function db\_drop\_field()

```
/**
 * Implements hook_update_N().
 */
function mymodule_update_7001() {
  db_drop_field('my_table', 'my_column');
}

```

---
Tags: 7, updating
---


# Question
Title: Display Special Characters in Drupal Forms API
I have a variable fetch from database which contains special character `ñ`. For Example:

```
$student = 'Evangeline O. MontañO';
$student = 'Rosalyn G. QuiñO';

```

Displaying it in my form causes ajax error, but when I use `check_plain` function it returns an empty string and no ajax error occur. How can I display a variable with special characters on it without causing ajax error?

# Answer
> 1 votes
I suspect you need to add `<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />` into `html.tpl.php` in your theme. This isn't an issue with Drupal, but your browser not recognising the UTF8 characters.

---
Tags: forms
---


title: cURL error (60) SSL certificate problem

text:
# Question
Title: cURL error (60) SSL certificate problem
On my local Wamp, I am trying to import feeds using the Feeds and import.io modules.

Each time I get the following error:

> cURL error (60) SSL certificate problem, verify that the CA cert is OK. Details: error:14090086:SSL routines:SSL3\_GET\_SERVER\_CERTIFICATE:certificate verify failed for https://api.import.io/store/connector

The error doesn't occur on my hosted environment.

I have looked HTTPS and SSL3\_GET\_SERVER\_CERTIFICATE:certificate verify failed, CA is OK, and tried adding my php.ini files located in:

* C:\wamp\bin\php\php5.3.0
* C:\wamp\bin\apache\Apache2.2.11

Adding `curl.cainfo = "C:/wamp/www/dev/curl/cacert.pem"` doesn't get any result.

# Answer
> 1 votes
Locally you can disable the error by adding this to your curl options:

```
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

```

This forces curl to not verify your local cert.

---
Tags: feeds
---


# Question
Title: Need to send "High" and "Critical" priority only in email subject line itself
I'm using Support Ticket System module and I need to send ticket "High" and "Critical" priority along with subject line of an email. Can i do the same through coding part as i have tried from mail settings tab of support ticket system, help if anyone have an idea.

Thanks.

# Answer
> 1 votes
A possible solution might be to use hook\_mail\_alter to modify the subject. As far as I have seen, the Support Ticket System uses `drupal_mail()` to send notifications, so this hook would be invoked.

Hope it helps,

---
Tags: hooks
---


# Question
Title: Get values from ajax replaced text field in a form
On a edit page I added a form so the user can select what he wants to edit. With that info I used ajax to show the info which belongs to that item.

But when submitting the form it isn't taking the values the way as I did it in a normal form. In this way (see code below) it gives an error: Notice: Undefined index: replace\_textfield in push\_notifications\_edit\_app\_form\_submit()

And When I leave out the \['replace\_textfield'\] part it gives no error but the values contain nothing.

Here is my code:

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

$query = db_select('push_notifications_api','pt');
$query->distinct();
$query->fields('pt',array('app_name'));
$result = $query->execute();
foreach ($result as $record){
$options[$record->app_name] = $record->app_name;
}

$form['title'] = array(
'#type' => 'fieldset',
'#title' => t('Edit application'),
'#description' => t('Select the application you want to edit.'),
'#tree' => TRUE,
);

$form['title']['changethis'] = array(
'#title' => t("Application Name"),
'#type' => 'select',
'#options' => array(
  'Select Application',
  $options,
),
'#ajax' => array(

  // #ajax has two required keys: callback and wrapper.
  // 'callback' is a function that will be called when this element changes.
  'callback' => 'push_notifications_edit_app_form_callback',

  // 'wrapper' is the HTML id of the page element that will be replaced.
  'wrapper' => 'replace_textfield_div',
  // There are also several optional keys - see ajax_example_autocheckboxes // below for details on 'method', 'effect' and 'speed' and // ajax_example_dependent_dropdown for 'event'.
),
);

// This entire form element will be replaced whenever 'changethis' is updated.
$form['replace_textfield'] = array(
// '#type' => 'textfield',
// '#title' => t("Why"),

// The prefix/suffix provide the div that we're replacing, named by
// #ajax['wrapper'] above.
'#prefix' => '<div id="replace_textfield_div">',
'#suffix' => '</div>',
);

// An AJAX request calls the form builder function for every change.
// We can change how we build the form based on $form_state.
if (!empty($form_state['values']['title']['changethis'])) {

$form['replace_textfield']['edit'] = array(
  '#type' => 'fieldset',
  '#title' => 'Application data',
  '#description' => 'Edit your application data here.',
  '#tree' => TRUE,
  );

$app_name = $form_state['values']['title']['changethis'];
$app_id = db_query('SELECT DISTINCT app_id FROM push_notifications_api WHERE app_name = :appname LIMIT 1', array(':appname' => $app_name))->fetchField();
$gcm_key = db_query('SELECT DISTINCT GCM FROM push_notifications_api WHERE app_name = :appname LIMIT 1', array(':appname' => $app_name))->fetchField();
$ios_key = db_query('SELECT DISTINCT ios FROM push_notifications_api WHERE app_name = :appname LIMIT 1', array(':appname' => $app_name))->fetchField();
$form['replace_textfield']['edit']['app_id'] = array(
'#type' => 'textfield',
'#title' => 'Application ID',
'#description' => 'Enter the application ID here.',
'#value' => $app_id,
'#required' => TRUE,
'#size' => 20,
'#maxlength' => 20,
'#weight' => 25,
  );

$form['replace_textfield']['oldid'] = array(
    '#type' => 'hidden',
    '#value' => $app_id,
  );

$form['replace_textfield']['edit']['GCM'] = array(
'#type' => 'textfield',
'#title' => 'GCM Api Key',
'#description' => 'Enter the GCM API key here.',
'#value' => $gcm_key,
'#required' => TRUE,
'#size' => 40,
'#maxlength' => 255,
'#weight' => 30,
  );

$form['replace_textfield']['edit']['iOS'] = array(
'#type' => 'textfield',
'#title' => 'iOS Api Key',
'#description' => 'Enter the iOS API key here.',
'#value' => $ios_key,
'#required' => TRUE,
'#size' => 40,
'#maxlength' => 255,
'#weight' => 35,
  );

$form['replace_textfield']['submit'] = array(
    '#type' => 'submit',
    '#value' => 'Edit',
  );
}
return $form;
}

function push_notifications_edit_app_form_callback($form, $form_state) {
// The form has already been submitted and updated. We can return the replaced
// item as it is.
return $form['replace_textfield'];
}

function push_notifications_edit_app_form_submit($form, &$form_state) {
// $app_id = $form_state['values']['app_id'];
$app_id = $form_state['replace_textfield']['values']['edit']['app_id'];
$gcm = $form_state['replace_textfield']['values']['edit']['GCM'];
$ios = $form_state['replace_textfield']['values']['edit']['iOS'];
$oldid = $form_state['replace_textfield']['values']['oldid'];

$query = db_update('push_notifications_api')
->fields(array(
'app_id' => $app_id,
'GCM' => $gcm,
'ios' => $ios,
))
->condition('app_id', $oldid)
->execute();
drupal_set_message(t('The form has been submitted.'));
}

```

Also in the following string it gives an error: $app\_id = $form\_state\['values'\]\['replace\_textfield'\]\['edit'\]\['app\_id'\];

Notice: Undefined index: replace\_textfield in push\_notifications\_edit\_app\_form\_submit() (line 790 of C:\wamp\www\drupal2\sites\all\modules\push\_notifications\includes\push\_notifications.admin.inc).

# Answer
I found the answer. The way to reach these values is by using: \['input'\].

eg: $app\_id = $form\_state\['input'\]\['edit'\]\['app\_id'\];
> 1 votes

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


# Question
Title: Is there a way to implement drag and drop for image upload in drupal 7
I amn looking for a way to inplement drag and drop image upload for the profile image field and serveral other image fields as well for drupal 7 is there a module that is easy to use or an easy way to implement uploading per drag and drop in template.php?

Thank you!

# Answer
You can do this by using any of these modules :

1. Drag & Drop Upload.

> This module provides a Drag & Drop Upload element and widgets for a File and an Image fields.

2. Plup

> This module allows you to modify your content types with a plup field for drag and drop uploads.

3. Drag'n'Drop Uploads

> The Drag'n'Drop Uploads module adds the ability to drag an image from your local filesystem, drop it onto a node body textarea and have the file automatically uploaded and referenced in your node.
> 2 votes

---
Tags: ajax, users
---


# Question
Title: Initiate file download and redirect to loged-in home page
The users can share the file download URL and user with credentials can download the file. All the things working fine. Once the user paste the download url in address bar, it redirects to login page and after successful login the file downloads. But its not redirecting to the loged in home page. Need to happen both things (file download & redirect to loged-in homepage) on successful login. How can we achive this.

# Answer
Try to use any of these modules. I hope below modules helps you to solve your issues :

1. LoginToboggan

> * Allow users to login using either their username OR their e-mail address.
> * Allow users to login immediately.
> * Provide a login form on Access Denied pages for non-logged-in (anonymous) users.
> * The module provides two login block options: One uses JavaScript to display the form within the block immediately upon clicking "log in". The other brings the user to a separate page, but returns the user to their original page upon login.

2. Login Destination

> The Login Destination module allows you to customize the destination that a user is redirected to after logging in, registering to the site (7.x), using a one-time login link or logging out (7.x). The destination can be an internal page or an external URL. It is possible to specify certain conditions like referring pages or user roles and make the destination depend upon them. You may use PHP snippets to provide custom conditions and destinations. It is also possible to keep users on the currently visited page after logging in or out.

3. Anonymous Login

> This is a very simple, lightweight module that will redirect anonymous users to the login page whenever they reach any admin-specified page paths, and will direct them back to the originally-requested page after successful login.

**OR**

You can do this by using Rules module.

> The Rules module allows site administrators to define conditionally executed actions based on occurring events (known as reactive or ECA rules).
> 1 votes

---
Tags: files, redirection
---


# Question
Title: How to translate the user profile page in commerce kickstart
Hello, I'm using commerce kicksart in my website, I use french as source language instead of english, I translated many words in the user profile page, but I can't translate or edit some titles:

-HELLO
-PRIMARY SHIPPING ADDRESS
-PRIMARY BILLING ADDRESS
-RECENT ORDERS

I didn't find them in the translate interface page admin/config/regional/translate/translate, also I didn't find any view or block to edit them.

How I can translate or edit them without touch the tpl file?

Thanks

# Answer
> 0 votes
The solution described in issue #1937982 has been used to solve an issue similar to yours. That issue includes a .PO file to handle at least these strings:

* Primary billing address
* Primary shipping address

If that would work in your case also, you can probably use the same solution by adding 2 similar lines for these 2 other strings (you may have to verify if it is case sensitive or not):

* HELLO
* RECENT ORDERS

---
Tags: i18n-l10n, commerce
---


# Question
Title: Remove HTML Markup from YouTube RSS Feed Import
Drupal newbie here- using D7 Commons on a WAMP Development setup (for now).

I am importing an RSS feed from YouTube (using Feeds & Media: YouTube modules). It's working great, except that the description text is inserting all the markup tags in the description text. I have tried setting the field text to simple text and filtered html, but neither eliminates the markup tags.

Q: Is there a way to import the description text without all the HTML markup tags?

Thanks guys!

# Answer
The simple answer is to configure the Text format setting Node Processor section of the Feed Importer found at admin/structure/feeds/\[importer name\]/settings/FeedsNodeProcessor, but there has to be more to your configuration that may be impacting this. HTML tags/brackets are not allowed in the description of YouTube videos.

So I'm not even sure what HTML you are referring to. I'm only aware of 3 options to get access to a list of YouTube videos formatted as RSS.

1) https://gdata.youtube.com/feeds/api/users/UC194cPvPaGJjhJBEGwG6vxg/uploads?v=1

2) https://gdata.youtube.com/feeds/api/users/UC194cPvPaGJjhJBEGwG6vxg/uploads?v=2

3) Using version 3 of the API as described in https://www.drupal.org/node/2181067. That configuration requires OAuth.

In option 1 and 2, replace UC194cPvPaGJjhJBEGwG6vxg with account name you want a feed for. In both those options, the description text is in the element...

```
 <media:description type='plain'>

```

That element cannot be mapped with just Feeds, Media and Media: YouTube. You'd need something like https://www.drupal.org/project/feeds\_mediarss

There may be another way to access the RSS, but without knowing what you are using it's impossible to provide a better answer. As long as the Feeds Parser and Processor acknowledge the text format setting in the Feed Importer, the resulting nodes should only have plain text in their body fields.
> 0 votes

---
Tags: feeds, files
---


# Question
Title: Drupal 7 drop down menu not showing on other pages
I have the main menu with 4 links (home, services, portfolio, contact)

under "services" I created a sub-menu, (service1, service2, service3)

The problem is that the little arrow that drops down the sub-menu shows ONLY on the "services" page and NOT the other pages.

How to fix that? thanks.

# Answer
To clarify:

1. Go to Structure/Menus;
2. Select the menu with the non-expanding menu item (ie. Main menu);
3. Select the List Links tab if not already;
4. Click the "edit" link for the non-expanding menu item - the "Show as expanded" button is there.
> 4 votes

# Answer
This just shows them expanded all the time. Not very 'internet standard'.... how about getting them to show on hover as is the basic? Do we HAVE to use modules, variables, template tweaks??? Can't Drupal provide arguably the most important part of a website without going though a bunch of hoops?
> 0 votes

---
Tags: routes, navigation
---


# Question
Title: Why is my .htaccess not working when uploaded to a Pantheon server?
My drupal site has a `.htaccess` file on which I am redirecting the page without changing the URL.

It's working fine on local server & other servers but when I upload the files & databases to pantheon server It will not redirect the page saying *404 not found*. I placed `.htaccess` at the root of code folder, I tried placing it in server root folder, sites/ folder & themes/ folder but nothing works for me.

Does anybody know what is the correct placement of `.htaccess` in a Drupal site on Pantheon? And why my `.htaccess` is not working on Pantheon?

# Answer
Because Pantheon servers use Nginx, and they don't enable .htaccess support.

You should contact them directly to discuss your options (if you're lucky and/or have a high enough subscription they'll probably add some custom rules to the nginx conf for you).
> 3 votes

---
Tags: .htaccess
---


# Question
Title: User profile picture - avatar uploader on all pages
I am trying to change my profile picture via ajax.

I used views to display my user profile picture in a block. This works Perfect. I am then using the avatar uploader module to change my user profile picture. This module is exactly what I want because it also crops my photos. The problem is, this works, but only if I am on the user edit page. I get the ajax uploader if I click on my profile picture that is displayed using views, but only on the user edit page.

Is there any way to get this module to work regardless of what page I am on?

Thanks.

# Answer
> 1 votes
Firstly, Check avatar\_uploader.js file, the default selector is '.profile .user-picture a', if you want to use this for other profile img, please change the selector Drupal.settings.avatar\_selector

```
Drupal.behaviors.avatar_uploader = {
    attach: function(context) {
        if (Drupal.settings.avatar_uid) {
            Drupal.settings.avatar_selector = Drupal.settings.avatar_selector || '.profile .user-picture a';
        var el = jQuery(Drupal.settings.avatar_selector);
        au.attach(el, Drupal.settings.avatar_uid, Drupal.t('Change avatar'));
         }
     }
}

```

Second, Check "avatar\_uploader.module".

These code is to use uploader only in 'user' page in order to reduce js for browser, so you can change here

hook\_init

```
$params = array('avatar_panel_id' => UPLOADER_PANEL_ID);
    if ($user->uid) {
        if (arg(0) == 'user' || (arg(0) == 'user' && arg(1) == $user->uid)) {
           $params['avatar_uid'] = $user->uid;
        }
    }

```

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

---
Tags: 7, users
---


# Question
Title: "Can't create table errno: -1" when trying to create the cache_rules table on D7
I'm having a very strange problem. I have a website on Pantheon (Nginx) that I attempting to import into my local dev environment, but when I import, it is failing when it gets to the cache\_rules table. So I dropped the cache\_rules table on the server DB, dumped the DB, and imported it, and then tried to re-create the cache\_rules table with the following command:

```
CREATE TABLE IF NOT EXISTS `cache_rules` (
  `cid` varchar(255) NOT NULL DEFAULT '' COMMENT 'Primary Key: Unique cache ID.',
  `data` longblob COMMENT 'A collection of data to cache.',
  `expire` int(11) NOT NULL DEFAULT '0' COMMENT 'A Unix timestamp indicating when the cache entry should expire, or 0 for never.',
  `created` int(11) NOT NULL DEFAULT '0' COMMENT 'A Unix timestamp indicating when the cache entry was created.',
  `serialized` smallint(6) NOT NULL DEFAULT '0' COMMENT 'A flag to indicate whether content is serialized (1) or not (0).',
  PRIMARY KEY (`cid`),
  KEY `expire` (`expire`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='Cache table for the rules engine to store configured items.';

```

which I found here. I am running the command in phpMyAdmin.

However, when I do that, I get this error message:

"Can't create table errno: -1"

I've attempted to search for this but the explanations suggested that it was usually caused by trying to create a table that had a key that depended on another table that hadn't been created yet, but that is not the case here.

**I can run the exact same command above with a different table name (e.g., cache\_rules2) and a cache\_rules2 table will be created without a problem-- so it's only the specific name cache\_rules that is causing this issue, whatever it is.**

How can I further debug this to figure out why it suddenly doesn't want to create a cache\_rules table?

# Answer
> 0 votes
In this case, as @Clive noted, the problem was with corruption in the database. I was able to fix the problem by dropping the database, and then manually deleting what still remained (but shouldn't have):

```
sudo rm -rf /var/lib/mysql/my_db_name

```

# Answer
> 0 votes
When importing/exporting databases from/to Drupal try using Backup & Migrate as this only attempts to backup the structure of the cache tables rather than the data too.

---
Tags: rules, debugging
---


# Question
Title: Filter module won't let me add nested values to my configuration
I'm working on the D8 port of my xbbcode module; my latest sources are here.

The module is supposed to let administrators enable individual BBCode tags either in the global default settings or in an individual text format that overrides those defaults.

The settings structure for both is basically (in YAML):

```
tags:
  abbr:
    module: xbbcode
    enabled: 0
  b:
    module: xbbcode_basic
    enabled: 1
  [...]

```

The default configuration (set in the annotation comment of my filter plugin class) is

```
/**
 * Provides a filter that converts BBCode to HTML.
 *
 * @Filter(
 *   id = "xbbcode",
 *   title = @Translation("Convert BBCode into HTML."),
 *   type = Drupal\filter\Plugin\FilterInterface::TYPE_MARKUP_LANGUAGE,
 *   settings = {
 *     "autoclose" = FALSE,
 *     "override" = FALSE,
 *     "tags" = {}
 *   }
 * )
 */

```

However, when I try to create a new text format, I get the following error:

```
InvalidArgumentException: The configuration property filters.xbbcode.settings.tags.abbr
doesn't exist.
in Drupal\Core\Config\Schema\ArrayElement->get()
(line 97 of core/lib/Drupal/Core/Config/Schema/ArrayElement.php).

Drupal\Core\Config\StorableConfigBase->castValue('filters.xbbcode.settings.tags.abbr', Array)
Drupal\Core\Config\StorableConfigBase->castValue('filters.xbbcode.settings.tags', Array)
Drupal\Core\Config\StorableConfigBase->castValue('filters.xbbcode.settings', Array)
Drupal\Core\Config\StorableConfigBase->castValue('filters.xbbcode', Array)
Drupal\Core\Config\StorableConfigBase->castValue('filters', Array)
Drupal\Core\Config\Config->save()
Drupal\Core\Config\Entity\ConfigEntityStorage->doSave('bb2', Object)
Drupal\Core\Entity\EntityStorageBase->save(Object)
Drupal\Core\Config\Entity\ConfigEntityStorage->save(Object)
Drupal\Core\Entity\Entity->save()
Drupal\filter\FilterFormatFormBase->submitForm(Array, Object)
Drupal\filter\FilterFormatAddForm->submitForm(Array, Object)
call_user_func_array(Array, Array)
Drupal\Core\Form\FormSubmitter->executeSubmitHandlers(Array, Object)
Drupal\Core\Form\FormSubmitter->doSubmitForm(Array, Object)
Drupal\Core\Form\FormBuilder->processForm('filter_format_add_form', Array, Object)
Drupal\Core\Form\FormBuilder->buildForm(Object, Object)
Drupal\Core\Controller\FormController->getContentResult(Object, Object)
call_user_func_array(Array, Array)
Symfony\Component\HttpKernel\HttpKernel->handleRaw(Object, 1)
Symfony\Component\HttpKernel\HttpKernel->handle(Object, 1, 1)
Drupal\Core\StackMiddleware\Session->handle(Object, 1, 1)
Drupal\Core\StackMiddleware\KernelPreHandle->handle(Object, 1, 1)
Drupal\Core\StackMiddleware\PageCache->pass(Object, 1, 1)
Drupal\Core\StackMiddleware\PageCache->handle(Object, 1, 1)
Drupal\Core\StackMiddleware\ReverseProxyMiddleware->handle(Object, 1, 1)
Drupal\Core\StackMiddleware\NegotiationMiddleware->handle(Object, 1, 1)
Stack\StackedHttpKernel->handle(Object, 1, 1)
Drupal\Core\DrupalKernel->handle(Object)

```

Some examination of the StorableConfigBase class reveal that it seems to insist on merging my configuration values with the existing ones, down to the bottom level, and when it doesn't find the "abbr" key it shuts down. This seems pretty silly, because obviously an array can gain or lose entries when you save it.

The weird thing is that the global defaults have absolutely no problem when I change them with `$this->config('xbbcode.settings')->set('tags', [...])->save()` in my own `ConfigFormBase` settings form.

Edit: filter.format.\* has a config schema, while my module doesn't. I'm not sure how to tell this schema "this array may have a number of keys, each of which has the form `{enabled: ..., module: ... }`

# Answer
> 1 votes
I figured out how to declare the filter settings schema by comparing with modules/filter/config/schema/filter.schema.yml and using the Schema docs.

Apparently my schema file simply needs to declare

```
filter_settings.xbbcode:
  type: filter
  label: 'XBBCode filter'
  mapping:
    [...]

```

---
Tags: 8, input-formats, configuration
---