title: Submitting a Form with AJAX in a block

text:
# Question
Title: Submitting a Form with AJAX in a block
So, I have a form that I wish to appear in a block. Now, I don't want the submission of this form to trigger an entire page reload, so I was hoping to use the built in AJAX framework.

I've tried several different things, but my current code is below. The data gets saved, but I can't figure out how to reset the form; anything I've tried has just left the data in the fields. Any help would be appreciated. Thanks.

```
/**
 * Implements hook_block_view()
 */
function test_contact_block_block_view($delta)  {
  switch ($delta) {
    case 'contact_block':
      $block['subject'] = t('Contact');
      $block['content'] = drupal_get_form('test_contact_block_form');
      break;
  }
  return $block;
}

function test_contact_block_form($form, &$form_state)   {
for_testing();

$form = array();
$form['form'] = array(
    '#prefix' => '<div id="form-wrapper">',
    '#suffix' => '</div>',
);
$form['form']['access_id'] = array(
    '#type' => 'textfield',
    '#title' => t('Customer Access ID'),
    '#size' => 10,
    '#required' => true,
);
$form['form']['summary'] = array(
    '#type' => 'textfield',
    '#title' => t('Summary'),
    '#size' => 20,
    '#required' => true,
);
$platforms = explode(chr(13), variable_get('test_waiver_platforms', ''));
$form['form']['platform'] = array(
    '#type' => 'select',
    '#title' => t('Platform'),
    '#options' => array_combine($platforms, $platforms),
);
$contact_channels = explode(chr(13), variable_get('test_waiver_contact_channels', ''));
$form['form']['contact_channel'] = array(
    '#type' => 'select',
    '#title' => t('Contact Channel'),
    '#options' => array_combine($contact_channels, $contact_channels),
);
$form['form']['minutes'] = array(
    '#type' => 'textfield',
    '#title' => t('Minutes'),
    '#size' => 10,
    '#required' => true,
);
$form['form']['category'] = array(
    '#type' => 'select',
    '#multiple' => true,
    '#title' => t('Category'),
    '#description' => t('ctrl+click (Win)/cmd+click (Mac) to select more than one.'),
    '#options' => _get_services(),
    '#size' => 15,
    '#required' => true,
);
$form['form']['submit'] = array(
    '#type' => 'button',
    '#value' => t('Submit Contact'),
    '#attributes' => array('onclick' => 'return false;'),
    '#ajax' => array(
        'wrapper' => 'form-wrapper',
        'callback' => 'test_contact_block_form_callback',
    )
);
$form['form']['message'] = array(
    '#type' => 'item',
    '#markup' => t('Only for <b><u>NON</u></b> waivers.'),
);

return $form;
}

function test_contact_block_form_callback($form, &$form_state)  {
if(!ctype_digit($form_state['values']['minutes']))  {
    form_set_error('minutes', 'You must enter an integer for minutes');
}
else {// THE INCLUDE IS JUST FOR THE FUNCTION BELOW THAT'S COMMENTED OUT
    //module_load_include('inc', 'test_waiver', 'test_waiver.admin');
    // Gather all the variables
    global $user;
    $user_accessid          = $form_state['values']['access_id'];
    $summary                        = $form_state['values']['summary'];
    $platform                   = $form_state['values']['platform'];
    $contact_channel      = $form_state['values']['contact_channel'];
    $time_spent                 = $form_state['values']['minutes'] * 60;
    $categories                 =   $form_state['values']['category'];
    $comments                   = '';
    $last_con_accessid  = '';
    $close = true;
    // Submit to Jira
    // THIS IS EFFECTIVELY WHERE THE DATA IS SAVED/STORED IN THE DB; this already seems to work okay, so I commented it out
    //test_waiver_submit_jira_ticket($user_accessid, $summary, $platform, $contact_channel, $time_spent, $categories, $comments, $last_con_accessid, $close);
    // Reset values
    $form_state['input']['access_id'] = '';
    $form_state['input']['summary'] = '';
    $form_state['input']['platform'] = null;
    $form_state['input']['contact_channel'] = null;
    $form_state['input']['minutes'] = '';
    $form_state['input']['category'] = null;
}
$form_state['rebuild'] = TRUE;
return $form['form'];
}

// FUNCTIONS BELOW WERE ADDED FOR TESTING

function for_testing()  {
variable_set('test_waiver_platforms', 'Windows' . chr(13) . 'Mac');
variable_set('test_waiver_contact_channels', 'Walk-In' . chr(13) . 'Phone');
}

function _get_services()    {
return array('service 1' => 'service 1', 'service 2' => 'service 2');
}

```

(I've done my best to remove superfluous/too specific/dependent code, in the event that anyone wants to attempt to run it themselves.)

I can NOT get this to work. I have questions like:

* Should I use '#type' 'button' or 'submit'? The docs aren't very clear on what the real difference between the two are, and I get slightly different behavior with each.
* Should I use an onClick attribute to return false with the button?
* Do I need and additional '#submit' callback to make the change? Or can/should it be done within the ajax callback? (I can't seem to change the $form\_state, even when receiving it as a reference.)

# Answer
You can use webform rather than custom code. Its very easy to use. No coding skill required.

Steps to do

* Install webform and webform ajax module
* Create a webform, add required fields.
* In form setting, Go to Advance setting and enable "available as block".
* Just below that, enable "ajax mode".

You can configure email also in email setting.
> 1 votes

# Answer
Try the below code snipped. It will try to rebuild the form

```
  $form_state = array('storage' => NULL, 'submitted' => FALSE);
  $form_build_id = $_POST['form_build_id'];
  $form = form_get_cache($form_build_id, $form_state);
  $args = $form['#parameters'];
  $form_id = array_shift($args);
  $form_state['post'] = $form['#post'] = $_POST;
  // Enable the submit/validate handlers to determine whether AHAH-submittted.
  $form_state['ahah_submission'] = TRUE;
  $form['#programmed'] = $form['#redirect'] = FALSE;
  drupal_process_form($form_id, $form, $form_state);
  $form = drupal_rebuild_form($form_id, $form_state, $args, $form_build_id);

```

Add this code on top of the test\_contact\_block\_form\_callback function.
> 0 votes

---
Tags: forms, ajax
---


title: Dynamic filtration in tree hirarchy

text:
# Question
Title: Dynamic filtration in tree hirarchy
I want a tree structure like below:`-parent1
 +child 1
 +child 2
 -child 3
 +sub child 1
+parent2
+parent3` ... and when a user click on lets say "child1" then items in views related to them will be filtered. How can I achieve this?Can any one please help me?

# Answer
> 0 votes
Did you try Simple hierarchical select module. You can build your tree structure with Drupal taxonomy.

Unlike Hierarchical select this module provides a simple widget for taxonomy terms only. As an addition Simple hierachical select works as Views exposed filter.

---
Tags: 7
---


# Question
Title: "contact" SQL table: what is it for and where do I edit it?
We are running a site with the Hotel Diamond theme. Today we received a bounced email: apparently, someone had tried using the contact form in the site to send us a message, and the system had tried sending it to "test@localhost.com".

Now, the Hotel Diamond theme has an option to configure the email for the contact page, but it is correctly configured (i.e., it's NOT "test@localhost.com"). So I decided to look for that address in the raw SQL dump of my site, and I found this:

```
INSERT INTO `contact` (`cid`, `category`, `recipients`, `reply`, `weight`, `selected`) VALUES
(1, 'Website feedback', 'test@localhost.com', '', 0, 1);

```

My question is: where do I edit that in the admin pages? And why is Drupal using this entry to send contact email, instead of the address we had configured in the Hotel Diamond config page?

# Answer
Go to `admin/structure/contact/edit/1` and change Recipients email address to whatever you want.
> 1 votes

---
Tags: database
---


# Question
Title: What is cache_menu in Drupal 7 DB? Safe to empty?
What exactly is doing this cache\_menu table in MySQL Database of my Drupal 7?

It is the hugest table of all = currently 308 mb.... (and I have disabled search term indexing, so this is absolutely the biggest now...)

Is it necessaru so huge?! I assume it is so huge, because I it includes a few of my Book - menus as well, but still...

If it is just a Cache - would it be safe to empty / disable somehow?

# Answer
> 1 votes
> What exactly is doing this cache\_menu table in MySQL Database of my Drupal 7?

Not to sound too glib, but it does exactly what it says - it stores cache for the menu system.

> Is it necessaru so huge?!

It's as big as it needs to be - if you have a lot of menu structure, it will be large. But 300mb isn't exactly a lot of data in this day and age.

> If it is just a Cache - would it be safe to empty / disable somehow?

Depends how you define "safe". Yes, your site will still work, but rebuilding the menus from scratch on every page load is likely to make your page requests take quite a bit longer.

You can safely truncate that cache bin and let it rebuild; maybe there is stale data in there that won't be re-added when the menus are built up again.

# Answer
> 0 votes
Change the Cache Expiry life time... It will clear all the cache table and lets your site to speed up. Go to "your\_site/admin/config/development/performance". If you delete this table, your site menu's wont work and gives error while loading pages"

---
Tags: database, caching
---


title: Do I need to clone a webform?

text:
# Question
Title: Do I need to clone a webform?
I have created a webform a few days back. Now I want to re-use the webform which I created earlier with other results, so to save my time and energy I just want to clone that webform and reuse for a different purpose.

Note: previous webform has some result. However I do not want to have this result in the exported webform, I only need the form.

# Answer
Use Webform Share(https://www.drupal.org/project/webform\_share) module to export & import

Example usage 1: Prepopulated webforms

1. Create a webform with the required components.
2. Export the webform
3. Edit the webform content type and paste in the content from the export (under Publishing options)
4. Use the standard node add content links and each new content item created should be prepopulated with the exported webform.
> 3 votes

# Answer
Node clone module is another option for webform

> The clone module allows users to make a copy of an existing item of site content (a node) and then edit that copy. The authorship is set to the current user, the menu and url aliases are reset, and the words "Clone of" are inserted into the title to remind you that you are not editing the original content.
> 3 votes

# Answer
You can use Node Clone for cloning webforms or any nodes. It provides a simple interface to clone webform or nodes on node page itself.

If you want to export the submission data also then you can use webform import module.
> 1 votes

# Answer
If you need the webform configuration of the webform node you can use https://www.drupal.org/project/webform\_template

> **Copy webform configuration from one node to another**
>
> This is an add-on module for Webform that allows you to select webform enabled content types as "source" and/or "destination" types. On node edit/creation of the so called "destination" types, you have to option to apply (= copy) the webform settings (including all webform fields) from nodes of the "source" type.

Im note sure about the submissions.
> 0 votes

---
Tags: 7, webforms
---


# Question
Title: "An illegal choice has been detected. Please contact the site administrator." with exposed sort fields
I have a panel which displays a page that was created in views. When a user clicks the next button on the pager, it displays the error "An illegal choice has been detected. Please contact the site administrator."

I've tracked this problem down to being caused by my exposed fields I use for sorting: When the pager is clicked, it submits to a URL like http://mysite.com/reviews?myfieldtosort\_tid=All&sort\_by=&sort\_order=DESC&page=0%2C0%2C1.

The problem is that sort\_by is empty; if I remove that attribute entirely the problem goes away. Alternatively, if I use the exposed sort, it adds the sort field and also works correctly.

What can I do to still use the pager, but have it remove the sort\_by field when it is not needed?

# Answer
> 2 votes
muka's answer is almost working, but if you have more than one filter, it overrides the additional filters. See the revised code:

```
function YOUR_THEME_form_views_exposed_form_alter(&$form, &$form_state) {
    if($form_state['view']->name == 'VIEW_NAME') {
        $sort_by = 'SORT_BY'; // Set Default Sort by Manually (see url for correct name)
        if(isset($_GET['sort_by'])){ // In case you have more filters you don't want to override them.
            $sort_by = $_GET['sort_by']; // Additional checks might be a good idea
        }
        $form_state['view']->set_exposed_input($_GET);
        $form_state['input']['sort_by'] = $sort_by;
    }
}

```

# Answer
> 1 votes
I've solved by setting a default value in the form alter callback for views exposed form

```
function mymod_form_views_exposed_form_alter(&$form, &$form_state) {
  if($form_state['view']->name == 'yourviewname') {
    $_GET['sort_by'] = 'default_sort_name';
    $form_state['view']->set_exposed_input($_GET);
    $form_state['input']['sort_by'] = $_GET['sort_by'];
  }
}

```

# Answer
> 0 votes
Slightly modified version of muka's code for multiple filters:

```
function yourmodule_form_views_exposed_form_alter(&$form, &$form_state) {
// if($form_state['view']->name == 'yourviewname') {
    if($_GET['sort_by'] ==''){
    $_GET['sort_by'] = 'your_def_sort';
    $form_state['view']->set_exposed_input($_GET);
    $form_state['input']['sort_by'] = $_GET['sort_by'];
   }
// }
}

```

---
Tags: views, panels
---


# Question
Title: Can't access admin after moving localhost to live server
Almost finished my site and thought I have completed the puzzle but there is one last frontier in my way and a rather annoying ankle-biter...

I moved my site off my localhost onto my live server everything was successful until I tried to login the first time and was denied access.. I requested a new password through the email I provided when i created the site on my localhost but the emails do not come to my inbox but when i try to recreate the process on my localhost I get the email and can change it etc. I have tried going into my DB\>users\>browse\> and change my password and put MD5 so it becomes encrypted but still no success on the live site.

I have tried to search online for the answer but have been going in circles and would like to see if anyone can offer some advice I am novice level and eager to learn so if responding kindly use terms a novice would be familiar with, thank you.

# Answer
> 1 votes
1. Install drush
2. Go to your `drupal-core/sites/mysite` folder in command line
3. type `sudo drush uli`
4. The console will print a link, use that to access your site as user 1

# Answer
> 0 votes
I haven't experienced this exact problem myself (and I'm also quite a novice), but I've been successful moving sites from development to production by following these steps. Perhaps you can try this:

1. Install the Backup and Migrate project in your localhost Drupal installation (https://www.drupal.org/project/backup\_migrate) and do a manual backup of the database to a directory in your computer
2. Do a clean (empty) install in your live server. Follow directions from https://www.drupal.org/documentation/install . Verify that you can log in!
3. In the remote server, install ALL modules that you are using in your localhost, and copy all your public files to your remote server installation. This means basically copying your local /sites/all/modules and /sites/all/themes (and /sites/all/libraries if in use) directories to your server. You also want to copy your /sites/default/files directory. But do not copy your settings.php file. Enable the Backup and Migrate module in your server installation.
4. In your server installation, navigate to /admin/config/system/backup\_migrate/restore and manually "restore" a backup by choosing the backup file you created in step 1.

This should get you up and running. By the way, Backup and Migrate is a great module that will save you many headaches in cases of database loss etc.

There are more detailed directions here: http://www.seascapewebdesign.com/blog/how-transfer-your-website-one-server-another

Good luck!

# Answer
> -2 votes
Hm, you didn't accidentally turn off browser cookies?

Happened to me a few times – no session means no access.

---
Tags: database
---


# Question
Title: Creating webform submissions programatically in order to use with SimpleTest
I'm trying to build out a SimpleTest to test out functionality on **submitted webforms**. I need to simulate loading a drupal webform node, applying fake data, and submitting the form (triggering a database save).

Currently, I'm forcing data in (on a vagrant box) a drupal instance, but I have a feeling there is a better way to do this.

**Question:** In Simpletest, how do I properly load a webform, inject fake data into the form fields, and submit the form?

**First attemtp:** Original fixture code. It works, but it's sloppy!

```
Class myTest extends DrupalWebTestCase {
.
.
.
  /*
  Drops ALL DATA in the tables being tested
  */
  function _dropData() {
     db_query('delete from {webform_submitted_data}');
     db_query('delete from {webform_submissions}');
  }

  /*
  Fixtures, test data. Clears both webform_submitted_data and webform_submissions
  and then adds a new set of mock data generated initially by a browser plugin
  that autofills forms. This allows for a standardized set of data used on the
  simple test form (import script included in the package).
  */
  function _populateTablesWithTestData() {
    $q1 = "SET SQL_MODE = \"NO_AUTO_VALUE_ON_ZERO\"; INSERT INTO `webform_submitted_data` (`nid`, `sid`, `cid`, `no`, `data`) VALUES (1, 59, 2, '0', 'Dignissimos enim dolorem quia et minim velit eiusmod eiusmod voluptas nemo nostrum cum aliquam unde mollit obcaecati'), (1, 59, 3, '0', 'pugy@example.com'), (1, 59, 4, '0', '2013-03-11'), (1, 60, 2, '0', 'Sapiente velit voluptatem et quod et proident voluptatem Sunt minima reprehenderit reprehenderit'),(1, 60, 3, '0', 'nejemuno@example.com'),(1, 60, 4, '0', '2014-05-16'),(1, 61, 2, '0', 'Id nisi pariatur Quidem in nihil culpa qui rerum minim nihil ea minim ipsa fugiat'),(1, 61, 3, '0', 'mohafowoba@example.com'),(1, 61, 4, '0', '2015-05-02'),(1, 62, 2, '0', 'Omnis quisquam nisi non et est est eiusmod qui qui odio ut dignissimos'),(1, 62, 3, '0', 'vujil@example.com'),(1, 62, 4, '0', '2015-03-02');";
    $q2 = "SET SQL_MODE = \"NO_AUTO_VALUE_ON_ZERO\"; INSERT INTO `webform_submissions` (`sid`, `nid`, `serial`, `uid`, `is_draft`, `submitted`, `remote_addr`) VALUES (59, 1, 59, 0, 0, 1424275998, '192.168.33.1'), (60, 1, 60, 0, 0, 1424276006, '192.168.33.1'), (61, 1, 61, 0, 0, 1424276013, '192.168.33.1'), (62, 1, 62, 0, 0, 1424276031, '192.168.33.1');";

    $this->_dropData();
    db_query($q1);
    db_query($q2);
  }

```

**Second Attempt:**

In a test script to be run from drush...

```
$form_state = array();
$form_state['values']['test2']='Something';
$form_state['values']['test_email']='Some@email.ext';
$form_state['values']['test_date']="";

drupal_form_submit('webform_client_form_1', $form_state);

```

However, this gives me:

```
$ drush scr test.php

Missing argument 3 for webform_client_form() webform.module:2268                                                               [warning]
Invalid argument supplied for foreach() webform.module:2843

```

**Third Attempt**

```
$form_state = array();
$form_state['values']['test2']='Something';
$form_state['values']['test_email']='Some@email.ext';
$form_state['values']['test_date']="";
$form_state['op'] = t('Submit');

drupal_form_submit('webform_client_form_1', $form_state, node_load(1), array());
print_r(form_get_errors());

```

Which gets:

```
$drush scr test.php

end() expects parameter 1 to be array, null given webform.module:3120                                                          [warning]
end() expects parameter 1 to be array, null given webform.module:3123

```

**What the form looks like**

Export Code:

```
$webform = array (
  'nid' => '1',
  'next_serial' => '63',
  'confirmation' => '',
  'confirmation_format' => 'filtered_html',
  'redirect_url' => '<confirmation>',
  'status' => '1',
  'block' => '0',
  'allow_draft' => '0',
  'auto_save' => '0',
  'submit_notice' => '1',
  'submit_text' => '',
  'submit_limit' => '-1',
  'submit_interval' => '-1',
  'total_submit_limit' => '-1',
  'total_submit_interval' => '-1',
  'progressbar_bar' => '1',
  'progressbar_page_number' => '0',
  'progressbar_percent' => '0',
  'progressbar_pagebreak_labels' => '1',
  'progressbar_include_confirmation' => '1',
  'progressbar_label_first' => 'Start',
  'progressbar_label_confirmation' => 'Complete',
  'preview' => '0',
  'preview_next_button_label' => '',
  'preview_prev_button_label' => '',
  'preview_title' => '',
  'preview_message' => '',
  'preview_message_format' => 'filtered_html',
  'preview_excluded_components' =>
  array (
  ),
  'record_exists' => true,
  'roles' =>
  array (
    0 => '1',
    1 => '2',
  ),
  'emails' =>
  array (
  ),
  'components' =>
  array (
    2 =>
    array (
      'nid' => 1,
      'cid' => '2',
      'pid' => '0',
      'form_key' => 'test2',
      'name' => 'TEST Text ',
      'type' => 'textfield',
      'value' => '',
      'extra' =>
      array (
        'title_display' => 'before',
        'private' => 0,
        'wrapper_classes' => '',
        'css_classes' => '',
        'width' => '',
        'maxlength' => '',
        'field_prefix' => '',
        'field_suffix' => '',
        'disabled' => 0,
        'unique' => 0,
        'description' => '',
        'placeholder' => '',
        'attributes' =>
        array (
        ),
        'analysis' => false,
      ),
      'required' => '0',
      'weight' => '1',
      'page_num' => 1,
    ),
    3 =>
    array (
      'nid' => 1,
      'cid' => '3',
      'pid' => '0',
      'form_key' => 'test_email',
      'name' => 'TEst Email',
      'type' => 'email',
      'value' => '',
      'extra' =>
      array (
        'title_display' => 'before',
        'private' => 0,
        'wrapper_classes' => '',
        'css_classes' => '',
        'width' => '',
        'unique' => 0,
        'disabled' => 0,
        'description' => '',
        'placeholder' => '',
        'attributes' =>
        array (
        ),
        'analysis' => false,
      ),
      'required' => '0',
      'weight' => '2',
      'page_num' => 1,
    ),
    4 =>
    array (
      'nid' => 1,
      'cid' => '4',
      'pid' => '0',
      'form_key' => 'date',
      'name' => 'Date',
      'type' => 'date',
      'value' => '',
      'extra' =>
      array (
        'title_display' => 'before',
        'private' => 0,
        'wrapper_classes' => '',
        'timezone' => 'user',
        'start_date' => '-2 years',
        'end_date' => '+2 years',
        'year_textfield' => 0,
        'datepicker' => 1,
        'description' => '',
        'analysis' => false,
      ),
      'required' => '0',
      'weight' => '4',
      'page_num' => 1,
    ),
  ),
  'conditionals' =>
  array (
  ),
);

```

Screenshot:

# Answer
> 1 votes
To programmatically submit a webform, you can use the following code.

```
global $user;

$node = node_load($nid);
$data = array(
  1 => array( $component1_value),
  2 => array($component2_value),
);

$submission = (object) array(
  'nid' => $node->nid,
  'uid' => $user->uid,
  'submitted' => REQUEST_TIME,
  'remote_addr' => ip_address(),
  'is_draft' => FALSE,
  'data' => $data,
  'serial' => _webform_service_submission_serial_next_value($node->nid)
);

module_load_include('inc', 'webform', 'includes/webform.submissions');
webform_submission_insert($node, $submission);
webform_submission_send_mail($node, $submission);

function _webform_service_submission_serial_next_value($nid, $increment = TRUE) {
  if ($increment) {
    db_transaction();
  }
  $next_serial = db_select('webform', 'w')
    ->forUpdate()
    ->fields('w', array('next_serial'))
    ->condition('nid', $nid)
    ->execute()
    ->fetchField();

  if ($next_serial && $increment) {
    $increment_amount = 1;
    db_update('webform')->fields(array('next_serial' => $next_serial + $increment_amount))
      ->condition('nid', $nid)
      ->execute();
  }
  return $next_serial;
}

```

# Answer
> 1 votes
You can programatically submit a Drupal form with drupal\_form\_submit() by passing it a `$form_state` array with its `values` sub-array pre-populated with the data you want to submit. You'll need the form id of the form you're submitting, too, which in the case of a Webform is `webform_client_form_<NODEID>` (of course, replace `<NODEID>` with the node ID of the webform you want to submit).

---
Tags: webforms, forms, testing
---


title: Instalment payments with ubercart

text:
# Question
Title: Instalment payments with ubercart
I'm building a student application on which we have the requirement that student can pay its fees via instalment.I have googled around the same but I does not found how to achieve it.Does there any existing module for to achieve the similar functionality.If you have any ideas then do let me know how to achieve this. The instalment payment will be charged only in two instalments(first instalment and second instalment).The amount of the first instalment can be vary from second instalment.

# Answer
> 0 votes
You can use the UC Down Payment module for this task.

> This module allows Ubercart store administrators to add partial payment functionality as a product feature. They can assign down payment amount and the due date to any product, and manage down payments and partially paid orders in the admin section.

---
Tags: 6, ubercart
---


# Question
Title: How to uncheck url path settings in node form alter for existing content?
Here I wonder how to uncheck url path settings in node form alter for existing content?

# Answer
> 0 votes
Here is your answer two ways of doing it

**Method 1:**

```
function module_node_update($node) {
  if($node->type == "blog"){
        $node->path['pathauto'] = TRUE;//to be checked
        $node->path['pathauto'] = FALSE;//To be unchecked
  }
}

```

or either you can do it in **node\_presave**

**Method 2:**

```
function module_node_presave($node){
 if($node->type == "blog"){
            $node->path['pathauto'] = TRUE;//to be checked
            $node->path['pathauto'] = FALSE;//To be unchecked
      }
}

```

Try and let me know hope it helps :)

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


# Question
Title: Add custom text field to field settings form
In the admin when click edit on Manage Fields page it shows settings for that field. Can we add a custom property (checkbox) here like the required checkbox?

For example, for a decimal field it show 'Label' textbox, 'Required field' check box, 'Help text' textarea and so on. Can I add my own checkbox or textfield to this form?

# Answer
What you'd have to do is define your own field type in a module, then use hook\_field\_settings\_form to set the global options for that field (or hook\_instance\_settings\_form for a specific content type's implementation).

Here's a general guide to creating your own field in Drupal 7, but to get a handle specifics of creating a custom settings option take a look at other modules' implementations of it.

For example, Drupal Commerce makes a set of options from existing customer profiles:

```
function commerce_customer_field_settings_form($field, $instance, $has_data) {
$settings = $field['settings'];
$form = array();

if ($field['type'] == 'commerce_customer_profile_reference') {
  $options = array();

// Build an options array of the customer profile types.
foreach (commerce_customer_profile_type_get_name() as $type => $name) {
  $options[$type] = check_plain($name);
}

$form['profile_type'] = array(
  '#type' => 'radios',
  '#title' => t('Customer profile type that can be referenced'),
  '#options' => $options,
  '#default_value' => !empty($settings['profile_type']) ? $settings['profile_type'] : 'billing',
  '#disabled' => $has_data,
 );
}

return $form;
}

```

Yours sounds more simple - but the same general idea. Get the field and instance data, do something with it, make another mini form and return it so it gets rendered.
> 1 votes

---
Tags: nodes, entities
---


# Question
Title: remove all active sessions for given uid
How to remove all active sessions for given uid who has logged in from different browsers or apps.

I used

```
drupal_session_destroy_uid($uid);
drupal_session_regenerate();

```

but old sessions still valid and user can create content from apps having that sessions.

I need to delete all sessions for that user and create new one .

# Answer
> 1 votes
Why not just delete the corresonding entries from the sessions table? e.g. in sql, `delete from sessions where uid = <uid>`

This won't work if you're using memcache for your sessions table, but I imagine there's an equivalent if you are.

---
Tags: users
---


# Question
Title: How to set a file upload monthly quota on a role basis in Drupal 7?
I'm using Drupal 7 and I'm quite a newbie here.

I'm building a small sharing/social network site where users will be able to upload different kind of files (mainly, pictures and zipped archives, but I'm not limiting the kind of files one can upload).

Is there a way to set a per-user upload limit/quota (say, 1Gb/month) on a user role basis?

**Edit**

* Using Amazon S3 and similar services is a viable option.
* Users' privacy should be protected, i.e. they should be able to set access permissions on the files they upload (private, friends-only, public), and it would be interesting to have the "expiry" option, i.e. a shared file could expire and be automatically deleted from server after a while.
* I know there is IMCE module, I never tried it but from its description it seems a bit buggy and not so safe from a privacy perspective.

# Answer
The IMCE module allows, "configurable limits for user roles: file size per upload, directory quota, file extensions, and image dimensions."
> 1 votes

# Answer
User Disk Quota seems to do the job as well
> 0 votes

---
Tags: 7, users, files
---


# Question
Title: How to Update Commerce Product Programatically
```
 $product_load = commerce_product_load(456);

 $product_load->uid = $GLOBALS['user']->uid;

 $product_load->example[LANGUAGE_NONE][0]['tid'] = 123;

 commerce_product_save($product_load);

```

As I am doing this it is not updating commerce product and takes lot of time to load the page.

# Answer
You may have better luck using entity metadata wrappers' -\>set() and -\>save() functions.
> 0 votes

---
Tags: commerce
---


# Question
Title: Multiple Date Argument Values with One Contextual Filter
I have a pretty simple view in D7:

**Fields**

* nid
* title

**Contextual Filters**

* nid
* date (from date, monthly granularity)

Now I'd like to fetch some results for a specific node, but across multiple months. I was hoping to be able to pass in the contextual filter arguments via the url like so:

```
123/201302+201303

```

This isn't working for me though. Is this even possible with Date fields in Views ? I heard it was only possible with term ids right now.

Are there other techniques to accomplish this? Perhaps hook\_views\_query\_alter() is in order here.

# Answer
> 0 votes
Try with the following method using `views_embed_view()`:

```
views_embed_view('viewname', 'display_name', array(123,'201302+201303'));

```

Or by using a `hook_views_query_alter` and modifying the where condition to span across both months.

---
Tags: 7, datetime, views
---


# Question
Title: Where is the "sites/all" folder for an ubuntu linux installation?
I have installed drupal 7 from the ubuntu repositories. All works well but I cannot locate the folder to install additional modules.

All the documentation says I need to upload files to the "sites/all" folder. This either doesn't exist or is somewhere I have yet to look.

Any pointers would be much appreciated.

ETA: I had to create the "/all/modules/contrib" subfolders manually, under the "/usr/share/drupal7/sites" absolute path.

# Answer
> 2 votes
It's referring to the "sites/all" folder in your website's root folder.

The location of your site's files will have been set by your web server software (probably Apache, in this case).

Have a look here: /var/www/

and see if there are any directories in there that look like "httpdocs" or anything with your site's name in it or anything.

# Answer
> 1 votes
As user5482 said, all your Drupal files are probably in this folder `/usr/share/drupal7/sites/`

Just to make sure, you could run this command (if locate command is available in your distribution) and see what paths you get:

```
updatedb
locate "sites/default"

```

If by default the `sites/all` folder is not created, you need to create it yourself. You could run:

```
mkdir /usr/share/drupal7/sites/all

```

Make sure it has the same permissions and owner as the `sites/default` folder: Check what are the permissions:

```
ls -lh /usr/share/drupal7/sites/ | grep default

```

In my case I have something like this:

```
drwxrwxr-x 2 www-data www-data 4.0K Mar  3 16:35 default

```

So to replicate it run (adjust it with your own permissions):

```
chown www-data:www-data /usr/share/drupal7/sites/all
chmod 775 /usr/share/drupal7/sites/all

```

---
Tags: 7
---


# Question
Title: "Notice: unserialize() [function.unserialize]: Error at offset 10301 of 11637 bytes on views_db_object->load_row()"
I use the E-Commerce Kickstart distribution. Almost always I get some error, every time I update and save any view.

Please could anybody tell me what is causing this error, or give me some suggestions?

# Answer
I have encountered the same issue and thus far to resolve but I found this article.

http://www.zyxware.com/articles/3337/drupal-errors-drupal-views-notice-unserialize-function-unserialize-error-at-offset-1009-of-1036-bytes-in-views-db-

so...i researched some more and found this solution. I added this line to bootstrap.inc

```
$data = preg_replace('!s:(\d+):"(.*?)";!e', "'s:'.strlen('$2').':\"$2\";'", $variable->value);
$variables[$variable->name] = unserialize($data);

```

in the variable\_init function
> 3 votes

# Answer
I know this was answered long ago, but this is to help out future Googlers.

All unserialize errors result from bad data in the database. Data stored in a serialized format will look like this:

```
s:9:"my string";

```
* s - datatype (in this case string)
* 9 - length of the data
* "my string" - the data

In your case, the unserialize error is resulting from a view. If you have a database viewer/query program (i.e. phpmyadmin, dbForge Express, Navicat etc.) you can look at the views tables. You'll find that the only one containing serialized data is the views\_display table; the display\_options field contains serialized data. You can then execute a query such as the following:

```
SELECT vid, display_title, length(display_options)
FROM views_display
WHERE length(display_options)="11637"

```
* vid, display\_title are used to identify which record from the database is corrupted
* display\_options is the **field containing serialized data**, could be stored in database as longtext or a blob
* views\_display is the table we are searching as it is relevant to the error and contains serialized data
* "11637" is the length of the data stored in the field and **corresponds to the bigger number on the error**

This particular query should return one result with the view id. You have the option to **delete the view** or try to **repair the data**.

To repair the data copy the serialized data into a text editor that will tell you what column/character you are on. In your case, you would go to column/character 10301 (the first number in the error) and see if you can identify a mismatch (wrong datatype, incorrect length, incorrect syntax). Copy the corrected data back into the database.
> 2 votes

# Answer
Recently I faced the same problem. Solutions above didn't look very reliable to run on production.. **Luckily I had a dev server where the view was working fine so I did the following**:

**Export the view:**

1. Login to my Drupal site dev server
2. Go to **/admin/structure/views** and **export the view** from there
3. Copy the exported view code

**Import the view:**

1. On the drupal site that has the view issue, goto: **/admin/structure/views/import**
2. And paste the view code there
3. Make sure to check "Replace an existing view if one exists with the same name"
4. **Click Import**
5. Do not forget to save!

The imported view code solved the issue for me and hope that works for you as well!
> 2 votes

---
Tags: views
---


# Question
Title: When I add the shipping line item that was selected to the orders view in commerce it duplicates orders
This seems to be related to how many products were in the order, as adding this shipping line item from the order to the view it shows every product that that applies to.

Is there a way to change the settings in views to only show the one listing that shows the shipping option and hide all the duplicates?

# Answer
> 0 votes
I found this module called Views Grouping Row Limit which works

# Answer
> 0 votes
it sounds like you might just need to learn more how database queries work, as the relationship you've added to your View is what's creating multiple rows. You can filter by any value you want to weed out "duplicates", including line item types, reference field delta values, etc. to ensure there's only one row per record. I'm not exactly sure what you're getting out of grouping, but some filtering option may give you better results - worth looking into! : )

---
Tags: commerce
---


# Question
Title: How do I display submenus separately from their menu tree?
I'm trying to display all 3rd level submenus for a menu item on one page, with each in its own display block. I've tried the Menu Block module but it only seems to work for the active trail, which means I can only display all 2nd Level and 3rd Level menus as one unit rather than just 3rd level menus as separate units.

In addition to the Menu Block module, I also tried access the menu tree directly with this code.

```
      $main = menu_navigation_links('main-menu', '2');
      echo theme('links__system_main_menu', array(
      'links' => $main,
      'attributes' => array(
      'id' => 'main-menu',
      'class' => array('links')
    ),
  ));
?>

```

Here's the menu structure:

```
- Parent Menu 1
- Parent Menu 2
  - Child Menu A
    - SubChild Menu 1A
    - SubChild Menu 2A
    - SubChild Menu 3A
- Child Menu B
  - SubChild Menu 1B
  - SubChild Menu 2B
  - SubChild Menu 3B

```

What I'd like to display when Parent Menu 2 is selected:

Block 1: SubChild Menu 1A | Subchild Menu 2A | SubChild Menu 3A

Block 2: SubChild Menu 1B | Subchild Menu 2B | SubChild Menu 3B

Any help on the right way to display submenus separate from their tree would be greatly appreciated.

# Answer
> 5 votes
I think the best way to go about it is to just use the Menu block module. Here is a quote about it (from the module's project page):

> ... have you ever used the Main and Secondary menu links feature on your theme and wondered “how the hell do I display any menu items deeper than that?”
>
> Well, that’s what this module does. It provides configurable blocks of menu trees starting with any level of any menu. And more!
>
> So if you’re only using your theme’s Main menu links feature, you can add and configure a “Main menu (levels 2+)” block. That block would appear once you were on one of the Main menu’s pages and would show the menu tree for the 2nd level (and deeper) of your Main menu and would expand as you traversed down the tree. You can also limit the depth of the menu’s tree (e.g. “Main menu (levels 2-3)”) and/or expand all the child sub-menus (e.g. “Main menu (expanded levels 2+)”).

# Answer
> 0 votes
You could use this module: https://www.drupal.org/project/yamb to get your 3rd level submenus with at 2nd level titles.

---
Tags: theming, routes
---


# Question
Title: When does the core search module become worth using?
I mean, is there any approximate number of nodes or just website pages (or any other measures of website size) when the out of the box Drupal search module is still worth using? I understand that much depends on webserver, but there should be some general guidelines. E.g., should I use the core search module if I have a Drupal website with 5K nodes?

# Answer
It really depends on your situation.

You should use Drupal search core module only when you don't have any performance issues (as it's using database backend), your site is not so complex (in terms of search functionality) or you're not advanced user and you are not looking to make make your site more complex than already is.

Please note that high traffic sites running search queries against the database can affect overall performance especially when the database becomes the bottleneck. Secondly Drupal core search doesn't scale much.

Therefore using Search module from Drupal core it's not adequate when you have thousands of nodes on site. In this case you should use either Search API (with solr backend) or Apache Solr Search modules. Using Apache Solr provides advanced and accelerated search platform which features faceted search (Facet API), searching multiple sites, real-time indexing, dynamic clustering, NoSQL features, indexing attachments and many more. It's a great way to have fast access to big data on a budget. Basically Solr solutions are designed for searching the same way as Search API is designed to replace the core "Search" module.

It's also worth to mention about Elasticsearch as alternative for Solr, but it's topic for another discussion. The decision to choose whether Elasticsearch or Solr really depends on the project requirements and the decision needs to be made by experienced Drupal developer or solution architect.

In overall, Databases and Solr have complementary strengths and weaknesses, so you've to investigate these further depending on your project. However core search has a very limited functionality.

Please find the following chart which shows Drupal core's search performance vs. Solr based on its execution time.

> The results are pretty clear: Drupal core's search takes longer as you put more words in the query. This may seem fair enough, as it makes the searching more complex. But when using Solr you can't barely see any difference at all. It doesn't really matter if you search for 1 or 6 keywords. The response time for a page is almost the same.
>
> DISCLAIMER: This is not a valid test, and the result is only used here to give a glimpse of what the difference might look like. The results will most likely look different on your environment. You can see the shell scripts I used to perform the test in the document folder I pointed out earlier. All tests were performed on a system where content was using cache.

Please find the following table which is comparison Solr v.s. Relational Database:

See also:
> 4 votes

# Answer
**Simpler Answer**

The previous answer provide you the details explanation so you can determinate your own conclusion.

My personal opinion that is not worth to used the core Search. Here are my scenarios base of what you need.

1. If you need a **very complex search** (Autocomplete, Facets ) you would need Search Api.
2. If you need a **better way to search but not complex your website**. I would recommend you to used Google CSE module . Google would craw your content and would show you better results Drupal Search Core would.
> 2 votes

---
Tags: 7, search
---


# Question
Title: Incorrect File Permissions When Images Are Uploaded in the CKEditor WYSIWYG using ElFinder on Windows
When I upload and image in the WYSIWYG, the image is added to the /sites/default/files/ folder, but cannot be seen on the web becasue IIS\_IUSRS does not have the correct file permissions. Also, the permissions are only viewable by an administrator.

I tried the answer given on IMCE image upload and permissions issue, but both the temp and destination folders give IIS\_IUSRS and IUSRS read/write/modify. I have even tried temporarily giveing 'Everyone' full control to get this working, but that does not help.

First, I have to click advanced to view the uploaded files permissions. I don't have to do that on the folders or other files in the folder.

Then I have to give Administrator permission. Again, this is not required on the folders or other files in the folder.

Then I can see the file permissions and IIS\_IUSRS has List folder/read data, not modify. Also, this is inherited from 'Parent Object' not the parent folder.

If I click Disable inheritence and remove all permissions, then click enable inheritrance and apply, the correct permissions re inherited and the image can be seen on the web.

Has anyone else experienced this? Why doesn't the uploaded file inherit the folder permissiosn correctly in the first place? Why do I have to disable then enable inheritence to get it to work?

I need to fix this because the web editors will be adding a lot of images and it is not practical for me to manually change the permissiosn every time.

I don't know if this is an error with Windows Server 2012, IIS 8.5, CKEditor or ElFinder.

I am using ElFinder, but was only able to tag this with CKfinder. I am using Plupload as well, but can't remember if it integrates with ElFidner or not.

P.S. This site is stil in development. I will remove 'Everyone' before it goes live.

# Answer
I was able to correct this by enabling inheritance on the c:\windows\temp folder, after verifying that the IIS\_IUSRS (machinename) account has read & execute/list folder contents/read permissions. I was prompted about a potential security risk, but ultimately this fixed it.
> 1 votes

---
Tags: files, wysiwyg
---


# Question
Title: Social Media Managament - Feed Scheduling
I am wondering if there is a module that allows you to set up a schedule and auto post to social networks?(FB and Twitter)

# Answer
> 0 votes
You can create a Feed that aggregates any data you need at the rate/schedule you want.

Once you have your feed set up, you could use a service like twitterfeed.com to automatically post your data to the social networks of your choice.

Basically you'd just create an RSS feed and plug it into twitterfeed.

---
Tags: 7
---


# Question
Title: Creating a dynamic URL in node--resource.tpl.php
I'm trying to create a URL in my node--resource.tpl.php file that contains fields from the resource in question in the URL. The following code is what I've been playing with, but when the user clicks the link it just shows as follows:

```
http://pf.dev/content/specific-resource-feedback?nid=&title=

```

Ie. The nid and title are not being filled out correctly. So here's the code I'm using (incorrectly) to create the URL:

```
    <div class="feedback-link">
    <a href="/content/specific-resource-feedback?nid=
<?php $content['nid']) ?>&title= <?php $content['title']) ?>">
Trouble with this resource? Let us know.</a>
    </div>

```

Any ideas why this might not be working as intended?

# Answer
The title is defined for a node.tpl.php file as $title, and the node id can be retrieved with: `<?php print $node->nid; ?>` therefore, it should read something like this:

```
<div class="feedback-link">
  <a href="/content/specific-resource-feedback?nid=<?php print $node->nid; ?>&title= <?php print $title; ?>">
  Trouble with this resource? Let us know.</a>
</div>

```
> 1 votes

---
Tags: theming
---


# Question
Title: How to attach block to page provided by logintoboggan
I have the logintoboggan module installed. By default, Anonymous users will be presented with a login form along with an access denied message when they try to access a page which they do not have the permissions to. Please, how can i attach a block to this page?

Thanks

# Answer
> 0 votes
One option would be to redirect users to login when access is denied.

another may be to create your own Access Denied page, and then attach a login block to that URL.

To create your own Access Denied page, first create the page as you would with any other content, then navigate to: /admin/config/system/site-information

# Answer
> 0 votes
This works for me with LoginToboggan 7x.-1.4:

1. Visit /admin/config/system/logintoboggan and make sure that "Present login form on access denied (403)" is enabled.
2. Visit /admin/config/system/site-information and confirm that toboggan/denied is the Default 403 page.
3. Create your block at /admin/structure/block/add.
4. Under Visibility settings, specify that the block only appear at toboggan/denied.

---
Tags: authentication-authorization
---


# Question
Title: How to load Ubercart orders for certain user ID?
How to load Ubercart orders for certain user ID programatically?

There is only uc\_order\_history() which returns formatted order table and does not work in that case.

# Answer
Find the following function in Drupal 7:

```
/**
 * Custom function to return list of orders for certain user
 */
function foo_get_user_orders($user, $order_status = 'completed') {
  $query = db_select('uc_orders', 'uo');
  $query->addField('uo', 'order_id');
  $query->addField('uo', 'order_total');
  $query->addField('uo', 'order_status'); // optional: $query->addField('uo', 'product_count');
  $query->addJoin('LEFT', 'uc_order_products', 'p', 'p.order_id = uo.order_id');
  $query->addField('p', 'nid');
  $query->condition('order_status', $order_status);
  $query->condition('uid', $user->uid);
  $result = $query->execute()->fetchAll();
  return $result;
}

```

For Drupal 6, please install dbtng module and it should work as well.
> 3 votes

# Answer
Here's a pretty simple function which will return all the order objects for a user (D7):

```
function my_module_uc_orders_by_user($uid = NULL, $status = 'completed') {

  global $user;
  $uid = is_numeric($uid) ? $uid : $user->uid;

  if ($results = db_query("SELECT order_id FROM {uc_orders} WHERE uid = :uid AND order_status = :status", array(':uid' => $uid, ':status' => $status))->fetchAll()) {
    $order_ids = array();
    foreach ($results AS $result) {
      $order_ids[] = $result->order_id;
    }

    return uc_order_load_multiple($order_ids);
  }
}

```
> 3 votes

---
Tags: ubercart
---


title: Using Left() with Drupal Custom Module

text:
# Question
Title: Using Left() with Drupal Custom Module
I'm trying to return only the first 200 characters (if there are more than that) from a body field in a Drupal custom module. I've found the general php/mysql solution here:

https://stackoverflow.com/questions/2080860/mysql-sql-retrieve-first-40-characters-of-a-text-field

But when I try to implement it with my SQL query in my custom module it doesn't work (ie. it still returns over 200 characters). Here's my code (see the field I used LEFT() on is LEFT(fdb.body\_value, 200) on line 6):

```
$result = db_query(
"SELECT n.title, n.nid, n.status,
fdfty.field_type_value, fdfi.entity_id,
fdfi.field_icon_fid, fm.uri, fm.fid, ua.pid,
ua.alias, el.field_experience_level_value,
**LEFT(fdb.body_value, 200)**,
fdfr.field_role_value, fdft.field_topics_value,
fdfed.field_event_dates_value,
fdfed.field_event_dates_value2
FROM {node} AS n
LEFT JOIN {field_data_field_type} AS fdfty
ON n.nid=fdfty.entity_id
LEFT JOIN {field_data_field_icon} AS fdfi
ON n.nid=fdfi.entity_id
LEFT JOIN {file_managed} AS fm
ON fdfi.field_icon_fid=fm.fid
LEFT JOIN {url_alias} AS ua
ON n.nid=ua.pid
LEFT JOIN {field_data_field_experience_level} AS el
ON n.nid=el.entity_id
LEFT JOIN {field_data_body} AS fdb
ON n.nid=fdb.entity_id
LEFT JOIN {field_data_field_role} AS fdfr
ON n.nid=fdfr.entity_id
LEFT JOIN {field_data_field_topics} AS fdft
ON n.nid=fdft.entity_id
LEFT JOIN {field_data_field_event_dates} AS fdfed
ON n.nid=fdfed.entity_id
WHERE n.status=:status AND n.type=:resource
AND (fdfty.field_type_value=:webinar OR fdfty.field_type_value=:conference) AND el.field_experience_level_value=:level
AND fdfr.field_role_value=:role
AND fdft.field_topics_value=:topic
AND ((fdfed.field_event_dates_value IS NULL)
OR (fdfed.field_event_dates_value >= CURRENT_DATE()))
GROUP BY n.nid, n.title
ORDER BY fdfed.field_event_dates_value",
array(':status' => '1', ':resource' => 'resource',
':webinar' => 'Webinar', ':conference' => 'Conference', ':level' => $level, ':role' =>
$role, ':topic' => $topic));

```

# Answer
why not use substr() let the SQL statement bring it all then use this function in your result

would be something like this:

```
<?php

$result = db_query('Your SQL statement');

print substr($result, 0 , 199);

?>

```
> 1 votes

---
Tags: database
---


# Question
Title: How do I change this code to use request_uri()?
I'm trying to write a patch to make a module follow the Drupal coding standards.

I get this complain and I don't know how to fix it.

> Line 148: the use of REQUEST\_URI is prone to XSS exploits and does not work on IIS; use `request_uri()` instead \[security\_12\] return "http" . (isset($\_SERVER\['HTTPS'\]) ? "s" : "") . "://" . "{$\_SERVER\['HTTP\_HOST'\]}{$\_SERVER\['REQUEST\_URI'\]}";

The function using that code is the following one.

```
function module_get_url() {
   return "http" . (isset($_SERVER['HTTPS']) ? "s" : "") . "://" . "{$_SERVER['HTTP_HOST']}{$_SERVER['REQUEST_URI']}";
}

```

Should I change the code to the following one?

```
function module_request_uri() {
  return "http" . (isset($_SERVER['HTTPS']) ? "s" : "") . "://" . "{$_SERVER['HTTP_HOST']}{$_SERVER['REQUEST_URI']}";
}

```

# Answer
It means replace `$_SERVER['REQUEST_URI']` with `request_uri()`.

So `module_get_url()` needs to change slightly.

```
function module_get_url() {
  $uri = request_uri();
  return "http" . (isset($_SERVER['HTTPS']) ? "s" : "") . "://" . "{$_SERVER['HTTP_HOST']}{$uri}";
}

```
> 2 votes

# Answer
Simply swap out `$_SERVER['REQUEST_URI']` with `request_uri()`.

The reasoning is that `$_SERVER['REQUEST_URI']` is Apache specific.

From the function documentation page:

> Returns the equivalent of Apache's $\_SERVER\['REQUEST\_URI'\] variable.
>
> Because $\_SERVER\['REQUEST\_URI'\] is only available on Apache, we generate an equivalent using other environment variables.
> 1 votes

# Answer
Try:

```
function module_get_url() {
  return url(current_path(), array('absolute' => true));
}

```
> 0 votes

---
Tags: 7
---


title: How to get node id from URL?

text:
# Question
Title: How to get node id from URL?
I want to pass a URL to a function. This function should get the node ID from the URL.

How to do this?

# Answer
> 1 votes
You can try the following code (please note that about-us is merely an example page - you can put whichever page you want here):

```
$url = 'about-us';
$path = drupal_lookup_path('source', $url);

if ($path) {
  $node = menu_get_object('node', 1, $path);
  return $node->nid;
}
else {
  //Error handling in case path provided does not exist
}

```

The code above returns a whole node object though, which might be expensive depending on how often you run it - another option would be to run `explode()` on the output of `drupal_lookup_path()` and just take the NID that way.

**References:**

`drupal_lookup_path();`

`menu_get_object();`

# Answer
> 1 votes
You may try the following one-liner:

```
$nid = end((arg())); // Get the last number from the URL.

```

# Answer
> 0 votes
You can read the URL values using arg() function.

For Example,

If your url is node/100 then

```
$argument_one = arg(0); // This will store "node" to the variable.
$node_id = arg(1); // This will store 100 to $node_id variable.

```

Like above using arg() function you read the URL components.

Hope it solves your issue !

# Answer
> 0 votes
Theirs tonnes of different ways to "pass the url to a function" which way suits best depends on the situation and preference really.

What is the exact purpose of passing this URL with the node id? is there going to need to be multiple Node ID's passed at any one point? More details would mean a more detailed answer also.

```
$URL = $_SERVER['REQUEST_URI'];
OR
$URL = $_GET['q']
// if using this then the full path needs prepending as this only gets node/nid
OR
$URL = current_path(); // same as GET[q] basically

// then this passes to that function you wanted
$nid = getNodeId($URL);

```

# Answer
> -1 votes
You could break the url string into an array as

```
$url_arr = explode('/', $url);

```

Then you can access the url parts from the array.

# Answer
> -3 votes
Pass the variable (node id) appending it to url like this:

```
    <?php
    $nodeid = $node->nid;
    ?>

<a href="http://www.mysite.com?nodeid="<? php print ($nodeid) ?>">

```

and then in get the value from url like:

```
<?php
$nodeid=$_GET["nodeid"];
?>

```

And then pass the value to the function.

http://php.net/manual/en/reserved.variables.get.php

---
Tags: nodes, uri
---


# Question
Title: How to assign a rendered view result to a variable without displaying it on the screen?
I am working on a module to collect the results from several views, to be concatenated and then displayed. The views are returning JSON data using the views\_datasource module.

To do this, I tried to set a variable to be the output of a view like so:

```
$my_view = views_get_view('drupalgap_content');
$my_view->set_display('getlatestdigest');
$output = $my_view->render();

```

Then I could concatenate the $output to another views output etc.

The problem lies in the fact that as soon as I call `$view->render()` it renders the view results to the screen (I presume with a print() function) somewhere deep in the views core module.

After a ton of googling, I found that in the past, `$view->render()` used to return a value, and this method was correct. However, somewhere along the line, they changed it so `$view->render()` it renders the view results to the screen, making it impossible to concatenate the view output to another view output.

Other options I've looked into that don’t work:

1. `$view_result = views_get_view_result('drupalgap_content','getlatestdigest');`

This gets the view result, but it does not get the rendered JSON output that I need from the views\_datasource module. So, it’s no good.
2. `$view-execute(),$view->preview('getlatestdigest'); $view->execute_display('getlatestdigest', array());`

All of these three functions do the same thing as view-\>render(), i.e. they output the nicely formatted results I want to the screen instead of assigning them to a variable.
3. `views_embed_view('drupalgap_content', ‘getlatestdigest');`

does the same thing as view-\>render(), i.e. outputs the nicely formatted results I want to the screen instead of assigning them to a variable.

I should also mention that I am calling this module’s function using an AJAX call from a mobile app to the menu\_hook for this page\_callback. So I can not have it outputting anything to the “screen” until it is ready since AJAX will return the data to the client as soon as the output to the screen is called.

# Answer
> 1 votes
This turned out to be an issue with the views\_datasource module, not the views module. Solved by enabling "Views API mode" in the View settings.

---
Tags: 7, views
---


title: Get current path in hook_file_download

text:
# Question
Title: Get current path in hook_file_download
I have implemented hook\_file\_download function in my module. When I call function current\_path in the body of this hook, it returns path of the file, not path of current URL in browser. The similar result I got when I try method request\_path or variable $\_SERVER\['REQUEST\_URI'\].

My hook\_file\_download is called after I am programatically displaying image with function

```
<?php
function some_page_callback() {
// $args = ...some args
$output = theme('image_style', $args);
return $output;
}
?>

```

How to get path registered in hook\_menu for "some\_page\_callback" in hook\_file\_download method?

# Answer
That's the correct behaviour.

If `current_path()` wasn't the URL of the file, then the file must never have been requested, and that hook would never have fired.

When you request a private file the current URL must be the file's URL, by definition. It sounds like you're looking to track the page that originally contained a link to your file. That's going to be almost impossible to do reliably.
> 1 votes

---
Tags: hooks, uri, files
---


title: How to detect the current URL?

text:
# Question
Title: How to detect the current URL?
I would like to add a body class in D6 if you are on a specific page(s) currently in my `template.php` I have:

```
if url('the/path') {
 add the body class...
}

```

but that function doesn't seem to be working for me.

# Answer
You should use the following code, as `url()` returns the URL for the path passed as argument; therefore, it returns a value that the IF-statement would consider equivalent to `TRUE` (except in the case the string is `"0"` or is an empty string).

```
if ($_GET['q'] == 'the/internal/Drupal/path') {
  // Do stuff
}

```
> 6 votes

# Answer
Drupal's Alias is what your looking for

```
<?php
$path = drupal_get_path_alias($_GET['q']);
if ($path == 'the/path') {
  // do stuff
}
?>

```

Others Below:

Full URL

```
<?php
global $base_root;
$base_root . request_uri()
?>

```

Drupal's "Internal" URL

```
<?php
$arg = arg();
// Path of 'node/234' -> $arg[0] == 'node' && $arg[1] == 234
?>

```
> 12 votes

# Answer
**Drupal 7**

```
// Retrieve an array which contains the path pieces.
$path_args = arg();

// Check if the current page is admin.
if (arg(0) == 'admin') {
  // This is wrong even in D7. path_is_admin() should be used instead.
}

// Conditionally add css or js in certain page.
function mymodule_page_build(&$page) {
  if (arg(0) == 'sth' && arg(1) == 'else') {
    drupal_add_css(drupal_get_path('module', 'mymodule') . '/css/my.css');
  }
}

// Load the current node.
if (arg(0) == 'node' && is_numeric(arg(1))) {
  // This is wrong even in D7. menu_get_object() should be used instead.
}

```

**Drupal 8 (procedural)**

```
// Retrieve an array which contains the path pieces.
$path_args = explode('/', current_path());

// Check if the current page is admin.
if (\Drupal::service('router.admin_context')->isAdminRoute(\Drupal::routeMatch()->getRouteObject())) {
}

// Conditionally add css or js in certain page.
function mymodule_page_build(&$page) {
  if (\Drupal::routeMatch()->getRouteName() == 'my.route') {
    $page['#attached']['css'][] = drupal_get_path('module', 'mymodule') . '/css/my.css';
  }
}

// Load the current node.
$node = \Drupal::routeMatch()->getParameter('node');
if ($node) {
}

```

**Drupal 8 (OOP)**

```
use Symfony\Component\HttpFoundation\Request;
use Drupal\Core\Routing\AdminContext;
use Drupal\Core\Routing\RouteMatchInterface;
class myClass {
  public function __construct(Request $request, AdminContext $admin_context, RouteMatchInterface $route_match) {
    $this->request = $request;
    $this->adminContext = $admin_context;
    $this->routeMatch = $route_match;
  }

  public function test() {
    // This might change in https://drupal.org/node/2239009
    $current_path = $this->request->attributes->get('_system_path');
    // Retrieve an array which contains the path pieces.
    $path_args = explode('/', $current_path);

    // Check if the current page is admin.
    if ($this->adminContext->isAdminRoute($this->routeMatch->getRouteObject())) {
    }

    // Load the current node.
    $node = $this->routeMatch->getParameter('node');
    if ($node) {
    }
  }
}

```

Source: arg() is deprecated and will be removed at Drupal.org
> 4 votes

# Answer
Have you tried request\_uri()?

http://api.drupal.org/api/drupal/includes--bootstrap.inc/function/request\_uri/6
> 2 votes

# Answer
You'll want to use the arg() function. You can use it one of two ways,

```
$args = arg();

```

Which will basically give you an array with each url argument being another value, or you can check specific arguments like so:

```
$arg = arg(0);

```

So for your example, you could do:

```
if(!is_null(arg(1)) && arg(0) == 'the' && arg(1) == 'path') { Do something  }

```

or I'd recommend this:

```
$args = arg();
if(!empty($args[1]) && $args[0] == 'the' && $args[1] == 'path') { Do something  }

```
> 2 votes

# Answer
If you don't want to have a different page template for pages with a specific URL, you can check the current URL using the following code.

```
if (arg(0) == 'the' && arg(1) == 'path') {
  // Add the extra CSS class.
}

```

url() is not the function that returns the URL of the current page; if you call `url()` without providing any parameters, you would get (at least on Drupal 7, and without any modules implementing `hook_ulr_outbound_alter()`) the base URL of the Drupal installation.
Calling `url('the/path')` will just return you `"the/path"`, if no module is altering the value returned from the function; that means that the code you have shown will always be executed, and the CSS class always added.
> 1 votes

# Answer
If you're looking for the canonical path that Drupal's serving a request for, you can hit $\_GET\['q'\], which should translate even if Drupal's using clean URLs.
> 0 votes

# Answer
**Drupal 8:**

arg() alternative since it no longer works:

```
$path_args = explode('/', current_path());
print $path_args[1];

```

Read more: https://www.drupal.org/node/2274705
> 0 votes

---
Tags: 6, uri
---


title: Views performance issue

text:
# Question
Title: Views performance issue
I have a website with 4 views (and sometimes 5 views) on the homepage. The problem is that when I try to open the website, it takes minutes to load and the cpu goes crazy because of mysql processes.

Screenshot of cpu usage

Output of `SHOW PROCESS LIST`

I work on a dedicated server with `8GB of RAM`, `1900Mhz Intel Hexa-Core Xeon` and `4 × 300GB SAS (RAID 10)`

I have been using drupal for years, and never encountered such an issue. Any ideas how to fix this?

**Update** Views query:

`SELECT DISTINCT node.title AS node_title, node.nid AS nid, node.language AS node_language, node.created AS node_created, users_node.picture AS users_node_picture, users_node.uid AS users_node_uid, users_node.name AS users_node_name, users_node.mail AS users_node_mail, taxonomy_term_data_node.tid AS taxonomy_term_data_node_tid, taxonomy_term_data_taxonomy_term_hierarchy.tid AS taxonomy_term_data_taxonomy_term_hierarchy_tid, 'node' AS field_data_field_news_photo_node_entity_type, 'node' AS field_data_field_op_section_term_node_entity_type, 'node' AS field_data_body_node_entity_type, 'user' AS field_data_field_user_realname_user_entity_type, 'user' AS field_data_field_user_organization_user_entity_type, 'user' AS field_data_field_profile_picture_user_entity_type
FROM
{node} node
LEFT JOIN {users} users_node ON node.uid = users_node.uid
LEFT JOIN (SELECT td.*, tn.nid AS nid
FROM
{taxonomy_term_data} td
LEFT JOIN {taxonomy_vocabulary} tv ON td.vid = tv.vid
LEFT JOIN {taxonomy_index} tn ON tn.tid = td.tid
WHERE (tv.machine_name IN ('sections')) ) taxonomy_term_data_node ON node.nid = taxonomy_term_data_node.nid
LEFT JOIN {taxonomy_term_hierarchy} taxonomy_term_data_node__taxonomy_term_hierarchy ON taxonomy_term_data_node.tid = taxonomy_term_data_node__taxonomy_term_hierarchy.tid
LEFT JOIN {taxonomy_term_data} taxonomy_term_data_taxonomy_term_hierarchy ON taxonomy_term_data_node__taxonomy_term_hierarchy.parent = taxonomy_term_data_taxonomy_term_hierarchy.tid
LEFT JOIN {field_data_field_news_photo} field_data_field_news_photo ON node.nid = field_data_field_news_photo.entity_id AND (field_data_field_news_photo.entity_type = 'node' AND field_data_field_news_photo.deleted = '0')
WHERE (( (node.status = '1') AND (node.type IN ('news')) AND (field_data_field_news_photo.field_news_photo_fid IS NOT NULL ) AND (node.language IN ('***CURRENT_LANGUAGE***')) ))
ORDER BY node_created DESC
LIMIT 12 OFFSET 0`

EXPLAIN output.

# Answer
The process list is saying that Mysql is writing to tmp tables. The issue is the way you configured mysql. Check the my.cnf configuration, and make sure that the temporary tables are large enough.
> 0 votes

---
Tags: 7, views, performance
---


# Question
Title: How to display references entities in single field?
I have a view of nodes. These nodes are connected with users via entity reference. User has a profile (Profile2). I want to display profile fields for all referenced users in single field.

# Answer
> 1 votes
You might need to use something like Views Field View and pass your node number as an argument, then use the reverse relationship to list members.

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


# Question
Title: How do I export all of my customers (not users) from Drupal into a CSV file?
I'm working on integrating a new accounting system and crm (Xero & Capsule) for a client - and they have just under 10,000 clients - only stored in their Drupal website. I need to export these with all their details (e mail, full name, address etc) - into a csv or excel file.

Currently under **Store Administration** I can "*View Customers*" - but this gives me no option to export.

But under **Reports \> Customer Reports** it gives me the option to export each page to a csv - however the information is not what we need - it only gives me usernames.

Any suggestions?

# Answer
> 2 votes
With the https://www.drupal.org/project/views\_data\_export module you can create views and export to CSV, Excel, XML, etc.

It also supports exporting in batches (default activated if the views has 1 000 or more rows). So 10 000 clients shouldn't be a problem.

# Answer
> 1 votes
Another module to consider for addressing these requirements is Forena.

You would use it's report writing features (such as its WYSIWYG report writer and/or it's query builder) to first create a report that fits your needs (e.g. to remedy your '... the information is not what we need - it only gives me usernames ...'). The result of it could be a tabular output and/or graph. After the report content matches the specifications,you could save it as (e.g.) a CSV file.

Here is a quote from one of the forena community docu pages, i.e. Reasons for considering Forena:

> Reports created by Forena (combined with SVGGraph and mPDF) can be saved (exported) as PDF documents with embedded graphs. Other supported formats for saving a report are CSV, XLS, DOC, HTML, etc.

The Forena Video demos and tutorials contain quite some links to live demos.

Any report created with Forena can be saved (exported) in various file formats, such as CSV or XLS. To do so, just add `.csv` as an extention to the report (output) URL. That contains the CSV equivalent of that report. As a sample, consider the sample report located at `/reports/sample.states` (in your own site, one of the samples shipped with Forena). Change the URL to `/reports/sample.states.csv` (= just add `.csv` to it) to get the same report in `.csv` format. If you'd add such `.csv` to the URL of the Simple Table of States in the demo site, the result is like so ...

Same technique applies for other supported extensions (export formats), such as adding `.html`, `.xls` (MS Excell), `.pdf` or `.doc` (MS Word).

By the way, all *data blocks* are accessible directly via their url also, provided you have permission to access that block. Here are a few samples of that, for the sample report located at `/reports/sample.states`:

For short, to answer this specific answer I'd write the various (custom) SQLs I need, format it as reports that fit my needs, and then just save it as an XLS (or CSV?).

Disclosure: I'm a co-maintainer of Forena.

---
Tags: database, importing-exporting
---


title: Drush not working properly on Ubuntu

text:
# Question
Title: Drush not working properly on Ubuntu
I am using Ubuntu 14.04 . When I try to download, enable, disable any module drush gives the following error:

# Additional uncaught exception thrown while handling exception.

## Original

Drupal\Core\DependencyInjection\ContainerNotInitializedException: \Drupal::$container is not initialized yet. \Drupal::setContainer() must be called with a real container. in Drupal::getContainer() (line 129 of /var/www/html/gitrepo/drupal/core/lib/Drupal.php).

```
Drupal::getContainer()
drupal8_bootstrap(0)
_drush_bootstrap_drupal_configuration()
drush_bootstrap(3, 7)
drush_bootstrap_max()
drush_bootstrap_to_phase(-2)
Drush\Boot\DrupalBoot->bootstrap_and_dispatch()
drush_main()

```

## Additional

Drupal\Core\DependencyInjection\ContainerNotInitializedException: \Drupal::$container is not initialized yet. \Drupal::setContainer() must be called with a real container. in Drupal::getContainer() (line 129 of /var/www/html/gitrepo/drupal/core/lib/Drupal.php).

```
Drupal::getContainer()
Drupal::theme()
_drupal_log_error(Array, 1)
_drupal_exception_handler(Object)

```

---

Drush command terminated abnormally due to an unrecoverable error. \[error\]

# Answer
Sounds like you are not using the right version of Drush. For Drupal 8.0-beta7, you need Drush 7.0.0-alpha9. For Drupal 8.0-beta6, you need Drush 7.0.0-alpha8.

Drupal 8 APIs are changing rapidly; if you have mixed versions, you can easily encounter spurious problems. Tracking HEAD of Drupal 8.0.x and Drush master is another viable strategy.
> 4 votes

# Answer
For D8 don't you need php 5.4+? Check your version of PHP. I believe Ubuntu 14.x has 5.3 by default but that's just a wild guess.

What do you see when you execute `php --version` on the commandline?

You may need to upgrade through a back channel upgrade through other PPAs or run Drupal in a Virtual Machine / Vagrant.
> 1 votes

# Answer
You probably have the wrong version or you installed wrong.

Here are the instruction on how to install Drush on Ubuntu.

```
# Install Composer
php -r "readfile('https://getcomposer.org/installer');" | php

# Access composer from anywhere on your system:
sudo mv composer.phar /usr/local/bin/composer

# Install Drush
cd /usr/share
sudo git clone --branch master https://github.com/drush-ops/drush.git
cd drush
composer install
cd ~/
# Access drush from anywhere on your system:
ln -s /usr/share/drush/drush /usr/bin/drush

```

Source: lazydubuntu/bin/basictools.sh

This would make sure that you installed the latest version
> 1 votes

---
Tags: drush
---


# Question
Title: Remove webform field while edit webform submission
I have one webform and need to do that there are 2 fields, TL approval and Manager approval, now if manager submission page will edit by admin then TL approval field should not be load, in short i want to remove specific fields role wise when webform submission will edit. If anyone have an idea about this then let me know.

# Answer
> 1 votes
Try to download & Install Webform Fields Permission module.

**Note :** Please read comments if you have any query.

If your issue not solved then try once Webform Component Roles module.

---
Tags: 7
---


# Question
Title: Overriding admin settings form from bootstrap sub theme
I need a little help here. I am creating a sub theme of bootstrap theme and I need to add an additional fieldset under "Bootstrap Settings" form (similar to Components, Advanced etc which are currently present) which appears under `Appearance->Settings-><THEME NAME>` page. I think we can use `hook_form_alter()` for this but the problem is that `hook_form_alter()` is being always invoked with `$form_id` set to "search\_form" and never "system\_theme\_settings". Thus any form updates I am making under this hook are getting applied to search box instead of admin settings form.

I referred code under `bootstrap_form_alter()` in `alter.inc` file in bootstrap theme and tried to replicate it in sub theme but it doesn't seem to work. In order to ensure that I am not making any mistakes while creating subtheme I also tried using other available subtheme such as one created by Adam Balsam (he has provided details on this in response to a question here.

Any help/pointers would be greatly appreciated.

I am listing below my code from `template.php` file of the `bootstrap_ignitor` sub theme

```
function bootstrap_ignitor_form_alter(&$form, &$form_state, $form_id) {
  drupal_set_message('<pre>'.print_r($form_id,TRUE).'</pre>'); ***<= this always prints as search_block_form***
  $form['actions']['submit']['#attributes']['class'][] = 'btn';
  _bootstrap_ignitor_settings_form($form, $form_state);
}

function _bootstrap_ignitor_settings_form(&$form, $form_state) {

  // Advanced settings.
  $form['themealter'] = array(
    '#type' => 'fieldset',
    '#title' => t('Theme Alter'),
    '#group' => 'bootstrap',
  );

  $form['themealter']['local_cdn'] = array(
    '#type' => 'fieldset',
    '#title' => t('NewBootstrapCDN'),
    '#description' => t('Testing...'),
    '#collapsible' => TRUE,
    '#collapsed' => TRUE,
  );

}

```

# Answer
You need to create `theme-settings.php` in your theme directory & add following function in that to add new fields as shown in code below:

```
<?php
function <THEME_NAME>_form_system_theme_settings_alter(&$form, &$form_state) {
    $form['campaign_pages'] = array(
        '#title' => t('Campaign Pages'),
        '#type' => 'textarea',
        '#description' => t('Specify pages by using their paths. Enter one path per line.'),
        '#default_value' => theme_get_setting('campaign_pages'),
    );

}

```

Here `theme_get_setting` stores the value of your field.
> 1 votes

---
Tags: theming
---


# Question
Title: How to use Views PHP get Taxonomy field value and field collection value?
I am currently using Views PHP module to use Field Global PHP to render view value, but I dont know how to read taxonomy field value and field collection value, did anyone know how to do it??

Beside, my field collection has three field, one is boolean and the other is taxonomy fields, did anyone also know how to extract the value??

# Answer
> 0 votes
To load your field collection item and then extract the values needed, you have to load a field collection item entity as following:

```
entities = entity_load('field_collection_item', array($item_id))

```

Where your item id is the id of the field collection. This will return an array of entities, with `array_shift` you can get the first element out of the array. This element will contain all 3 fields.

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


title: Image file keeps getting deleted

text:
# Question
Title: Image file keeps getting deleted
I'm using the Image Title module with Drupal 7. I can successfully upload an image to be used as a title, however the images keep getting deleted. It looks like the problem is similar to this question on SO.

Oddly, I've been using image\_title for several years but never encountered this problem until now. And the module is basically abandoned, so there are no recent changes to it that would have changed the behavior - so has there been some change in Drupal itself that could explain this?

As a workaround I went into mysql and did `update file_managed set status = 1` for the image file in question, is that likely to solve it?

# Answer
> 1 votes
To be honest I would forget about using that module and simply have a field that contains the desired image, and change your node template file to display that image in place of the title.

It is important to have a text title (even if it is not displayed) because it is used in search engine listings.

---
Tags: 7, media, files
---


# Question
Title: invoking a block and attaching it to a specific html element
I have been having this problem for quite some time now and I don't know how to proceed.

I am trying to get a block by invoking it, the simple way:

```
 $block2 = module_invoke("module", "block_view", "nameofblock");
  print $block2["content"];

```

and insert it after a specific div with a unique id.

I tried using JavaScript and jquery:

```
(function($,Drupal,window,document,undefined){$(document).ready(function(){
$('#page-title,page').append('#invokedblockid');
 });})(jQuery,Drupal,this,this.document);

```

//and

```
document.getElementById("page").appendChild(document.getElementById("invokedblockid"));

```

//and all these

```
(function($) {

$(window).ready(function() {
$("page-footer-wide").detach().append("page-title");
$("#faresisgod").insertBefore("#page");
$("#faresisgod").appendTo("#page");
});})(jQuery)

```

but still the block is rendered where i originally added it, and if i put php inside of javascript, the new block will return a and close my script prematurely...

so is there a way to show this block in the specific div id by using javascript/jquery or is there a way to use php aray to check for the required id then invoking the block.

this is giving me a headache for quite sometime and i am out of options.

thanks in advance

# Answer
You can achieve this by creating a custom module which prints block content as shown below:

```
<?php
function mymodule_menu(){
    $items = array();

    $items['ajax/replace/block'] = array(
        'title' => t('Ajax Block'),
        'page callback' => 'ajax_callback',
        'access callback' => true,
        'type' => MENU_NORMAL_ITEM
    );

    return $items;
}

function ajax_callback(){
    $block2 = module_invoke("block", "block_view", 1);
    print $block2["content"];
}

```

Then add following jQuery line in your page to replace the target element with block content:

```
jQuery("#target-selector").load("/ajax/replace/block");

```
> 0 votes

---
Tags: javascript, theming
---


title: Are there any performance comparisons?

text:
# Question
Title: Are there any performance comparisons?
Are there any reliable performance comparisons between vanilla Drupal 8 versus Drupal 7?

I have searched the web but only find the post "Drupal 7 vs Drupal 8 Performance Comparison", which is far from encouraging.

# Answer
No, there is no reliable comparison, because doing that is almost impossible. There are various reasons for that, one is that D8 vanilla is like D7 vanilla + a whole bunch of modules, especially views.

If you compare a single request on a vanilla installation, then D8 is clearly slower than D7 (even if you add views), quite a bit actually. That might still improve more or less until the release, but it's not going turn around completely.

D8 is just running a lot more code, our own and vendor code like symfony underneath, so that takes more time. The service container also adds quite a bit of overhead.

However, D8 has a number of things that are hopefully going to make more than up for that on real sites

* Javascript by default runs in the footer, which improves front-end performance, as pages build up faster and you can see and use them earlier.
* The *highly* improved caching, especially render caching with cache tags and contexts, means that caches on real sites with changing content will perform much better. In D7, every time a node was changed or created, the complete block and page cache were invalidated. In D8, thanks to cache tags, D8 *knows* where that node shows up and might show up and only has to invalidate the relevant pieces. There's still a lot of work going on to improve that, but D8 provides a lot more tools to build faster big sites.
* There's also the argument that you would have to run D7 on hardware that is as old as that version while running D8 on modern hardware, which is considerably faster. Also, early benchmarks show that vanilla D8 runs up to 50% faster with PHP7, because that version is much better at running a lot of code fast. (You can also run D7 on modern hardware and with PHP7 (probably), so that argument only works so far...)
* Thanks to those decoupled services and better API's, which in a first step make things slower, is D8 going to have much better support for running partially/completely (depending on how daring you are I guess) with MongoDB and other alternative backends (like redis for the key value store). Again, for big sites, that allows to take at least part of the load away from MySQL, and store parts of your data (or, again, everything) elsewhere, which in turn helps to distribute the load across multiple servers.

Also keep in mind, if you care about performance, then you're very likely not running vanilla D7/D8 sites, you have large sites with a lot of content. And as mentioned above, D8 brings a lot of tools to help you to make those kind of sites faster. Some things will require work as a developer and need to be done right (just like in D7), but if you do, then I think that D8 can perform pretty well in real world scenarios.
> 27 votes

# Answer
There are a bunch of patches for D8 that should land before it is released. This presentation at the 2015 LA DrupalCon should explain what is happening to make sure D8 is fast.

See here for an example of one of the patches that is being worked on right now was committed.

See the issue queue for most of the open issues in terms of D8 performance improvements.
> 6 votes

---
Tags: 8, performance
---


# Question
Title: Check if entity reference field (user) contains current user
I have a node page of **Project** content type which contains a multiselect enitity reference field of user type called **field\_team**. I also have a block created by my custom module which is displayed at Project type pages only. What i'm trying to achieve is to do smth like this:

```
if ($current_node->field_team contains $current_user->uid) {
  $output = 'some_specific_content';
} else {
  $output = 'you are not a team member of this project';
}

```

How can I check if currently viewed node contains current user in its reference field?
Will be very thankful for any help or advice.

# Answer
> 0 votes
Check following code:

```
global $user;

$team_members = array();
foreach ($current_node->field_team['und'] as $team) {
  $team_members[] = $team['target_id'];
}

if (in_array($user->uid, $team_members)) {
  $output = 'some_specific_content';
} else {
  $output = 'you are not a team member of this project';
}

```

---
Tags: entities
---


# Question
Title: How to access the contents that are created by custom content type using module
I am new to drupal, I wished to view the contents using custom modules. For that, I have created custom content type and added some contents. Now I want to create a module to display all the contents that are created by those content types, in a page. Contents should have title, image, description, date field. How can I do that.?

# Answer
You can use Views to list content of custom content type.

Update(Programmatically load nodes):

```
<?php
$type = "custom_content_type";
$nodes = node_load_multiple(array(), array('type' => $type));
foreach($nodes as $node):
?>
<?php print $node->nid; ?>
<?php print $node->title; ?>
<?php endforeach; ?>

```

Ref: https://api.drupal.org/api/drupal/modules!node!node.module/function/node\_load\_multiple/7
> 1 votes

---
Tags: 7, nodes
---


title: Allow character variants in username

text:
# Question
Title: Allow character variants in username
I am trying to import some users from a phpBB forum and found an odd thing: in phpBB I have some users with weird characters in the username. Eg: Henriëtte .

The problem is that in Drupal I can't create 2 users with the username "Henriëtte" and "henriette". Apparently "Henriëtte" = "henriette" and this will give an warning saying that the username already exists.

Is there any way to import both usernames in Drupal? Thanks.

**\[LATER EDIT\]**

The database encoding is `utf8_general_ci`. Also, after further investigation the `user_load_by_name()` function is responsible for returning a valid user even if one letter is different (ë \> e). Also, `user_load_by_name` will in the end use `entity_load()` to load the user object.

# Answer
> 1 votes
Found the answer.

The encoding should be `utf8_bin` not `utf8_general_ci`

---
Tags: 7, users
---


# Question
Title: Drupal 7 different urls with same information
I have a new drupal site,it was built by other website designer.Now i got a problem for the url.There are some different url with same information.For example: "/taxonomy/term/31/0" and "/projects/led-tunnel-lighting".I only need the url like "/projects/led-tunnel-lighting". Please tell me how to fix this problem.Thank you very much! I was a novice of drupal.

# Answer
> 0 votes
I believe your two URLs are the same, but one is the system URL and the other one the aliases URL. They are both valid and normal to have, but in that case what you need is this module: Global Redirect

> an alias provides a nice clean URL for a path on a site. However Drupal does not remove the old path (eg node/1234). The problem is that you now have two URLs representing the same content.

# Answer
> 0 votes
Whenever you need to link to a node or a term (or something else in which might have an URL-Alias), use the l() function. The link to the term will then be rewritten to the given URL-Alias (as long as there is one).

---
Tags: uri
---


# Question
Title: How to programmatically trigger a click on an AJAX enabled form submit button?
I'm trying to programmatically (with jQuery) trigger a click on button with AJAX behavior in a Drupal form, but so far `jQuery('#edit-submit').click()` doesn't do anything.

A **real mouse click on** that button works as intended. Any ideas how to make it work?

# Answer
> 48 votes
`jQuery('#edit-submit').mousedown()` \- apparently there's a big difference.

# Answer
> 12 votes
Actually, there's no need to guess.

You should use Drupal behaviors

```
Drupal.behaviors.yourFunctionName = {
    attach:function (context, settings) {

       // Your code goes here....

    }
}

```

This will give you access to the settings' ajax property,

```
Drupal.behaviors.yourFunctionName = {
    attach:function (context, settings) {

       console.log(settings.ajax);

    }
}

```

Depending on your configuration, you should see a list of triggering elements, with various properties such as the name of the callback function, the selector's id as well as the name of the triggering event.

You can then use the relevant information to trigger your event.

```
// $(selector).trigger(eventName);
// for example...
$('#edit-product-id-15', context ).trigger('change');

```

# Answer
> 7 votes
Create ajax submit like the following.

```
 $form['button'] = array(
    '#type' => 'button',
    '#value' => 'Click',
    '#ajax' => array(
      'callback' => '_kf_reading_user_points',
      'wrapper' => 'reading-user-points',
      'method' => 'replace',
      'event' => 'click',
    ),
  );

function _kf_reading_user_points(&$form, &$form_state) {
  // Something within the callback function.
}

```

Then the jquery .click() event would be work in the drupal ajax form.

# Answer
> 3 votes
You can also use `.trigger()` jQuery method. `$('#element').trigger('click');`

# Answer
> 3 votes
In my case, the above recommended solutions didn't work for me, but the mention of .mousedown() led to the following idea that worked for me (Drupal 7):

```
$('#custom-submit-button').click(function() {
  $('#ajax-submit-button').trigger('mousedown');
});

```

There's some helpful background info about "why" this is the case in the Form API Reference under #ajax\_prevent

# Answer
> 2 votes
Looking at the Better Exposed Filters module, they submit the AJAX form by finding $(.ctools-auto-submit-click') and trigging a click.

```
<?php
// ... near line 190 of better_exposed_filters.js

// Click the auto submit button.
$(this).parents('form').find('.ctools-auto-submit-click').click();
?>

```

# Answer
> 0 votes
You have to trigger the `submit` event on the form. `Click` and `mousedown` events on buttons are not working.

---
Tags: 7, ajax, javascript
---


# Question
Title: Drush on windows - Command pm-enable needs a higher bootstrap level to run
I installed aquia drupal and added a core drupal folder into the sites list.

I also installed the windows installer of drush, it works ok for downloading modules but when I try to enable them I get this screen:

```
C:\Documents and Settings\Administrator\Desktop\drupal>drush en ctools
Command pm-enable needs a higher bootstrap level to run - you will       [error]

need invoke drush from a more functional Drupal environment to run
this command.
The drush command 'en ctools' could not be executed.                     [error]

Drush was not able to start (bootstrap) the Drupal database.             [error]

Hint: This error often occurs when Drush is trying to bootstrap a
site that has not been installed or does not have a configured
database.

Drush was attempting to connect to :
  Drupal version    : 7.9
  Site URI          : http://default
  Default theme     : garland
  Administration theme: garland
  PHP configuration : C:\Program Files\Propeople\Drush\Php\php.ini
  Drush version     : 5.0-dev
  Drush configuration:
  Drush alias files :
  Drupal root       : C:/Documents and
Settings/Administrator/Desktop/drupal
  Site path         : sites/default
  Modules path      : sites/all/modules
  Themes path       : sites/all/themes
  File directory path: sites/default/files
  %paths            : Array

You can select another site with a working database setup by
specifying the URI to use with the --uri parameter on the command
line or $options['uri'] in your drushrc.php file.

```

Anyone know how to solve this?

As a side note, whats the easiest way to get drush with the bash working on windows? Any good tuts?

# Answer
This particular error happens when drush cannot find the settings.php file to read in and "bootstrap" itself.

You need to cd into the drupal directory (Document root) of your drupal install in order for it to read in a settings.php file.

Looks like your pwd (present working directory) is on your desktop. Which i'm going to make a quick assumption that that directory isn't where your drupal install is located at.

> As a side note, whats the easiest way to get drush with the bash working on windows? Any good tuts?

I highly recommend looking into installing/using Cygwin on windows; as it's a slight improvement.

From there you'll be able to do more things with Drush. The sql-sync and several other functions i hear don't totally work reliably. For even more bonus points you may want to move to a linux or mac environment (something that has a terminal built in).

If you must stay with windows, please consider a drupal project called, quickstart, that creates a virtual machine that allows you to run ubuntu through a remote desktop terminal.
> 10 votes

# Answer
If your sites folder is not named default, then cd to the folder that contains settings.php and try again. You can also specify the root and site explicitly with the --root and --uri options. See `drush topic` for more drush help; in particular, read the example aliases topic.

Be aware that there are still open issues with Drush on Windows. For best result, be sure that you are using the latest installer (23 Nov as of this writing).
> 5 votes

# Answer
I had a similar issue but the root cause was a little different. Drush wasn't able to find the php.ini file. An easy way to check if you have the same problem is to run `drush status` and see if the `PHP Configuration` value is blank or not.

If it is, the quick and easy way to solve this problem is to specify the PHPRC path variable in `Environment Settings` and point it to the right php.ini file.
> 2 votes

# Answer
From my experience, this error strikes, when php invoked by drush is not loading the additional modules, which are used, when php is used inside the web-server (such as pdo and pdo\_mysql).

Find, where on your system the files like pdo.ini and pdo\_mysql.ini are located. Then set environment variable PHP\_INI\_SCAN\_DIR to point to that directory and try running drush again.
> 1 votes

# Answer
you have like me probably forgot to add a docroot/sites/default/settings.local.php

```
<?php
$databases = array(
    'default' => array(
            'default' => array(
                    'database' => 'database_name',
                    'username' => 'root',
                    'password' => '',
                    'host' => '127.0.0.1',
                    'port' => '',
                    'driver' => 'mysql',
                    'prefix' => '',
            ),
    ),
);
$conf['file_temporary_path'] = '/tmp';

```
> 0 votes

---
Tags: 7, drush
---