title: Remove addresses with only a country

text:
# Question
Title: Remove addresses with only a country
For a site I am working on I am using the address field. Each node can have multiple addresses and at least one is required. All the addresses are in the US so I set the default to the US.

When the user enters and address a new field shows up with the default country address. Whenever the go to edit the page a new one with just the country is also their. They save and soon there is a bunch of addresses with only a country. This causes other parts of the site to break.

I need a way to either make the default in the form none or to delete addresses that have only a country when the node is saved/updated.

I didn't have luck with either but admitably I am new to using hooks. Below is my most recent attempt by using the node presave hook.

```
function postal_default_node_presave($node) {
  if ($node->type == 'micro_property') {
    foreach($node->field_micro_address[LANGUAGE_NONE] as $address){
        dpm($address);
        unset($address['country']);
        unset($address['element_key']);
        $found = false;
        // Cycles all submitted address field components for the country to see if any have been filled
        foreach ($address as $value) {
            if (!empty($value) > 0) { $found = true; }
        }
        // Empty the address and location arrays if the fields were blank
        if (!$found) {
            dpm('not found reseting');
            $node->field_address = array();
            $node->field_location = array();
        }
    }
    return $node;
  }
}

```

The dpm messages are posting what I would expect but the node being saved is not.

# Answer
I was on the right track and made a really stupid mistake and don't know why I didn't notice it. I was deleting the correct way but I was deleting the wrong thing. I was in a loop since there are multiple addresses.

```
// Empty the address and location arrays if the fields were blank
if (!$found) {
    unset($node->field_micro_address[LANGUAGE_NONE][$k]);
}

```
> 1 votes

# Answer
I think the code to delete the fields content is wrong. Have a look at: http://fooninja.net/2011/06/06/updating-nodes-programmatically-in-drupal-7/

In that blog post they use `unset()`:

```
// Delete field with index 0
unset($node->field_textfoo[$node->language][0]);

// Delete third field from a multi-value field
unset($node->field_textfoo[$node->language][2]);

// Delete whole field (if field is multi-value, all values are deleted)
unset($node->field_textfoo[$node->language]);

```
> 0 votes

---
Tags: 7
---


# Question
Title: How to speed up node add form with around 50 fields?
I had a node add form with around 50 fields, mostly text with 1 field collection (with another 5 fields) and a few entity and term references.

The page is taking around 30 seconds to load making it unusable.

There are several slow queries (99.28 - DrupalDatabaseCache::getMultiple, 34.21 - views\_plugin\_query\_default::execute, 20.51 - DrupalDefaultEntityController::load, 18.46 - DrupalDatabaseCache::getMultiple, 17.46 - DrupalDatabaseCache::getMultiple.. they go on)

The Cache::getMultiple query has 1087 placeholders, and the EntityController::load has 1084 placeholders.

If a click on the "Add Another Item" on the field collection that takes a further 30 seconds to complete.

What can I do to speed up the load times of the page?

EDIT: I just installed APC which removed all of the caching queries but did not solve the problem - still around 30 second load time. I don't think the slow load times are related to caching. Is taking around 280MB of memory load build the page.

EDIT: Removing the field collection, installing memcache and entitycache has shaved 20 seconds off the load time. However 10 seconds to initially load the page and another 10 seconds per ajax request is still unacceptable. How do webforms perform with a large number of fields? Maybe that would be a better option?

# Answer
Have you considered using multistep forms for your node creation?

Given that you have a lot of fields, you can do it at multiple page loads via various logical steps. There are lots of tutorials for multistep form implementation in Drupal and the example module ships with one.
> 3 votes

---
Tags: nodes, forms, caching, performance
---


# Question
Title: How can users share entities if they have a relation?
Im setting up a pretty complicated website, where users are going to have access to a certain nodes depending on which entities the user of the relation has.

with profile 2, i did add an entity reference field, which displays the nodes im going to grant / restrict permissions on the profile registration.

Its going to be something like this:

Me (admin) is going to create a SUB ADMIN user, i set which nodes is he / she going to be able to access.

The SUB ADMIN user, creates users with the role of normal users. The user itself is going to have less privileges than the SUB ADMIN user, and is going to have the same restrictions on the nodes than the SUB ADMIN user.

... i know its a bit complicated, but i would love to know if there's any way to share the entities of the SUB ADMIN user to the user he creates?.

Using this modules right now: ENTITIES REFERENCE PROFILE 2 RELATION SUB USER

Hope you guys could help me... Thanks in advance!.

# Answer
Do you know about Node Access Relation, it sounds like maybe you want to use it.

> * You use or plan on using the Relation module and want to grant users access to view/edit/delete content based on their relations.
> * You find Drupal roles too broad but per-node access controls too much to manage
> 0 votes

---
Tags: entities
---


title: how can I use drush in ftp host

text:
# Question
Title: how can I use drush in ftp host
Is this possible to use drush in dedicated host that only I can access cpanel?
If yes how can I do it?

# Answer
Shell access is required to use Drush.
> 2 votes

---
Tags: drush, files
---


title: Localize views menus links

text:
# Question
Title: Localize views menus links
I need a way to *localize* menu Items pointing to Views in a menu that has field translation.

I cannot create them neither from views nor manually (weird access denied messages).

EDIT: Here comes the original post. The title was "Translate the main menu with preserving English in case the translation is missing". I learned a thing or two in the process ;-)

I think I am doing something basically wrong... I have set up a basic multilingual site with fields (entity) translation. Now, all works fine up to the menus. If I translate the menus, however, only the menu links that *have actually been translated* show up in the other languages. What's more, the menu structure does in other languages does not preserve the weights of the particular links.
What I'd like is to happen is:

1. English (or other provided) menu link show up when no translation is available.
2. The translated links preserve the weights.

Settings the menu links to "language neutral" solved the issue to a point. I cannot apply this practice, however, to views. Menu Items from views have English by default. What's more, when I remove the menu item in Views menu and try to make a menu item that points to it by path, I get:

> You are not authorized to access this page.

Any ideas?

# Answer
> 0 votes
You should set in the content type translation settings, to show **no fallback language**, and **set all english nodes to English**, rather than Language neutral (if they are such).

# Answer
> 0 votes
So, my problem was: How to *localize* menu links created by views?

In fact, I could neither create links by views \*nor add menus links that point to those views manually (I got access denied messages). Eventually I used the Menu Tokens module with paths like `[site-url]\xxx`. This worked.

---
Tags: 7, routes, users, i18n-l10n
---


# Question
Title: Table not creating while installing a custom module in Drupal 7
I am creating a simple module. In that module I need to save the values in a table and I have created an .install file to create the table when the module is installed.

While installing the module, it is not creating the table and it gives a PDOException Error. I am unable to find the issue with my code.

The error message:

> PDOException: SQLSTATE\[42000\]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'unsigned NOT NULL COMMENT ' AMOUNT', `rate` unsigned NOT NULL COMMENT 'R' at line 3: CREATE TABLE {sampletest} ( `id` INT unsigned NOT NULL COMMENT 'My unique identifier', `amount` unsigned NOT NULL COMMENT 'AMOUNT', `rate` unsigned NOT NULL COMMENT ' RATE', `time` unsigned NOT NULL COMMENT ' TIME', PRIMARY KEY (`id`) ) ENGINE = InnoDB DEFAULT CHARACTER SET utf8 COMMENT ' table'; Array ( ) in db\_create\_table() (line 2717 of H:\xampp\htdocs\drupal7\includes\database\database.inc) ;

Content of the .install file :

```
<?php
/**
* Implements hook_install().
*/
function sampletest_install() {
 drupal_install_schema('sampletest');
}
/**
* Implements hook_install().
*/
function sampletest_uninstall() {
  drupal_uninstall_schema('sampletest');
}
/**
* Implements hook_schema().
*/

function sampletest_schema() {
  $schema['sampletest'] = array(
    'description' => t('EMI table'),
    'fields' => array(
      'id' => array(
        'description' => t('My unique identifier'),
        'type' => 'int',
        'unsigned' => true,
        'not null' => true,
      ),
      'amount' => array(
        'description' => t('AMOUNT'),
        'type' => 'bigint',
        'unsigned' => true,
        'not null' => true,
      ),
      'rate' => array(
        'description' => t('RATE'),
        'type' => 'bigint',
        'unsigned' => true,
        'not null' => true,
      ),
      'time' => array(
        'description' => t('TIME'),
        'type' => 'bigint',
        'unsigned' => true,
        'not null' => true,
      ),
    ),
    'primary key' => array('id'),
  );
  return $schema;
}

```

# Answer
> 1 votes
I can see 2 problems with in your code:

1. You should not call `drupal_install_schema()` from `hook_install()` in Drupal 7. `hook_schema()` will be called and the table will be automatically created/dropped on installing/uninstalling. See here: https://drupal.org/node/224333#install-schema
2. As @Ollie also stated, there's no field type named `bigint`. You should use `int` and set its size to `big`.

Like following:

```
'amount' => array(
  'description' => t('Amount'),
  'type' => 'int',
  'size' => 'big',
  'unsigned' => TRUE,
  'not null' => TRUE,
),

```

# Answer
> 0 votes
I think the problem is in using 'bigint' as the type. Use 'type'=\>'int', 'size'=\>'big', instead.

---
Tags: 7, database
---


# Question
Title: Upload image programmatically in user account
I used the below code to upload default picture field. Other than this default picture field, I have another field to upload image (for Example, field name "field\_house\_image"). How to upload file Programmatically.

```
$tmp_photo_realpath = "images/".$userimgname;
        $tmp_photo = "images/".$userimgname;
          $file = new stdClass();
          $file->uid      = $uid;
          $file->status   = 0; // mark the file as temporary
          $file->filename = basename($tmp_photo_realpath);
          $file->uri      = $tmp_photo;
         // $file->filemime = image_type_to_mime_type(exif_imagetype($tmp_photo_realpath));
          $file->filesize = filesize($tmp_photo_realpath);
         $infofile = explode("/",$tmp_photo);
        $infoext = explode(".",end($infofile));
        $imgext = end($infoext);

      // The file should be an image
      $errors = array();
      $errors += file_validate_is_image($file);
      $errors += file_validate_image_resolution($file, variable_get('user_picture_dimensions', '100x100'));
      $errors += file_validate_size($file, variable_get('user_picture_file_size', '30') * 1024);

      // Make sure file extension is a valid image
      if (!in_array(strtolower($imgext), array('jpg', 'png', 'gif'))) {
        $errors[] = ' invalid image file extension.';
      }

      if (count($errors)) {
        drupal_set_message(t('Profile Image Import:') . ' ' . $errors[0], 'warning');
        // Clean up (set fid to avoid error messages)
        $file->fid = 0; file_delete($file);
      }
      else {
        // We'll need a valid file id on the file object; file_save() will give us one
        $file = file_save($file);
        // Update user account (fid is not empty, status is temporary -- image
        // will be moved to proper directory and assigned to the user)
        $fields['picture'] = $file;
        $account = user_save($account, $fields);
    }

```

---

```
EntityDrupalWrapper Object
(
    [id:protected] => 26679
    [bundle:protected] =>
    [entityInfo:protected] => Array
        (
            [path] => user/%user
            [metatags] => 1
            [label] => User
            [controller class] => UserController
            [base table] => users
            [uri callback] => user_uri
            [label callback] => format_username
            [fieldable] => 1
            [entity keys] => Array
                (
                    [id] => uid
                    [revision] =>
                    [bundle] =>
                )
        [bundles] => Array
            (
                [user] => Array
                    (
                        [label] => User
                        [admin] => Array
                            (
                                [path] => admin/config/people/accounts
                                [access arguments] => Array
                                    (
                                        [0] => administer users
                                    )

                            )

                        [rdf_mapping] => Array
                            (
                                [rdftype] => Array
                                    (
                                        [0] => sioc:UserAccount
                                    )

                                [name] => Array
                                    (
                                        [predicates] => Array
                                            (
                                                [0] => foaf:name
                                            )

                                    )

                                [homepage] => Array
                                    (
                                        [predicates] => Array
                                            (
                                                [0] => foaf:page
                                            )

                                        [type] => rel
                                    )

                            )

                    )

            )

        [view modes] => Array
            (
                [full] => Array
                    (
                        [label] => Doctor Login
                        [custom settings] =>
                    )

                [token] => Array
                    (
                        [label] => Tokens
                        [custom settings] =>
                    )

            )

        [static cache] => 1
        [field cache] => 1
        [load hook] => user_load
        [translation] => Array
            (
            )

        [schema_fields_sql] => Array
            (
                [base table] => Array
                    (
                        [0] => uid
                        [1] => name
                        [2] => pass
                        [3] => mail
                        [4] => theme
                        [5] => signature
                        [6] => signature_format
                        [7] => created
                        [8] => access
                        [9] => login
                        [10] => status
                        [11] => timezone
                        [12] => language
                        [13] => picture
                        [14] => init
                        [15] => data
                    )

            )

        [token type] => user
        [bundle label] => User
        [xmlsitemap] => Array
            (
                [process callback] => xmlsitemap_user_xmlsitemap_process_user_links
            )

        [plural label] => Users
        [description] => Users who have created accounts on your site.
        [access callback] => entity_metadata_user_access
        [creation callback] => entity_metadata_create_object
        [save callback] => entity_metadata_user_save
        [deletion callback] => user_delete
        [form callback] => entity_metadata_form_user
        [view callback] => entity_metadata_view_single
        [configuration] =>
    )

[propertyInfo:protected] => Array
    (
        [bundles] => Array
            (
                [user] => Array
                    (
                        [properties] => Array
                            (
                                [field_enterprise_blog_firstname] => Array
                                    (
                                        [label] => First Name
                                        [type] => text
                                        [description] => Field "field_enterprise_blog_firstname".
                                        [getter callback] => entity_metadata_field_property_get
                                        [setter callback] => entity_metadata_field_property_set
                                        [access callback] => entity_metadata_field_access_callback
                                        [query callback] => entity_metadata_field_query
                                        [translatable] =>
                                        [field] => 1
                                        [required] => 1
                                    )

                                [field_enterprise_blog_lastname] => Array
                                    (
                                        [label] => Last Name
                                        [type] => text
                                        [description] => Field "field_enterprise_blog_lastname".
                                        [getter callback] => entity_metadata_field_property_get
                                        [setter callback] => entity_metadata_field_property_set
                                        [access callback] => entity_metadata_field_access_callback
                                        [query callback] => entity_metadata_field_query
                                        [translatable] =>
                                        [field] => 1
                                        [required] =>
                                    )

                                [field_enterprise_blog_picture] => Array
                                    (
                                        [label] => Picture
                                        [type] => field_item_image
                                        [description] => Field "field_enterprise_blog_picture".
                                        [getter callback] => entity_metadata_field_verbatim_get
                                        [setter callback] => entity_metadata_field_verbatim_set
                                        [access callback] => entity_metadata_field_access_callback
                                        [translatable] =>
                                        [field] => 1
                                        [required] =>
                                        [auto creation] => entity_metadata_field_file_create_item
                                        [validation callback] => entity_metadata_field_file_validate_item
                                        [property info] => Array
                                            (
                                                [file] => Array
                                                    (
                                                        [type] => file
                                                        [label] => The image file.
                                                        [getter callback] => entity_metadata_field_file_get
                                                        [setter callback] => entity_metadata_field_file_set
                                                        [required] => 1
                                                    )

                                            )

                                    )

```

# Answer
I'm doing that using `entity_metadata_wrapper` since it's the easiest way. You should have Entity API installed to use this function. A working example from one of my projects (I've changed the variables to fit your question):

```
$user_wrapper = entity_metadata_wrapper('user', $uid);

$tmp_photo_realpath = "images/" . $userimgname;
$contents = @file_get_contents($tmp_photo_realpath);
$uri = 'public://images/user/' . $userimgname;

$file = file_save_data($contents, $uri);
$file_info = array(
  'fid' => $file->fid,
  'filename' => $file->filename,
  'filemime' => $file->filemime,
  'uid' => 1,
  'uri' => $file->uri,
  'status' => 1,
  'display' => 1,
);

$user_wrapper->field_house_image->set(array($file_info));
$user_wrapper->save();

```

If your field `field_house_image` is a multi-value field, you can use a loop like (suppose you have an array of multiple images named `$file_infos`):

```
foreach ($file_infos as $key => $file_info) {
  $user_wrapper->field_house_image[$key]->set($file_info);
}
$user_wrapper->save();

```
> 1 votes

---
Tags: users
---


# Question
Title: Views expose filter of start and end dates
I want an expose filter of start date and end date. I want to show the events that have start or end date between these two dates. If end date is not given in filter then display all the events having start date greater than filter's start date.

# Answer
Add the filter like that :

```
Start Date >= Filter's Stat Date

End Date <= Filter's End Date

```
> 0 votes

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


# Question
Title: preg_replace() not working on node title in hook_preprocess_page()
Here's code from my module:

```
function mymodule_preprocess_page(&$variables) {
  // load the node object
  $node = node_load(arg(1));
  $fied = $node->field_building_sell['und'][0]['value'];

  // regexp
  $pattern = '/(\w+\s\w+,\s\w+\s.{3}\s\/\/\s\w+)(.*)/i';
  $replacement = '$1';
  $subject = $node->title;
  $replaced = preg_replace($pattern, $replacement, $subject);

  $variables['title'] = $replaced;

  dpm($replaced);
}

```

My node title looks like this:

**building Sell, Alatau r-n // City - mon, 03/03/2014 - 22:29**

But i still get the full node title unchanged. Is `preg_replace()` not working in preprocess\_page hook?

**UPDATE**

I have noticed, if i replace:

```
$subject = $node->title;

```

to

```
$subject = 'building Sell, Alatau r-n // City - mon, 03/03/2014 - 22:29';

```

It works! But it's not working with `$node->title`, though, node title output is exactly the same as the string i posted above.

# Answer
Just did dpm($node-\>title) and noticed extra white-space here:

```
building  Sell, Alatau r-n // City - mon, 03/03/2014 - 22:29

```

Though, when i was just printing it `$node->title` it didn't showed any extra white-spaces.
> 0 votes

---
Tags: 7, hooks, theming
---


# Question
Title: Active menu for a node with two different terms
I have a node which has two different terms. The problem is when I'm on such a node, the active menu and breadcrumbs point only to one of the terms. How can I find a solution to this problem without duplicate that node for each term. Or if you have an idea how to duplicate that node but they will be edited in one place that's is also a good solution. Thanks!

# Answer
> 0 votes
You can adjust the breadcrumb using `hook_menu_breadcrumb_alter()` in your custom module. There's an answer about proper using of `hook_menu_breadcrumb_alter()` similar to your use case and with helpful references at https://drupal.stackexchange.com/a/49952/10176

---
Tags: taxonomy-terms, routes
---


# Question
Title: When enabling Clean URLs, test passes, but ticking & updating fails
I have mod rewrite running fine and the test passed ont he CLean URLs page, however when I tick the box to 'Enable clean URLs' and click 'Save configuration', I get a message saying 'The configuration options have been saved.' however the box remains unticked and I get the same page below!

Any ideas why it is not enabling here?

# Answer
> 0 votes
This has taken me a *long* time to resolve also. You need to set the relevant line in /sites/default/settings.php to

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

```

Mine was set to zero. When I updated this, I realized that my server account didn't have permissions to change the `settings.php` file, and I suspect this is why it was not able to be updated by Drupal.

Hope this helps

---
Tags: uri
---


# Question
Title: Can a database serve two different installations on localhost?
I have a Drupal 6 live site backed up to my localhost and I want to transition the localhost version to 7 before uploading to become the live site.

In my mind the ideal process would be to have a separate 7 install accessing the same (or mirrored) database so I still have a clean 6 backup in case of trouble with the live site. Does anyone have an opinion if this possible and/or the best way to do it?

I have MAMP Pro driving the localhost.

# Answer
There is no problem using a single database to serve multiple applications (including multiple Drupal instances). However, they need to be completely separate instances. You cannot use a Drupal 6 database instance as part of a Drupal 7 instance. You must set up a clean Drupal 7 instance, and then migrate the content from a Drupal 6 instance into it, using the standard procedures for upgrading from Drupal 6 to Drupal 7.

To do this, you use something known as "table prefix". When you install Drupal (both 6 and 7) on the database setup page you get during installation, you can expand a tab to get to *Advanced options*. This gives you access to some extra options, including "table prefix".

The "table prefix" allow for multiple instances sharing the database. For instance, if your existing Drupal 6 site is set up *without* a table prefix, you can use the table prefix `d7_` to set up a Drupal 7 configuration in the *same* database that will not interfere with your Drupal 6 configuration.
> 2 votes

# Answer
Drupal codebase is always strongly connected with same version of database. You can not use Drupal 6 version of codebase with Drupal 7 version of database and viceversa... Because schema differs from D6 to D7 versions..

From your question .. I understand that you are trying to upgrade your Drupal 6 version to Drupal 7 version.

For Drupal core upgrade you can follow this Documentation in D.O

For Upgrading Contributed Modules from D6 to D7 version Documentation

There is also a "Coder project that can help automate the process of converting your custom modules from D6 to D7.

As you mentioned, It's always good to have backups. Make sure you have a backup before upgrading your Drupal Website.
> 0 votes

---
Tags: upgrading
---


# Question
Title: Create node with taxonomy field using services in drupal 7
I am creating node from my android app using services 3. I hit this URL www.mysite/endpoint/node with the following json:

```
{
    "title": "my act for tax",
    "type": "activity",
    "field_activity_type": [{
        "tid": {
            "tid": "[tid:45]"
        }
    }]
}

```

`field_activity_type` is a taxonomy term autocomplete filed.

Node is created successfully but `field_activity_type` remains empty. I am unable to find a correct way to populate taxonomy field. Anyone who knows please help me.

# Answer
Here is the Json format to create node having taxonomy filed

```
{"title":"my act for tax","type":"activity","field_activity_type":{"und":"termname"}}

```
> 4 votes

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


# Question
Title: Drupal 8 devel dpm does not expand Drupal\node\Entity\Node
I'm getting a feeling that Devel got pretty much useless with D8. When I try to dump most of the drupal objects I get only `(Object) Namespace\Class` output. No fields data is printed. `print_r` is able to print a lot of information but it's close to useless because it's output is virtually unreadable.

Is there a way to nicely print (dpm?) contents of objects in D8?

# Answer
dpm() does not print any protected properties and it also doesn't know about methods. That's especially bad for content entities but applies to most objects in 8.x now.

The issue referenced in the answer from Daniel Wehner adds Kint, which is already much better, as it will give you protected properties and methods.

However, for content entities, it still won't be that helpful as the values are all within -\>values and -\>fields and it's not trivial to understand how those work, especially with multiple languages.

That's why we're also working on better integration for content entities with Kint, so that it will display the fields and their values, see the screenshot in that issue.

Until then, you can also always use the following to debug what's inside a node or other content entity:

```
<?php
dpm($node->toArray());
dpm($node->getFieldDefinitions());
?>

```

At least the first one also works well with debug(), which has the advantage that it also works when running tests.
> 10 votes

# Answer
https://drupal.org/node/2034919 will care about this.

It first bring in a new library which somehow will be extendable so that drupal's own logic can be supported.
> 3 votes

# Answer
See what berdir wrote +

```
dsm(get_object_vars($entity));
dsm(get_class_methods($entity));

```
> 1 votes

---
Tags: 8, debugging
---


# Question
Title: Saving a unpublished node without validation
I have site with a content type that has a large number of fields on it.

I would like to allow users to start to create nodes, but not have to fill out all of the fields in one sitting. Partially completed nodes don't have to be published, but they do need to be saved in the database.

Is is possible to save the node in an uncompleted state without the validation rules running. I am mainly interested in required fields not being required, unless the node is published.

When users finish populating nodes, the validation rules should run when the node is published.

Are there any ways to accomplish this workflow?

# Answer
Another option here is to add a custom validation function to force validation to run, and then also have a custom submit handler to clear any errors produces and save the node.

The code here is mostly taken from this question but this question and this post have also helped.

```
function mymodule_form_alter(&$form, &$form_state, $form_id) {
    switch($form_id) {
        case 'my_form_id':

            $form['actions']['draft'] = array(
                '#type' => 'submit',
                '#value' => t('Save draft'),
                '#weight' => '9',
                '#submit' => array('save_draft_submit'),
                '#validate' => array('save_draft_validate'),
                '#attributes' => array(
                    'class' => array('cancel'), // add the class cancel will skip any clientside validation
                ),
                //'limit_validation_errors' => array(), // this should be enough to skip validation however does not work for me
            );

            break;
    }
}

function save_draft_validate($form, &$form_state) {
    // Set as unpublished.
    $form_state['values']['status'] = 0;
    // Force validation.
    $errors = &drupal_static('form_set_error', NULL, TRUE);

}

function save_draft_submit($form, &$form_state) {
    // clear error messsages
    drupal_get_messages();
    // save the node
    node_form_submit($form, $form_state);
    $form_state['redirect'] = 'node/'.$form_state['nid'].'/edit';
}

```
> 3 votes

# Answer
**Use the following answer at your own risk:**

You need to remove the validation functions from the form. You will need to do a hook\_form\_alter and then remove the validate functions that are defined by the node module. You might need to inspect the `$form` variable to find out where the validation methods are being set and then unset them.

```
<?php

THEME_form_alter(&$form, &$form_state, $form_id) {
  // Only remove the validate functions when adding a form, not edditing.
  if ($form_id == 'FORM_ID') {
    unset($form['#validate']);
  }
}

```

If you make sure the nodes are not published when this code runs and that you do not unset the validators when editing the node, you can pretty much assure that when you go to try publish the node the validators will run in the regular way and you can catch the errors at that point.

As mentioned in the comments, this is a strange thing to be doing and should be avoided, however if you are sure this is the correct course of action, this should help you.
> 2 votes

---
Tags: 7, nodes
---


title: login redirection

text:
# Question
Title: login redirection
I'm using a modal form module to display a modal login window, so far so good, but when I attempt to let it redirect on the current page that the user is displaying it redirect me to a not existing page. For example, when I do login it redirect me to www.mydomain/m instead of www.mydomain/current-page

What I've already tried is to set as a redirect in the login destination module, but it won't work (It redirect me to the the page above). I've tried as well to build a rule that will redirect me to \[site:current-page:url\], but the result is http://www.mydomain/modal/ajax/login, it seems to bring the link of the page that make the access.

The question is, how I can get the current page during the redirect? Do I need to get the previous page somehow?

Thanks for the help.

# Answer
> 1 votes
The login toboggan module will probably help for this redirection issue.
\- Install and enable the module : https://drupal.org/project/logintoboggan
\- Go in the admin interface and choose the login destination : admin/config/system/logintoboggan if you want to override the default behavior which is the destination parameter I think, so the current page.

---
Tags: 7, users, javascript, redirection
---


title: function “L” cannot work

text:
# Question
Title: function “L” cannot work
I am trying to highlight nids of pages when I am using $nid = $node-\>nid they stop working of function l in drupal 7 but our nids is highlighted here is my code

```
$ch1=db_query("SELECT th.tid FROM taxonomy_term_hierarchy th
  INNER JOIN taxonomy_term_data td ON th.tid=td.tid
  INNER JOIN field_data_field_books book ON book.field_books_tid = th.tid
  WHERE td.vid = '6' AND th.parent = $ch AND book.entity_id = $nid
  ")->FetchField();

$chap1=taxonomy_get_children($ch1);
echo "<ul>";
foreach($chap1 as $ca1){
  $pnid = db_query("SELECT n.nid FROM node n
  INNER JOIN field_data_field_books book ON book.entity_id = n.nid
  WHERE  book.field_books_tid = $ca1->tid AND n.nid = $nid " )->FetchField();
  if($nid == $pnid){
    print "<li class='b'><b>".$ca1->name."</b></li>";
  } else {
    $link = l($ca1->name, 'node/' . $pnid);
  print "<li class='a'>". $link."</li>";
  }
}
echo "</ul>";

```

how can I solve this problem ?

# Answer
> 1 votes
I can't say for sure without debugging your code and actually knowing what about your link is not working but I will make assumptions.

I would *guess* the problem is that $pnid is not a node ID. If your query above returns nothing then $pnid will be FALSE and your link will break.

You need to check that $pnid is a real result but also you probably need to rewrite your sql so it works.

To check that $pnid is something do this:

```
foreach ($chap1 as $ca1) {
  $pnid = db_query("SELECT n.nid
                      FROM node n
                INNER JOIN field_data_field_books book ON book.entity_id = n.nid
                     WHERE book.field_books_tid = :tid
                       AND n.nid = :nid", array(':tid' => $ca1->tid, ':nid' => $nid))->FetchField();
  if ($pnid) {
    if ($nid == $pnid) {
      print '<li class="b"><b>' . $ca1->name . '</b></li>';
    }
    else {
      $link = l($ca1->name, 'node/' . $pnid);
      print '<li class="a">' . $link . '</li>';
    }
  }
}

```

As an aside, the way you are writing your database queries is bad for security reasons. You shouldn't use variables directly in the query like:

```
$ch1=db_query("SELECT th.tid FROM taxonomy_term_hierarchy th
  INNER JOIN taxonomy_term_data td ON th.tid=td.tid
  INNER JOIN field_data_field_books book ON book.field_books_tid = th.tid
  WHERE td.vid = '6' AND th.parent = $ch AND book.entity_id = $nid
  ")->FetchField();

```

If you are passing in valid variables then there must be no node that matches the tid you're passing into the query.

Instead it should be like this:

```
$ch1=db_query("SELECT th.tid FROM taxonomy_term_hierarchy th
  INNER JOIN taxonomy_term_data td ON th.tid=td.tid
  INNER JOIN field_data_field_books book ON book.field_books_tid = th.tid
  WHERE td.vid = '6' AND th.parent = :ch AND book.entity_id = :nid
  ", array(':ch' => $ch, ':nid' => $nid))->FetchField();

```

Notice how it uses the tokens with the preceeding colon instead of putting the variable directly in the string. This allows the database query function to sanitize the variable so users cannot hack your website with SQL injection.

Another thing (specific to (db\_query()) is you should wrap tables in curly braces or it can break if your code is ever used on a site where the database has table prefixes. For example:

```
FROM {node} n

```

I would also advise against using classes like 'b', because what does that represent? Someone else (or you in the future) reading your code could be quite confused.

---
Tags: 7
---


# Question
Title: Trying to create a table with an uid field that auto-increments and is the primary key, but keep getting an error
I'm working on an .install file for my module in Drupal 7. I want to create two tables, one called tls\_connect\_floormap\_images and one called tls\_connect\_floormap\_coords. I'm not having any trouble with the \_images table. But when I try to make the uid field of the \_coords table a unique key that auto-increments, I get an error that says:

> Fatal error: Unsupported operand types in C:\Program Files (x86)\Zend\Apache2\htdocs\TLSConnect3App\includes\database\mysql\schema.inc on line 85

I get this error on install, When I Save Configuration I get the WSOD with the error message. When I put in the url for /admin/modules there is an error that says Notice: Undefined variable: schema in floormap\_install() (line 37 of C:\Program Files (x86)\Zend\Apache2\htdocs\TLSConnect3App\sites\all\modules\custom\TLSConnectPackage\floormap\floormap.install). I see that the module is installed though, and when I check for my tables in phpMyAdmin they are there, uid auto\_increments but is not a unique or primary key.

Here is my code:

```
function floormap_schema(){
    $schema['floormap_images'] = array (
            'description'   => 'Floor map images.',
            'fields'        => array (
                'image'     => array('type'     => 'blob',      'not null'  => TRUE,),
                'name'      => array( 'type'        => 'varchar',       'length'        => 30,      'not null'  => TRUE,),
                'active'    => array('type'     => 'int',           'unsigned'  => TRUE,    'not null'  => TRUE,),
            ),
            'unique keys'   => array('name' => array('name'),
            ),
        );
    $schema['floormap_coords'] = array (
        'description'   => 'Floor map images.',
        'fields'        => array (
            'uid'       => array( 'type'    => 'serial',    'unsigned'  => TRUE,    'not null'  => TRUE,),
            'floormap'  => array( 'type'    => 'text',  'not null'  => TRUE,),
            'item_type' => array( 'type'    => 'text',  'not null'  => TRUE,),
            'pos_a_x'   => array( 'type'    => 'int',       'unsigned'  => TRUE,    'not null'  => TRUE,),
            'pos_a_y'   => array( 'type'    => 'int',       'unsiged'   => TRUE,    'not null'  => TRUE,),
            'pos_b_x'   => array( 'type'    => 'int',       'unsigned'  => TRUE,    'not null'  => TRUE,),
            'pos_b_y'   => array( 'type'    => 'int',       'unsiged'   => TRUE,    'not null'  => TRUE,),
            'pos_c_x'   => array( 'type'    => 'int',       'unsigned'  => TRUE,    'not null'  => TRUE,),
            'pos_c_y'   => array( 'type'    => 'int',       'unsiged'   => TRUE,'   not null'   => TRUE,),
            'pos_d_x'   => array('type' => 'int',       'unsigned'  => TRUE,    'not null'  => TRUE,),
            'pos_d_y'   => array('type' => 'int',       'unsiged'   => TRUE,    'not null'  => TRUE,),
        ),
        'unique keys'   => array('uid' => array('uid'),),
    );
    return $schema;
}
function floormap_install() {

    //Create table to store floor map images if it doesn't already exist
    if(!db_table_exists('tls_connect_floormap_images')){
        db_create_table('tls_connect_floormap_images',$schema['floormap_images']);
    }
    //Create table to store floor map coordinates if it doesn't already exist
    if(!db_table_exists('tls_connect_floormap_coords')){
        db_create_table('tls_connect_floormap_coords',$schema['floormap_coords']);
    }
}

```

I only get the error when I have

```
'unique keys' => array('uid' => array('uid'),),

```

in the $schema\['floormap\_coords'\] array. It works in the \['floormap\_images'\] array though, not sure why its not working for coords. The only difference is that the 'uid' field is serial datatype and name is varchar.

# Answer
> 0 votes
First of all please provide which version of drupal you are using ?

If you are using d7 than you don't need to check in hook\_install is table exists ?

Just provide hook\_schema in your module file and it will create your tables. For floormap\_coords make uid as primary ( primary key itself unique) 'primary key' =\> array('uid'),

# Answer
> 0 votes
When do you get that error message? Is it on installing the module or any time the module is loaded (i.e. a parse error).

The "Unsupported operand types" error indeed seems like something is wrong. However, it usually indicates you are doing division on an array or using a = where it should be a =\> or something. I tried just compiling/printing the code you pasted here in 3v4l.org and it appears to work fine so I don't see how you could get that error from it.

---
Tags: theming, database
---


# Question
Title: How to override template for a Profile2 page
I'm working on a project which request, for a particular type of user, the need to choose a different template for the main profile page (public page). I need to override the main profile page but I can't find the php file to edit. Can you help me.

# Answer
> 0 votes
You need to put user-profile.tpl.php in your theme directory.

---
Tags: 7, users
---


# Question
Title: Colorbox links not working on Ajax loaded content
I am using latest stable version of the Colorbox module

I have an image gallery with small thumbnails and a big one.

When I click on a small thumbnail it loads via Ajax a big image:

```
$commands[] = ajax_command_html(
    '.big-image', l(theme('image_style', array('style_name' => 'node-image', 'path' => 'public://' . $get_src)), file_create_url('public://' . $get_src), array('attributes' => array('class' => 'colorbox'), 'html' => TRUE))
  );

```

As you see i have added class `.colorbox` to a link, but it works only on the images that were loaded during the page load and it's not working on AJAX loaded images.

How can I re-initialize colorbox on Ajax images?

# Answer
> 1 votes
You need to attach your js using Drupal behaviors.

```
Drupal.behaviors.yourmodulename = {
  attach: function (context, settings) {
    // This code is run on page load and after every ajax request
    // attach colorbox functionality here...
    // the following line should do the job but I've not tested it
    // we are using context so it only applies to the newly added objects
    $('.colorbox', context).colorbox();
  }
};

```

I found this blog post on the subject really useful.

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


title: cron.php failing with errors

text:
# Question
Title: cron.php failing with errors
I have a site running `Drupal 6.30` which has started giving errors when it run the hourly call to cron.php.

The cronjob in question is and run as root:

```
0 * * * * wget -O - -q -t 1 http://example.org/cron.php

```

I get the following rather cryptic / truncated message when it runs

```
could not

```

I have looked in system logs and apache logs but do not see anything that would indicate reason for the problem.

Would anyone be able to suggest anywhere else I could look on the system to troubleshoot.

**edit** additional logs from `administer -> reports -> dblog` around the time the cron fails.

1

```
mysql_connect() [<a href='function.mysql-connect'>function.mysql-connect</a>]: Access denied for user 'mann'@'localhost' (using password: YES) in /var/www/example.org.org/includes/common.inc(1743) : eval()'d code on line 7.

```

2

```
in /var/www/example.org.org/includes/common.inc(1743) : eval()'d code on line 7.

```

3

```
mysql_select_db(): supplied argument is not a valid MySQL-Link resource in /var/www/example.org.org/includes/common.inc(1743) : eval()'d code on line 8.

```

4

```
Cron run exceeded the time limit and was aborted.

```

# Answer
> 1 votes
View watchdog logs at Administer \>\> Logs \>\> Recent log entries. (admin/logs/watchdog)

More details in this post Drupal.org: Watchdog: monitor your site

---
Tags: cron
---


title: Commerce Checkout ignores CAPTCHA

text:
# Question
Title: Commerce Checkout ignores CAPTCHA
I'm running a Drupal 7 web-site with Drupal Commerce and CAPTCHA modules. I have a CAPTCHA challenge set up on the checkout page. Although an incorrect solved CAPTCHA will show an error, the CAPTCHA still gets ignored when I click "Continue to next step", thus the CAPTCHA can be left empty and the site will still take the user to the next form.

The CAPTCHA is added in the CAPTCHA config (admin/config/people/captcha) to the form "commerce\_checkout\_form\_checkout".

Things I've tried (but didn't help):

* Add a CAPTCHA field to the form programmatically;
* Add "\[required\] =\> 1" to said field;
* Tried with both the Math CAPTCHA and reCAPTCHA.

How can I make CAPTCHA work on Drupal Commerce's checkout form?

# Answer
I don't know exactly how your CAPTCHA module works, but one possible problem is that the checkout form uses button level validate / submit handlers instead of the form level handlers your CAPTCHA module might be working through. In Drupal forms, if the button used to submit the form has those handlers, the form level handlers will be ignored.
> 2 votes

# Answer
This might not help but I'm just giving it a try: are you logged in? Does it make any difference when you are not?
> 0 votes

---
Tags: forms, commerce, captcha
---


# Question
Title: How to change modified date in a node when users votes more than 5 times?
Mayday, mayday! :-) I have 2 views of nodes showing "published nodes" and "moderation nodes". I'm using vote\_up\_down in my nodes.

I want, when the users vote up a node more than 5 times, to modify the date of the node, and put it "now".

Can somebody tell me how I could do this?

Thanks.

# Answer
Since vote\_up\_down uses voting API underneath, you can use the voting rules module to allow you to configure rules to fire when votes are made.

You could then make a rule that fires when a vote is made, that then checks the total number of votes for that node and if it has 5 votes update the nodes updated date and save.

So the event/trigger would be voting on the node, the condition would be that the node has 5 votes (after a quick look it is likely the "Evaluate the results of a vote on a ..." condition), and the action would be updating the modified/updated date of the node.
> 1 votes

# Answer
Finally I did with the Rules Bonus Pack. There was one option to modify date information of the node.

cheers!
> 0 votes

---
Tags: rating
---


title: Webform custom submit handler rebuild

text:
# Question
Title: Webform custom submit handler rebuild
I am acutally trying to build a custom webform submit handler to force the form to be rebuilded. I know that this is possible with the integrated webform settings, but I need to do it programmatically.

Here is what my code looks like at the moment:

```
function he_helper_form_alter(&$form, &$form_state, $form_id) {
    dsm($form);
    dsm($form_state);
    dsm($form_id);

    if(strpos(current_path(), 'print') !== false && $form['#node']->type == 'genericforms') {
        $form['actions']['submit'] = array (
            '#type' => 'submit',
            '#value' => 'submit',
            '#submit' => 'he_helper_custom_redirect'
        );
    }
}

function he_helper_custom_redirect($form, &$form_state) {

    $form_state['rebuild'] = TRUE;

}

```

The problem now is, that the rebuild works as expected, but the form data does not get submitted. I tried it with $form\_state\['redirect'\] as well, but ran into the same problem.

Anyone got an idea how to solve that?

UPDATE:

```
function he_helper_form_alter(&$form, &$form_state, $form_id) {
  // dsm($form);
  // dsm($form_state);
  // dsm($form_id);
  if(strpos(current_path(), 'print') !== false && $form['#node']->type == 'genericforms') {
    // $form['#after_build'][] = 'he_helper_after_build';
    $form['actions']['submit'] = array (
      '#type' => 'submit',
      '#value' => '2hello',
      '#submit' => array('_he_helper_custom_submit'),
    );
  }
}

function _he_helper_custom_submit(&$form, &$form_state) {
  $form_state['redirect'] = 'print';
  $form_state['rebuild'] = TRUE;
}

```

This is what my code now actualy looks like. The redirect now works fine, but the data wont get submitted. I tried the after\_build function as well, but when i am using this, even my redirect wont work. This is what my code looked like with the after\_build

```
function he_helper_form_alter(&$form, &$form_state, $form_id) {
  // dsm($form);
  // dsm($form_state);
  // dsm($form_id);
  if(strpos(current_path(), 'print') !== false && $form['#node']->type == 'genericforms') {
    $form['#after_build'][] = 'he_helper_after_build';
  }
}

function he_helper_after_build(&$form, &$form_state) {
  $form['actions']['submit'] = array (
    '#type' => 'submit',
    '#value' => '2hello',
    '#submit' => array('_he_helper_custom_submit'),
  );
  return $form;
}

function _he_helper_custom_submit(&$form, &$form_state) {
  print 'hello';
  dsm('hello');
  $form_state['redirect'] = 'print';
  $form_state['rebuild'] = TRUE;
}

```

# Answer
> 2 votes
I think I've just used $form\_state\['redirect'\] in the submit handler in the past.

However I'm not sure what order your submit handlers are firing in, maybe it would work if you added the after\_build function to the form array as opposed to the button array. (If your custom submit handler is firing first then your redirect could get overwritten.)

```
E.g: $form['#submit'][] = 'he_helper_custom_redirect';

```

If that doesn't work then this post suggests using rebuild with redirect:

```
$form_state['redirect'] = 'where-do-you-want-to-go-today';
$form_state['rebuild'] = TRUE;

```

This code shows how to add a new custom submit handler without overwriting the original one:

```
function he_helper_after_build(&$form, &$form_state) {

  // add to the existing submit array to not override the default submit handler
  $form['actions']['submit']['#submit'][] = '_he_helper_custom_submit';

  // change the button text
  $form['actions']['submit']['#value'] = '2hello';

  return $form;
}

```

---
Tags: webforms, redirection, forms
---


title: Multi template files for a content type

text:
# Question
Title: Multi template files for a content type
is it possible to use multiple templates select for a content type. I am thinking of having a select\_list which will be shown while adding the content and you can choose how your page will look like, based on existing template files.

thanks

# Answer
Sure. You can use hook\_preprocess\_node() to do this, eg, something along the lines of:

```
function YOURTHEME_OR_MODULE_preprocess_node(&$variables) {

  $node=$variables['node'];

  $foo= /* get the value of this field from $node */ ;

  $variables['theme_hook_suggestions'][] = 'node__' . $foo;

  // or....

  switch ($foo) {

    case 'FIRSTVALUE':
      $variables['theme_hook_suggestions'][] = 'node__FIRSTSOMEOTHERSTRING';
      break;

    case 'SECONDVALUE':
      // etc etc etc

  }

}

```

and then Drupal 7 will look for a `node--WHATEVER.tpl.php`.

ADDITION:

If you are wanting the PAGE itself to be different based upon this field, then you would use hook\_preprocess\_page() with similar logic but using `page__WHATEVER` instead in the theme hook suggestions and `page--WHATEVER.tpl.php` in the template names.
> 1 votes

# Answer
You could, in theory, use the page.tpl to check for content type and change the HTML accordingly, however, it would be far easier to actually create content types. they exist for the exact purpose you're describing, and the CMS admin functions are already there to handle doing that for it.
> 0 votes

---
Tags: theming
---


# Question
Title: How to create a view that automatically shows all fields as a table, even if new ones are added to the entity?
I need to create a table view that shows all of the user accounts on the site and their fields. The client has the ability to add new fields to the user entity but I do not want to make them go into the view to add the field as well. Is there a way to have views just output all fields? I know I can change the display as an entity and select a view mode but I need this to be in table format.

# Answer
I've run into exactly the same use-case. So far my intuition has been to create a fieldset to which the client can add fields, and develop a new Views plugin to add a whole fieldset to a view using every field's defaults. (The challenge here is that each field has different parameters to configure when you add them to a view.)
> 0 votes

---
Tags: views
---


# Question
Title: How to add a field for each taxonomy term or entity reference chosen in Content Type?
I have a content type ‘Product’. When the user add a product it is necessary to choose a Store (a taxonomy term or another content type). After stores are chosen, it is necessary to add the directly url to that product in that store. More than on store is selectable and he could add or remove another. There are more data in Store type.

It is something like one to multiple to one for each I think…

```
Product01   > Store 1 > URL01
            > Store 2 > URL02

Product02   > Store 1  > URL03
            > Store 10 > URL04

```

My options are:

1) Create a field with multiple values. So if the user choose 3 stores he adds 3 fields to that link. Problem: It is not directly associate and if he changes orders it will associate de wrong url and chaos will happen.

2) Using Conditionals field (Taxonomy Term) Problem I could not make it work with multiple selected store and for each new term I need to create a specified field.

3) Entity Reference (Content Type) Can’t find a way to associate multiple select to adicional fields.

X) Rules? Too much crazy for me, could not even begin thinking with that…

Any help?

# Answer
Answer is Field Collection Module (https://drupal.org/project/field\_collection). There is another called Multifield, you could try (https://drupal.org/project/multifield).

After installed, edit your content type and add an field with field type Field Collection. Go to Structure\>Field Collection and there add fields to the Field Collection created in your content type.

After that it is equal to adding a field with reference term to content type.

What this Video https://www.youtube.com/watch?v=1V1ofpgUw-Y
> 1 votes

---
Tags: 7, taxonomy-terms, nodes, entities
---


# Question
Title: How to tell Drupal to use tpl file from my module?
I have a custom module and placed comment.tpl.php here:

**/sites/all/modules/mymodule/comment.tpl.php**

But Drupal is not looking for that file in my custom module directory. How can i make it work?

# Answer
You need to use hook\_theme:

```
/**
 * Implements hook_theme().
 */
function MY_MODULE_theme($existing, $type, $theme, $path) {

  if($type != 'module') {
    return [];
  }

  // If you want to put your templates in a templates directory
  // in your module directory add .'/templates' to the end.
  $module_path = drupal_get_path('module', 'MY_MODULE');

  return [
    'comment' => [
      'template' => 'comment',
      'path'     => $module_path,
    ],
    'other_template' => [
      'template' => 'comment',
      'path'    => '/my/custom/path/here',
    ],
  ];
}

```

This has set up our custom theme, then when you want to use it you can:

```
$tpl_data = [
  'param1' => $foo,
  'param2' => $bar,
];

return theme('comment', $tpl_data);

```

Now $param1 and $param2 will be available in your template file too.

If you don't need any custom data in your template then $tpl\_data can be omitted.

Happy days.
> 5 votes

# Answer
You can do this by using hook\_theme() as described on api.drupal.org. It allows you to register your module's theme implementation.
> 0 votes

---
Tags: 7, theming
---


title: Get full expanded menu?

text:
# Question
Title: Get full expanded menu?
How can I render out my main menu as entirely expanded? I am working on mobile navigation and need to have the entire tree rendered out in my code for this to work the way I want it to. I do not want to make admins go into the menu and select "expanded" every time they create a child item. Can this be done with a module or

# Answer
I think menu\_tree\_all\_data should do the trick.

You will need to put this in a custom module and then loop over the array to manually build your menu.
> 0 votes

---
Tags: 7, routes
---


title: Date tokens for file path

text:
# Question
Title: Date tokens for file path
I have a big site with a lot of images and I want to use Date tokens for the File path. So I edit the image file and set Filepath: \[current-date:short\]

I have the following issue: 1)Uploaded images are broken What could be the reason for this? thanks

# Answer
Configuration \> Regional and Language \> Date and Time

Check what your default Short time format is. If its being printed with spaces, it could be part of the problem. You could add a new date type, and see if that fixes anything.

The easy way around this, is when managing the image and file upload CCK fields, just specify a directory for those images in the field settings there.
> 0 votes

---
Tags: files
---


# Question
Title: Fill a form on one website and second website automatically grabs it
I have two websites, which have exactly same forms and fields. When the user fills the form on first website, the content gets published on first website. I manually do it on another website. Is there any simpler way of doing this? Is it possible that it automatically grabs the data from 1st website as user fills the form?

# Answer
You can do this with a bit of JQuery. Assuming your form action is action1.php which is on site 1 and you have another handler action2.php on site 2:

```
$('#form_id').submit(function(event){
    event.preventDefault();  // Stop default handling
    var $form = $(this);
    $.ajax({
        type: 'post',
        url: 'action2.php',  // Submit to the second site
        data: $th.serialize(),
        success: function(){
            $th.submit();    // Submit to the first site
        }
    });
});

```

And now the form will be submitted to both sites and they will both handle it
> 2 votes

---
Tags: forms, rules
---


# Question
Title: Connect to remote DB using global php drupal 7 views
I am using Views PHP module for custom coding in views.

I tried using `mysql_connect` function to connect to a remote database using the "GLOBAL PHP" field and get some data through custom coding. Is it safe to connect to database through the "GLOBAL PHP" field? Or are there any security risks?

# Answer
> 2 votes
Nothing is a security risk in and of itself. If you know basic PHP and the basic usage of `mysql_query` and how to sanitize your input -- you're fine.

What you're proposing is not by any means a best practice, proper use of Views or the Drupal API (sorry).

All of these options make use of Drupal core features for interacting with 3rd party databases, Drupal API or Views contributed module API.

Your approach is taking an embedded php field in a view and ignoring Drupal and its architecture to achieve what you want. It's as secure and safe *as your experience and knowledge* make it. I prefer to stand on the shoulders of others and leverage the security built into Drupal and its *supported* APIs.

You may find the Data module useful in making your 3rd party data play nicer with Views.

> Data module helps you model, manage and query related sets of tables. It offers an administration interface and a low level API for manipulating tables and accessing their contents. Data module provides Views integration for displaying table data and Drupal search integration for searching table content.

---
Tags: security, database
---


# Question
Title: Can I avoid creating a new revision of every attached field upon entity save?
I have created a custom entity with several properties and several attached fields.

When I load a instance of my custom entity, update a property of the entity (e.g UID) and save it a new revision of the entity is created, but also a new revision of every attached field is created.

To avoid saving lots of redundant data I only really want to create a new revision of an attached field if the data in that field has changed.

I've noticed that this same behavior is exhibited by core node objects, but is still not really desirable.

My function which currently saves my entity looks like this:

```
/**
* Saves a emtr safe check to the database.
*
* @param $emtr_safe_check
*   The emtr_safe_check object.
*/
function emtr_safe_check_save(EMTRSafeCheck $emtr_safe_check) {

    $is_new = isset($emtr_safe_check->is_new) ? $emtr_safe_check->is_new : false;

    // always make a new revision
    $emtr_safe_check->is_new_revision = TRUE;
    $emtr_safe_check->save();

    if($is_new) {
        // now we have the new emtr safe check id lets save the attached fields
        field_attach_insert('emtr_safe_check', $emtr_safe_check);
    } else {
        // This is where my attached fields are saved
        // Can I do something clever here to avoid creating redundant revisions?
        field_attach_update('emtr_safe_check', $emtr_safe_check);
    }

    return $emtr_safe_check;
}

```

# Answer
> 1 votes
I have looked around and found one HACKY solution. I think it probably has some serious side effects that you may be able to handle with custom code and db queries. This is definitely not a generic solution.
I did my test on the node entity and every thing worked fine in my 5 min test case. Here is what I did:

```
function playground_node_presave($node){
  dpm($node);
  // do a query here and check if the value is in the field_revision_table is
  // equal to the value on the node/entity object.
  unset($node->field_cookies);
  dpm($node);
  // The node will be saved without changing the value of the field and without creating
  // creating a new entry in the field_revision_table.
}

```

---
Tags: 7, entities, nodes
---


# Question
Title: Programmatically Change Administrative Area in AddressField
I have some external data that I have introduced to Drupal for a users address (not in an address field). I am setting it so that when a user loads the checkout page in commerce their info is populated as the default field values.

How do I change the State (administrative area) to match the country that is set? Right now, if I have it set to Australia for instance, the State field is still set to United States relevant states.

Code Example:

```
    $form['customer_profile_billing']['commerce_customer_address']['und'][0]['#address']['first_name'] = $firstname;
    $form['customer_profile_billing']['commerce_customer_address']['und'][0]['#address']['last_name'] = $lastname;
    $form['customer_profile_billing']['commerce_customer_address']['und'][0]['#address']['thoroughfare'] = $street;
    $form['customer_profile_billing']['commerce_customer_address']['und'][0]['#address']['locality'] = $city;
    $form['customer_profile_billing']['commerce_customer_address']['und'][0]['#address']['administrative_area'] = $state;
    $form['customer_profile_billing']['commerce_customer_address']['und'][0]['#address']['postal_code'] = $zipcode;
    $form['customer_profile_billing']['commerce_customer_address']['und'][0]['#address']['country'] = $country;
    $form['customer_profile_billing']['commerce_firstdata_billing_phone']['und'][0]['value']['#default_value'] = $phone;

```

# Answer
> 1 votes
Here is an example, You need to use ajax. I think you will just need to alter the form structure a bit from what I have but the basic logic is there.

```
$country_list = array(0=>'USA',1=>'Canada');
$value_country = isset($form_state['values']['country']) ? $form_state['values']['country'] : key($country_list);

$form['country'] = array(
    '#type' => 'select',
    '#title' => t('Select Country'),
    '#options' =>  $country_list,
    '#ajax' => array(
        'event' => 'change',
        'callback' => 'mymodule_ajax_callback',
        'wrapper' => 'name_replace',
        ),
 );

$form['state'] = array(
    '#type' => 'select',
    '#title' => t('Select State'),
    '#prefix' => '<div id="name_replace"; style="margin-top:50px;">',
    '#suffix' => '</div>',
    '#options' =>  mymodule_find_states($value_country), //pass country, run query, return correct states
    '#default_value' => isset($form_state['values']['country']) ? $form_state['values']['country'] : '',
 );

```

Add this function make sure this function is NOT inside form\_alter function

```
function mymodule_ajax_callback($form, $form_state) {
    return $form['state'];
}

```

---
Tags: 7, entities, commerce
---


# Question
Title: Notices and Warnings Drupal Commons 7.x 3.9 Undefined index, invalid argument, illegal string offset
I get these 7 messages every time a user goes to an event listing.
Happens in this order. I'd like to troubleshoot and eliminate.

> Notice: Undefined index: title in commons\_origins\_preprocess\_form\_content() of profiles/commons/themes/commons/commons\_origins/template.php).
>
> Notice: Undefined index: #items in commons\_events\_entity\_view\_alter() of ….profiles/commons/modules/commons/commons\_events/commons\_events.module).
>
> Warning: Invalid argument supplied for foreach() in element\_children() of /includes/common.inc
>
> Warning: Illegal string offset '#children' in drupal\_render() (line 5890 ) of …includes/common.inc
>
> Warning: Illegal string offset '#children' in drupal\_render() (line 5900 ) of …includes/common.inc
>
> Warning: Illegal string offset '#children' in drupal\_render() (line 5983 ) of …includes/common.inc
>
> Warning: Illegal string offset '#printed' in drupal\_render() of /includes/common.inc).

# Answer
> 1 votes
title is not defined. #items is not defined. foreach is not getting a value to work with. #children doesn't exist to render.#printed doesn't exist to render. go into the function where title is supposed to be defined and check that there is a value. Do the same for the rest. Check what further up the chain in your code is calling these values. Try doing a backtrace.

---
Tags: 7
---


# Question
Title: Display blockquote of text in article post, while showing original
Can anyone provide an idea for how I can add a block quote in an article post where that text is also in the body of the message?

What I mean by this, is that right now when one of our users wants to create a blockquote, they use the CKeditor WYSIWYG module and choose 'blockquote'. What this does is highlight that specific text as a blockquote. What I am more looking for is the ability of the writer to choose what they would like to have as a blockquote and also see that same text again where it belongs in the article. Please see the image below for what I mean.

Ideally it would be great to have certain text highlighted that it is a blockquote. Then have that blockquote be right next to the original.

Update: I just talked with our themer and maybe the best solution is to highlight any text that we want blockquoted and include it in there twice. Then we can style the text with CSS that has the blockquote tag. But if there is a better way, then great!

# Answer
You can style the block quote using the blockquote {} tag in CSS.

For example, something similar to the image you uploaded...

```
blockquote {
float:left;
margin:20px;
font-size:1.2em;
color:red;
}

```

However, your client would need to enter the piece of text twice.
> 1 votes

---
Tags: 7, theming, wysiwyg
---


# Question
Title: Drush make command error when unzipping superfish module / library
I am moving a website from my local machine to the prod server. I intend to do this with drush sync, looks like the most straightforward way. So, I've created a makefile on my local website, when i issue drush make myfile.make, I get this error :

```
superfish-7.x-1.9 downloaded.                                                               [ok]
Found makefile: superfish.make                                                              [ok]
superfish downloaded from https://github.com/mehrpadin/Superfish-for-Drupal/zipball master. [ok]
Unable to unzip /tmp/make_tmp_1386076010_529dd76a9b232/master.                              [error]

```

Then in tried another download link, fail with same message.

```
superfish downloaded from https://github.com/mehrpadin/Superfish-for-Drupal/archive/1.x.zip. [ok]
Unable to unzip /tmp/make_tmp_1386076010_529dd76a9b232/1.x.zip.                              [error]

```

I guess all zip files are not corrupt, something must be wrong, may be on my local install, but the error message isn't very helpful so I am stuck.

so what to do then ? anyway to fix this ? I guess the superfish module will not be installed if I move my website with drush sync ? can I reinstall superfish with admin GUI then ?

# Answer
Unzipping files needs, simply, the unzip program. Check that you have `unzip`-package installed on your server.
> 4 votes

---
Tags: drush, navigation
---


# Question
Title: Rules - Send mail to all addresses in email field of specific content type
I have a content type (school) with an unlimited email field (field\_email). Now on creation of another node (page), I would like to send to all emails stored in the "field\_email" of all school nodes an email.

I started by created a rule with the "rules" module but i cannot figure out how to pull the data from a separated node (school).

Could someone point me in the right direction?

# Answer
You can use Views Rules module. For achieve this goal first you have to create a view to get all mail values of content type (school) and than its result provide to rules using this module. For more information go through the documentation of Views Rules module.
> 1 votes

---
Tags: rules, tokens
---


# Question
Title: How to handle refunds / returning goods with drupal commerce
i'm just trying to figure out whatcould be the bestway to handle "refunds" and the return of the shipped goods with Drupal Commerce.
Is there some custom modules for that?How would you handle this case?

# Answer
> 1 votes
There hasn't been created any module that handles this. How to approach this also depends a lot on the custom logic in your store like

* How are payments created
* How should payments be refunded
* What happens if returned goods has damage
* ...

Anyways, what you could do for starters, is to create a custom order status to mark that the goods have been returned. Most of the rest is most likely custom store logic anyways.

# Answer
> 0 votes
Please refer to this link http://www.drupalcommerce.org/questions/9199/full-or-partial-creditrefundreturn. Commerce RMA is mentioned to handle this then.

# Answer
> 0 votes
great that the free RMA module in https://drupal.org/project/commerce\_rma offers us the function. However, it may cause some fatal issues.

---
Tags: 7, commerce
---


# Question
Title: How to alert users that they have a survey / webform to complete
Using D7 with the latest version of webform. We have created several surveys and all is working fine, but a question came up in a meeting, is there an easier/automated way of sending emails to the specific users that need to complete the survey. What we do now, is create the survey, save, then go into our email client and send out a note that a survey is ready for you to complete at whatever url.

We would like to click a button "send survey url to:" and then add the email address of the user who needs to be alerted of the availability of the survey. They would jsut click the link and be taken to the the survey.

# Answer
You can achieve this goal using Views Send module.

> * Create a view and add at least one column containing e-mail addresses.
> * \[Optional\] Expose Views filters to let the user easily build list of recipients using UI.
> * Add the "Global: Send E-mail" field to your view. This field provides the checkboxes that allow the user to select multiple rows.
> * Create a "Page" (or "Block") display.
> * Save the view, load the page, use exposed filters to build the list, select all or some rows and then click the "Send e-mail" button.
> * Fill the message form to configure the e-mail. Use tokens to personalize your e-mail. The module provide also row-based tokens,
> taken from the current row of the view. For example, if the view has
> a column with the key users\_name (the user name) you can use this
> replacement token \[views-send-users\_name\].
> * Preview and send the mail.

For more information go through the module documentation.
> 0 votes

---
Tags: 7, webforms
---


# Question
Title: Integrating the Webform module in a page
I want to have a form that will take end user inputs (text, sentence, text of multiple values and an image upload of png or jpeg format).

These inputs would be later stored in database and would be retrieved using views mysql module and displayed in webpage.

I tried to integrate the Webform module in my page, but it didn't work well with images while displaying through a view. It displays numbers instead of images (actually this is the place where I am facing issues).

Is there any ways that I can fix this, or do I need to build a module from scratch?

# Answer
You can achieve this goal using Entityforms module.Using this module you can take input of text as well as image like webform. This module can be integrated with rules and data export etc. for sending mail and downloding submission as like webform.

There are a lot of advantage over webform but it is different form webform.

For more info go through module documentation.
> 0 votes

---
Tags: 7, views, webforms
---


# Question
Title: How to disable copy and paste in webform textarea?
Is there a way to disable pasting into a webform textarea field?

I've created a textarea field called: my\_words and I want to forbid anyone from copying and pasting text into this field.

# Answer
I've not tested this code, but a quick Google search suggests the following (obviously change #Password to the ID of your textarea field).

```
$(document).ready(function() {
    $('#Password').bind('cut copy paste', function(event) {
        event.preventDefault();
    });
});

```
> 4 votes

# Answer
This is not a drupal question. But anyway, if you disable Javascript, you still can paste into your textarea with the JS solution from chapabu. The proper solution is to have the textarea disabled. `<textarea disabled="disabled">` Or something like that: http://api.drupal.org/api/drupal/developer--topics--forms\_api\_reference.html/7#disabled Note that disabling a form field doesn't necessarily prevent someone from submitting a value through DOM manipulation. It just tells the browser not to accept input.

But why would you prevent someone to copy-paste values into it? Seems strange. Maybe I write my words in a word-file with spellchecking and then want to copy my words into your field? Why not? Do you want a security solution, that someone can not copy-paste words, that are not his into your textarea? As long as there is not a solution that prevent us from lying you will fail ;-)
> 0 votes

# Answer
jQuery is the only best choice to disable text editing,

http://kvcodes.com/2014/03/disabling-textbox-cut-copy-and-paste-operations/
> 0 votes

---
Tags: entities, javascript, webforms
---


# Question
Title: how to customize autocomplete TO field in privatemsg module - drupal 6
Using the privatemessage module, users can send messages to each other as in facebook. The page displays a form with a TO field, subject and message. The TO field is an autocomplete field by default. Upon searching for a user name, it shows a drop down with only the names. How can i customize it to show the user's profile picture also in the drop down??? I dont know where to go and make the code changes.

# Answer
> 2 votes
Open `privatemsg.module`

in `hook_menu` search for `$items['messages/user-name-autocomplete']` this particular menu item defines that auto complete path.

Search for `privatemsg_user_name_autocomplete` function where the output defines.

Edit this function. Thats all. Also Create a patch if youre familiar with patching, so that others c

# Answer
> 0 votes
Note: Tested in Drupal 7 only, years later...

Here's an example of a modification that can be made to `privatemsg_autocomplete` in the `privatemsg.pages.inc` file such that a custom Profile2 picture field can be added instead of simply names.

I don't know how it performs though or if there are any scenarios under which it may fail. Compare the code with the original.

```
/**
 * Return autocomplete results for usernames.
 *
 * Prevents usernames from being used and/or suggested twice.
 */
function privatemsg_autocomplete($string) {
  $names = array();
  // 1: Parse $string and build list of valid user names.
  $fragments = explode(',', $string);
  foreach ($fragments as $name) {
    if ($name = trim($name)) {
      $names[$name] = $name;
    }
  }
  // 2: Find the next user name suggestion.
  $fragment = array_pop($names);
  $matches = array();
  if (!empty($fragment)) {
    $remaining = 10;
    $types = privatemsg_recipient_get_types();
    foreach ($types as $name => $type) {
      if (isset($type['autocomplete']) && is_callable($type['autocomplete']) && privatemsg_recipient_access($name, 'write')) {
        $function = $type['autocomplete'];
        $return = $function($fragment, $names, $remaining);
        if (is_array($return) && !empty($return)) {
          $matches = array_merge($matches, $return);
        }
        $remaining = 10 - count($matches);
        if ($remaining <= 0) {
          break;
        }
      }
    }
  }
  // Allow modules to alter the autocomplete list.
  drupal_alter('privatemsg_autocomplete', $matches, $names, $fragment);

  // Format the suggestions.
  $themed_matches = array();
  foreach ($matches as $key => $match) {
    $themed_matches[$key] = privatemsg_recipient_format($match, array('plain' => TRUE));
   $profile = '';
   if (isset($match->uid)) {
        $profile = profile2_load_by_user($match->uid);
}

    $picture = '';
    if(isset($profile['main']->field_profile_photo['und'][0]['uri'])) {
        $picture = theme('image_style', array( 'path' =>  $profile['main']->field_profile_photo['und'][0]['uri'], 'style_name' => 'profile_thumbnail'));
    } else {
        //I'm using sites/default/files/default_images/profile-default.jpg as the default image
        $picture = theme('image_style', array( 'path' =>  "public://default_images/profile-default.jpg", 'style_name' => 'profile_thumbnail'));
    }
    $picture_matches[$key] = $picture;
  }

  // Check if there are any duplicates.
  if (count(array_unique($themed_matches)) != count($themed_matches)) {
    // Loop over matches, look for duplicates of each one.
    foreach ($themed_matches as $themed_match) {
      $duplicate_keys = array_keys($themed_matches, $themed_match);
      if (count($duplicate_keys) > 1) {
        // There are duplicates, make them unique.
        foreach ($duplicate_keys as $duplicate_key) {
          // Reformat them with unique argument.
          $themed_matches[$duplicate_key] = privatemsg_recipient_format($matches[$duplicate_key], array('plain' => TRUE, 'unique' => TRUE));
        }
      }
    }
  }

  // Prefix the matches and convert them to the correct form for the
  // autocomplete.
  $prefix = count($names) ? implode(", ", $names) . ", " : '';
  $suggestions = array();
  foreach ($themed_matches as $key => $match) {
    $suggestions[$prefix . $match . ', '] = $picture_matches[$key] . $match;
  }

  // convert to object to prevent drupal bug, see http://drupal.org/node/175361
  drupal_json_output((object)$suggestions);
}

```

---
Tags: privatemsg
---


title: Drupal7 - User/Registration customizing

text:
# Question
Title: Drupal7 - User/Registration customizing
Please any one help me to how I can do customizing User/Registration page in Drupal 7. For example I have a select option for user group, suppose if I choose 'others' option ’ then user is allowed to create new group in separate text box.

I'm new to Drupal. Please anyone help me

# Answer
In Drupal 7 you can use **Select (or other)** module for your requirement

> **Select (or other)** module : Provides a new Forms API element which is a select/radios/checkboxes element that has an 'other' option. When 'other' is selected a textfield appears for the user to provide a custom value.
> 1 votes

---
Tags: 7, users
---


# Question
Title: How to add active-trail class to a links in a view?
How to add an active-trail class to all links in a view, which a parents of a current page (according to a result of menu\_get\_active\_trail())?

# Answer
> 0 votes
One solution is to add an invisible PHP-field to a view (let the field identifier will be php).

Set a setup code to

```
$static = module_exists('crumbs') ? crumbs_get_trail() : menu_get_active_trail();

```

Set a value code to

```
$href = 'taxonomy/term/' . $data->tid;
foreach ($static as $item) {
  if ($item['href'] === $href) {
    return 'active-trail';
  }
}

```

And at last add a custom CSS class to a link field with token \[php\]

---
Tags: views, routes
---


# Question
Title: How do I get Location / GMap / Views setup to display non-US map nodes?
Drupal 6, Views 2

I'm using the Location module to store address information for various contacts in nodes. I am then using the Views module along with the GMap sub-module of Location to display these nodes as map markers on a Google Maps style map on a page in my site.

This works perfectly for USA addresses, but I can't get Canada or UK addresses to display on the node map. The link inside the node (from Location module) to view the location in an external Google Map works just fine, so I can confirm the addresses are valid. However, they do not display on my Drupal Views generated Google Map a la Location/GMap.

Note - disabled and/or cleared cache to make sure this wasn't an issue. Also Regenerated marker cache inside of Location configuration to rule that out also.

Is there some kind of configuration setting I'm missing?

# Answer
I can confirm that it is possible to get locations and GMAP running on Drupal 6 for Canadian addresses. I have done this on more than one occasion.

From your description it simply sounds some setting preventing the reverse geocoding of addresses. Edit one of your nodes with canadian addresses and confirm that the Lat and Lon field are empty. Save then edit again and confirm it is still empty.

If the lat/lon fields are empty try the following

1. Make sure you have a valid google maps API key for the URL you are running the site under.
2. Confirm that the location module has access to this API keys. Reverse geocoding settings for locations module is under `/admin/settings/location/geocoding` go to Canada and click "Configure parameters"
Or go there directly: `/admin/settings/location/geocoding/ca/google`
**Your Gmap google map api key should be displayed.**
3. Confirm that as a user you have permission to save lat/long info. Under user permissions (`/admin/user/permissions`) go to "location module" and check that "submit latitude/longitude" is selected for users that will be creating the nodes with address information. If not then there will be no reverse geocoding for any address, Canadian or otherwise.
4. Once you have confirmed the above, revisit a node with a Canadian address. Edit and hit save. This will re-run the reverse geocoding. If a lat/long is not saved then I will have to do some more digging. Also if you have lots of nodes in need of reverse geocoding, it is possible to do this programmatically.
5. Are you using CCK field or location module itself to save the address and lat/on? I am uncertain whether or not reverse geocoding works with the cck location field in D6.
> 1 votes

# Answer
Hi there is a table in drupal which stores locations postal code.

The name of the table you should look is for drupal.zipcodes

Now, you need to import Canada's zipcode sql dump to this zipcode table.

Once you have imported the codes, refresh the cache and then create content and it should display Canada's location nodes.
> 1 votes

---
Tags: views, location, google-maps
---


title: Administration menu module not working

text:
# Question
Title: Administration menu module not working
Im using D7.24 I downloaded admin\_menu module (I tried also previous releases) but when trying to enable it I can't, and I get this info message in the description module field :

> Requires : System (\>7.10) (is incompatible with version \> 7.x-1.0-beta3) Required for : Administration menu Toolbar style (disabled)

I searched about this problem but I did not found anyone has this problem before!

Thanks in advance

**EDIT:** This is the info that I get in status report :

# Answer
> 2 votes
Per this line in admin\_menu.info:

```
dependencies[] = system (>7.10)

```

The module requires a core version of Drupal greater than 7.10. Currently yours must be less than that.

Drupal core is currently at 7.26; you'd be wise to update ASAP, there have been a number of security updates in recent memory.

---
Tags: 7
---


# Question
Title: Assign content automatically to specific user
I added a new roles - technical support and management. Added several user to that role.

Created new content type called Claim Report contain fields ( title, body, area ).

What I want to achieve is, when authenticated user create new content claim report, select specific area and save, it will automatically shown to specific technical support user account sort by area.

Ex :

techspp1 - area 1

techspp2 - area 2

techspp3 - area 3

When authenticated user create content and choose area1, that specific content only shown in techspp1 account page, choose area2 shown in techspp2 account page only.

Then techspp1 reply / give solution and the user claim content get updated with that solution and get status solved / on-progress.

Can anyone help ?

# Answer
> 1 votes
You can use Node Access Rules to achieve this goal. Using this you can create rule to access that particular content having some condition as per your requirement.

# Answer
> 0 votes
What I think you're looking for is a creating a publishing workflow using a workflow module like Workbench. Check out this YouTube video to see what it does: Part 1: Creating a Publishing Workflow in Drupal 7 Using Workbench

---
Tags: nodes, users
---


# Question
Title: Hooking into the user login block to modify prefill default text in username and password
I am having problems getting a custom module to recognize the user login block.

Ultimately I need my user login block to only show the username and password fields, without any labels. Instead of labels I need to prefill the form fields with the words 'username' and 'password' and have this text disappear onfocus. This drupal answers question demonstrates how to do this with the search block and a custom module. I have been able get this to work without any problems.

I have tried to do a similar thing with the user login block.

First of all i used this to get the form id:

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

 // uncomment to get form id
 drupal_set_message("Form ID is : " . $form_id);
 }

```

This returns `Form ID is : user_login_block` for the login block page and it returns `Form ID is : search_block_form` for the search block

When on a page with the search block enabled I can use this:

```
if ($form['#id'] == 'search-block-form') {
    dpm('search-block-form showing');
}

```

but when on the user login block page this doesn't work. Neither of these show anything in the message area:

```
 if ($form['#id'] !== 'user-login-block') {
     dpm('user-login-block showing');
 }

 if ($form['#id'] !== 'user_login_block') {
    dpm('user_login_block showing');
}

```

I am very confused as to why this isn't working. I would appreciate being shown how to write an if statement that targets the user login block.

My entire function is:

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

    // uncomment to get form id
    drupal_set_message("Form ID is : " . $form_id);

    if ($form['#id'] !== 'user-login-block') {
          dpm('user-login-block showing');
      }

    if ($form['#id'] !== 'user_login_block') {
          dpm('user_login_block showing');
      }

    if ($form['#id'] == 'search-block-form') {
          dpm('search-block-form showing');
          $search_text = 'Your search text here';
          $form['search_block_form']['#default_value'] = $search_text;
           $form['search_block_form']['#attributes'] = array(
          'onfocus' => "if (this.value == '$search_text') {this.value = '';}",
          'onblur' => "if (this.value == '') {this.value = '$search_text';}");
      }

  }

```

# Answer
> 1 votes
To target a specific form you can use `hook_form_FORM_ID_alter()`, e.g.:

```
function MYMODULE_form_user_login_block_alter(&$form, &$form_state, $form_id) {
  $form['foo']['#default_value'] = 'bar';
}

```

If you'd rather do it all in one alter hook though, use the provided `$form_id` parameter instead of `$form['#id']`...it's guaranteed to be the right one.

```
function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'user_login_block') {
    $form['foo']['#default_value'] = 'bar';
  }
}

```

As a side note, it's probably not working at the moment because you're *negating* the condition:

```
if ($form['#id'] !== 'user-login-block') {

```

should be

```
if ($form['#id'] === 'user-login-block') {

```

# Answer
> 1 votes
Clive's answer is correct, and Jimajamma's comment is valid

So working custom module code for this is:

```
function custom_prefill_login_form_user_login_block_alter(&$form, &$form_state, $form_id) {
 print_r("working");
 $form['name']['#default_value'] = 'Username';
}

```

Where the custom module is named `custom_prefill_login`

But as Jimajamma explained this doesn't work with the password field. I'm investigated a little and we can set the placeholder text in drupal too. So here is the complete solution:

```
function custom_prefill_login_form_user_login_block_alter(&$form, &$form_state, $form_id) {
 $form['name']['#attributes']['placeholder'] = t('Username');
 $form['pass']['#attributes']['placeholder'] = t('Password');
}

```

---
Tags: 7, users
---


# Question
Title: I have 4 facets set to filter results by taxonomy terms but only one of the four filters work
I'm using Apache SOLR with Facet API and am having trouble getting my facets to show. I have 4 facets that are set to filter results by taxonomy terms. Each filter uses a different vocabulary. For some reason only one of the four filters work. The other three don't even show up. Any ideas as to why this is happening?

# Answer
> 0 votes
Did you check the corresponding blocks for each facet are set in sidebar region (or where ever you want them to be?).

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


title: No-index a node

text:
# Question
Title: No-index a node
I'm trying to no index 2 different nodes, I found the Node noindex module for it but I don't think it works. So I'm wondering if there is alternative to doing this.

# Answer
> 0 votes
When you use the Node noindex plugin make sure you check the content types and enable it there. Here is an excerpt about it from the module's project page:

> ... makes it possible to include a noindex-header on specific nodes. This should ensure that the node does not get indexed by search engines.

# Answer
> 1 votes
Have you looked at NodeWords or MetaTags modules? Otherwise you can always handle it through the templating engine if you don't want to use a module.

# Answer
> 1 votes
**Option #1**: Node Noindex Module

This works and is pretty simple as answered by @Jeremy Love

**Option #2**: Metatag Module

Not immediately apparent and not simple, but it is powerful:

1. Enable Metatag and Metatag Context (you will need to enable Context and want Context UI)
2. Create a new context in Context UI with a Path condition of node/123 (the particular node ID)
3. Add a Meta data Reaction to that context to "prevent search engines from indexing this page" and a whole lot of others.

---
Tags: 7, nodes
---


# Question
Title: Drupal7: How to add the alt and title attribute to an image by code
I am using the file\_create\_url() function to create the URL for images. The code is:

```
<img src="<?php echo file_create_url($node->field_history_image['und'][0]['uri']); ?>">

```

But I just noticed that the alt and title attributes are not added to the HTML output, eventhough I added them for the image in the admin.

How would I change the above code, so that it adds the *alt* and *title* attributes if they are filled in the Admin interface. Or what other function should I use?

Thanks.

Boutros.

# Answer
> 1 votes
Here is my answer to my own question:

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

```

The above code, prints the image (the URL and the alt and title attributes if they exist). It does exactly what I wanted.

# Answer
> 1 votes
Since you are rendering a field , you can use below code

```
<?php
$image = field_get_items('node', $node, 'field_history_image');
$output = field_view_value('node', $node, 'field_history_image', $image[0]);
print render($output);
?>

```

OR

```
$view = field_view_field('node', $node, 'field_history_image');
print render($view);

```

---
Tags: media
---


# Question
Title: How to remove the pagination from the Print / PDF output of search results?
I am displaying search results with 20 per page. I have total 100 results.

The print/pdf only display that 20 results in the pdf version and in print version.

I want to display all the results in print and in pdf?

How will I do this?

# Answer
You will need to either create another view of the search results to print, so when a user clicks print it either pops up a page or takes them to a new page with everything you want to see on the PDF.

Another option would be to expose a filter for the search that allows them to select the number of results displayed. Put a note on the page that says if they want to see all results on a PDF, to change the filter.
> 1 votes

---
Tags: 7
---


# Question
Title: Cannot set form #default_value when altering Views Exposed Filter forms
```
function mymodule_form_alter(&$form, &$form_state, $form_id) {
  drupal_set_message($form_id);

  if ($form_id == 'views_exposed_form') {
    $options = array(
      'All' => t('All'),
      '$' => '$',
      '€' => '€',
      'тг' => 'тг',
    );

    $form['field_price_second']['#type'] = 'select';
    $form['field_price_second']['#options'] = $options;
    $form['field_price_second']['#default_value'] = '$';
    $form['field_price_second']['#size'] = 1;
    $form['field_price_second']['#validated'] = TRUE;

    dpm($form);
  }
}

```

However, the default value isn't working, i see instead 'All' value as default in my views exposed form's select list. What's wrong?

DPM output:

# Answer
> 0 votes
Try overriding the whole element, like this:

```
...
if ($form_id == 'views_exposed_form') {
    $options = array(
      'All' => t('All'),
      '$' => '$',
      '€' => '€',
      'тг' => 'тг',
    );

  $form['field_price_second'] = array(
    '#type' => 'select',
    '#options' => $options,
    '#default_value' => '$',
    '#size' => 1,
    '#validated' => TRUE,
  );

    dpm($form);
  }
 ....

```

# Answer
> 0 votes
Solved my issue. I had to set:

```
$form_state['input']['field_price_seconds'] = NULL;

```

Only after that i could see my #default\_value

Spoke too soon, when i set this up - even if i change the value it reverting back to a default one.

---
Tags: 7, hooks
---