# Question
Title: What's the best way to delete all content without a content type?
Due to an error during migration, some of the content has been left hanging without a content type and did not port over correctly.

What is the best way to delete these around 1000 records? Unfortunately they do not share any particular characteristics to be able to search them from the frontend easily.

# Answer
> 3 votes
> Due to an error during migration, some of the content has been left hanging without a content type and did not port over correctly

If you're comfortable writing code you could write an SQL query to look for nodes or entities without a `type` set -- and output or save their IDs to a list. You may be able to use EntityFieldQuery for this but it may blow up, I'm not sure.

Once you have the IDs of content missing it's type you could try to use Drush Entity on your site to delete the entities. It supports deleting a list of entities by their ID (I assume in the Node table). Below is an excerpt from **entity.drush.inc**

```
  $items['entity-delete'] = array(
    'description' => 'Delete entities.',
    'arguments' => array(
      'type' => $type,
      'nids' => $nids,
    ),
    'options' => array(
      'json' => $output_json,
      'bundles' => $bundles,
    ),
    'examples' => array(
      'entity-delete' => '.',
      'entity-delete node 64' => '.',
      'entity-delete node --type=story' => '.',
    ),
    'aliases' => array('ed'),
  );

```

So you could try to take your IDs and issue the command:

```
drush entity-delete node -v --nids=<list-of-nids-seperated-with-commas>

```

If this fails try:

```
drush entity-delete node --debug --nids=<list-of-nids>

```

Obviously you could try to do this all by hand with a query, and using `node_delete()` for instance, but I'm trying to find you a slightly less programming intensive solution.

**EDIT**

**1) ALWAYS BACKUP YOUR WEBSITE FILES + DB FIRST BEFORE ATTEMPTING DISASTER RECOVERY.**

2) If the data is somehow improperly save and fragmented across disjointed tables good luck -- I've fixed mess-ups like this but end up scanning tables visually by hand and dropping obsolete fields or field\_instances for example.

---
Tags: 7, nodes
---


title: Custom form register

text:
# Question
Title: Custom form register
i have any fields form register user drupal 7. I want to when user choice select box : User 1 or User then any fields hide or show. Please help me Thank to all.

# Answer
> 1 votes
Look at Conditional Fields:

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

**EDIT**

To learn how to use the Field UI and create these form items for Users please see:

---
Tags: forms
---


# Question
Title: How do you edit the link count on /poll index page?
In Drupal 7 how do you increase the number of polls listed on domain.com/poll ?

The current limit appears to be 15 polls per page and then there is pagination at the bottom. I would much rather have all my polls listed without pagination.

Is there anyway to increase the number of polls listed?

# Answer
It's hard coded in poll module poll.pages.inc file...

```
function poll_page() {
  $polls_per_page = 15;

  $count_select = db_select('node', 'n');
  $count_select->addExpression('COUNT(*)', 'expression');
  $count_select->join('poll', 'p', 'p.nid = n.nid');
  $count_select->condition('n.status', 1);

  // List all polls.
  $select = db_select('node', 'n');
  $select->join('poll', 'p', 'p.nid = n.nid');
  $select->join('poll_choice', 'c', 'c.nid = n.nid');
  $select->addExpression('SUM(c.chvotes)', 'votes');
  $select = $select->fields('n', array('nid', 'title', 'created'))
    ->fields('p', array('active'))
    ->condition('n.status', 1)
    ->orderBy('n.created', 'DESC')
    ->groupBy('n.nid')
    ->groupBy('n.title')
    ->groupBy('p.active')
    ->groupBy('n.created')
    ->extend('PagerDefault')
    ->limit($polls_per_page)
    ->addTag('node_access');
  $select->setCountQuery($count_select);
  $queried_nodes = $select->execute()
    ->fetchAllAssoc('nid');

  $output = '<ul>';
  foreach ($queried_nodes as $node) {
    $output .= '<li>' . l($node->title, "node/$node->nid") . ' - ' . format_plural($node->votes, '1 vote', '@count votes') . ' - ' . ($node->active ? t('open') : t('closed')) . '</li>';
  }
  $output .= '</ul>';
  $output .= theme('pager');
  return $output;
}

```

Override the menu item using hook\_menu\_alter and change the callback as well as setting which you can see in first line of above function using a custom module.. Otherwise use views to build your own page which will display polls...
> 1 votes

---
Tags: 7, polls
---


# Question
Title: How does the theme folder work in drupal 7?
In Drupal 7, I would disable a theme within the admin section and i would physically rename the theme directory (from themeName to themeName\_old), clear cache and restart the server, to my surprise, drupal 7 still picks up the theme (themeName\_old).

The only only way i managed to get rid of a theme completely is by removing the the directory from the theme folder. Why is that?

# Answer
> 0 votes
Folder name does not matter. What matters is name of the info file. If you have `themeName.info` in folder, Drupal knows it's a folder for a theme named *themeName*.

---
Tags: theming
---


# Question
Title: Cannot change date input format in views exposed filter
I am unable to change the date format for an exposed field in views. I am using BEF datepicker popup. I overrode the jquery settings to get it to enter a UK date in the dd-mm-yy format but because views is expecting it in mm-dd-yy form, the results of the filter are wrong.

This problem is addressed in this discussion https://www.drupal.org/node/1409120 but supposedly has been fixed for other people in Date 7.x 2.x. I am using BEF 7.x-3.0-beta4, Date 7.x-2.9-alpha1+2-dev, and Views 7.x-3.8, and the problem isn't fixed. I can't see any extra options in the view settings or in the config menu to change the date format.

The field name is field\_activity\_date\_time and I have created a custom module with the following code, based on other stackoverflow suggestions (I don't have a max and min field, just a single date)

```
function hook_form_views_exposed_form_alter(&$form, &$form_state) {
    if($form['#id'] == 'views-exposed-form-test-page') {
       $form['field_activity_date_time']['#date_format'] = 'd/m/Y';
      }
    }
}

```

I have tried a number of different possibilities for the array key, such as 'activity\_date\_time', and 'views\_field\_activity\_date\_time', none of which worked. This date field is coming from a CiviCRM table which may be why the other suggestions haven't worked, but it feels to me more of a drupal problem than a civicrm one.

---

as suggested by harsh in the comments, I have used a different hook, but the problem still persists...

```
function HOOK_form_alter(&$form, &$form_state, $form_id){
  if ($form_id == 'views_exposed_form' && $form_state['view']->name == 'test' && $form_state['view']->current_display == 'page') {
     $form['activity_date_time']['#date_format'] = 'd/m/Y';
     echo '<pre>';
     print_r($form);
     echo '</pre>';
 }
}

```

This gave me the following

```
Array
(
    ...

    [activity_date_time] => Array
        (
            [#type] => textfield
            [#size] => 30
            [#default_value] =>
            [#attributes] => Array
                (
                    [class] => Array
                        (
                            [0] => bef-datepicker
                        )

                )

            [#date_format] => d/m/Y
        )
)

```

# Answer
Well, I am not proud of the clunky fix but it works!

```
function gmcvo_date_format_views_query_alter (&$view, &$query){
    $newDate = DateTime::createFromFormat('Y-d-m H:i:s', $query->where[1]['conditions'][0]['value']);
    $query->where[1]['conditions'][0]['value'] = $newDate->format('Y-m-d H:i:s');
}

```

If someone has a better way to do this it would be great to hear it...

*edited to use the new datetime object instead of strtotime*
> 1 votes

---
Tags: views, datetime
---


title: "Ghost" pending update (backup_migrate)

text:
# Question
Title: "Ghost" pending update (backup_migrate)
Working on a project on localhost, for which I installed the backup\_migrate module, it seems one update procedure for this module had some problem (can't really remember what). And now every time I update *any* module (even totally unrelated), when performing the "update.php" script, Drupal states that there's the following pending update for the backup\_migrate module:

`7303 - Add a serial id field to all tables to allow them to be ctools exportable.`

If I click apply, I get the usual progress bar, then the following error message:

`backup_migrate module`
`Update #7303`

`Failed: PDOException: SQLSTATE[42000]: Syntax error or access violation: 1075 Incorrect table definition; there can be only one auto column and it must be defined as a key: ALTER TABLE {backup_migrate_sources} DROP PRIMARY KEY; Array ( ) in db_drop_primary_key() (line 2904 of C:\xampp\htdocs\my_site\includes\database\database.inc).`

So it seems to me that the update job #7303 has already been applied successfully, but for some reason Drupal hasn't registered that and *thinks* it still needs to be done.

How can I correct that?

# Answer
OK I think I found it, although I haven't yet been able to confirm that the problem has been corrected, since all my modules are up to date.

Based on this question, here's what I did:

* find the ID number for the pending update. In my case it was stated plainly in Drupal's update.php messages, so it's `7303`. This information can also be found in the `.install` file in the module folder (e.g. `function backup_migrate_update_7303`).
* access the database (e.g. via phpmyadmin) and go to the `system` table.
* in this table, find the entry corresponding to the module whose update is still pending (in my case: backup\_migrate)
* edit the `schema_version` column for this row and give it the value of the update ID found in step 1 (e.g. `7303`).

And that's it.
> 2 votes

---
Tags: 7, updating
---


# Question
Title: I want to add more fields to be indexed by solr. How can I do that
I am now using search\_api and search\_api\_solr. I want more custom fields, to be specific, like the weight for a term referred by a node content type, to be indexed together the out-of-the-box filed(like content type, created, language, etc.). How can I achieve that? what is the hook or api to do that?

# Answer
Go to `admin/config/search/search_api` and click "Edit" next to your Index and select "Fields".

Check the checkbox next to the fields you want indexed under the column "Indexed" and click "Save Changes" when you're done.
> 0 votes

---
Tags: search
---


title: Multi Dimensional Taxonomy

text:
# Question
Title: Multi Dimensional Taxonomy
I'm trying to extend my already existing Taxonomy list by a second value per existing one. Let's say I have a Taxonomy list like this:

* First Item
* Second Item
* Third Item

Now i want to store a second value (FI, SI, TI) to receive a list:

* First Item | FI
* Second Item | SI
* Third Item | TI

where I can access either the first or the second value of one taxonomy item. Is that somehow possible?

The only thing I would know to achieve that, is a custom content type.

# Answer
> 2 votes
You can add new field to taxonomy terms. Go to vocabulary and than to Manage Fileds tabs and add new textfiled. After that you can edit you tems and add seecond values.

---
Tags: taxonomy-terms
---


# Question
Title: Drupal File upload only allowing one upload at a time
I'm having a problem with the File widget. I have created a content type with a file field that allows unlimited values. When I upload a file I am expecting to be able to immediately upload another file.

but what actually happens is the upload box disappears, meaning I have to save the node and re-edit it in order to upload another file

both these example have exactly the same content type settings, both running the same version of Drupal. I'm not getting any JS errors or anything. Any ideas on why this is happening? I've even updated all my modules and drupal core and tried disabled all my theme's JS files, still have this issue.

# Answer
> 1 votes
Probably same issue as here https://drupal.stackexchange.com/a/112999

As suggested in the post above, you should consider Plupload and file field sources, you'll never look back, imagine dragging 10 files from your explorer/finder to your form field and uploaden them all at once ... ;)

---
Tags: files
---


title: update shipping profile on user update

text:
# Question
Title: update shipping profile on user update
I use drupal commerce, I want if user info update if there is exist shipping profile update it else create new.

```
function mymodule_user_update(&$edit, $account, $category){
    $def_id=commerce_addressbook_get_default_profile_id($account->uid,'shipping');
    if($def_id){
       $profile=commerce_customer_profile_load($def_id);
       }
    else{
         $profile = commerce_customer_profile_new('shipping', $account->uid);
    }
        // Add the address value.
        $profile_wrapper = entity_metadata_wrapper('commerce_customer_profile', $profile);
        $profile_wrapper->phone_mobile=$edit['field_mobile']['und'][0]['value'];;
        $profile_wrapper->phone_home=$edit['field_telephone']['und'][0]['value'];
        $profile_wrapper->field_user_addres = array_merge(addressfield_default_values(), array(
        'country' => $edit['field_user_addres']['und'][0]['country'],
        'thoroughfare' => $edit['field_user_addres']['und'][0]['thoroughfare'],
        'postal_code' => $edit['field_user_addres']['und'][0]['postal_code'],
        'locality' => $edit['field_user_addres']['und'][0]['locality'],
        'name_line' => $edit['field_name']['und'][0]['value'] . '  ' .$edit['field_last_name']['und'][0]['value'],
        'first_name' => $edit['field_name']['und'][0]['value'],
        'last_name' => $edit['field_last_name']['und'][0]['value'],
       ));
        // Save the profile.
        $profile_wrapper->save();
        //ym($profile,'message');
    //ym($account,'message');
}

```

but when I submit it in any manner ( even thought default exists) $profile filled by shipping default profile and create new shipping profile, where is my fault? how can I update shipping profile?

# Answer
> 0 votes
Thanks Clive for get clue me about this prblem.
according https://drupalcommerce.org/user-guide/configuring-creating-customer-profiles \`EDIT CUSTOMER PROFILE Here we are editing the customer profile. Normally this might need to be updated to account for a customer who needs to change their shipping address or other kinds of updates. Note that the original customer profile does not get lost, we simply clone a copy of the original and make the changes. We are doing this action to show you how this process works. Note that this means, by default, if you edit a customer profile it does not change the original order.'

---
Tags: users, entities, commerce
---


# Question
Title: How to generate images for profile picture in Drupal 7?
Let's say I've a site with hundreds of users. I would like to provide a profile picture to users who don't have a picture on their profile.

How can I do that?

# Answer
I could achieve that by the Identicon module.

> This module generates and displays identicon images in place of the user picture for users who do not have a picture.
>
> The generated identicons are pixel style images. The number of pixel blocks that the images contain can be configured. You can choose whether the generation is based on the user's email address or the user id. If the generation is email-based, users will get a new image if they change their email address. On the other hand, they get the same image even if they cancel their account, and register again using the same email. If the generation is user id based, changing the email address will not change the identicon, but if the user account is cancelled, the user will not get the same image when they re-register.

Checkout the similar modules Gravatar and User Pic Kit
> 2 votes

---
Tags: 7, users
---


title: convert ' to html character

text:
# Question
Title: convert ' to html character
I have this code:

```
$items[$k]->user->nome = $accounts[$item->uid]->field_nome['und'][0]['safe_value']." ".$accounts[$item->uid]->field_cognome['und'][0]['safe_value'];

```

And the output is this:

```
L'itto Giovanni

```

But I want (in HTML)

```
L'itto Giovanni

```

in html head I have

```
 <meta charset="utf-8">

```

Where is my error?

# Answer
"safe\_value" is a "value", passed through the function \_text\_sanitize().

You can use php function html\_entity\_decode or use "value" instant of "safe\_value". Differences between value and safe\_value
> 3 votes

---
Tags: 7
---


# Question
Title: select nodes whose created date in hours is equal or larger than 48 hours
I make a PHP routine in which all node is selected and check created date and delete those nodes which is created in last 48 hours or greater.

```
$result = db_query('SELECT n.nid, n.title, n.created FROM {node} n ');

foreach ($result as $record) {

        $createdDate = $record->created;
        $currentDate = time();

        $diff = $currentDate - $createdDate;
        $diff_in_hrs = ceil($diff/3600);

        if($diff_in_hrs => 48)
        {
            node_delete($record->nid);
        }
}

```

but i think it is a bad approach that i select all nodes (which may be 10000 nodes) and then iterate each node. i am bad in sql but i think there may be sql query through which i can get the same result.

# Answer
> 2 votes
Even quicker (and more efficient):

```
$sql = 'SELECT n.nid, n.title, n.created FROM {node} n WHERE (UNIX_TIMESTAMP(CURRENT_TIMESTAMP()) -n.created)/3600 >= 72');
node_delete_multiple(db_query($sql)->fetchCol());

```

# Answer
> 0 votes
```
$result = db_query('SELECT n.nid, n.title, n.created
                    FROM {node} n
                    WHERE (UNIX_TIMESTAMP(CURRENT_TIMESTAMP()) -n.created)/3600 >= 72
                    AND
                    ');

foreach ($result as $record) {

        node_delete($record->nid);

}

```

This solve my problem. :)

---
Tags: database
---


# Question
Title: how to setup cron to run everytime when new file is generated in drupal files folder
I created webform and saving submitted data into text file in drupal files folder. A remote script performs calculations and outputs new text file to the same folder . I want cron to run everytime text file is generated, so that i can print result from text file to webform and also save them to database

So far i created custom module for webform and used hook\_cron() as shown below

```
function simulation_ignition_view_cron()
 {
  $uri = 'default/files/simulation/generatedfile.txt';
  if (file_exists($uri)) {
  drupal_set_message("hello cron");
 }
}

```

Please let me know if my explanation is not clear and please give some suggestions

# Answer
> 1 votes
> I want cron to run everytime text file is generated

I think you're misunderstanding what cron is. Cron is

> a command to an operating system or server for a job that is to be executed at a specified time.

It doesn't respond to file system triggers, it's a scheduled task.

If a file is created as part of the normal Drupal content add/edit, you can just implement `hook_file_insert()`:

```
function MYMODULE_file_insert($file) {
  if ($file->uri == 'foo') {
    // Do something.
  }
}

```

If you want to start the scheduled jobs running in that hook you can use `drupal_cron_run()`, but it would probably make more sense not to involve cron in this.

---
Tags: webforms, files, cron
---


# Question
Title: Why hook_form_alter implementation is being called twice?
I have a module where I implemented hook\_form\_alter:

```
function mymodule_form_alter(&$form, $form_state, $form_id) {
  krumo($form_id);
}

```

And I always get each form\_id displayed twice. Duplicate form\_id for each form!! The problem is that if I add in hook\_form\_alter line like:

```
$form['#submit'][] = 'my_submit_function';

```

then this function is getting called twice, and this follows errors. I have no idea why Drupal calls hook\_form\_alter implementation twice, possibly you have. Thank you in advance!

# Answer
I ran into the same problem today, a hook\_form\_alter() override in a custom module was being called twice on every form.

My custom module's name was "project\_name" and my theme was also called "project\_name" (folder/machine names). I uninstalled my custom module and renamed it to "project\_name\_different" and re-installed it. After that change, hook\_form\_alter() only gets called once.

Don't know the super technical explanation for this answer, but generally Drupal doesn't like duplicate names across modules and themes, so make sure machine names are unique across all modules and themes living within your site.
> 3 votes

# Answer
I believe that hook\_form\_alter() will be called once for each form on the page. So, if there is a second form, possibly in a block or added by another module, that form will also be processed through hook\_form\_alter().
> 2 votes

# Answer
Probably you are giving to your module and theme the same name!
> 0 votes

# Answer
Note that when your custom module and your theme have the same name, hook\_form\_FORM\_ID\_alter will be called twice.
> 0 votes

---
Tags: forms
---


# Question
Title: How to make a reference on same node without recursion problem
Here is the situation.

I have a content type called Product.

```
Content Type : Product
Title
Body
Color
Product Reference (Entity Reference on content type Product)

```

Thats mean For a specific product, I could referer this product to more product.

My problem right now is there is a Recursion problem.

Is there any other way to perform my needs.

Thanks a lot

# Answer
There is no reason you can't have an entity reference field that references the same content type, the problem only comes when you have nodes that reference each other in a loop.

For example if nodes A, B & C have these relations you cause a loop and get the error you describe:

A \> B \> A
A \> C \> A
A \> B \> C \> A
A \> C \> B \> C
etc.

If you create your content in a way that avoids loops you avoid the problem, however there is also another work around you can use (which is described at https://www.drupal.org/node/2301499#comment-8973869):

1. Have a new view mode for your nodes. This could be done in custom code as per the linked example, or by using the Entity View Modes module.
2. Configure your entity reference field on the product content type to display using your new view mode.
3. Configure the display settings for your new view mode on the product content type to not display your rendered referenced entity.

This way when you view a product it will display its referenced entity for that field but that referenced entity will not print out its rendered entity, avoiding the recursion.

That linked issue also has a patch that apparently addresses the issue but the maintainer has said it will never be committed so I would use caution if thinking about using that.
> 1 votes

---
Tags: views, entities
---


# Question
Title: what is the default file template in drupal when you set your own theme?
What is the default template in drupal when you set your own template and you don't have page.tpl.php ?? where does the html beeing rendered from?

# Answer
If the active theme doesn't have a page.tpl.php, the default page.tpl.php from core is used.

See Default theme implementations for more information.
> 1 votes

---
Tags: theming
---


# Question
Title: How do I add a class to a row based on the value of a field in that row?
I have a view with a page display showing a list of events. I'd like to add a class to the rows of those events that are in the past.

The problem I have is that views-view-list.tpl.php doesn't have access to the values of fields within the rows.

And I can use views-view-fields.tpl.php to check the date field of one row, and wrap each field in that row with a div or span based on whether or not the date field is in the past.

I just can't figure out how to use the value of a field within a row to wrap the whole row in something with a class.

# Answer
> 7 votes
The following will add the class 'hello' to the li tag. I used a view with machine name 'dates' and a display name of 'page'. The time field is the node created time. You can just install Devel and uncomment the dpm($vars) statement to get what you need. I also left the conditional logic up to you.

Put this in your theme's template.php file:

```
function MYTHEME_preprocess_views_view_list(&$vars) {
  if ($vars['view']->name == 'dates' && $vars['view']->current_display == "page") {
    // dpm($vars); //uncomment to see variables
    foreach($vars['view']->result as $key => $value){
      $timestamp = $value->node_created;
      if ($timestamp) { // add whatever conditional logic you need here
        $vars['classes_array'][$key] .= ' hello'; // note the space in front of class
      }
    }
  }
}

```

An **alternative method** is as follows:

Put this in your theme's template.php file:

```
function MYTHEME_preprocess_views_view_fields(&$vars) {
  if ($vars['view']->name == 'dates' && $vars['view']->current_display == "page") {
    $timestamp = $vars['row']->node_created;
    if ($timestamp < strtotime('now')) {
      $vars['classes_array'][] = 'bye';
    }
  }
}

```

and use this views-view-fields--VIEWNAME.tpl.php file:

```
<div class="<?php print $classes;?>">
<?php foreach ($fields as $id => $field): ?>
  <?php if (!empty($field->separator)): ?>
    <?php print $field->separator; ?>
  <?php endif; ?>

  <?php print $field->wrapper_prefix; ?>
  <?php print $field->label_html; ?>
  <?php print $field->content; ?>
  <?php print $field->wrapper_suffix; ?>
<?php endforeach; ?>
</div>

```

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


title: Views sorting by date

text:
# Question
Title: Views sorting by date
I want an overview of articles sorted by their post date (some articles will be posted back in 2007). But then the possibility should be there to move an article back to the top of the list (we want to recycle old content). We don't want to change de post date manually, because this is valuable information (so the post date should be the original post date), I also don't want to use the updated date, since sometimes you'll need to edit a node without having it move back to the top of the list.

I was thinking, Weight module, but maybe there are better alternatives, i don't need as much control on the sorting as the weight module is giving. I'm not afraid of creating (small) custom modules, if i'm properly guided through the Drupal API.

Ideally i'd want: 1. an action 'move to top' on the content overview page and a simple checkbox on a node edit page: move to top. 2. an action and checkbox that says: reset to post date, so that we can put it back in the order it's intended to be...

I was thinking a date field, that gets updated to now() every time the 'move to top' action is called... and is emptied when 'reset to post date' is chosen...

Does anyone know a module that does this? Or can guide me in creating it?

Kind regards and thank you in advance

**The workflow i'm going for**:

1. Enable custom module (i know how to create a module and activate it)
2. Add option in each node type I wish to have this function (maybe in the publishing options, simple checkbox should suffice)
3. In a node have a checkbox 'Move back to top' and 'Reset order'. Both should then edit a extra node field timestamp (\*remark at the bottom). The checkboxes should not be checked when re-editing the node, since it is more of an action (it's difficult to explain, but I think it should be clear what i'm trying to say)
4. Have this extra date field available in views

\*Remark: I read somewhere you could actually add a field to the node table itself, I think it was with schema\_alter hook. If the timestamp is in this table, the query's would be faster then when it's in an axtra table (which would mean an extra join)

**edit2:** Went for a custom module with views, operations and actions integration. The module is finished, maybe i'll make it public. Does anyone think this might be interesting for others? How does this module uploading work on drupal.org?

# Answer
> 1 votes
You could add a simple checkbox to your content type and call it "sticky" or somewhat. Then you add an attachment to your view, choose position before your default view and let this attachment display only the nodes with "sticky" checked, while you exclude the sticky ones from your default view.

In the second step you can add more logic to the sorting of your sticky nodes inside your view attachment. I really like DraggableViews for such tasks. But maybe that's already too much, then you might simply add another integer field to your content type and let the sticky nodes sort by that.

# Answer
> 1 votes
A very easy solution is to add a global flag on the node type. You expose the flag only to admin.

In your view you add the flag as a relationship: Limit results to only those entity flagged by a certain flag. Make sure not to select 'Include only flagged content'. Make sure to select By 'any user'

Add the 'Display flag/unflag link' as a field is optional. It will only display for admin, so no worries.

Then add Sort Criteria: 'Sort by whether entities have or have not been flagged' and slect 'Flagged first'. Move this sort criteria above in the list.

Now all flagged content will be promoted, and still retain post date sorting amongst themselves.

And to include this functionality on the 'Content overview page' just add Administration Views and add the flag as a relationship, field and sort once again.

And of course you will expose the flag on the node view page also.

And for even more functionality you can add a date field on the flag also and use that in views to sort on if you prefer. **Flags are now fieldable!** To enable that you need to set the flag up with a confirmation form as Link Type. Flags also expose a 'flagged time' to views which can also aid in sorting.

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


# Question
Title: How to fix 'Cannot redeclare ctools_content_process' problem after sql-sync?
I'm encountering a really weird bug with Drupal. I'm running Debian's Drupal in a multisite configuration on the same host with both the dev and live websites. I know it's not ideal but this is a constraint I cannot avoid for a variety of reasons.

So I have my sites (e.g. dev.example.com and www.example.com) and I sync them with `drush sql-sync`. Right after doing so, I cannot access the synced website anymore and Apache throws the following errors:

```
PHP Fatal error:  Cannot redeclare ctools_content_process()
(previously declared in /etc/drupal/7/sites/www.example.com/modules/ctools/includes/content.inc:18)
in /etc/drupal/7/sites/dev.example.com/modules/ctools/includes/content.inc on line 84

```

To make my website work again, I have to manually do a find-replace in MySQL to change any instance of dev.example.com to www.example.com in tables field\_data\_body and field\_revision\_body.

I reckon the problem is linked to CTools (and hence to views), but I have no idea why. Have any of you ever encountered such a problem?

# Answer
In Drupal 7; this could be caused by corruption in the code registry. The code registry

> is an inventory of all classes and interfaces for all enabled modules and Drupal's core files. The registry stores the path to the file a given class or interface is defined in, and loads the file when necessary.

ref: Drupal Code Registry

The solution to this particular problem would be to force a rebuild of the registry; which you can do as per this post; Code Registry Rebuild.
> 1 votes

# Answer
Are you using Drupal 6? In Drupal 6, the full path to the sites folder is written into the database for a variety of purposes. Because of this, if you change the path to settings.php, you break Drupal. The usual solution to this problem is to put your settings.php file in sites/default instead of sites/www.example.com; however, it sounds like that is not an option in your instance.

If you are using Drupal 7, it could be that CTools has taken on the practice that was common in Drupal 6, but for the most part this has been left behind in Drupal 7.

In any event, it sounds like you have your workaround. Stream-editing an SQL dump is inelegant, but since "dev" and "www" are the same length, it would be possible for you to do this. (If the site names were different lengths, this would not work, because serialized strings contain length bytes, and the path to the sites folder probably appears in serialized strings.) I really wouldn't recommend it -- better to try to overcome some of the constraints you've mentioned -- but if you're really stuck, it beats not being able to make a dev site. I will also advise you to only sync from www.example.com to dev.example.com to avoid overwriting user content. Look into the features and ctools export bonus as possible alternate ways to move configuration from dev to live without using sql-sync.
> 0 votes

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


# Question
Title: Send out a unique (unprotected) link per user
I'm the admin of a Drupal site with 200+ users. I sort of rolled into this, so I'm no Drupal expert, although I've managed to understand it quite good now.

This is a site for our sportsclub and we want all existing users to confirm their membership (of the club) for the coming season.

We would prefer to do this a simple as possible and send each user a link which, when clicked on, will confirm their renewal. Ideally, this is a link with some sort of unique hash, so we can make it unprotected. This would avoid having to log in.

We want to do this (keep it as simple as possible) because we've noticed a lot of members just don't do it (go to the site, log in, go to the correct page if not already there, and click the yes link to renew).

Is this possible (with a module perhaps)? Sending out a unique link per user?

# Answer
This is how I solved it, although jdu is right, it should be in a custom module. I have made one before, so I will look into that, but for now, here's my solution:

I created a computed field for my users where I calculate a hash based on their username.

I created a new unprotected page, and I will send them the link with their unique hash by mail. As an aside: I'm using Mailchimp which integrates with Drupal so I should be able to take out that hash and use it in the mail.

Once on the page, I execute custom PHP where I check if the necessary query string parameters are present. Then I set the necessary field, confirming their new membership, save the user and notify them on the page.

The mail hasn't been sent out to all our users yet, but I've tried it myself, and it works.

As jdu said, the biggest barrier is the fact that they won't login, because this also means a lot of them will only half-read the mail, won't click on the link, will postpone it,... But it can't be any more simple than this.
> 0 votes

# Answer
I don't know of a single module to do this.

I would suggest looking at the VBO module (views bulk operations).

You can create an "email" action and customize what gets sent.

From your description I think the biggest barrier you're facing is that users don't want to login, and you'd like them to just click a link.

To do that you're going to have to roll your own module and likely make use of a menu hook with a callback to a function that processes the link.
> 2 votes

---
Tags: users, navigation
---


# Question
Title: Custom field widget that displays a button with JS action and a hidden textbox
I have no background in working with the Drupal API, so answers will have to explain it like I'm a child.

I am trying to create a custom field module. The widget should show a button with JS onClick action that opens an external form. The user selects through a series of prompts and the external form returns XML to the page that should be stored in a hidden XML field (I'm using the XML Field module). The XML is never shown to the user, but instead powers a JS script on node view.

The formatter for the field should deliver the content of the XML field as a JS variable and not display anything on the page.

I've read through the Drupal API documentation and several tutorials on building custom fields. However, these all assume a working knowledge of the Field API, which I do not possess.

Is this possible in a field module, or should I be looking at a different way of implementing this?

I'm using Drupal 7 and the external form is a client metadata requirement I have no control over.

# Answer
> 0 votes
Welcome here. You're question is complicated with many steps some involving the Drupal API and others involving Javascript and Ajax. Your question is specific to your needs, so you'll likely not find a module that does exactly what you're asking for out of the box.

You're correct that the Drupal API should be able to do this -- but by asking people to show you how to do like your 5; is basically asking someone to do your homework for you. I can outline the tools you'll need. It's up to you to come to a working solution.

1st off -- outline your code outside of the Drupal API and simply thing "how would this form work in psuedocode" using say PHP and JS; building those steps will take you a long way.

Drupal Resources to help you:

* The Field API Documentation pages.
* The Official Field API Tutorial, which links some 3rd party tutorials as well.
* If the above 2 resources aren't enough to understand what the Field API does look at the Examples module for Developers.
* It sounded like you wanted AJAX in your form. Read up on the Drupal Javascript API Documentation, specifically the Ajax Forms section, and again if that's not enough look at the Examples module, or google "drupal jquery form" as while Drupal has it's own JS API, Drupal *bundles* jQuery so you could try to just use jQuery to fulfill your needs mostly without the field api explicitly.
    + what do I mean by this? Here is a jquery autocomplete tutorial which uses a text field "in" drupal but is simply using jquery's native autocomplete functions. I used Google Translate for that page and View Source in my browser to fill in the tutorial gaps -- to re-engineer this on a site I have.

Lastly, either route you'll take you will likely be integrating with an existing Node form. You probably want to use hook\_form\_alter to inject your custom business logic into the existing Drupal functionality.

---
Tags: entities
---


# Question
Title: execute drush command from devel/php drupal
Can any one please tell me how can I execute drush command from devel/php?

I can execute PHP codes from devel/php. But I don't know how can I execute drush command from devel/php. (As we know "devel/php" URL coming from devel module).

I have written some custom drush command for cron purpose. I can able to run those commands from command line.

```
> drush my-cmd or drush cc all or drush status , etc ... I can run it through command line.

```

Expecting some function as mentioned below to run from devel/php

```
some_function("drush cc all");

```

# Answer
> 12 votes
Someone tried to create a module to provide shell access from within a Drupal site, but it was never fully debugged. See the Drupal Terminal project. Perhaps there have been advances in the jQuery terminal that might make it easier to get this working if someone revisited it.

If you want to exec Drush from within php, it is generally better to use `drush_invoke_process()` rather than `exec("drush ...")`.

```
$values = drush_invoke_process("@site", "cc", array("all"), array("verbose"));

```

If you are just running a one-off command and you don't care about the command results, then `exec("drush ...")` is fine, though.

# Answer
> 6 votes
As kalidasan suggests, you could use the exec() function, to do something like:

```
exec("drush fra -y", $output); var_dump($output);

```

Normally, devel will run this command where the settings.php is located, in case you have a custom multi-site architecture and you need to run the drush command from another path, you could chain commands (using ";" semi colon) to access to the right path and run the drush command:

```
exec("cd {absolute or relative path to your settings.php site}; drush fra -y;", $output); var_dump($output);

```

Sometimes, running drush commands from devel/php is useful when you need to execute functionalities from drush but you don't have access to the command line shell or permission to run it.

Note: I used "drush fra" only as an example, it could be used with any other drush command.

# Answer
> 5 votes
Finally found solution. **shell\_exec("drush status")** is working fine.

# Answer
> 2 votes
Drush is a **command line shell** and **Unix scripting** interface for Drupal.

You **must** have **shell access** to execute the **drush** commands.

---
Tags: 7, drush, debugging
---


# Question
Title: How to get location (longitude and latitude) from json data show on map?
I am using Openlayers module to have a map. In my json, it has longitude and latitude field. I want to get them to show on map so that user can see the location with the marker.

Is there any way to help me solve this problem? Any help would be appreciated.

# Answer
1) Add Geofield in your content type.

2) Select widget type as "Latitude / Longitude". Here you can store values and show it on map.

For your reference listed some links :

Setting drupal 7 locations

Getting Started with OpenLayers in Drupal 7

Openlayers
> 1 votes

---
Tags: javascript
---


# Question
Title: drupal_http_request redirect is not a fully qualified uri. Throws missing schema error 1002
I am trying to authorise with an Viagogo API using oauth in my custom module (i have my credentials from Viagogo). I can construct the initial URL OK but the redirect response from the API is a relative reference with an absolute path i.e. /Public/SimpleOAuthAccessRequest/Authorize?oauth\_token=Y%34hg5k34jhg5%3D

Which in turn is throwing a missing schema error using drupal\_http\_request.

> object(stdClass)#466 (4) { \["error"\]=\> string(14) "missing schema" \["code"\]=\> int(-1002) \["redirect\_code"\]=\> string(3) "302" \["redirect\_url"\]=\> string(87) "/Public/SimpleOAuthAccessRequest/Authorize?oauth\_token=Y%2Fbm9asdfasdfdsfjJfdd3D"

How can i get around this?

Is there a simpler way my custom module can authorise with oauth and access this API instead of my having to write this connector? The PHP code sample provided by Viagogo is using CURL and works fine outside of Drupal but once I bring the functions inside my custom module it doesn't work hence me using drupal\_http\_request.

# Answer
> 0 votes
I was trying to dump out the results coming back from my API call one step too early and before the redirect (to present the token) had taken place so inside Drupal it didn't appear as if anything was happening.

---
Tags: authentication-authorization
---


title: Sort Entity Reference Fields

text:
# Question
Title: Sort Entity Reference Fields
I am trying to find a way to sort the referenced entities in a node. I have found a related question "Ordering of referenced entity" but it cannot be applied in my case for the following reasons:

1) The manual ordering is out of the question in my case. In some of the nodes that need to be fixed there are more than 2000 referenced entities and they are ordered randomly right now. I also need to find a way to do that efficiently, since there will be a lot of nodes in the future that will also have multiple entity references that will need to be ordered.

2) The array\_reverse option will obviously not work since the referenced entities are ordered in a completely random manner.

3) The third option in the accepted answer does not even apply to sorting.

4) The rest of the answers are just improvements over the accepted answer's methodology and obviously cannot be applied.

What I would ideally like to achieve is grab the first number in the title of the referenced entity and use this to sort the referenced entities.

Note: It is very important to handle cases of "software release number ordering" which in plain English means that 1.1 comes before 1.2 which in turn comes before 1.10.

# Answer
I recently faced a similar problem and I solved it using the hook\_form\_FORM\_ID\_alter hook so that I can have an overview of the changes before actually applying them. My idea was to set the weight of each entity reference field to the number that can be found in the referenced entity's title. In your case however, the "numbers" in your title are not actual numbers with decimal parts but 2 different numbers that happen to be connected with a period (the first number has higher priority in the ordering than the second).

In your case you should do something like this:

```
function YOUR_MODULE_NAME_form_YOUR_CONTENT_TYPE_node_form_alter(&$form, &$form_state, $form_id) {
  if($form['nid']['#value'] == "22312") {  // The node id instead of 22312
    $keys = array_keys($form['field_FROM_ENTITY_REFERENCE']['und']);
    foreach ($keys as $value) {
      if (is_numeric($value)) {
        $weight = preg_match_all("/\d+\.\d+/", $form['field_FROM_ENTITY_REFERENCE']['und'][$value]['target_id']['#default_value'], $matches);
        if (empty($matches[0])) {
          $weight = preg_match_all("/\d+/", $form['field_FROM_ENTITY_REFERENCE']['und'][$value]['target_id']['#default_value'], $matches);
        }
        if (!empty($matches[0])) {
          $tempweight = explode(".", $matches[0][0]);
          $lengthtopad = (isset($tempweight[1])) ? 5 - strlen($tempweight[1]) : 5;
          $tempweight[0] = str_pad($tempweight[0], $lengthtopad, "0");
          $finalweight = implode("", $tempweight);
          $form['field_FROM_ENTITY_REFERENCE']['und'][$value]['_weight']['#default_value'] = $finalweight;
        }
      }
    }
  }
}

```

This solution is based on the idea that if from the 2 different-priority numbers that you have, you create numbers with the same amount of digits by padding the number with the highest priority with zeros, your final numbers will be properly ordered.

I assumed that the first number is single digit and that the second number can only go up to 3 digits. You can however adjust this to support more digits in the "decimal" part of the number.

Just to give you a couple of quick examples of how the numbers will look like after the transformation described above:

1 -\> 10000
1.1 -\> 10001
1.2 -\> 10002
1.10 -\> 10010
2.45 -\> 20045
2.456 -\> 20456

Of course, you can apply the same method to change the weights implicitly by using node\_load, altering the weights and then using node\_save to apply the new weights. It would work just fine, but with the solution described above, you edit the node-in-question and you can inspect the referenced entities and their ordering before deciding whether to save the node or not.
> 2 votes

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


title: Increase search field maxlength?

text:
# Question
Title: Increase search field maxlength?
Currently the search field has a maxlength of 128, I am wondering if there is any way to increase it too maybe 255?

# Answer
> 0 votes
Yes but it's not pretty. Drupal really doesn't want you to change field definitions after they've been created.

The correct way would be to create a new field definition and migrate values from the old field into the new one.

The quick and dirty way would be to manually change the field definition in the database directly.

The quick and dirty way that is deployable via code is to do a two-step process:

1. Export the field (such as with Features) and alter the `#maxlength` setting in the code.
2. TEMPORARILY hack core by commenting out the code in `hook_field_update_forbid()` in field.api.php.
3. Deploy a tag containing 1 and 2. Run updates.
4. UNCOMMENT `hook_field_update_forbid` and deploy that tag so further changes are not allowed and core is put back in its natural state.

This is terrible but I have done it and it works.

---
Tags: 7
---


title: "Add to cart" form alter

text:
# Question
Title: "Add to cart" form alter
want to change a few things with the hook they provide. The form id is *commerce-cart-add-to-cart-form-626* and the submission button ID is *edit-submit*.

I created a module (*jch\_test*) which contains the following code.

```
function jch_test_form_commerce_cart_add_to_cart_form_alter(&$form, &$form_state) {
  $line_item = $form_state['line_item'];
  $product = commerce_product_load($line_item->commerce_product[LANGUAGE_NONE]  [0]['product_id']);
  if ($product->type == 'product') {
    $form['submit']['#value'] = t('Test');
  }
}

```

The module loads, but the hook isn't invoked. What am I doing wrong?

# Answer
Try something like this:

```
/**
 * Implements hook_form_FORM_ID_alter().
 */
function MY_MODULE_form_commerce_cart_add_to_cart_form_alter(&$form, &$form_state, $form_id) {

  //drupal_set_message($form_id);

  $form['submit']['#attributes']['value'] = t('Buy Now');

  /*
  $current_product = $form_state['default_product'];
  if ($current_product->type == 'product') {
    // Make alternations for products...
  }
  */

}

```

You can use the `$form_id` and/or `$current_product` to make custom alterations for a specific product(s) and/or product type(s).

Flush Drupal's caches so your custom form alteration hook will be recognized.

***Note***, I'd also like to point out that once a user changes a value on the add to cart form, and the form is reloaded via AJAX, `MY_MODULE_form_commerce_cart_add_to_cart_form_alter()` will be called again, which is good.

However, it appears the `$form_state['default_product']->language` value may only be present the first time the page is loaded. Once the form is reloaded via AJAX, the `language` value may be empty in this hook, so watch out if your code is depending on it being there!
> 2 votes

# Answer
You can try

```
$form['submit']['#attributes']['title'] = $form['submit']['#attributes']['value'] = t('Test');

```
> 0 votes

---
Tags: forms, commerce
---


# Question
Title: How to set up the database for load-balanced Drupal 7
We currently run two Drupal instances (www1 and www2) behind a load balancer, and both instances are reading/writing the same mysql database. This seems like the wrong setup to me. Shouldn't we have it set up so that www1 reads and writes to db1, www2 reads and writes to db2, and db2 is a slave of db1?

# Answer
db2 should never be written to if it is a slave of db1, because any write to db2 will never be propagated to db1, and they will quickly get out of sync. The database must be shared and consistent.

There are 3 ways of getting a shared and consistent database experience: (1) Only have one database for all reads and writes. This is the easiest, but provides a single point of failure, and unless the db is on a separate machine, it can result in unequal response times for the different servers. (2) Use a Master-Slave setup and split your read and write requests between the master and slave. Ideally, a master and slave databases are on different machines than the application servers. (3) Use a multi-master so that writes to one are propagated to the other databases automatically, and vice-versa. Again, usually the database machines are separate from the application servers.

The question is on how big does your system need to be? If you are big enough to need more than one database server, then you should be looking at a cluster solution (MariaDB with Multi-Master Galera cluster, for example), but for that you need an odd number (minimum of 3) machines, which should be separate from your application servers. Furthermore, in order to minimize bandwidth and cache rebuilding, you should also use a shared memcached server for cache tables.

As a point of reference, I implemented our system with a MariaDB Galera Cluster setup as a Multi-Master, but I treat it as a Master-Slave (which minimizes the chance of write conflicts). I use AutoSlave to separate read and write requests, and send the read and write requests to different ports using HAProxy. HAProxy then sends them to either a read or write server. The "read" and "write" servers are really just part of the same Multi-Master cluster, but if my write master goes down, I have configured HAProxy to failover to the "read" servers until the "write" server comes back up. The same thing happens for the "read" requests: Read requests are load balanced between the available read servers, but should they ever go down, HAProxy is configured to redirect all reads to the write server. The end result is that Drupal thinks it is splitting up reads and writes, the cluster thinks that it is a multi-master, and it performs like a Master-Slave, with the advantage that it does not fail if either the master or the slaves go down.
> 6 votes

---
Tags: database
---


# Question
Title: Send email with URL of same page as the email link?
We have a page that displays a logged-in user's selections from a Flag Lists process. The page includes code to generate the specific URL of that page, so it can be copied and pasted elsewhere. (essentially a "share this" type of thing, but this is definitely not intended for social media) That code is: " onclick="this.select();" /\>

We want to provide an email link (ideally, a button) which sends a preformatted message including this URL, to a specific person's email address. (i.e. always to the same person) I am having trouble visualizing how this can be done, since the interface I am using for adding an email link (via CK Editor) isn't able to process the "current-page:url" PHP code and just displays it as code in the resulting message.

Any suggestions? -- Thanks! --

# Answer
insert a Drupal `token` of the `current page url` into the WYSIWYG. This token is provided by drupal 7 core I believe.

See the Token Insert module.

> This module allows you to insert tokens into a textarea. It supports both plain text and wysiwyg textareas. The format used for the insert is compatible with Token Filter.
>
> This module contains three modules:
>
> * Token Insert UI: Allows you to select which tokens are available for the insert, by default all tokens are shown. This module doesn't have to be enabled to use the others.
> * Token Insert (text): Add a fieldset under each textarea, works for both plain text fields and wysiwyg fields.
> * Token Insert (wysiwyg): Adds an extra button to wysiwyg editors and opens a popup to select the token to insert.
> 0 votes

---
Tags: emails
---


# Question
Title: How to get rid of a duplicate title on the front page?
When I first made the front page, I created a Basic Page and selected "Promoted to Front Page" and thought I was done. Drupal insisted on showing this page as an article summary, and no manner of tweaking settings on my part prevented this behavior. I decided instead to put the main front page content in a block because it will seldom ever change.

I created my block, and yay! No more summarized front page content. However, the title of the page shows twice. The first is the title of the original basic page I created, the second is the title of the block I created. I've already cleared the cache and there was no change.

How do I get rid of the duplicate?

# Answer
> 1 votes
It sounds like you have `node` as your front page which lists summaries of content that is promoted to the front page by default. That's the way Drupal comes configured out of the box. If I understand correctly, what you're looking for though is a single node to be displayed in full on the front page.

You can change it from `node` (which shows a list) to your specific Node at `admin/config/system/site-information` or Configuration -\> Site Information under the "Front Page" section. Simply change "node" to "node/\[node-id\]" where \[node-id\] = the nid of the node you want to appear on the front page:

# Answer
> 1 votes
I will address your situation by telling you both the solution to your previous problem, followed by your current conundrum.

The "promoted to front page" option is intended to be a list of several things (think of the front page of a blog). If you want a single front page, then change the settings for the front page (under `admin/config/system/site-information`). It is currently set to "node", which is a list of everything that is "promoted to the front page". Instead, change it to "node/#" (where "#" is the number of the node itself).

The other option is the way that you did it. It works, but as you see, it's a bit of a kludge. You can hide the title of the block by editing the block contents. There are 2 titles, so to speak. One is used for identification on the block administration page (the description), and one is for display (the title). Just leave the title blank.

# Answer
> 0 votes
Assuming you want to keep the block as your page content rather than setting a node to be displayed as the front page, there are a few ways to get rid of the title on the front page. Preferably using CSS since you don't have a H1 anywhere else on the page.

```
.front .page__title {
  display: none;
}

```

Or you could remove it completely by duplicating your themes `page.tpl.php` \> removing the line that prints the page title \> saving it to your templates folder as `page--front.tpl.php`

---
Tags: 7, nodes
---


title: Views No Results: Show Block Instead?

text:
# Question
Title: Views No Results: Show Block Instead?
I have a view that is set up to report breaking news from a "breaking news" text field. But this field is often empty, and in the no results behaviour, we would like to show one of our special offer blocks instead.

I can see an option for "Entity:Rendered Entity" in no results behaviour, but this is only nodes or users, I cant see a way to display a pre existing block?

# Answer
> 2 votes
There is a module that exposes blocks to the view header/footer and no results. It's called the Views Block Area.

> This module exposes all available blocks as a views area. This way you can add any block inside a footer or header from your view.
>
> Blocks that are generated by views, can't be selected. These blocks can be inserted by views areas.

This is also only for Drupal 7

# Answer
> 0 votes
This answer is for Drupal 7...

The quick and dirty way would be to use a `Global: Text area`. With the PHP text filter enabled, you can input the PHP code necessary to render your block.

```
$block = block_load( $module, $delta);  // if you defined the block via UI, then go to the configuration page for the block.  The configure URL follows the structure: block/manage/MODULE/DELTA/configure
$output = drupal_render(_block_get_renderable_array(_block_render_blocks(array($block))));
print $output;

```

See block\_load() and \_block\_get\_renderable\_array(). The PHP Filter is explained here: https://www.drupal.org/node/1046700

Here's a really long conversation of people struggling to just try to render a block by hand: https://www.drupal.org/node/1034524

Optimally I'd be able to point you to a module, but I can't find one.

---
Tags: 7, blocks, views
---


# Question
Title: Displaying Line Item Fields in a View (SQL Error)
I've built a conference registration system using Commerce and Custom Line Item types, and I'm having trouble figuring out how to display my Custom Line Item fields in a View. Here's a short summary of what I've done:

* The registration fields (e.g. name, email, etc.) are fields in a custom line item type.
* My product view doubles as a registration form. It displays the fields of my custom line item type as part of the add to cart form. It also references a custom product type I created for the conference.
* Some of the fields in the custom line type are booleans that trigger rules that add additional related products to the cart (e.g. hotel accommodations, meals, etc.).

I've built a View that summarizes the store's Orders, so that the conference organizer can see all of the Order info without having to know anything about Commerce or the Drupal admin pages. When I add the Line Items to this Order View, only the products show up (both the product referenced in my view, and those added by rules) - the other fields I've created for capturing the registration data (name, email, etc) don't show up.

I've also attempted to make a View that shows only Line Items (filtered to only my Custom Line Item Type), but nothing shows up and I get the following SQL error:

* SQLSTATE\[42S22\]: Column not found: 1054 Unknown column 'commerce\_line\_item.uid' in 'field list'

Any help on getting my other Line Item fields to show up, or insight into this SQL error, would be MOST appreciated. Thanks!

(For some brief background, I have built other solutions using Commerce in conjunction with the Registrations module. This has caused a lot of problems, so I am attempting to recreate similar functionality without the Registration module)

# Answer
I was running into the same problem too. You have to create the relationship "Commerce Line Item: Order ID" and display the field "Commerce Order: Order ID" to get around the mysql error.

You can get the view by importing the following code:

```
    $view = new view();
    $view->name = 'commerce_line_items';
    $view->description = '';
    $view->tag = 'default';
    $view->base_table = 'commerce_line_item';
    $view->human_name = 'Commerce Line Items';
    $view->core = 7;
    $view->api_version = '3.0';
    $view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */

    /* Display: Master */
    $handler = $view->new_display('default', 'Master', 'default');
    $handler->display->display_options['title'] = 'Commerce Line Items';
    $handler->display->display_options['use_more_always'] = FALSE;
    $handler->display->display_options['access']['type'] = 'none';
    $handler->display->display_options['cache']['type'] = 'none';
    $handler->display->display_options['query']['type'] = 'views_query';
    $handler->display->display_options['exposed_form']['type'] = 'basic';
    $handler->display->display_options['pager']['type'] = 'full';
    $handler->display->display_options['pager']['options']['items_per_page'] = '10';
    $handler->display->display_options['style_plugin'] = 'default';
    $handler->display->display_options['row_plugin'] = 'fields';
    /* Relationship: Commerce Line Item: Order ID */
    $handler->display->display_options['relationships']['order_id']['id'] = 'order_id';
    $handler->display->display_options['relationships']['order_id']['table'] = 'commerce_line_item';
    $handler->display->display_options['relationships']['order_id']['field'] = 'order_id';
    /* Field: Commerce Line Item: Line item ID */
    $handler->display->display_options['fields']['line_item_id']['id'] = 'line_item_id';
    $handler->display->display_options['fields']['line_item_id']['table'] = 'commerce_line_item';
    $handler->display->display_options['fields']['line_item_id']['field'] = 'line_item_id';
    /* Field: Commerce Order: Order ID */
    $handler->display->display_options['fields']['order_id_1']['id'] = 'order_id_1';
    $handler->display->display_options['fields']['order_id_1']['table'] = 'commerce_order';
    $handler->display->display_options['fields']['order_id_1']['field'] = 'order_id';
    $handler->display->display_options['fields']['order_id_1']['relationship'] = 'order_id';
    $handler->display->display_options['fields']['order_id_1']['link_to_order'] = 'customer';

```
> 4 votes

---
Tags: views, commerce
---


# Question
Title: How to connect to MySQL with SSL connection
I have Drupal 7.24 / PHP 5.3.27 and am using the PHP native MySQL drivers. PHPinfo shows that SSL is supported.

I can't seem to get Drupal to connect to MySQL with SSL. Works fine without it. I did find a patch 726192-arbitrary-pdo-options-attributes.patch that looked like it was committed back about 7.17. However I did not see the patch in my 7.24 that I downloaded. So I applied the patch. Still doesn't work. There are a lot of bad examples of configurations in others questioning how to connect. My best guess is this configuration. But again it does not work. I have test these SSL certs and connection Navicat and it does connect fine

Any suggestions on what to try or where to look??

```
$databases = array (
  'default' =>
   array (
    'default' =>
     array (
       'database' => 'drupaldb',
       'username' => 'drupaluser',
       'password' => 'password',
       'host' => '192.168.10.100',
       'port' => '3306',
       'driver' => 'mysql',
       'prefix' => '',
       'pdo attributes' => array(
           PDO::MYSQL_ATTR_SSL_KEY => '/path/client-key.pem',
           PDO::MYSQL_ATTR_SSL_CERT => '/path/client-cert.pem',
           PDO::MYSQL_ATTR_SSL_CA => '/path/ca-cert.pem',
        ),
     ),
   ),
);

```

# Answer
> 3 votes
Finally got it figured out. It's "driver options", not "PDO attributes".

```
  $databases = array (
    'default' =>
     array (
       'default' =>
        array (
          'database' => 'drupaldb',
          'username' => 'drupaluser',
          'password' => 'password',
          'host' => '192.168.10.100',
          'port' => '3306',
          'driver' => 'mysql',
          'prefix' => '',
          'driver options' => array(
              PDO::MYSQL_ATTR_SSL_KEY => '/path/client-key.pem',
              PDO::MYSQL_ATTR_SSL_CERT => '/path/client-cert.pem',
              PDO::MYSQL_ATTR_SSL_CA => '/path/ca-cert.pem',
           ),
       ),
    ),
  );

```

# Answer
> 1 votes
I did not find a way to setup a new site using SSL. So during the setup phase you cannot use SSL. That means, after turning on SSL you should change your passwords to ensure data safety and hope that no one use the small window during setup and change of password in a malicious way.

After you have your drupal site up and running, update settings.php as follows:

```
$databases = array (
  'default' =>
  array (
    'default' =>
    array (
      'database' => 'drupal7',
      'username' => 'drupaladmin',
      'password' => 'P@ssw0rd',
      'host' => '12.23.34.45',
      'port' => '',
      'driver' => 'mysql',
      'prefix' => '',
      'pdo' => array (
            PDO::MYSQL_ATTR_SSL_KEY => '/etc/pki/tls/private/client-key.pem',
            PDO::MYSQL_ATTR_SSL_CERT => '/etc/pki/tls/certs/client-cert.pem',
            PDO::MYSQL_ATTR_SSL_CA => '/etc/pki/tls/certs/ca-cert.pem',
                     ),
      ),
  ),
);

```

Adjust the paths and names to your certificates as needed. Restart apache or what ever webserver you are using.

On the MYSQL server use

```
GRANT USAGE ON database.* TO 'USERNAME'@'%' REQUIRE SSL;
FLUSH PRIVILEGES;

```

to force use of SSL.

If you should need to revoke that, you can use the following command:

```
GRANT USAGE ON database.* TO 'USERNAME'@'%' REQUIRE NONE;
FLUSH PRIVILEGES;

```

I hope that helps.

---
Tags: 7, database, ssl
---


# Question
Title: Commerce add to cart form fails when loaded via Ajax
Edit: more details below

I'm setting up a store page as follows, using Views, Commerce, and Drupal AJAX via a custom module:

There is a View that lists product display Nodes (B). Clicking on a Node in the View loads that Node's 'full' view on the page via AJAX (C), which includes the Product reference field / add to cart form (D). There are also AJAX links (A) that will swap the View for another display of the same view (with different criteria for loading the Nodes). The add to cart button works on Nodes included in the View display that loads initially on the page, but not if the View display is switched. When clicked, the form submits, but the product is never added to the cart. No errors or log messages. The exception is that any product Nodes that were loaded in the initial View display will work in subsequent ones.

So if 'new\_releases' is the Views display loaded during the initial page load, and it includes 'title 1', then when 'title 1' is loaded, then the 'buy' button works. If 'full\_catalog' is then loaded, then 'title 1' is loaded, then the 'buy' button works. But if 'full\_catalog' includes 'title X', not included in 'new\_releases', then they 'buy' button won't work when 'title X' is loaded.

This makes me think something is going on (perhaps with form\_token or form\_build\_id) that gets initialized properly during the first page load that doesn't happen via subsequent AJAX loads, but I'm not sure what that would be. The form HTML seems to be correct in both cases, both include the product ID and hidden quantity fields. No error messages shown.

Here's my code that loads the node:

```
function my_module_node_loader($nid = 0) {
 $node = node_load($nid, NULL, false);

 if($node) {
   $nodeview = node_view($node,'full');
   return render($nodeview); //will be returned in my_module_ajax_callback via drupal_json_output
 }

```

}

The function that retrieves the view:

```
function my_module_store_contents($display) {

 $view = views_get_view('view_name');
 $view->set_display($display);
 $view->execute();
 $response = $view->result;

 foreach($response as $id=>$row) {
   //do some custom formatting, put the results in $html
 }

  return $html; //returned via my_module_block_view on intial page load, my_module_ajax_callback subsequently

```

}

I'm already sure the AJAX callbacks are working ok, as the content gets loaded as I'd expect. It's just the issue with the form. Is there an extra step to make sure that a form is initialized properly if loaded via AJAX?

# Edit:

Thanks to a tip on drupal commerce's site, I discovered the cause of this was my altering the form's #action, which I had forgotten about. The add-to-cart form seems to take its #action from the path that loads it, so rather my /shop url, it was trying to load the /my-module/ajax callback. Since the add-to-cart form isn't itself ajax-enabled, it was redirecting the page with that url rather than doing it via ajax - I'd get the JSON response - so I was attempting to set the #action back to /shop:

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

     if(substr($form['#action'],0,15) == '/my-module/ajax') {
       $form['#action'] = '/shop';
       $form_state['rebuild'] = TRUE;
     }
   }

```

I attempted to use the 'rebuild' directive, with no effect. But if I remove the code altering the #action, then the product is added to the cart, albeit first sending me to /my-module/ajax.

So I need to either alter the add-to-cart form to submit properly via ajax, or figure out how I can alter the #action without breaking the form.

# Answer
> 1 votes
This is an old issue, but it was never answered and ranks high on google. The solution is to rebuild the submit button via javascript after the view has loaded:

```
$(".view").ajaxComplete(function(event, XMLHttpRequest, ajaxOptions){
          response = XMLHttpRequest.responseText;
          result = response.search(/"status": false/i);
          if(result == -1){
            $("form.commerce-add-to-cart").each(function(){
              $(this).attr("action",window.location.pathname);
            });
          }
          else{
            //console.log("failure binding on ajax complete");
          }
        });

```

Solution taken from here: https://www.drupal.org/node/1294164#comment-5343066

---
Tags: views, forms, commerce, ajax
---


# Question
Title: Custom Field Type hook_field_widget_form() not showing #title values
I have created a custom field type. When creating a piece of content with this field type I get a select list and a text area like the image below. However, I have stated that the '#title' for the select list is Label and the textarea is Value.

These '#title''s I've given them do not show up. From looking at other modules that provide a field type that has multiple elements on its widget form seem to be doing it the same way but their titles show up.

```
function civsearch_property_labels_field_widget_form(&$form, &$form_state, $field, $instance, $langcode, $items, $delta, $element) {
  if (isset($items[$delta]['label'])) {
    $default_label = $items[$delta]['label'];
  }

  if (isset($items[$delta]['value'])) {
    $default_value = $items[$delta]['value'];
  }

  // We are unserializing the variable_get because the string that was
  // serialized with variable_set was a serialized array. So we need to run the
  // unserialize process one more time.
  $options = array();
  $list_items = unserialize(variable_get('civsearch_property_labels', ''));
  foreach ($list_items as $list_item) {
    $explode = explode('|', $list_item);
    $options[$explode[0]] = $explode[1];
  }

  $labels = $element;
  $labels += array(
    '#type' => 'select',
    '#title' => t('Label'),
    '#options' => $options,
    '#default_value' => isset($default_label) ? $default_label : '',
    '#suffix' => '<br \>',
  );

  $values = $element;
  $values += array(
    '#type' => 'textarea',
    '#title' => t('Value'),
    '#default_value' => isset($default_value) ? $default_value : '',
  );

  return array(
    'label' => $labels,
    'value' => $values,
  );
}

```

# Answer
According to `hook_field_widget_form()` the `$element` parameter will already have a `#title` set. If you take a look at the docs for PHP array operators:

> The + operator returns the right-hand array appended to the left-hand array; **for keys that exist in both arrays, the elements from the left-hand array will be used, and the matching elements from the right-hand array will be ignored.**

Emphasis mine.

So your new `#title` is currently being ignored.

Try this instead:

```
$labels = array(
  '#type' => 'select',
  '#title' => t('Label'),
  '#options' => $options,
  '#default_value' => isset($default_label) ? $default_label : '',
  '#suffix' => '<br \>',
) + $element;

```

The example in `hook_field_widget_form()` might be a bit confusing as it uses an approach similar to your original one, but if you look closely neither of the properties added exist in the list of defaults that `$element` will contain, so there's no chance of a collision.
> 1 votes

---
Tags: 7, entities
---


title: How can I pass parameters to a block?

text:
# Question
Title: How can I pass parameters to a block?
Is it possible to programmatically pass parameters to a block?

# Answer
> 6 votes
Per the other answer, blocks are 'dumb' and don't have the ability to have arguments 'passed in'. They can, however, grab arguments from the context of the page, like node IDs, current user etc.

You have two 'easy' choices really:

* Write your own block: It is pretty easy, if you can do a little PHP. Create a module and implement hook\_block(). There are many examples on Drupal.org.
* Use the Panels and/or the Views module: Panels allows you to create panes that can have all manner of variables and contexts passed in, BUT without a special theme the block will have to live in the content area, not a Drupal region; so it depends on your site, and where you want the block. Views can create blocks too, and receive arguments from the page URL, current user and also custom code via the Views PHP module. Views and Panels work together very well.

# Answer
> 3 votes
For the specialized (but widespread) case where your block is a display of a View, you can use `views_embed_view` to render the block with parameters that it gets via the contextual filters of the View (that is, normally from the URL).

For example:

```
print views_embed_view('news', 'panel_pane_1', 'world');

```

Any parameters after the second will be passed as contextual filter values to the block.

**Source:** Rewritten from this answer by David Thomas, licenced CC-BY-SA 3.0

# Answer
> 2 votes
You can't pass anything *programatically* to a block AFAIK. You can allow a block to be configurable (using hook\_block\_configure in D7). Alternatively you could create your own theme function, and you can pass arguments to that. What is it you're trying to do?

# Answer
> 1 votes
Configure contextual filter choose "Provide default value" type =\> "php code" and use the argument you want. ex: return arg(1);

---
Tags: blocks
---


# Question
Title: Creating a vanilla instance from a site already set up
I have a Drupal site which is set up, running and being continuously used. It has a variety of content\_types, taxonomies and field\_collections etc saved in the database. The plan is to sell on vanilla instances of this Drupal site - which means, clearing out all the content and resetting all table indexes to 1 etc.

Any ideas how to achieve this?

# Answer
There are 2 easy options:

* Use the Delete All Module and it's Drush interface.
* If that's not thorough enough, I typically just end up using an `SQL` script to set foreign key checks to 0; and then truncate all fields, cache, revision, users, user\_roles ... etc tables specific to my site. While it seems like alot of work it's basically a 1 time audit of the underlying DB for the script creation and simply tracking what new tables are needed for wiping when you add new modules. I've then used Rules\_Link and the `php filter` to make this SQL statements runnable via a button press from a displaysuite panel ...
> 0 votes

---
Tags: nodes
---


# Question
Title: Drupal 7, form api - file field default_value
I've created a formular where the user can upload an image using a file field. In another formular the user is able to change the image he previous uploaded.

So far I was able that the user can upload a new picture or let the field empty and the existing image remains. My question is, how do I show the user in a nice way which file he previously uploaded with the field? Setting a #default\_value (@code below) does nothing for me.

```
//$smallimage = fid of image
$form['smallimage'] = array(
  '#type' => 'file',
  '#title' => t('Image'),
  '#default_value' => $smallimage,
  '#description' => t('Upload a file, allowed extensions: jpg, jpeg, png, gif'),
);

```

Has anyone a solution/workaround without switching to managed\_file?

Thank you in advance

Edit:

As seen in the answers there is no direct solution for the problem. So I've changed the type back to managed\_file and gave user1 and node1 the responsibility of being the reference of my files. I'm not happy with that but it works.

# Answer
File element only have these properties:

`#access`, `#after_build`, `#array_parents`, `#attached`, `#attributes`, `#description`, `#disabled`, `#element_validate`, `#parents`, `#post_render`, `#prefix`, `#pre_render`, `#process`, `#required`, `#size` (default: 60), `#states`, `#suffix`, `#theme`, `#theme_wrappers`, `#title`, `#title_display`, `#tree`, `#type`, `#weight`

As you can see, no `#value` or `#default_value` there. If you want to manage files, managed file element is there for you. If you insist on not using them, simply display old image as image, and add tip like this to your file element on the second screen:

> Use this field to upload image that will be used to replace image above.

Now, if you have a problem with `file_usage_add(stdClass $file, $module, $type, $id, $count = 1)` \- the fact that your module *"doesn't create any "type" like a node or a user"* Should not be a problem. Just use your form id as `$type`, and auto increment `$id`, or use any other means - you are identifying these files somehow already, that's or sure.
> 1 votes

# Answer
No, there's no way to do this. The restriction is with HTML, not Drupal. A file input simply doesn't have the capacity for a default value to be set; allowing such behaviour would introduce a security hole (imagine you pre-filled it with `/~/.ssh/id_rsa`, auto-submitted the form, and the user didn't have permissions set up correctly). See this post.

If you check the FAPI guide you'll see there's no `#default_value` available for a `file` field type.

You'll need to switch to a managed\_file element if you need a default value for the field.
> 3 votes

# Answer
If you really don't want to use managed\_file, what about providing that info under description:

```
$form['smallimage'] = array(
  '#type' => 'file',
  '#title' => t('Image'),
  '#description' => t('Current file: '.drupal_basename($smallimage) .' Update file, allowed extensions: jpg, jpeg, png, gif'),
);

```
> 1 votes

---
Tags: 7, forms, files
---


title: Any way to edit Term Page?

text:
# Question
Title: Any way to edit Term Page?
When I click a Term (such as "Garden Accesories"), I get some kind of a blog list with all the content associated with the term. I fear it might cause content duplication (it copies whole texts from different parts of the site). Is this fear rational?, and if it is, is there any way to control it (without Views)?

Thx.

# Answer
It is default behaviour to show content tagged with that term. It does not copy content, it just runs a SQL query against it. You can control it easily by activating the view 'Taxonomy term' that is installed but inactive. Through that view you can more easily control how the associated content is displayed.

There are also various hook and theme functions that you can implement to change the output, such as hook\_taxonomy\_term\_view\_alter, template\_preprocess\_taxonomy\_term etc.

Look at this post for more detail on that: Custom taxonomy term pages

There might be situations where you do not want your taxonomy terms to be links (to similar content tagged with that term). In that case you can set the field display formatter (which is link by default) to plain text.
> 1 votes

---
Tags: taxonomy-terms
---


# Question
Title: How to print the HTML content of the text field in Drupal 6 programmatically
I am printing the `$node->field_abc[0]['value']` in php code where node is node content and `field_abc` is text field .

How can I print the html format of the field in Drupal 6

# Answer
> 1 votes
You can use **content\_view\_field**

> content\_view\_field : Render a single field, fully themed with label and multiple values.

Code

```
$node = node_load('NODE_ID');
echo content_view_field(content_fields("field_example"), $node, FALSE, FALSE);

```

Reference

---
Tags: entities, 6
---


# Question
Title: Why isn't my programmaticlly created field showing up to be added to a content type
I'm trying to create a field that I can add to content types via my module, here is how I'm doing it:

```
/* Create the field to hold RSVP info */
function kade_rsvp_enable(){
    if(field_info_field(FIELD_REQUIRE_RSVP)) return; //field already created

    $field = array(
        "field_name" => FIELD_REQUIRE_RSVP,
        'cardinality' => 1,
        'entity_type' => 'node',
        'type' => 'list_boolean',
        'description' => 'Enable RSVP for this event?',
        'label' => 'Enable RSVP',
        'widget' => array(
            'type' => 'options_onoff',
        ),
        'settings' => array(
            'allowed_values' => array(
                '0' => 'No',
                '1' => 'Yes',
            ),
        ),
    );

    field_create_field($field);
}

```

And the field is getting created when the module is enabled. Here is the var\_dump of the field\_info\_field for it's id:

```
array(20) {
  ["entity_type"]=>
  string(4) "node"
  ["description"]=>
  string(27) "Enable RSVP for this event?"
  ["label"]=>
  string(11) "Enable RSVP"
  ["widget"]=>
  array(1) {
    ["type"]=>
    string(13) "options_onoff"
  }
  ["settings"]=>
  array(2) {
    ["allowed_values"]=>
    array(2) {
      [0]=>
      string(2) "No"
      [1]=>
      string(3) "Yes"
    }
    ["allowed_values_function"]=>
    string(0) ""
  }
  ["entity_types"]=>
  array(0) {
  }
  ["translatable"]=>
  string(1) "0"
  ["storage"]=>
  array(5) {
    ["type"]=>
    string(17) "field_sql_storage"
    ["settings"]=>
    array(0) {
    }
    ["module"]=>
    string(17) "field_sql_storage"
    ["active"]=>
    string(1) "1"
    ["details"]=>
    array(1) {
      ["sql"]=>
      array(2) {
        ["FIELD_LOAD_CURRENT"]=>
        array(1) {
          ["field_data_field_require_rsvp"]=>
          array(1) {
            ["value"]=>
            string(24) "field_require_rsvp_value"
          }
        }
        ["FIELD_LOAD_REVISION"]=>
        array(1) {
          ["field_revision_field_require_rsvp"]=>
          array(1) {
            ["value"]=>
            string(24) "field_require_rsvp_value"
          }
        }
      }
    }
  }
  ["foreign keys"]=>
  array(0) {
  }
  ["indexes"]=>
  array(1) {
    ["value"]=>
    array(1) {
      [0]=>
      string(5) "value"
    }
  }
  ["id"]=>
  string(2) "23"
  ["field_name"]=>
  string(18) "field_require_rsvp"
  ["type"]=>
  string(12) "list_boolean"
  ["module"]=>
  string(4) "list"
  ["active"]=>
  string(1) "1"
  ["locked"]=>
  string(1) "0"
  ["cardinality"]=>
  string(1) "1"
  ["deleted"]=>
  string(1) "0"
  ["columns"]=>
  array(1) {
    ["value"]=>
    array(2) {
      ["type"]=>
      string(3) "int"
      ["not null"]=>
      bool(false)
    }
  }
  ["bundles"]=>
  array(0) {
  }
}

```

However, it doesn't show up when I go to add it to a content type

What am I doing wrong?

# Answer
> 1 votes
You also need field instance to add that field to a content type.

> **field\_create\_instance()** : Creates an instance of a field, binding it to a bundle.

```

  // Create field.
  $field_name = 'field_rsvp';
  if (!field_info_field($field_name)) {
    $field = array(
      "field_name" => $field_name,
      'cardinality' => 1,
      'entity_type' => 'node',
      'type' => 'list_boolean',
      'description' => 'Enable RSVP for this event?',
      'label' => 'Enable RSVP',
      'widget' => array(
        'type' => 'options_onoff',
      ),
      'settings' => array(
        'allowed_values' => array(
          '0' => 'No',
          '1' => 'Yes',
        ),
      ),
    );
    field_create_field($field);

    // Create the instance.
    $instance = array(
      'field_name' => $field_name,
      'entity_type' => 'node',
      'bundle' => 'article',
      'label' => 'Enable RSVP',
      'description' => 'Enable RSVP for this event?',
      'required' => TRUE,
    );

    field_create_instance($instance);
  }

```

If you created a new field say for **article** content type, then you can see that field for other content types in the **Add existing field** field as mentioned in the comment by **tenken**

---
Tags: entities
---


# Question
Title: Views Php how to select actual term name not term ID
How to select term reference field with variables in views global PHP field? I need to not Term ID, but actual term name. My views is fields of a content type that contains term reference field. And php field selects term reference fields as term ID. But I need actual term name.

# Answer
You can either create a relationship with taxonomy in order for the term name to be available in views as a field, or use `taxonomy_term_load()`.
> 1 votes

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


title: Remove AJAX in views form (on change)

text:
# Question
Title: Remove AJAX in views form (on change)
I have a problem with a views form. It should only be submitted when I hit the submit button. Currently it is submitting when I change a value in any textfield. When I select "Using AJAX: no" it doesn't change anything. :/

Can somebody help me out here?

Thanks!

# Answer
> 0 votes
You have to change the settings in view as follows

1. Go to view and find Exposed Form (under Advanced).
2. Click on Settings

3.Uncheck 'Autosubmit' option to prevent 'Automatically submit the form once an element is changed'.

4.Click on Apply and save the view.

That's it.

# Answer
> 0 votes
It seems you use better\_exposed\_filters module. You can disable autosubmit in Exposed form style in your views.

---
Tags: views, forms, ajax, panels
---


# Question
Title: 3-rd decimal digit has disappeared in the output
I created a field, attached it to the entity: `coefficient_to_second_side`. Type in the database is decimal(10,3). Then I added a value: 1.001. When I select this field manually from the database, the value is correct. In the edit form it is correct:

But when I output the field on the entity page:

```
field_attach_prepare_view('event', array($entity->id => $entity), 'full');
entity_prepare_view('event', array($entity->id => $entity));
$entity->content += field_attach_view('event', $entity, 'full');

```

I get this:

```
Coefficient to second side:
1.00

```

The third digit has disappeared. How to fix?

# Answer
If you type of "Coefficient" is float, you can change scale in display options for your Content Type. (admin/structure/types/YOUR\_CT/manage/display). By default it's 2.
> 2 votes

---
Tags: entities
---


# Question
Title: Hide results of drupal view when filter value is empty after search
Help needed, how to hide all results of a view when filter value is empty, after search button pressed.

(I have this: Set Advanced | Exposed Form | Exposed Form Style to input required. Not working well. When open view OK, but for empty search field, and search button pressed all appear)

I know there are lot of solutions here: (5 years old) https://www.drupal.org/node/358546 but I can't find those options in views in Drupal 7.

Can somone provide a working solution for Drupal 7 and Views version 7.x-3.x?

Explain question, end the operator for VIN and kod sterownika set to: "is equal to"

# Answer
Ok till someone provide better solution

I create this one, and it's working :) It is important that i heave "is equal to" in VIN search field, so when I inject "X" as a value, if there is no conditions this will solve my problem.

```
function hook_views_query_alter(&$view, &$query) {

  if ($view->name == 'my_view_name') {

      //print_r($query);
      if (!isset($query->where[1]['conditions'][0] ))
      {
           $query->where[1]['conditions'][0] = array(
                                'field' => 'guarantee.vin',
                                'value' => 'X',
                                'operator' =>'LIKE'
                            );
      }
  }
}

```
> 1 votes

# Answer
Edit your view and then set the "Exposed form style" to basic.

Hope that helps!
> 4 votes

---
Tags: 7, views
---


# Question
Title: How to prevent drupal form's managed file upload ajax field from resetting the $form_state?
Edit: working code, although pretty ugly:

```
if (
        isset($form['submitted']['stelle']['#default_value'])
        && $form['submitted']['stelle']['#default_value'] !== ''
        && is_numeric($form['submitted']['stelle']['#default_value'])
        && !isset($form_state['stelle'])
    ) {
    $nid = $form['submitted']['stelle']['#default_value'];
    $node = node_load($nid);

    if ($node === false || (isset($node->type) && $node->type !== 'job')) {
        $redirect_form = true;
    }
    else {
        $type = $node->type;
        if ($type == 'job') {
            $form['submitted']['stelle']['#default_value'] = $node->title;
            $form['submitted']['stelle']['#attributes']['disabled'] = 'disabled';
            $form_state['stelle'] = $form['submitted']['stelle'];
            $form['submitted']['related']['#value'] = $nid;

            $unhide_components = array(
                'einleitung_standard'
            );
        }
    }
}
elseif (isset($form_state['stelle']['#default_value']) && $form_state['stelle']['#default_value'] !== '' && strlen($form_state['stelle']['#default_value']) && $form_state['stelle']['#default_value'] !== 'initiativ') {
    $form['submitted']['stelle']['#default_value'] = $form_state['stelle']['#default_value'];
}
else {
    $form['submitted']['related']['#value'] = 'initiativ';
    $form['submitted']['stelle']['#value'] = 'initiativ';
    $form['submitted']['stelle']['#attributes']['disabled'] = 'disabled';
    $unhide_components = array(
        'einleitung_initiativ'
    );
}

```

---

I am pretty much facing the same problem as this buddy here: https://www.drupal.org/node/2311199

I have a webform with 2 fields where users can upload a file to attach to the form. In the webform there is another field `stelle` which gets populated via `%get[stelle]` by webform. If it is set and a valid node id, a node gets loaded and the field `stelle` is set to that node's title.

However, when a user picks a file and clicks upload the ajax processing seems to reset that form state, completely removing that parameter.

When I just choose a file and dont click the upload button (so that no AJAX happens) and submit the form, everything works fine.

I followed the instructions of the above link but I it seems to be buggy: the ajax response returns the complete form again, not just the field itself.

Here is my original module:

```
<?php

/**
 * Altering the form! this will add class to the file upload/ remove buttons
 */
function mymodule_form_alter(&$form, &$form_state, $form_id) {
    if (isset($form['submitted']['lebenslauf'])) {
        // add css to the upload button
        $form['submitted']['lebenslauf']['#process'] = array('mymodule_my_file_element_process');
    }

    $nid = $form['#node']->nid;

    if (isset($form['submitted']['stelle']['#default_value']) && $form['submitted']['stelle']['#default_value'] !== '' && is_numeric($form['submitted']['stelle']['#default_value'])) {

        $nid = $form['submitted']['stelle']['#default_value'];
        $node = node_load($nid);

        if ($node === false || (isset($node->type) && $node->type !== 'job')) {
            $redirect_form = true;
        }
        else {
            $type = $node->type;
            if ($type == 'job') {
                $form['submitted']['stelle']['#default_value'] = $node->title;
                $form['submitted']['stelle']['#attributes']['disabled'] = 'disabled';
                $form['submitted']['related']['#value'] = $nid;

                $unhide_components = array(
                    'einleitung_standard'
                );
            }
        }
    }
    else {
        $form['submitted']['related']['#value'] = 'initiativ'; // this is always the case when using ajax
        $form['submitted']['stelle']['#value'] = 'initiativ'; // this is always the case when using ajax
        $form['submitted']['stelle']['#attributes']['disabled'] = 'disabled';
    }

    // ...
}

function mymodule_my_file_element_process($element, &$form_state, $form) {
    $element = file_managed_file_process($element, $form_state, $form);
    $element['upload_button']['#attributes'] = array('class' => array('button', 'light-grey'));
    $prefix = '<label class="browse-slave">';
    $prefix .= '<span class="button light-grey">' . t('Choose a file') . '</span>';
    $element['upload']['#prefix'] = $prefix;
    $element['upload_button']['#prefix'] = '</label>';

    $element['remove_button']['#attributes'] = array('class' => array('button', 'light-grey'));
    $element['remove_button']['#prefix'] = '</label>';

    return $element;
}

```

# Answer
Problem is not with managed file upload, but with your code. You simply ignored the fact that form building process may be invoked many times, if AJAX comes into play.

Simplest way is to add item to `$form_state`, store the node id there, and if it is set, use it instead of whatever is provided (or not) after AJAX call.
> 3 votes

---
Tags: forms, ajax
---


# Question
Title: Get a configuration option from node type structure
I'm working on a module and was wondering how to get a node type setting (that was set when creating the node type at: admin/structure/types/manage/YOUR-TYPE) inside a node creating/editing page.

I added a node structure setting with the hook: mymodule\_form\_node\_type\_form\_alter() and now I want to check if this option is active when creating/editing a node, hook: mymodule\_form\_node\_form\_alter()

# Answer
> 1 votes
Node type forms save their data in variable table prefixed with form field name and suffix will be node type.

If field was `$form['MY_SETTING']=array(...);` you can get the value with `variable_get('MY_SETTING_' . $node->type, '');`

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


title: How to remove entity type from drush?

text:
# Question
Title: How to remove entity type from drush?
How do I remove an entity type via drush?

List of entity types I can get via:

```
drush eval 'print_r(array_keys(entity_get_info()));'

Array
(
    [0] => node
    [1] => taxonomy_term
    [2] => comment
    ...

```

# Answer
> 2 votes
Entity types can't be generically deleted. First of all, *node* is entity type and can't be deleted using `node_type_delete`. You can only delete content type - and that's a *bundle* of entity called *node*.

To delete bundles that belongs to other modules, module providing entity type needs to provide drush command to delete bundle. You will find that command in module's documentation. And to remove entity type altogether, you need to disable and uninstall module that provides said entity type.

An Introduction to Entities may be a good read for you now. I advise caution, because it's status is "Needs technical review", but it covers basics nicely.

# Answer
> 1 votes
Entity types are provided by the modules (hook\_entity\_info), therefore the only way to remove them is to disable and uninstall the appropriate module.

---

**Troubleshooting**

* The following drush command finds the invalid entity types:

```
drush eval 'foreach (entity_get_info() as $entity_type => $entity_info) { !isset($entity_info[label], $entity_info[bundles]) && var_dump($entity_type, $entity_info); };'

```
* If you already disabled and uninstalled module and entity is still there, check if other modules (or custom code) are not using or referencing to it (e.g. hook\_entity\_info\_alter, views, fields, features, etc.).
* Rebuild the entities and caches via drush:

```
drush eval "entity_defaults_rebuild();"
drush -y cc entity
killall -HUP memcached # If you're using memcached.
drush -y cc all

```

---
Tags: drush, entities
---