# Question
Title: DB Query exclude duplicates, returning only the newest
I need to alter the query below to only return one row for each unique 'name'. The row returned should be the most recent based on the contents of 'date'. 'date' is an integer.

```
$query = db_select('updates_summary', 'n')
->fields('n', array('upid', 'name', 'date','previous_version','new_version'))
->orderBy('date', 'DESC') //Most recently updated first.
->execute();
return $query;

```

I have looked at the Drupal page on Expressions, another Drupal answers question and questions on drupal.org like this and this. Unfortunately I am new to the db-api and am struggling to get anywhere.

This works to return a single date but nothing else in the other columns:

```
  $query = db_query("SELECT MAX(upid) as max_id FROM updates_summary")->fetchCol();
  return $query;
}

```

NEW ADDITIONS:

This is the mySQL query I need an equivalent of:

```
SELECT `name`, MAX(date) FROM `updates_summary` GROUP BY `name`

```

Adding `->groupBy('name')` to my query seems to do what I need it to. However, i am confused as to why this seems to be working without specifying that I want to return the maxium from the date column. My current code that seems to work is:

```
  $query = db_select('updates_summary', 'n')
->fields('n', array('upid', 'name', 'date','previous_version','new_version'))
->groupBy('name')
->execute();

```

return $query;

I would like to add a MAX(date) as I did in the mySQL statement above. This answer suggests that adding the following should work: `->addExpression('MAX(date)', 'max_date')` but i get `Fatal error: Call to a member function fields() on a non-object`.

# Answer
> 0 votes
You can use range() to limit your results

```
$query = db_select('updates_summary', 'n')
->fields('n', array('upid', 'name', 'date','previous_version','new_version'))
->orderBy('date', 'DESC')->range(0,1);
$query = $query->execute();
return $query;

```

# Answer
> 0 votes
The solution I found is to loop through each unique name, then specify which name I am looking for in my query using a condition: `->condition('name', $name,'=')`. i also use a `->orderBy('date', 'DESC')` to get all the fields ordered by date.

Aftwerwards perform a fetch. Fetch only returns the first result, and because the results are ordered in the query it returns the correct row:

```
$query = db_select('updates_summary', 'n')
      ->fields('n', array('date','name','previous_version','new_version'))
      ->condition('name', $name,'=')
      ->orderBy('date', 'DESC')
      ->execute();

if ($query->rowCount() > 0) {

      // results are returned

      $myrecord = $query->fetch();  // just fetches the first row, which is why we order the $query by date

      // now do anything you want with the returned result. For now just dpm it (needs devel module installed)
      dpm ('FETCH RESULTS: ' . $myrecord->name . ' | new version: ' . $myrecord->new_version);

    }

```

I've got a feeling that there might be a more elegant solution, but since this works fine I thought I would post it in case it helps someone else.

---
Tags: database
---


# Question
Title: Tables are not creating with hook_schema
I need to create a module to save data of term page visits.

```
<?php

function term_count_schema() {
  $schema['term_search'] = array(
  'description' => 'Stores timestamp range..',
'fields' => array(
  'tid' => array(
    'type' => 'int',
    'not null' => TRUE,
    'default' => 0,
    'size' => 'tiny',
    'description' => 'Taxonomy ID.',
   ),
  'vid' => array(
    'type' => 'int',
    'not null' => TRUE,
    'default' => 0,
    'size' => 'tiny',
    'description' => 'Vocabulary ID.',
    ),
  'timestamp' => array(
    'type' => 'int',
    'not null' => FALSE,
    'description' => 'UNIX timestamp.',
   ),
 ),
 'primary key' => array('tid'),

  );

  $schema['term_count'] = array(
'description' => 'Total views.',
'fields' => array(
  'tid' => array(
    'type' => 'int',
    'not null' => TRUE,
    'default' => 0,
    'size' => 'tiny',
    'description' => 'Taxonomay ID.',
  ),
  'vid' => array(
    'type' => 'int',
    'not null' => TRUE,
    'default' => 0,
    'size' => 'tiny',
    'description' => 'Vocabulary ID.',
  ),
  'totalviews' => array(
    'type' => 'int',
    'not null' => TRUE,
    'default' => 0,
    'size' => 'tiny',
    'description' => 'Total number of views which increments on every page load.',
  ),
),
'primary key' => array('tid'),
  );
  return $schema;
}

```

This is not creating tables term\_search & term\_count ind DB. Any thing wrong in my code.

# Answer
```
    <?php
/**
 * @file
 * Contains install and update functions for Views.
 */

/**
 * Implements hook_install().
 */
function mid_components_install(){

}

/**
 * Implements hook_schema().
 *
 */
function mid_components_schema(){
    $schemas = array();
    $schemas['mid_components'] = array(
        'description' => 'The mid_components data.',
        'fields' => array(
            'cid' => array(
                'description' => 'Primary key',
                'type' => 'serial',
                'unsigned' => TRUE,
                'not null' => TRUE,
            ),
            'title' => array(
                'description' => 'Human readable name of the component.',
                'type' => 'varchar',
                'length' => 255,
                'not null' => TRUE,
            ),
            'machine_name' => array(
                'description' => 'Unique machine name of the component',
                'type' => 'varchar',
                'length' => 255,
                'not null' => TRUE,
            ),
            'description' => array(
                'description' => 'Description of the component.',
                'type' => 'varchar',
                'length' => 255,
                'not null' => FALSE,
            ),
            'options' => array(
                'description' => 'A serialized array of options for this display; it contains options that are generally only pertinent to that component.',
                'type' => 'blob',
                'size' => 'big',
                'not null' => FALSE,
            ),
            'status' => array(
                'description' => 'Status of the component',
                'type' => 'int',
                'not null' => TRUE,
                'default' => 0,
                'unsigned' => TRUE,
            ),
            'created' => array(
                'type' => 'int',
                'description' => 'The Unix timestamp when the item is created',
                'not null' => TRUE,
                'default' => 0,
            ),
            'changed' => array(
                'type' => 'int',
                'description' => 'The Unix timestamp when the item is modified.',
                'not null' => TRUE,
                'default' => 0,
            ),
        ),
        'primary key' => array('cid'),
        'unique key' => array('machine_name' => array('machine_name')),
    );
    return $schemas;
}

/**
 * Implements hook_uninstall().
 */
function mid_components_uninstall(){

}

```

Follow this method. And Make sure after doing any chnagings to your .install file, uninstall your module and reinstall it again.
> 1 votes

---
Tags: database
---


# Question
Title: redirect internal body urls temporarily for local development
I have painstakingly moved my production site to a local dev server to do some offline edits. However, all of the internal site links located in the body of whatever page still point to the production site.

How do I temporarily redirect urls in the body of pages to the local dev server?

I need

> "examplepage.org/randomcontent"

to redirect to

> "examplepage/randomcontent"

NOTE: All the drupal nav pages via admin menu work correctly. Seems like a common problem, but I can't find a straight forward solution.

# Answer
> 0 votes
If there is given hard coded URL then you need to change it one by one , and if its coming through program or Drupal standard behavior then you can check it with clearing the cache.

Following are the way you can check:

```
1. Check settings.php to ensure that $base_url is set to "http://localhost"

2. Check settings.php to ensure that MySQL settings are correct

3. Take an SQL dump of the entire local database and searched for any references to live site URL

4. Delete all the local cache data from database

5. Check various blocks to ensure that there was no hard coding of links

```

# Answer
> 0 votes
you could make an entry in your hosts file, like

```
127.0.0.1      examplepage.org

```

---
Tags: redirection
---


# Question
Title: http to https htaccess always redirecting to home page
I have found following .htaccess code on stackoverflow.com to convert the http requests to https

```
RewriteEngine On
RewriteCond %{HTTPS} !=on
RewriteRule ^.*$ https://%{SERVER_NAME}%{REQUEST_URI} [R,L]

```

it is converting the http to https but always goes to the home page

suppose If I am trying to go to http://domain.com/about-us it routes me to https://domain.com

Just for information I am using redirect and global redirect module but even if I am disabling them both the result is same.

# Answer
> 3 votes
By default, Drupal includes an .htaccess file that has instructions in the comments for doing https redirection. I suggest you follow the instructions in that file.

From Drupal 7.22:

```
# Various rewrite rules.
<IfModule mod_rewrite.c>
  RewriteEngine on

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

```

# Answer
> 0 votes
Somewhere halfway the htaccess file drupal rewrites every request to non-existing files to index.php for fancy urls. Be sure to put your rewrite before that.

---
Tags: .htaccess, ssl
---


# Question
Title: How to get historical content having historical date that happened in current week in Views?
I have a content type having date field contains historical date like 1897-06-15. Now i need to fetch it by week if historical date's week matches current week in Views? How to do it in views.Any suggestions?

# Answer
> 0 votes
I used DAYOFYEAR function.

```
$startDateNumber = date('z', strtotime("-4 days"));
$endDateNumber = date('z', strtotime("+3 days"));

$query = db_select('field_data_field_historical_date', 'fd');
$query->fields('fd');
$query->where('DAYOFYEAR(fd.field_historical_date_value)>=:startDate', array(':startDate' => $startDateNumber));

$or = db_or();
$or->where('DAYOFYEAR(fd.field_historical_date_value)<=:endDate', array(':endDate' => $endDateNumber));

$nid = $query->condition($or)->execute()->fetchField(3);

if (!is_bool($nid)) {
    print_r($nid); exit;
} else {
    print 'no';
}

```

---
Tags: views, datetime
---


# Question
Title: Display Text using flags on user profile?
I'm running a D7 site and want to use a flag to display message/text on user profiles.

I'm currently using 'Form' to capture message when user flags himself/herself but cannot find a way to display that message/text on user profile.

Is there any way to capture that message using 'Form' within flags and than display that message on user profile flag till unflagged.

# Answer
> 0 votes
I achieved 'Out of office' flag functionality using rules module.

* Placed an out-of-office flag on user profile and set visibility rules (panels) to show flag only if its user's own profile
* Within flags used flagging form to capture user out-of-office message
* Added an extra field 'out-of-office' within user's profile.
* Created a rule on flagging-event to populate 'Out-office-field' with text from flagging form.
* Created a rule to delete the text from 'out-of-office' field on unflagging.

---
Tags: 7, entities, users, flags
---


title: Using Flags for 'Out of office'

text:
# Question
Title: Using Flags for 'Out of office'
I'm trying to use flags to create 'Out of office' functionality for my site users where user profiles are built into panels.

* How can I add a flag where user can only see flag on his own profile
* When user flags 'out of office' he gets displayed with a text field and then that text field get rendered within user profile displaying 'out of office' message.

Thanks

# Answer
> 0 votes
I achieved 'Out of office' flag functionality using rules module.

Placed an out-of-office flag on user profile and set visibility rules (panels) to show flag only if its user's own profile Within flags used flagging form to capture user out-of-office message Added an extra field 'out-of-office' within user's profile. Created a rule on flagging-event to populate 'Out-office-field' with text from flagging form. Created a rule to delete the text from 'out-of-office' field on unflagging

---
Tags: 7, panels, flags
---


# Question
Title: How to upload a csv file with an admin form?
In a custom module, I created an admin form but I need an input to upload a csv file. When the file is uploaded I need to parse in and then I add data to db.

I already made "add to db" and "parsing" functions because when I installed the module, a default file is parsing and added to the db.

Thanks.

EDIT :

I'm using Drupal 7...

The data is stocked in a custom table that is create when the admin user will install the module. There is no node or content type. I just need to save all data of the CSV file (5 columns) in the table by an admin user form. 1 time par month the admin user need to update the table with a new .CSV.

In frontend I have a form and when the user will submit it I check that the code is in the table.

My issue is that I didn't know how to upload the file into a Drupal directory and then access to it after the form submit.

As I said above I already created a parsing function and I tested with a CSV file directly in the module directory, it's working. Data is insert into the table that I have created.

# Answer
In your custom form create input button like

```
$form['upload_csv'] = array(
        '#name' => 'files[mycsv_data]',
        '#type' => 'file',
        '#title' => 'Upload csv'
    );

```

Next in form submit you can use

```
file_save_upload($source,
                array('file_validate_extensions' => array('csv')),
                $destination_dir,
                FILE_EXISTS_REPLACE)

Here for getting uploaded file details like file name and file path you can use $_FILES global variable.

```

and then,

```
if ($file) {
    $file->status = FILE_STATUS_PERMANENT;
    file_save($file);
}

```
> 2 votes

# Answer
use **node import** module or feeds import.
> -2 votes

---
Tags: 7, files
---


# Question
Title: Getting fatal error in drupal when open the site
I am working on a site in which it was perfectly, but now its given this error

> Fatal error: require\_once(): Failed opening required '/var/www/.../includes/sites/all/modules/context/plugins/context\_condition\_sitewide.inc' (include\_path='.:') in /var/www/.../includes/bootstrap.inc on line 3139.

Here we can see the path is changed `.../includes/sites/.....` where as the "include" and "sites" are on root folder.

So please guide me that how to solve this issue.

# Answer
> 0 votes
Install Context module using drush en "context".

Your site is not get `/context_condition_sitewide.inc` file or you may be accidently delete this module without disabling it from module list. Try reinstalling this module again.

---
Tags: views, 7
---


# Question
Title: How do I tell Drupal not to aggregate my css file
I have enabled Drupal's *Aggregate and compress CSS files*. What should I do in order to exclude certain css files from being aggregated and compressed? Thanks.

# Answer
> 12 votes
To stop a file being aggregated, you can add a flag to the drupal\_add\_css() command which loads the file. To do this, hunt where the CSS is added and add `array('preprocess' => FALSE)` after the style, e.g.

```
drupal_add_css('/fonts/fonts-min.css', array('preprocess' => FALSE));

```

Alternatively, external CSS are never compressed, so if you change the CSS to the absolute URL of the file it won't be compressed.

```
drupal_add_css('http://mysite/css/fonts-min.css');

```

If you want to change a CSS included from a .info file, it might be best to add it as an external file with `_preprocess_html` in template.php. This is well explained under 'Adding external stylesheets' on this page.

# Answer
> 1 votes
I had this problem too, but instead of using drupal\_add\_css I attached my files to a page like this:

```
function module_preprocess_page(&$variables) {
  $variables['some_element']['#attached'] = array(
    'css' => array(
      'path/to/css/style.css',
    )
  )
}

```

While digging in the attached core code I found that we can use John C's solution here too like this:

```
function module_preprocess_page(&$variables) {
  $variables['some_element']['#attached'] = array(
    'css' => array(
      'path/to/css/style.css' => array(
        'preprocess' => FALSE,
      )
    )
  )
}

```

# Answer
> 0 votes
How I did this really dirty on Drupal 8 since it's still in dev and too much is changing now:

**THEMENAME.theme** file:

```
function THEMENAME_preprocess_html(&$variables) {
  $variables['css_address'] = drupal_get_path('theme', 'themename') . '/cssfile.css';
}

```

And added something like this to head tag in **html.html.twig** template file:

```
<link rel="stylesheet" type="text/css" href="{{ css_address }}">

```

There's going to be a better way soon.

---
Tags: 7, theming, css-js-aggregation
---


title: Rules condition for comment status

text:
# Question
Title: Rules condition for comment status
Sometimes, when a user post a comment, it not published immediately; this can be for several reasons (e.g. spam suspect, anonymous user). I want to use the Rules module to send an email to users that flagged the node for new comments, but only when the comment is published. I cannot find any condition in the Rules module that allows me to check if the comment is published or not.

Perhaps someone has a way to accomplish this.

# Answer
What you need is a rule that is fired when the comment is first published and that seems very straight forward to me. If you need any further help on that, please let us know.
> 3 votes

# Answer
I cannot find this condition too. There is a condition "Content is published" for nodes. But I cannot find the similar one for comments. Action "After saving a new comment" works for both cases:

* comment is saved and published
* comment is only saved (not published)

I want for a rule to fight only for the 1st case.

**EDIT:**

In fact, Rules module have not changed too much and I have already found a solution, so I'll share it here.

Add a new condition as usual -\> select "Data comparison" -\> input "comment:status" and select "equals" to "Published". That's it!

Another point that should not be forgotten if you use Rules for email notifications is to send emails after an administrator has approved a comment. It should fight on event "After updating an existing comment" and the conditions are configured in a similar way

```
comment-unchanged:status == Unpublished
AND
comment:status == Published

```

If you notify users about publishing Nodes - do not forget about this point too. The difference is that you should create new rule "After updating existing content" and the conditions are:

```
node-unchanged:status == Unpublished
AND
node:status == Published

```

Please note that it will fire your actions every time the comment changes its status from Unpublished to Published - it might be an issue for you.

HTH, Alexander
> 0 votes

---
Tags: rules
---


# Question
Title: Field Formatter: how to know where "i'm"
I have a node type called fotogallery. In this node type there is a field of type "field collection". With hook\_field\_formatter\_view() I create a custom output for this field.

Now, the same node type is linked to another node type via entity reference. In this case I want to create another type of output for the "field colletion" field. But how I (drupal cms) can know if I'm inside node type "fotogallery" or I'm inside an entity reference ?

Do I need to load the current node (via node\_load(arg(1)) and see the "type" value?

# Answer
A Field Formatter has no awareness of when it's used. It's simply just a unique way to display a field.

You want to use something like Entityreference ViewMode Selector. And create 2 formatters for the Field Collection. 1 formatter is the `default` output for collections, 1 formatter is the `viewed as entityreference` formatter.

When you set the entityreference, you would set the formatter as needed.
> 0 votes

---
Tags: 7, entities
---


# Question
Title: How to implement a multi-node edit workflow?
I'm not sure if this exists. I'm looking for a multi-node edit workflow. I want to select multiple nodes then for each node selected show an edit form. This would be something like showing the first node edit form, then on save, show the next edit form, etc.

I came across the Multi Node Edit module, but it looks to be dead.

There's also this answer but it's not exactly what I want. VBO seems to work only for multiple edits on the same field, not one after another node edit forms.

# Answer
You can achieve something similar with a combination of editable fields and views.

Then by loading all the nodes in a view with a table format, you can use the editable field and edit it right on the spot with AJAX. Updating multiple nodes in a view using editablefields

If you wanted to update multiple nodes at once (assuming fields are the same) you can use Views Bulk Operations

The exact functionality you are asking for is defiantly custom and will require your own module. Selecting the nodes you want then editing them one after another is highly inconvenient IMO. A report/table format is much better for working with data.
> 1 votes

---
Tags: nodes, forms
---


title: How do I add a COALESCE to a db_select?

text:
# Question
Title: How do I add a COALESCE to a db_select?
I want to achieve the following query using `db_select()`:

```
SELECT
  Column1,
  Column2,
  COALESCE(Column1, Column2) AS Column3
FROM TEST_ATTRIBUTES

```

How do I add the coalesced column to the query?

Thank you

# Answer
You can add an expression:

```
$query = db_select('TEST_ATTRIBUTES', 't')
  ->fields('t', array('Column1', 'Column2'));

$query->addExpression('COALESCE(Column1, Column2)', 'Column3');

```

The above yields:

```
SELECT
  t.Column1 AS Column1,
  t.Column2 AS Column2,
  COALESCE(Column1, Column2) AS Column3
FROM TEST_ATTRIBUTES t

```
> 8 votes

---
Tags: database
---


title: Filtering a view by a checkbox field

text:
# Question
Title: Filtering a view by a checkbox field
My site has a node type called "Resource". This node type has a field called "Reviewed"; this field is a single on-off checkbox:

I've created a view that lists all of the nodes of node-type "Resource". I'd like to filter that view so it only displays nodes that have the "Reviewed" checkbox checked. However, when I try to add that field to my view, I'm shown the following:

I would expect the "Options" select box to be a checkbox that I could either check or leave empty. Instead, I'm given a select box with "Select all" in it. Whether I select this or not, I'm then presented with an error message saying that there are "No valid values found on filter: Content: Reviewed.":

I've tried the "exposing the master display trick" at http://technology.blue-bag.com/top-tip-drupal-views-no-valid-values-found-filter, but that hasn't worked: there's no "unknown" filter in the master display, so there doesn't appear to be anything to fix.

Any idea as to how I can achieve the result I'm looking for? And what's the deal with the strange UI with the select box rather than a checkbox? Would be good to know if there's some logic to it; if not, I'll post an issue to the appropriate drupal.org issue queue.

# Answer
this is some sort of a bug / incosistency of how the boolean field is made. if you leave it in default, without any 0 / 1 values, it wont show them in places like this filter.
But : the values are there :) under "Select all" you have 2 rows that just dont have captions. When you pick one of them, you can see that the SQL for your view is changed.
The workaround would be to add some captions to the values in the field defintion.
> 11 votes

# Answer
I was also facing the same problem, the Label of the field was not displayed in the view's exposed filter.

I then went to the field settings in content type for that checkbox field and updated *On Value* as **1** and *OFF value* as **0**.

Now the Label appears in exposed filter and works as expected.
> 2 votes

# Answer
I encounter the same issue and instead using *Select All* you should select no value. If you already have a value selected use *Ctrl* to undo your selection.

Source
> 1 votes

---
Tags: 7, views
---


title: drush update - php.ini problem

text:
# Question
Title: drush update - php.ini problem
I am trying to update drupal using drush from Version 7.36 to 7.38 with \>drush up drupal the process finishes in 2-3 seconds stating update has successfully finished and a backup has been created.

As a result, drupal is still on 7.36 - no updates have been made.

but there is also an error stating no php.ini found - and the created backup directory (where drush is looking for the php.ini) is empty:

```
(uiserver):xxxxx:~/kochlounge > drush up drupal
Update information last refreshed: Sa, 07/11/2015 - 16:07
 Name    Installed Version  Proposed version  Message
 Drupal  7.36               7.38              SECURITY UPDATE available

///some update-warnings snipped for readability

Do you really want to continue? (y/n): y

Source directory                      HERE COMES THE ERROR  [error]
/htdocs/drush-backups/db570947934/20150712144116/drupal/profiles/php.ini
is not readable or does not exist.

Project drupal was updated successfully. Installed version is now 7.38.
Backups were saved into the directory                                [ok]
/htdocs/drush-backups/db570947934/20150712144116/drupal.
Backups were restored successfully.

```

my drush status (snipped):

```
 PHP executable                  :  /usr/bin/php5.5-cli
 PHP configuration               :  /usr/lib/php5.5/php.ini /usr/bin/php5.5-cli
 PHP OS                          :  Linux
 Drush script                    :  /htdocs/.composer/vendor/drush/drush/drush.php
 Drush version                   :  7.0-dev

```

my .profile:

```
alias php="/usr/local/bin/php5.5"
alias php-cli="/usr/bin/php5.5-cli"
alias composer="php-cli ~/composer.phar"

export DRUSH_PHP="/usr/bin/php5.5-cli"
export DRUSH_INI="/usr/bin/php5.5-cli"
alias drush="~/.composer/vendor/bin/drush"

```

Has anyone got a clue as to why the update is not working, what may be wrong with the php.ini... ? when trying to do updates for modules from drupal-backend, the site throws an error and goes in maintainance-mode.

Thank you!

# Answer
> 0 votes
Turned out that after a complete wipe and restore of my site the upgrade worked without that error.

Sorry, no idea what caused this in the first place!

---
Tags: drush, updating
---


# Question
Title: How to use fixed width in AT Panels everywhere (site template)?
I am using the AT Panels Everywhere theme and its ATPanels Everywhere Site Template. However, apparently it overrides the At panels everywhere theme because the width seems to be fluid and not fixed. How can I change the width to fixed? I tried it in admin/structure/pages/site\_template and added css code but nothing changes. The site keeps it fluid width.

```
/* set a fixed overall width */
  #page-wrapper  {
    width: 960px;
    margin-left: auto;
    margin-right: auto;
  }

  /* Add some margin to the main content row. This class was set in the layout designer. */
  #page-wrapper .main-content {
    padding: 0 10px;
  }

```

The question is: How can I create a fixed width with AT panels everywhere site template?

# Answer
> 1 votes
Found the answer: look at default site template, copy-paste the css of the sample variant and set the page-wrapper.

---
Tags: theming, panels
---


title: How to make summary of body searchable?

text:
# Question
Title: How to make summary of body searchable?
I've already looked at this answer and tried to change the search index view so that when I ran a search, I could type in a word appearing in a summary it would appear in my search results. I also ran cron to get the site reindexed but still, nothing appears when I type in a word that only appears in a summary. How do I make the summaries in content searchable?

# Answer
I did not figure out to do this, but a workaround was to actually make a separate field called summary and remove the default body and add a new body field without a summary.
> 0 votes

---
Tags: views, search, cron
---


# Question
Title: How can I have two nodes of different content types update to each other?
I have two different content types(A & B), and I want to be able to have a field in content type A that is a select list of all the nodes from content type B, and then I want to have a field in content type B that is a select list of all the nodes from content type A. Is there a way that I can have those two fields update each other?

Ex: in node 'Atest' from content type A in the select list field I select the 'Btest' node from content type B, and then if I edit 'Btest' in it's select list field I can see 'Atest' already selected. (showing that 'Atest' has it selected)

Is that possible? if so, what would be the beat way to go about setting that relationship up?

# Answer
You can try Corresponding node references.

I used this to sync up Events and Venues on one of my sites, and whenever I switch a venue for an event it automatically changes the node reference on the other node, so I only have to change the node reference once, instead of twice. Keeps things tidy, works with multiple.
> 2 votes

---
Tags: nodes
---


# Question
Title: How to display the translated value of a boolean field when viewing a translated page?
I have this problem with translation of a custom checkbox (boolean) field. To be specific, I'm able to translate everything but the options (Yes / No) that are shown on node view page.

I have the modules `locale`, `i18n_nodes`, and `i18n_fields` enabled, and translation strings imported (with corresponding context and to appropriate textgroup), and default language set to English. The translation shows correctly everywhere but on node view where it's still untranslated.

The content type is custom and is created via hook\_node\_info() and it's fields via field\_create\_field, and field create\_instance.

---

BTW: I don't need translation of the content (every node will always have just one language and should be accessible regardless of what language the user has selected) but only of the user interface (descriptions, titles, ...). So if there's a simpler way to translate my custom fields and content types, please let me know.

---

Screenshot proofs that I've done everything I could:

Settings:

Edit page:

View page (note the only string that is in English but should be in Czech and should be Aktivni)

# Answer
Try what's mentioned in Comment #1 of issue # 1762488, i.e:

> ... visit 'Manage Display' and switch from "Default" to "Default translated".
> 1 votes

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


# Question
Title: How to create a chart about the number of node views per day (since last week)?
I want to show my users a chart that lists the node views hit for that day (Content statistics: Views today), something like this:

So the user can see how many views each node of his had in each day of last week!

I'm using the Charts module for making the charts, using the Google charts API as the charting engine (library) and it works just fine.

Issue is, that I have no idea if it's possible to list last 7 days date in Views at all or not, let alone integrating it with Charts.

Any suggestions about how to do so?

# Answer
> 8 votes
# Using the Charts module

### Step 1: Create the tabular format of the view

First to address the "*if it's possible to list last 7 days date in views at all or not*" part of your question, you really need to first work on getting the view created correctly. That's also what's recommended in the ***Bonus tip*** within Steps to create charts using the views UI, i.e.:

> You may find it easier to start with a "Table" display and convert it to a chart display after setting up the data. **It can be easier to visualize what the result of the chart will be if it's been laid out in a table first.** ...

### Step 2: Add the chart to your view

Do not try to start this step if you didn't first complete the prior step.

There is an issue which might help to answer this question, or at least to understand the challenge here. I.e. Graph node input over time (support date formatting on a continuous axis).

In Comment #3 of that issue is stated: 'The trouble here is that neither Views nor Date modules provide aggregation options for date-based fields.'.

# Using the Quant module

If using the Charts module you can't get it to work (or don't want to consider the suggestions above), then you may want to look at the Quant module as an alternative. Here are some excerpts from its project page:

> ... provides an engine for producing quantitative, time-based analytics for virtually any Drupal component. Quant takes raw data about normal Drupal actions, such as node creation, and plots the activity over time, with the selected time being configurable. See the screenshot provided for a better understanding.
>
> Provided charts:
>
> * Content creation
> * Comment creation
> * Content creation by type
> * Aggregate content creation
> * User creation
> * Page views (requires Statistics)
> * User shouts (requires Shoutbox)
> * User point transactions (requires User Points)
> * Group creation (requires Organic groups)
> * Group joins (requires Organic groups)
> * Invites sent (requires Invite)
> * Invites accepted (requires Invite)
> * Statuses shared (requires Facebook-style statuses)
> * Private messages (requires Private message)

Especially the "Page views\* chart that is provided might be close to what you're looking for.

# Using the Visitors module

If you're looking for info related to visitors of a website (registered users is a subset of them ...), the Visitors module might be a valid alternative to consider also (and/or addition to the above modules). In this case, all you have to do is to enable the module and review the various out-of-the-box reports (which include charts created with the **pChart** library).

The demo site contains some sample reports (charts) available to anonymous users also. This demo site also shows some additional blocks with reports also created by the Visitors module.

In this specific case, you probably would want to look at the Days of week report (and chart). Note that, as a bonus, you can specify the desired date filter (from / to) also.

Refer to the Visitors community docu for some more details.

Extra reporting features can be enabled via these sub-modules:

* The **Visitors GeoIP** module, to also report about countries and cities.
* The **Visitors Browscap** module, providing statistics on visiting browsers.

# Evaluating other charting modules

If none of the above modules would work in your case, then you might want to look at the "Comparison of Charting modules" documentation.

Disclosure: I'm a (co-)maintainer of all modules mentioned above (and original author of the comparison), I hope this does not violate the site's policy on self-promotion.

---
Tags: 7, views, nodes, datetime, charts
---


# Question
Title: Where should I store 3rd Party external js libraries?
This is a follow up to Define JavaScript library in Drupal 8

I have a third party library that I don't want to bundle with a module. In Drupal 7 I could just ask the user to extract to `sites/all/libraries` what is the best practice in Drupal 8?

# Answer
One option is to do it exactly like in D7. Put it in /libraries or /sites/all/libraries and use the libraries module to detect the location.

location.module itself unfortunately doesn't work that well in 8.x yet, so you have to define an 8.x-1.x library and then use the libraries API to get the location and dynamically alter. Or I guess you could also do that part yourself.

I'm doing that in the JW Player project, see jw\_player\_libraries\_info() + jw\_player\_library\_info\_alter(). It unfortunately still requires a bit of code, maybe that will improve in the future when libraries.module works better in 8.x.
> 1 votes

# Answer
If we follow what symfony2 uses, we have to use then: /vendor/libraryname/lib/Libraryname/src/libraryname.js
> 0 votes

---
Tags: javascript, 8
---


# Question
Title: drush sql-sync fails with PHP Fatal Error
drush sql-sync @devyau @stageyau returns:

> Unable to load class Drupal\Driver\Database\Drush
> PHP Fatal error: Call to a member function dump() on a non-object in /root/.composer/vendor/drush/drush/commands/sql/sql.drush.inc on line 275

Drush command terminated abnormally due to an unrecoverable error.

> Error: Call to a member function dump() on a non-object in /root/.composer/vendor/drush/drush/commands/sql/sql.drush.inc, line 275

# Answer
My alias file was the problem:

```
<?php
$aliases['devyau'] = array(
'uri'=> 'dev.[sitename]',
'root'=> '/var/www/vhosts/dev.[sitename]/',
'db-url' => 'mysql://[username]:[password]/devDBname',
  );
?>

```

My alias file apparently didn't have enough data to function.

See my previous question at: drush sql-sync fails

burnsjeremy provided this model alias file, which answered my question and allowed me to use Drush again! Thanks!

```
$remote_sites = '/path/to/site'; // usually /var/www/drupal-root-name
$aliases['site.dev'] = array(
 'uri' => 'sitename.com',
 'remote-host' => '{ip to remote}',
 'remote-user' => '{remote ssh user}',
 'root' => $remote_sites,
 'ssh-options' => '-p {if you ssh in on another port like 2222}',
 'path-aliases' => array(
 '%drush-script' => '/root/.composer/vendor/bin/drush', // This is so you can
 have multiple drush installs and use different ones on different sites.
 'php'=> '/usr/local/bin/php', // Again if you have different php's for
 different sites.
 '%site' => 'sites/default/', // This is the important part here, it will
 ensure the proper bootstrap
 '%dump-dir' => '/path/to/drush.dbdumps', // This is where you want to dump
 your databases, normally /tmp folder I think.
 '%files' => $remote_sites . '/files' // Your sites file folder, incase it is
 somewhere else.
),
// You may actually need this, especially if you are running D7 since I
   haven't ever tested the db-url thing on D7 or above.
 'databases' => array (
   'default' => array (
    'default' => array (
     'driver' => 'mysql',
     'database' => '{db_name}',
     'username' => '{db_user}',
     'password' => '{db_pass}',
   ),
  ),
 ),
);

```
> 0 votes

# Answer
First you run this command on console. if command is run successfully after then you check your drush library, I think this is drush library problem.

Second is you can try other command like :-

drush ard
> 0 votes

# Answer
You should ensure that your remote alias is correctly declared:

```
$aliases['remote'] = array (
  'root' => 'absolute_path_to_your_drupal',
  ...
)

```

try other commands like

```
drush @devyau uli
drush @stageyau uli

```

If doesn't work the path may be the problem.
> 0 votes

---
Tags: drush
---


# Question
Title: How to redirect to user organic group on login
I am trying to redirect the user to a page for which he is an organic user, and I want this redirect to happen after user login.

I am trying to use the `hook_user_login()` to make this redirect. However, I have found that when I inspect the `$user` object when it hits that hook, the `$user->og_user_node` field is empty. When I look at the user's edit screen (or when I inspect it with devel), it does have associated groups.

How can I retrieve a user's groups to make this redirect?

# Answer
Since you are using code to do this you should be able to use og\_get\_groups\_by\_user to return that information. This will return all groups of either the active user or the $account object that you pass to the function.

You can also use Rules to do this without code pretty easily. There is a rule export on this page to help get started if you want to go that way.

Just to add: the place you are looking for the og group should be under og\_membership I think, not og\_user\_nodes but that's off the top of my head :)
> 1 votes

---
Tags: users, organic-groups
---


title: Allow end user to choose sorting method

text:
# Question
Title: Allow end user to choose sorting method
How can I allow an end-user (site visitor) to choose a view sorting method themselves?

Or more specifically have the visitor choose Ascending or Descending based on an integer?

# Answer
You need to set a checkbox "Expose this sort to visitors, to allow them to change it" in the "Configure sort criterion" window
> 0 votes

---
Tags: views
---


title: Trying to pass icon into the menu

text:
# Question
Title: Trying to pass icon into the menu
I am trying to use the icon API to pass an icon to the menu - I would use the icon menu module, but I want the icon to switch based on programmatic logic.

Here's what I have so far:

```
/**
 * Implements hook_menu().
 */
function MYMODULE_menu() {
  global $user;
  $icon = theme('icon', array('bundle' => "fontawesome", 'icon' => "envelope"));
  $items = array();
  $items['user/' . $user->uid . '/messages'] = array(
    'access callback' => 'user_is_logged_in',
    'title callback' => FALSE,
    'type' => MENU_NORMAL_ITEM,
    'menu_name' => 'main-menu',
    'title' => $icon . t('Messages'),
    'page callback' => 'views_embed_view',
    'page arguments' => array('message_private', 'page_1'),
    'file path' => drupal_get_path('module', 'views'),
    'file' => 'views.module',
        'options' => array('attributes' => array(
       'html' => true
       )),
  );
  return $items;
}

```

However this just seems to get the escaped icon HTML in the menu.

How do I get the actual item from the icon API?

Is there some way to tell hook\_menu to pass everything as it is?

# Answer
> 0 votes
by `hook_menu` you are just registering a path to Drupal.

> Define menu items and page callbacks.

To get this printed with icon you can try contributed modules like

1. Menu Icons
2. Icon API

**Icon API module is able to apply your programmatic logic**

---
Tags: routes
---


# Question
Title: How can I log in as admin to my Commerce-kickstart demo site?
I am new to Drupal and I have completed the installation process for Commerce Kickstart in my XAMPP environment.

When I try to access the admin page of my sample commerce-kickstart demo eshop, I get an error like so:

> error 403 access denied

I am using the predefined Username (admin) and password and PHP 5.3.6.

Can anyone help me to get logged in as admin?

# Answer
Check if anything in this list of typical things might help:

* Check if you get the same problem using another browser. If with another browser it works, then it might be a cookie problem. To solve that, delete the cookie in the browser where you have the problem.
* Make sure "clean urls" is enabled. Refer to "Clean URL leads to duplicate URL after migration to another hosting" for more details on that.
* Make sure the value of "base\_url" is set correctly (in your settings.php).
> 2 votes

# Answer
For all Drupal installs you can use /users to /user/login to access login form, unless the paths have been changed.
> 1 votes

---
Tags: 7, users, commerce
---


# Question
Title: Drupal 7 Form API, Checkboxes with key -> value from database
I'm working on a custom module and I'm adding a form that uses checkboxes. All is fine with using code like:

$form\['tags'\] = array( '#type' =\> 'checkboxes', '#options' =\> array( 88 =\> 'option1', 100 =\> 'option 2', 79 =\> 'etc' ), '#title' =\> t('Tag this project as...'), );

The problem comes from the fact that I'd like to pull the key and value from the database (a specific taxonomy). I do not want to use an autocomplete, I want to use checkboxes.

Specifically, how do I get the results from the database and format into a proper array for the options array? Also, on the edit version of the form I'm creating, how do I show items that have been "checked" based on their value?

All of the examples I've seen are extremely basic and never show how to do this from a database call. Thanks for reading/answering

# Answer
To populate your options array with data from table `my_table`, with value keys from column `value` and text from column `atext`, you can use:

```
$options = array();
$result = db_select('my_table', 'mt')
            ->fields('mt', array('value', 'atext'))
            ->execute();
foreach ($result as $row) {
  $options[$row->value] = $row->atext;
}

```

To get taxonomy terms, you could use the code above to query `tid` and `name` from the `taxonomy_term_data` table (plus add a `condition()` for the vocabulary id), but for this specific usage you'd better to use the right API:

```
$options = array();
// Get term tree for vocabulary which id is in $vid.
$terms = taxonomy_get_tree($vid);
foreach ($terms as $term) {
  $options[$term->tid] = $term->name;
}

```

Just do not forget that vocabularies are tree structures. See the documentation for the `taxonomy_get_tree()` API to know how to limit the terms you want to get from a vocabulary wrt starting term and tree depth.
> 1 votes

---
Tags: 7, forms
---


# Question
Title: Logins with port numbers not including ports on redirect/login
We recently upgraded our site to use Drupal 7. Previously we were using Drupal 6. In the testing phase, the Drupal 7 instance was available at ports 8000 and 8443 of the main domain, while Drupal 6 was on the defaults, i.e.:

That worked fine for the testing phase; we were able to log in to each site and restrict D7 access to our internal network. Once we went live, we switched the ports, i.e.:

This is working in terms of production traffic, so the new D7 site is working fine. However, when we try to log in on the old D6 site for reference, we're redirected to and logged in on the D7 site. That is, operating to `https://www.example.com:8443/user` and logging in results in being directed to `https://www.example.com/user/foo/bar`, successfully logged in. Going back to the D6 site (on 8443) shows that we are not logged in there.

I thought it could be related to the cookie domain we were using (`.example.com`), which seemed a stretch, but removing that didn't help. I also thought it might be a base URL problem, though we have no base URL configured. The secure pages base URLs are configured with the port numbers.

Does anyone know or have an idea as to why this is happening?

I have a feeling that it's a simple thing I've overlooked in our configuration.

HTTPS is enforced on both sites by the Secure Pages module.

EDIT: we think we narrowed it down to the login form submission. The form appears to be submitted to the main domain, without the port. That's logging us in on the wrong site and preventing us from logging in on the D6 one. Why the form would submit without the port and how to fix it is now the issue.

# Answer
> 0 votes
Check if anything in this list of typical things might help:

---
Tags: 6, users, uri, redirection, cookies
---


# Question
Title: 2 views blocks on 1 page - no duplicate results
I have 2 views blocks with the same filter criteria. Both are displayed in different regions on 1 page. But they should not display the same results.

Is there a solution for that?

**Note**: The views have the same data. But they are sorted randomly.

# Answer
There are a few solutions:

1. You can use Panels module to build your page. Using this module you can insert a block in multiple times.
2. You can use this code into different regions to display the view

```
<?php print views_embed_view("VIEW_NAME","MACHINE_NAME","ARGUMENTS");

```

The views\_embed\_view displays the view.
3. You can also load the block itself despite of what entity has generated it's content by the following code

```
<?php
  $block = module_invoke('module_name', 'block_view', 'block_delta');
  print render($block['content']);
?>

```

The How to insert a block into a node or template in Drupal 7? gives you more details about the arguments of above code.
> 0 votes

# Answer
# Assumption

I'm assuming that the total number of rows returned by the view is at least twice the number of rows you display in each view. If not there is no correct solution possible to your question. E.g.: if you display 5 rows in each block, you must have at least 10 results (total number) ...

# Approach

Sort the view in the 1st block on "some column", say ascending (alternative: descending). And sort the view in the 2nd block on "the same column", say descending (alternative: ascending). In case you don't want the selected column to be shown in your block, just "hide it from the display".

# Pick a column

Probably a good (best?) fit could be the column you already used for that "random sorting" (you didn't mention yet HOW you implemented that sorting ...). If you don't have such column yet, check if any of the existing fields available in your view can be used for it (such as a node Id or something similar).
> 0 votes

---
Tags: views
---


# Question
Title: Is it possible to theme node add form in drupal 7
I am using zen drupal-7 sub theme. I have created a content type named *edison*. I need to change the node add form for the user. I've tried adding **page--node--add--edison.tpl.php** in **template.php**. I used the following code:

```
if (isset($variables['node'])) {
  $variables['theme_hook_suggestions'][] = 'page__node__' . str_replace('_', '--', $variables['node']->type);
}

```

When the `$variables['theme_hook_suggestions']` variable is printed, it looks like this:

```
Array (
  [0] => page__node
  [1] => page__node__add
  [2] => page__node__add__edison
  [3] => page__node__edison
)

```

The custom .tpl is not overriding the page.tpl.php.

# Answer
The `$variables['theme_hook_suggestions'][]` only suggests theme for the node itself not the form to add content!

**You have to let us know how exactly do you want to display your form. Some times a few CSS codes may be enough.**

Anyway to theme the node add content you can use `hook_form_alter` to add some attributes to the form elements, add CSS classes or ... . You can also use Firebug to get the fields ID or class names then use CSS to theme them.

The following code

```
function THEME_form_alter(&$form, $form_state, $form_id) {
      print $form_id;
}

```

gives you the ID of the form. Find the ID of the node add form and do the changes. like

```
function THEME_form_alter(&$form, $form_state, $form_id) {
      if($form_id == "NODE_ADD_FORM")
            ////
}

```
> 2 votes

---
Tags: 7, theming, nodes
---


# Question
Title: Which hook will use for checking taxonomy term page
I need to run a hook on every taxonomy term page load.

```
function mymodule_WhichHook(){
   if (arg(0) == 'taxonomy' && arg(2) == 'term' && is_numeric(arg(2)) ) {
    // Store taxonomy details to DB
   }
}

```

Which Hook can i use for this. Please suggest.

# Answer
> 1 votes
You may implement hook\_taxonomy\_term\_load in your module

---
Tags: taxonomy-terms
---


# Question
Title: Get Order Object on Checkout Complete Page
I'm trying to develop a new module but just can't get the correct solution, I hope you can help me.

On the checkout complete page i need the order object with all information of the just created order to print out an javascript code which will be created with the order data and execute when the user completes the checkout process. With the hook ***"myModule\_footer"*** I am getting into the footer to print my code and with "arg(2)" I can check if the URL is "complete". But now I need to get the order object but I just can't find the right way to do it.

I also tried other hooks like ***"myModule\_checkout\_complete"*** but they won't work:

```
function myModule_checkout_complete($order, $account) {
drupal_set_message('It works');
}

```

Is there an better solution to hook into the checkout complete page, get the order object and return some code to the frontend?

Thanks

# Answer
The hook `hook_uc_checkout_complete()` is the function you're looking for. However, you're going to have problems here since the function runs after the page display.

One way to get around this is override the theme function on the complete sale page:

```
function THEME_uc_cart_complete_sale($variables) {
  $order_json = json_encode($variables['order']);
  drupal_add_js('jQuery(document).ready(function () { var order = '.$order_json.'; console.log(order); });','inline');

  return $variables['message'];
}

```

This will execute JS code with the order object upon sale completion.
> 0 votes

---
Tags: 6, ubercart
---


# Question
Title: How to create custom search filter using view
I am using ubercart module in site. I need to create search filter,that will be search product sku,title and description etc.

# Answer
> 0 votes
i think Better Exposed Filters module helps you.

# Answer
> 0 votes
Yes, you can have multiple fields search in a single exported filter using Global: Populate filters and "Views filter populate" module.

Please, also, check this answer: https://drupal.stackexchange.com/a/43762

---
Tags: 7, views
---


# Question
Title: Customizing Drupal Commerce Bundle module
How can I customize Drupal Commerce Bundle module? My situation is that I am developing an Ecommerce site where user can buy Necklaces from necklace collection and lockets from locket collection, both combined to form a single product. So I have used commerce bundle module to achieve this. Now I am stuck in an issue which is what if the user wants to buy multiple lockets or multiple necklaces? Currently the user have the option to select only one of each type to form a single product. How can I achieve multiple selection?

Thanks In Advance

# Answer
IIRC you may have better results using Commerce Product Add-on, which allows you to have other products as add-ons. Product Bundles work well when you have fixed bundles - i.e. "A fork, spade, and bucket", not "Forks", "Spades", and "Buckets" you want to cross/upsell - if you know what I mean...!

https://www.drupal.org/project/commerce\_pado
> 1 votes

---
Tags: commerce
---


# Question
Title: WHen I delete products andvariations via VBO some are still left
I delete all my products and also the variations were deleted at the same time

but still after VBO delete under commerce/#overlay=%3Fq%3Dadmin%252Fcommerce%252Fproducts

some products are still left

why? I am attaching the image, there are empty products without variations inside that I cant delete

why is this happening?

# Answer
In Drupal Commerce there are products and product displays. Did you delete the products and perhaps these are the remaining displays, which aren't displaying properly because you deleted the products?
> 0 votes

---
Tags: commerce
---


# Question
Title: How to get a flag counter for anonymous users?
I'd like to have a counter for flagged nodes for anonymous users. I'd like to use a view. In this view I need a relationship to the anonymous user (session).

How can I get it?

Or is there another solution to get a flag counter for anonymous users?

# Answer
> 1 votes
The Session API module is required (a prereq) to make the Flag module functionality available for anonymous users (even with page caching enabled),

Consider checking out the great article about Enhancing the Anonymous User Experience: Adventures with Flags to get this to work.

---
Tags: 7, views, flags
---


title: Webform submissions

text:
# Question
Title: Webform submissions
I'd like to get the submission information from Webform, I checked the API but it's can't get me the data I need. The main goal would be to get every submission in a xml/json/array so I could get work done with the data. Anyone done this before?

Also I'd like to point out that I know I could read it out of the database directly, but it would look definitely nicer with API if it can be done with it.

# Answer
> 1 votes
Can't you just intercept the submission by a adding a a custom submit function with hook\_form\_alter, a la $form\['#submit'\]\[\] = 'yourModule\_yourForm\_submit'; ? Here I add it to the end of the submit functions array, but you can also put it first with array\_unshift. There you can grab the values before they go in the db and do as you please with them.

# Answer
> 0 votes
There's a module webform\_mysql\_views that exposes webform submissions to mysql views and combined with the data module you can expose them to views.

Als have a look at #680386: Views integration for the webform\_submitted\_data table

# Answer
> 0 votes
The function you need is webform\_get\_submissions. Here is a sample usage:

```
$submissions = @webform_get_submissions(array('nid'=>97));
foreach ($submissions as $submission {
  dpm($submission);
}

```

(Obviously, this is only for test and works if you have the Devel installed.

---
Tags: 7, webforms
---


# Question
Title: How to import url of the nodes via feeds
When I use url field in feeds import the url does not get imported for some reason

# Answer
> 0 votes
IIRC because the link field is multiple fields (title, link, description, etc.) you need to map it to the correct one, from quick google searching it seems the Link module dev version has a migrate file in it for this.

---
Tags: feeds
---


title: Can't open these tabs in my Browser

text:
# Question
Title: Can't open these tabs in my Browser
I'm working with my college on a drupal website. However, we're both logged in as Admin, but I can't open these tabs.

He says he has no problem with it and told me it could be a Java problem. I reinstalled Java and checked in mutiple browsers, but I still can't open them. Do you guys have any clue why?

I run on windows 8.1, I have the latest Java and Flash installed.

Thanks in advance.

# Answer
As *Clive* pointed out,

> You have javascript errors, the most common cause of that in the admin theme is using the jQuery Update module with its default settings. If you do have that module installed, just go to its config page, and select the default Drupal jQuery for the admin theme

The ***Jquery Update Module*** cause the problem. I configured the module and set my Jquery version to 1.10. This solved my problem
> 1 votes

---
Tags: javascript
---


# Question
Title: Need to make something like this in views
It contains Title of taxonomy term, thumbnail image and a trimmed Description. I am new to using views and adding HTML to them, can anyone help me how can i achieve this? I know basic steps but don't know what HTML should i add to achieve this kind of view. Thanks in advance

# Answer
> 2 votes
Is the picture a good start? Use a field picture and text. Add CSS to the field picture (see picture)

Add a custom text Use the replacement pattern to show picture and text.

Alter the css (with picture!) with something like .yourclass {float: left;}

# Answer
> 1 votes
I think you can done this using Views PHP or Global Text. First add all the needed fields in view, then add a global php field or global text field. You can use the replacement patterns for all initially added fields inside this global field and format it using html. Add all initial fields as 'exclude from display' in your view. Hope this will help you.

# Answer
> 1 votes
You can customize the HTML and CSS for a view. You can also enable or disable the default CSS classes.

```
1.Navigate to the edit screen for a view (for example, admin/structure/views/view/MYVIEWNAME/edit).
2.In the Fields section, click a field. The Configure Field dialog box displays.
3.Click Style Settings.
4.Enable one or more of the following options:
5.Customize Field HTML
6.Customize Label HTML
7.Customize Field and Label Wrapper HTML.
8.For each of the enabled options, specify the HTML element to wrap around the item. You can also click Create a CSS Class and specify a class name.
9.Enable or disable the Add Default Classes option. When enabled, this option specifies that the field uses Views default classes.
10.Click Apply.

```

You can create custom design of views with help of these things. Try and revert back.

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


# Question
Title: Cannot find out what is rendering a view block?
I am working on an existing Drupal 7 website. I have a view that has a block display. The block is being displayed on some pages in the "second\_sidebar" region. The mystery is that I cannot figure out how this block is being rendered/displayed in that region of those pages! In other words, the block is being added to the $page\['sidebar\_second'\] variable, but cannot find how it is being included in that variable.

Please take into consideration the following facts:

* The block is not being assigned to any region in "admin/structure/block
* In the page.tpl.php, there is no inclusion of that block in the page\['sidebar\_second'\] variable
* None of the theme templates are directly rendering that block

# Answer
> 1 votes
I have just found out that the Context module is installed which was rendering the block on those pages.

The "Themer Info" should have indicated that somehow.

# Answer
> 0 votes
Are you working on the right theme? How many theme's are installed? When you lock at admin/structure/block, how many theme's are mentioned under the title?

And: if you open the block, is there something in the tab 'pages'?

---
Tags: views, blocks, theming
---


# Question
Title: How can an author mark the update date of a node to be visible or hidden for visitors?
I want to let the author to specify whether node update date should be visible to visitors or not, per node (not node types) with a checkbox at node insert/edit form?

**Update**: I know how to use fields but I considered using something other than a new field. Something like variables.

Because I just want to save a simple Boolean value and I think fields will push an unreasonable overhead to Drupal for such a simple task.

# Answer
> 1 votes
I think using the Flag module could be a solution for this. A "Flag" is like a variable, and boolean (it is turned on or off, or set or unset). In this case a flag to indicate either "*Visible to vistors*" or "*Hidden to visitors*".

Probably combined with the Rules and the Content Access module. So that when the author SETs the flag to "Visible to vistors" (= The event used in the "Rule"), then via Rules you trigger an "action" to grant access to "the entire node" for anonymous users (if that is what you'd want to do).

If however the author should only be able to specify if visitors can yes or no see the update date of the node (so not to make the entire node yes/no visible), then these refinements/variations apply:

* Refine the meaning of the flag, something like "Update date visible to vistors", versus "Update date hidden for vistors".
* Use the Field Permissions module to grant access to the "update date" fields.
* If flagged as "Update date visible for vistors", then via Rules you trigger an "action" to grant field level access to "update date" for anonymous users also.

If you think like "hm, 3 modules instead of just using 1 extra field?", then think twice ... And note that this approach gives you so much more funtionality. Moreover, modules like Flag and Rules should be part of mostly any site (there are so much usecases for them ...).

# Answer
> 2 votes
You could add new field as a checkbox author check if he needs the update date visible to visitors.

Use panels and page manager to build a custom page view for that node type

Add visibility rule to display the update date if the checkbox field is checked

---
Tags: 7
---


# Question
Title: Select option values loaded with AJAX call, shows error illegal choice has been detected
I have a select field in my form named country. on change country i need to load values in state. I already placed the field for listing state, only want to load the values from ajax. In same way I need to add city field also. whenever I submit form it shows state (field loaded by ajax) is ' An illegal choice has been detected. Please contact the site administrator'. How can I update the new option values of field state which I have loaded from ajax call to the drupal form. How to clear the particular field cache data? i will provide a code sample soon .

```
$('#edit-field-p-location-value').change(function(){
        form_build_id = $('input[name=form_build_id]').val();
        locationval = $(this).val();
        var url = window.location.href;
        var arr = url.split("/");
        var result = arr[0] + "//" + arr[2];
        if(locationval!= ''){
            $.ajax({
                type : 'POST',
                url: result+"/gasf/getIPSecZone/"+locationval,
                data:{datacenter:locationval},
                success : function(data){
                    //$('#edit-field-p-ipseczone-value-wrapper').html(data);
                    $('#edit-field-p-ipseczone-value').html(data);
                }
            });
        }
    });

```

# Answer
You need to use the in-build Drupal AJAX functions rather than writing your own. The Examples for Developers module has detailed examples you can copy.
> 1 votes

# Answer
In this case you can add to select box

```
'#validated' => 'true'

```

in your form or in form\_alter. But i would like to suggest you, use Drupal AJAX.
> 0 votes

# Answer
Form Api in drupal 7 has some attributes like `["#ajax"]` etc which needs to be used for this, not the jquery way as you posted.

Try implementing the below logic, you will need to change the sql queries etc for fetching country/city etc

```
    function mymodule_country_state_city($form, & $form_state, $no_js_use = FALSE) {
        $options_first = _profile_myprofile_get_first_dropdown_options();
        if (isset($form_state['values']['state_of_residence'])) {
            $selected = isset($form_state['values']['country_of_residence']) ? $form_state['values']['country_of_residence'] : key($options_first);
        } else if ($profile_country_residence_country_id > 0) {
            $selected = $profile_country_residence_country_id;
            // $profile_country_residence_country_id is the default value
        }
        //$options_second = _ajax_example_get_second_dropdown_options($selected);

        $form['country_of_residence'] = array(
            '#type' = > 'select',
            '#title' = > 'Country of Residence',
            '#options' = > $options_first,
            '#default_value' = > $selected,
            '#required' = > TRUE,
        // Bind an ajax callback to the change event (which is the default for the
        // select form type) of the first dropdown. It will replace the second
        // dropdown when rebuilt
        '#ajax' = > array(
        // When 'event' occurs, Drupal will perform an ajax request in the
        // background. Usually the default value is sufficient (eg. change for
        // select elements), but valid values include any jQuery event,
        // most notably 'mousedown', 'blur', and 'submit'.
            'event' => 'change',
            'callback' = > 'ajax_example_dependent_dropdown_callback',
            'wrapper' = > 'dropdown-second-replace', ), );
        if (isset(
        $form_state['values']['state_of_residence'])) {
            $selected_state = isset($form_state['values']['state_of_residence']) ? $form_state['values']['state_of_residence'] : key($options);
        } else if ($profile_country_residence_state_id > 0) {
            $selected_state = $profile_country_residence_state_id;
        } else {
            $selected_state = 0; // 0 is default value
        }

        $form['state_of_residence'] = array(
            '#type' = > 'select',
            '#title' = > 'State of Residence',
            '#required' = > TRUE,
        // The entire enclosing div created here gets replaced when country_of_residence
        // is changed.
            '#prefix' = > '<div id="dropdown-second-replace">',
            '#suffix' = > '</div>',
        //    // when the form is rebuilt during ajax processing, the $selected variable
        //    // will now have the new value and so the options will change
            '#options' = > _ajax_example_get_second_dropdown_options($selected),
            '#default_value' = > $selected_state,
            '#ajax' = > array(
        // When 'event' occurs, Drupal will perform an ajax request in the
        // background. Usually the default value is sufficient (eg. change for
        // select elements), but valid values include any jQuery event,
        // most notably 'mousedown', 'blur', and 'submit'.
            'event' => 'change',
            'callback' = > 'ajax_example_dependent_dropdown1_callback',
            'wrapper' = > 'dropdown-third-replace', ), );

        $form['city_of_residence'] = array(
            '#type' = > 'select',
            '#title' = > 'City of Residence',
            '#required' = > TRUE,
        //    // The entire enclosing div created here gets replaced when country_of_residence
        //    // is changed.
            '#prefix' = > '<div id="dropdown-third-replace">',
            '#suffix' = > '</div>',
        //    // when the form is rebuilt during ajax processing, the $selected variable
        //    // will now have the new value and so the options will change
            '#options' = > _ajax_example_get_third_dropdown_options($selected_state),
            '#default_value' = > $profile_country_residence_city_id, );
        return $form;
    }

    function ajax_example_dependent_dropdown_callback($form, $form_state) {
        $commands = array();
        $commands[] = ajax_command_replace("#dropdown-second-replace", render($form['state_of_residence']));
        $commands[] = ajax_command_replace("#dropdown-third-replace", render($form['city_of_residence']));
        return array('#type' = > 'ajax', '#commands' = > $commands);
        //return $form['state_of_residence'];
    }

    function ajax_example_dependent_dropdown1_callback($form, $form_state) {
        return $form['city_of_residence'];
    }
    /**
     * Helper function to populate the first dropdown. This would normally be
     * pulling data from the database.
     *
     * @return array of options
     */
    function _profile_myprofile_get_first_dropdown_options() {
        $country_query_result1 = db_query("SELECT country_id,country_name FROM country ORDER BY country_name ASC");
        $country_array = array();
        foreach($country_query_result1 as $row1) {
            $country_array[$row1 - > country_id] = $row1 - > country_name;
        }
        return $country_array;
    }
    /**
     * Helper function to populate the second dropdown. This would normally be
     * pulling data from the database.
     *
     * @param key. This will determine which set of options is returned.
     *
     * @return array of options
     */
    function _ajax_example_get_second_dropdown_options($key = '') {
        ///$i = 1;
        $options = array();
        $country_query_result1 = db_query("SELECT country_id FROM country ORDER BY country_id ASC");

        foreach($country_query_result1 as $row1) {
            $country_id = $row1 - > country_id;
            //    $country_id = $key;

            $state_query_result2 = db_query("SELECT state_id,state_name FROM state WHERE country_id = :country_id", array(':country_id' = > $country_id));
            $state_array = array();
            $state_array[0] = '-- Select State --';
            foreach($state_query_result2 as $row2) {
                $state_array[$row2 - > state_id] = $row2 - > state_name;
            }
            $options[$country_id] = $state_array;
        }
        if (isset($options[$key])) {
            return $options[$key];
        } else {
            $options1 = array('0' = > '-- Select State --');
            return $options1;
        }
    }

    function
     _ajax_example_get_third_dropdown_options($key = '') {
        ///$i = 1;
        $options_second = array();
        $country_query_result1 = db_query("SELECT country_id FROM country ORDER BY country_id ASC");
        $state_array1 = array();
        foreach($country_query_result1 as $row1) {
            $country_id = $row1 - > country_id;

            $state_query_result2 = db_query("SELECT state_id FROM state WHERE country_id = :country_id", array(':country_id' = > $country_id));
            $state_array = array();
            foreach($state_query_result2 as $row2) {
                $state_id = $row2 - > state_id;
                $state_query_result3 = db_query("SELECT city_id,city_name FROM city WHERE state_id = :state_id", array(':state_id' = > $state_id));
                $state_array3 = array();
                $state_array3[0] = '-- Select City --';
                foreach($state_query_result3 as $row3) {
                    $state_array3[$row3 - > city_id] = $row3 - > city_name;
                }
                $options_second[$state_id] = $state_array3;
            }
        }

        if (isset($options_second[$key])) {
            return $options_second[$key];
        } else {
            $options1 = array('0' = > '-- Select City --');
            return $options1;
        }
    }

```

Some useful links: http://w3shaman.com/article/creating-ajax-dropdown-drupal-7 http://taggartjensen.com/code-snip/drupal-7-custom-form-ajex-use-custom-table
> 0 votes

---
Tags: 6, ajax
---


# Question
Title: How to call form function in menu callback in drupal7?
I have **one menu and two functions** that want to call on **same menu**. What I am doing is, in ***hook\_menu*** page callback i am calling a function and in that function i am calling another function.Means, ***calling function inside a function in page callback of menu***. Now my ***PROBLEM IS***, my secong function is a form.

```
$items['component/%/edit'] = array(
    'title' => 'Edit Component item',
    'page callback' => '**component_list_edit**',
    'page arguments' => array(3),
    'access arguments' => array('administer users'),
    'file' => 'popup.inc',
    'type' => MENU_CALLBACK,
  );

```

My Page callback:

```
/**
 * ajax popup edit function : ctools implementation
 */
function component_list_edit() {
ctools_include('modal');
  ctools_modal_add_js();
  return _mid_component_make_link('Title').component_type_select_list_form($form, $form_state);
}

```

It is giving "ARRAY" as an output. no form m getting. I also tried to `return drupal_get_form('component_type_select_list_form');` This is also not working.

# Answer
After some sort of study, I got to the answer. we can get form by using drupal\_get\_form and then in return function, we need to render it also. for example:

```
function component_list_edit() {
  $form = drupal_get_form('component_type_select_list_form');
  // Load the modal library and add the modal javascript.
  ctools_include('modal');
  ctools_modal_add_js();
  return '<div class="title_display">Title:'._mid_component_make_link('Title').drupal_render($form).'</div>';
}

```
> 1 votes

---
Tags: forms, routes, chaos-tool-suite
---


title: Search module issue

text:
# Question
Title: Search module issue
I am using drupal search module, when I searched for let say "MG-1055" (this is one of my product's article number) it successfully display the results but if I try to search only "MG" or "1055" then it did not search.

# Answer
Drupal's core search don't allow faceted search. It should be replaced with
> 1 votes

---
Tags: 7, search
---


# Question
Title: how to display array in div structure in drupal 7?
How can I render arrays in div structure in drupal?. I am having a select list with ajax callback.Everytime I choose option, it's fields get fetched into an array. Now how can I show that array fields value?

```
$nodes = array();
    $output = array();
    $i=0;
    $nids = db_select('node', 'n')
      ->fields('n', array('nid'))
      ->condition('type', 'article', '=')
      ->execute()
      ->fetchCol();
    $nodes = node_load_multiple($nids);
     foreach ($nodes as $node => $value) {
      $output[$i]['title'] = $value->title;
      $output[$i]['body'] =$value->body['und']['0']['value'];
      $i++;
    }
    return output;

```

If I used `return theme('item_list', array('items' => $output));`, it is not working for me. Please help.

# Answer
After a research of 20 minutes, I came to this answer.`theme('item_list', array('items' => $output));` This function follows a simple array key value structure.It doesn't support multiple idexes. so remove $i from array, and it will work.
> 1 votes

---
Tags: nodes, 7
---


# Question
Title: How to translate the Automated Logout module administration?
How to translate language of the Automated Logout module administration?

I was searching for translation of polish language and tired other modules.

# Answer
There IS a Polish translation of the autologout module available. Though it is currently only translated for 42%.

The way I understand (translate???) your question is something like so: **How can I show the admin interface for the Automated Logout module in the Polish language?**

To answer that question, just swich to the Polish version of your site, and then use the admin link. As an alternative, enable the "language switcher block" so that it is shown within the theme you're using for Administration. Then navigate to anywhere within admin (whatever language), and use the language switcher block to show the admin interface in Polish (for about 42%). If you also want the remaining 58% to be shown translated, then it's up to you to actually add your custom translations of the various missing translations.
> 0 votes

---
Tags: i18n-l10n
---


# Question
Title: Associate webform submissions with the user created
I am allowing anonymous user create submissions, and creating a user programmatically based on these submissions. How do I associate this submission with the user I've just created?

UPDATE: I thought I could use db\_update for this but I'd be interested to know if there is a more functional way.

# Answer
If you inspect your `webform_submissions` table you'll see the relevant column. So to do it after the fact you could do:

```
UPDATE webform_submissions SET uid = 123 WHERE sid = 456;

```

(just an example, use db\_update and proper placeholers for this)

If you do it in the context of `hook_webform_submission_presave` then you should just be able to update the submission which is being passed by reference:

```
function mymodule_webform_submission_presave($node, &$submission) {
  global $user;
  $submission->uid = $user->uid;
}

```
> 0 votes

# Answer
I would recommend checking out the available hooks provided by the Webform module: http://cgit.drupalcode.org/webform/tree/webform.api.php

It looks like `hook_webform_submission_insert()` will be your best bet, with that you should be able to not only programmatically create the user at that point, but then update the submission with the newly created user id.

```
function my_module_webform_submission_insert($node, $submission) {
  // Create new user.
  // Retrieve new user id.
  // Update webform submission with new user id.
}

```
> 0 votes

---
Tags: hooks, webforms
---


# Question
Title: how to get list of field names by select its node type in drupal?
I got the all node type list in a variable using get\_node\_type\_info() and now am passing this variable to field\_info\_instances as:

```
array_keys(field_info_instances("node", $op_keys));

```

ps: *$op\_keys is the variable to get node types.* But this is giving me list of **node\_type** "keys" and I want **field** "keys".

Either tell:

> (1)how to pass list of all node types as a $bundle\_name in field\_info\_instances() ?

or

> (2) when selecting any of the **node\_type** (*as an option of select list*) from select list, it's corresponding **field's name** will get rendered. I mean to say for example: node\_type = "Article" and its field names = *"body", "title", "image"*. when "**article**" got clicked from select list, *"body", "title", "image"* should get rendered.

# Answer
Try field\_read\_fields you should be able to request `keys` as a parameter in argument 1. And then for the conditions in argument 2 limit the fields returned by the inquiry by supplying `entity` and `bundle` keys to limit how many fields you get back. You may get back the fields used in the bundle -- but it should include the keys value.
> 0 votes

# Answer
To get a list of field names for each content type,, stored in a variable "list", given an array of bundle names, you could do: `$list = array();
foreach($bundle_names as $bundle){
 $list[$bundle] = array_keys(field_info_instances('node', $bundle));
}` Hope that helps.
> 1 votes

---
Tags: nodes
---


title: Modal Bootstrap in page.tpl.php

text:
# Question
Title: Modal Bootstrap in page.tpl.php
Have been struggling with view and modal to display related node content for a few days, but in vain.

In view, a page is to display / list only thumbnail images (Display Suite) with rewritten link to trigger the modal with data-target. Then bootstrap modal code is placed in page.tpl.php.

So on view page, on click the thumbnail, the modal shows up. The problem is how to display title, body and images? Tried `<?php print $node->title; ?>` but when refreshing the view page, it shows blank page.

Is it not possible to display related node content of the thumbnail on modal?

Have tried Bootstrap modal and JQuery Ajax Load but they don't work at all. Documentation isn't clear either.

Help very much appreciated

# Answer
> 0 votes
If you want to show your node in a modal, a simpler approach would be to use the Colorbox and the Colorbox node modules (the last one has Views integration).

So after installing both modules, go to your View; in your Fields, when you click on any of them, you will see that the option "Link this field to the original piece of content" now has another one that says "Display the content inside of a colorbox". Check it, and it will make your nodes open in a modal window (colorbox).

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


# Question
Title: How to display a views grid in a responsive (mobile friendly) grid layout?
I have a Views grid format, with 3 columns. I want to see the columns in cascade on mobile devices.

Any suggestions how to do so?

# Answer
> 1 votes
Consider the Views Responsive Grid module. Here is a quote about it (from its project page):

> ... provides a views plugin for displaying content in a responsive (mobile friendly) grid layout. Rather than trying to force the standard Views grid display to work for mobile this provides the same functionality, but in DIVs instead of tables. Provided is also the ability to specify a horizontal or vertical grid layout which will properly stack the content on a mobile display.
>
> Features:
>
> * Horizontal or vertical grid layouts
> * Custom classes for use with responsive themes

**Note**: available for D7 only (not for D6). This is what the project page states regarding D8:

> This module will not be ported for Drupal 8. Views grids in core have been replaced with DIVs (#1903746: Replace the views grid table template with one using divs)!

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


# Question
Title: How to change the "Check boxes/radio buttons" fields weight?
I have created a radio buttons field in entity form. I just want to move yes label above and No label below. How to achieve that i am not getting any option.

# Answer
You can try hook\_form\_alter to reorder your field options.

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

  if($form_id == 'myform_id'){

    $form['field_like_event']['und']['#options'] = array(1 => 'Yes', 0 => 'No');
  }
}

```

Note: You can change the "On" and "Off" values by interchanging "Yes" as Off value (0) and "No" as On value (1) at edit form field settings. But in general we will use 1 for "Yes" and 0 for "No". My suggestion is to use form alter method.
> 0 votes

# Answer
In field edit settings page, you can organize your options in "Allowed values list" section.
> 0 votes

---
Tags: forms
---


title: db_query and db_select

text:
# Question
Title: db_query and db_select
I have static query (db\_query works great) but for some reason, I have to put a condition to the query result

I don't want to re-write the same db\_query with "where", I'm looking for a way to write just the condition part and avoid to re-write all the query.

So I want to add a condition (that is for dynamic query) to a static query

Is there any solution ?

Here is one example on my code :

```
$resultat = db_query(
    "SELECT `field_titre_en_arabe_value`, `field_etat_du_livre_value`, e.denomination_ed, entity_id, `field_prix_value`, `name`
    FROM (
        SELECT `nid`, ta.entity_id,  n.created, `field_titre_en_arabe_value`, `field_etat_du_livre_value`,`field_prix_value`,`name`, n.uid, edi.field_edit_target_id, COALESCE (edi.field_edit_target_id, n.uid) as newid
        FROM {node} as n
            left join {field_data_field_etat_du_livre} as et on n.nid = et.entity_id
            left join {field_data_field_titre_en_arabe} as ta on n.nid = ta.entity_id
            left join {field_data_field_edit} as edi on n.nid = edi.entity_id
            left join {field_data_field_prix} as pr on n.nid = pr.entity_id
            left join {field_data_field_categorie} as cat on n.nid = cat.entity_id
            left join {taxonomy_term_data} as tax on cat.field_categorie_tid = tax.tid
        ) as tabb
        left join {editeur} as e on e.uid = tabb.newid
        order by  field_etat_du_livre_value asc, created desc"
);

```

Now here is the condition I was talking about, and look at the 'where' part, it came after I re-write the same first query, I want to write only the "where" part after the if

```
if (isset($form_state['storage']['etat_livre'])){
    $resultat = db_query(
        "SELECT `field_titre_en_arabe_value`, `field_etat_du_livre_value`, e.denomination_ed, entity_id, `field_prix_value`, `name`
        FROM (SELECT `nid`, ta.entity_id,  n.created, `field_titre_en_arabe_value`, `field_etat_du_livre_value`,`field_prix_value`,`name`, n.uid, edi.field_edit_target_id, COALESCE (edi.field_edit_target_id, n.uid) as newid
            FROM {node} as n
                left join {field_data_field_etat_du_livre} as et on n.nid = et.entity_id
                left join {field_data_field_titre_en_arabe} as ta on n.nid = ta.entity_id
                left join {field_data_field_edit} as edi on n.nid = edi.entity_id
                left join {field_data_field_prix} as pr on n.nid = pr.entity_id
                left join {field_data_field_categorie} as cat on n.nid = cat.entity_id
                left join {taxonomy_term_data} as tax on cat.field_categorie_tid = tax.tid
        ) as tabb
        left join {editeur} as e on e.uid = tabb.newid
        where field_etat_du_livre_value = :field_etat_du_livre_value
        order by field_etat_du_livre_value asc, created desc", array(
            ':field_etat_du_livre_value' => $form_state['values']['etat_livre']
        )
    );

```

As it is now, it works, but i think the code is redundant is there any way to avoid that please ?

# Answer
Since you are querying some tables to get the value of an entity field, I would rather use the `EntityFieldQuery` class.

To answer your question, what you want to achieve can be obtained by concatenating strings to the the query string.

```
$query = "The first part of the query";
$args = array();

if (isset($form_state['storage']['etat_livre'])) {
  $query .= "WHERE field_etat_du_livre_value = :field_etat_du_livre_value";
  $args[':field_etat_du_livre_value'] = $form_state['storage']['etat_livre'];
}

$query .= "ORDER BY field_etat_du_livre_value ASC, created DESC";

$result = db_query($query, $args);

```

As side note:

* The query should not use back-ticks
* The reserved words should be written in upper case
> 1 votes

# Answer
The Database abstraction layer would help make this far more simple. For example:

```
$results = db_select('table_name', 't')
    ->fields('t')
    ->condition('t.column_name', $form_state['storage'])
    ->execute();

```
> 1 votes

---
Tags: database
---


# Question
Title: Show only comment textarea, if entered something show required fields for anonymous user
I want to make commenting easy for anonymous users. ***"Anonymous posters must leave their contact information."*** is enabled.

## What I want to do is to show **only** the comment text field **at first** and if the user **enter** some text (more than 20 characters etc) then show the other fields (name, e-mail, homepage).

I think it will be better not to show 3-4 empty fields instead of one text area to comment. First, **focus** on the comment (content) and then the required fields.

**Is there any out of the box solution for this or if anybody did that before?**

# Answer
### Paste in file `template.php`

```
function MYTHEME_form_alter(&$form, &$form_state, $form_id) {
  if($form_id == 'comment_node_blog_form') {
    $form['author']['name']['#attributes']['class'][] = 'validate[required]';
    $form['author']['mail']['#attributes']['class'][] = 'validate[required,custom[email]]';
    $form['comment_body']['und'][0]['#attributes']['class'][] = 'validate[required,minSize[20]]';
    $form['#attached']['js'][] = drupal_get_path('theme', 'MYTHEME') . '/js/jquery.validationEngine-en.js';
    $form['#attached']['js'][] = drupal_get_path('theme', 'MYTHEME') . '/js/jquery.validationEngine.js';
    $form['#attached']['js'][] = drupal_get_path('theme', 'MYTHEME') . '/js/scripts.js';
  }
}

```

### change `form_id` with your form comment

### Source jQuery validate and file scripts.js

```
(function ($) {
    $(document).ready(function(){
        $("#comment-form").validationEngine();
        $('#comment-form').find('.form-type-textfield').hide();
        $('#edit-comment-body').keyup(function() {
            var value = $(this).find('.text-full').val(),
                lenght = value.length;
            if (lenght > 20) {
                $('#comment-form').find('.form-type-textfield').show();
            }
            else {
                $('#comment-form').find('.form-type-textfield').hide();
            }
        });
    });
})(jQuery);

```

### Form with empty text

### Form with more 20 characters
> 3 votes

# Answer
You need to have an js file to hide and show elements , if you dont know how to write that code , read Jquery text change event , jquery hide and jquery show . now in your module file Implement form-alter for comment form , and add your js file to form using :

```
 function mymodule_form_alter(&$form, &$form_state, $form_id) {
  if($form_id == *****){//find comment form id using firebug
    $form['#attached']['js'][] = array(
      'data' => drupal_get_path('module', 'MODULE_NAME').'/js/myscript.js',
      'type' => 'file',
    );
  }
}

```

if you don't know how to find comment form\_id look here : http://www.digett.com/blog/05/26/2011/how-theme-comment-form-drupal-7
> 2 votes

# Answer
To do so you can use Field Conditional States or Conditional Fields modules.

> Conditional Fields allows you to manage sets of dependencies between fields. When a field is “dependent”, it will only be available for editing and displayed if the state of the “dependee” field matches the right condition. When editing a node (or any other entity type that supports fields, like users and categories), the dependent fields are dynamically modified with the States API. You can, for example, define a custom “Article teaser" field that is shown only if a "Has teaser" checkbox is checked

These dependencies are not only between the fields of the content type but also between the fields of the comment fields as well. As an example

These modules allows you set dependencies among the fields of comments as well, As you can see *Comment Dependencies* is for doing such thing:

You can also use Field formatter conditions module. This module changes the format of fields in *manage display* base on conditions of other fields.

> Adds conditions to field formatters. Configuration happens on the "Manage Display" screens of every entity type on a per field basis when clicking on the cogwheel on the right.

So by this module you can

* Hide source field when target field is empty.
* Hide source field when target field is not empty.
* Hide source field when current user has specific roles.
* Hide source field on specific pages.
* Hide source field when target field contains a specific string.
* Hide source field when target field doesn't contain a specific string.
* Hide link field if title is empty.
* Hide date field if from/to has expired.
> 1 votes

---
Tags: 7, comments
---


# Question
Title: Boost Module: Delete Cache for single node on update
I use Boost module for Drupal Commerce. How can i clear the cache for only one cached node after updating that node. I don´t want to clear the cache for all nodes but only for the one i updating.

# Answer
You should be able to do this using the Cache Expiration module: https://www.drupal.org/project/expire

You might use the rules integration:

* event: a node is saved
* condition: (type of node, etc - depends on your scenario, might be nothing)
* action: expire URL
> 1 votes

---
Tags: commerce, caching
---


title: require doesn't work in a module's file

text:
# Question
Title: require doesn't work in a module's file
I have this module's inc file, which hold `page callback` functions. Also I have a 'config.php' file that hold the parameters. I know this is not a good practice, but I would like to leave these config there for now.

Here is the question, I cannot get access to the parameters in the config.php file after I used `require 'config.php'` or `require_once 'config.php'`.

e.g. I have admin.inc which holds these:

```
<?php
    require 'config.php';

    function my_page_callback(){
        global $config;

        var_dump($config); //this prints NULL when I access this menu item.
    }

```

and config.php holds these an located in the same folder:

```
<?php

    $config = array();
    $config['key'] = 'value';
    $config['name'] = 'foobar';

```

The file is successfully included since there is no fatal error, but why can't I get these values?

## update

`var_dump($config);` this would print the right content after I move the require statement to the body of `my_page_callback`, but I don't think this is how PHP works.

Explicitly set `$config` as global in the required file could give non-NULL result, but it is not needed in my test files.

# Answer
> 1 votes
I'd comment on sceo's answer, but I can't yet.

More information on declaring it as global $var: https://www.drupal.org/node/633230#comment-2267370

But as is recommended here, in the link and everywhere really, if you want globals use variable\_set and variable\_get (or use constants? You can serialize the array, as constants before PHP 5.6 can't accept arrays).

You can also make a function in your module file that simply returns the array you want to use. Not sure how correct or efficient that is, but it does work.

```
function mymodule_get_config() {
    return array(
      'key' => 'value'
    );
}

```

# Answer
> 1 votes
You can use this approach to include a file in .module

```
function module_name_init(){
    module_load_include('inc', 'module_name', 'includes/common');
}

```

and place common.inc file in includes folder in your custom module.Now write your php code here.

# Answer
> 0 votes
Agree that this is bad practice and you should be setting these values using variable\_set and variable\_get, or with a module config form.

However, it should work the way you have it with the exception that you will need to 'global $config' in the config.php file AND then again in my\_page\_callback().

You would do better to rename $config to something more specific, so you don't have collisions with anything else in the global scope, so change $config in config.php to something like $my\_module\_config or something.

---
Tags: 7
---


# Question
Title: How can I encapsulate Drush command with option to use arguments
I have a drush command for installing a Drupal website with configuration in it. I do not want to type this command with all the configuration all the time because it is long so I would like to encapsulate the command as alias but I still want to pass additional arguments to the original command.

Specifically I need to pass at least the db url since that will always be different.

I was thinking something like this: `drush install-mysite --db-url="..."`

So basically any argument that is provided to my alias would override the defined argument defined in my alias.

From what I have read this could be done with drush aliases but I am not sure about the syntax and the arguments themselves. Another way is to create a new drush function but I think alias is simpler and I don't need any additional functionality.

This is for Drupal 8 so Drush 7 but I think it is not that relevant.

# Answer
The best way to provide default options to a Drush command, whether it is a core Drush command or a custom command you have written, is to place your default values into a drushrc.php file under a command-specific option.

For example, if you wanted the Drush site-install command to always name the site admin 'superuser', and you wanted to always install with the password 'secretsecret', then you could add the following definition:

```
$command_specific['site-install'] = array(
  'account-name' => 'superuser',
  'account-pass' => 'secretsecret',
);

```

If you later decided you wanted to use a different account name for a site you were installing, then you could just run `drush site-install --account-name=su`, and the option from your configuration file would be overridden.

If the only purpose of your `install-mysite` command was to select default values for `site-install`, then the above configuration is all that you will need. If you want to add additional code that does other things after the install, though, then you could go ahead and write your custom command, and place a `$command_specific['install-mysite']` entry in your drushrc.php file to provide the default values for your command's options.

If you only want to make minor changes to the way the `site-install` command works, you might want to also consider providing a "policy file" that provides a hook that runs after the install command finishes. See policy.drush.inc for details.
> 1 votes

---
Tags: 8, drush
---