title: Maintaining Old Drupal Versions

text:
# Question
Title: Maintaining Old Drupal Versions
Is there a list of best practices (or anything on drupal.org) for maintaining Drupal versions after end-of-life, specifically, when upgrading isn't an option? The best solution, of course, is to upgrade, but some organizations do not have the resources to make that happen.

I'd like to know some good practices here, especially when it deals with financial or private data.

The Drupal LTS project looks to be dead. I do my best to monitor info problems through things like CVE, but those sources seem to only mention exploits on the currently maintained branches.

# Answer
> 1 votes
I assume you're aware that Drupal 6 has been announced to be end of life as of Feb 24, 2016, as detailed in Drupal 6 end-of-life announcement. That mean that D6 will soon be considered as "old" also, right?

So looking at your question in this D6-context , I think "a" practise that may fit for D6 ("*when upgrading isn't an option*", as in your question) is to ***Buy Drupal 6 Long-Term Support (LTS) from one of the “official” vendors*** (up to you to decide if it is a 'good' or 'best' practise of course).

Moreover, as a variation of that "Drupal LTS project" that you mentioned, there now seems to be the D6LTS project.

For more details, refer to "What to do about Drupal 6 End of Life?". Some more details (from this link):

> **What, specifically, will happen after February 24th?**
>
> * All D6 modules will be marked as “unsupported” on Drupal.org - which will mean the ‘update’ module will start telling you that ALL your modules are out-of-date.
> * Also, the status information that the ‘update’ module uses could go away at any time - so, you’ll no longer be able to rely on that in general.
> * The Drupal security team will no longer be making Security Advisories (or coordinating security releases)
> * In general, most module maintainers will no longer pay attention to Drupal 6 issues and will stop making new releases.
>
> **What should people with Drupal 6 sites do?**
>
> * Archive the site, or
> * Plan upgrade.
> * Buy Drupal 6 Long-Term Support (LTS) from one of the “official” vendors.
>
> **What makes the “official” vendors special (vs. any other vendor)?**
>
> * Get confidential information from Drupal security team.
> * Agree to follow security team processes and release all security patches publicly.
> * Vetted by the Drupal security team.
>
> **How will the Drupal 6 LTS work?**
>
> * Same process as security team - but work done by vendors rather than security team.
> * Will publish patches on the D6LTS project.
> * Likely, but not 100% decided:
>     + Announce new patches on the D6LTS issue queue.
>     + Make new Pressflow 6 releases with the Drupal core patches.
>
> **Can the community get this without working with a vendor?**
>
> * Yes!
> * But each vendor only supporting those modules their customers depend on
> * Question: And what about security issues that hackers find first?

---
Tags: security, upgrading
---


# Question
Title: Override name of file field link in Drupal field.tpl template
I have a file download field in a node. The field displays as a simple link with the name of the file that will be downloaded, eg:

**picture.png**

What I want to do is rename the name on the link, i.e. I want it to stay the same but say:

**Download the picture**,

instead.

I have created a field--resource.tpl template, I don't know how to get started to get the name that is displayed overridden.

Here is what is in my field--field-source--resources.tpl file:

```
<div class="<?php print $classes; ?>"<?php print $attributes; ?>>
  <?php if (!$label_hidden): ?>
    <div class="field-label"<?php print $title_attributes; ?>><?php print $label ?>: </div>
  <?php endif; ?>
  <div class="field-items"<?php print $content_attributes; ?>>
    <?php foreach ($items as $delta => $item): ?>
      <div class="field-item <?php print $delta % 2 ? 'odd' : 'even'; ?>"<?php print $item_attributes[$delta]; ?>><?php print render($item); ?></div>
    <?php endforeach; ?>
  </div>
</div>

```

Thanks!

# Answer
There is an easier way to approach this without having to go through the template file:

On the 'edit' page for your content type, you can set it to 'enable description field'

which will add a new field to your content form that will let you override the label for the file, ex:

This should be easier than trying to parse the template approach and will work seamlessly with other modules that interact with the file field.
> 2 votes

---
Tags: nodes, entities
---


# Question
Title: Will Drupal 6 be left in a secure state after it becomes unsupported?
I created a custom database interface using Drupal 6 + Views \+ CCK that works really well for my company and recently I had to migrate it to another server.

I thought *"Hey, why not install Drupal 7 and then dump the database in it: then I can upgrade Drupal to the latest version while we migrate!?"*

That turned out to be a bad idea. Drupal 7 doesn't seem to have the slightest clue what to do with the DB info I gave it. And the upgrade guide looks very time consuming to me, right now.

So my question is: will Drupal 6 be left in a secure state after it becomes unsupported? Or will the platform become deprecated and vulnerable forcing an even more massive upgrade on me?

# Answer
I think until some of the major contributed modules like Views have Drupal7 modules that are stable and not alpha, beta I think drupal6 will be used for some time to come.

I'm certain that drupal6 will be supported for years to come as there are A LOT of drupal6 sites out there.

So the answer is No you don't HAVE to upgrade.
> 8 votes

# Answer
Once Drupal 8 comes out, Drupal 6 will be marked "end of life": the Drupal security team will stop working on it and official security releases won't come out for it. If any new vulnerabilities come out, you'll have to patch it yourself. So it's really in your benefit to upgrade at that point.

But upgrade paths for Drupal are from the previous version to the current version: that is, an upgrade path is provided from the last release of Drupal 6 to Drupal 7, and an upgrade path will be provided from Drupal 7 to Drupal 8.

There won't be an upgrade path for Drupal 6 to Drupal 8: if you don't want to rebuild your site from scratch when Drupal 8 comes out, you'll need to first upgrade your Drupal 6 site to Drupal 7, then upgrade to Drupal 8.

So, it really comes down to economics and long term planning. Drupal 6 will be supported until Drupal 8, but when Drupal 8 comes out in a couple of years, will you have an opportunity to rewrite the site? If not, you should plan to upgrade to Drupal 7 at some point in the future.
> 15 votes

# Answer
There are always 2 versions of Drupal supported at the same time. So when Drupal 8 will be released, Drupal 6 will become unsupported. There is some time left until that will happen, so you don't have to hurry.

If enough people are willing to continue patching security bugs, you might continue to use it safely even if it is not officially supported anymore. Anyone that wants to can continue to support Drupal 6 with security patches indefinitely, the question is whether enough people are interested in doing that. I would not count on Drupal 6 being still supported after the official release of Drupal 8.
> 4 votes

# Answer
Your original problem is that you don't want to spend massive amount of time upgrading your site - I can understand this well, but I would definitely recommend to do the upgrade. A couple of reasons:

* Sooner or later you will **have to** upgrade because Drupal 6's is nearing end of life.
* If you're working with Drupal sites, you'll benefit greatly if you learn how to do a major upgrade. Many people like me started with Drupal 6, so this is the first upgrade that we should be able to apply - it's valuable knowledge.
* You can "alter" the upgrade process written in the Handbook - ***nobody*** *mentioned that you should do that on one afternoon, for example...* If I were you, I would spend several hours with preparations, checking modules and themes, checking the core etc. and on the next day I would proceed with the upgrade in a test environment. This way you can have a little more comfort. The main thing is, **take notes of everything**. It's better to have each click documented (which would be crazy) than to have *nothing* written down. Try to enjoy doing this, the upgraded site will be better than ever!

And remember, we have a huge community with a lot of energy and support, so **talk about what you do, write a blog post or something** \- someone will benefit from it greatly, perhaps even you.
> 2 votes

# Answer
About 5 years after this question was asked, here is another answer based on what we know today ...

> Will Drupal 6 be left in a secure state, come the day that it is unsupported?

Drupal 6 has been announced to be end of life as of Feb 24, 2016, as detailed in Drupal 6 end-of-life announcement **(\*)**. So unless you take some appropriate actions, sites that will still be using Drupal 6 after that date are at risk of becoming insecure.

However, in the meantime the myDropWizard module has been released ... for D6 ... ***still***, and ***only*** !!!. Refer to "How to get accurate information about available security updates after End-of-Life?" for more details on that.

> Or will the platform become deprecated and vulnerable forcing an even more massive upgrade on me?

For situations where "*upgrading a D6 site isn't an option*", a possible alternative is to ***Buy Drupal 6 Long-Term Support (LTS) from one of the “official” vendors***. Moreover, there seems to be the D6LTS project. For more details on that, refer to the answer to How to proceed with a D6 site after Feb 24, 2016 when D6 is end of life?.

For those who wonder "*How many reported Drupal 6 installs do we have left?*", go check the Usage statistics for Drupal core (about D5, D6, D7, D8)... As of Jan 31, 2016, there seem to "*only*" be about 110K sites left (as compared to about 1046K for D7, and 64K for D8). That's about 40K less as compared to a year ago (at that rate it'll take another 3 to 4 years ...).

**(\*)**: this link also contains a lot of interesting comments, such as the very first comment below it, which is like so:

> By definition, a release on a project page is supported when two conditions exist:
>
> 1. the project maintainer believes it to be supported.
> 2. the security team is accepting reports of security issues and making advisories about it.
>
> That's what "supported" status means and has meant since May of 2009 (and reiterated in May of 2010).
>
> That is why item 4 is in this list:
>
> > **All Drupal 6 releases on project pages will be flagged as not supported.**
>
> As of the Drupal 6 EOL, item #2 will no longer be true so it makes sense to mark them as unsupported.
>
> This post about the EOL is the result of numerous conversations over the past 3 years about when the EOL should be. People who want Drupal 6 and/or contributed modules to be supported longer.
> 2 votes

# Answer
When a new Drupal version comes out, there is no attempt to make new builds "backward compatible" with old ones. Some fundamental things changed with Drupal 7, including the fact that what was the "CCK" module is now a feature in the core functionality of Drupal. So a Drupal 7 install won't know what to do with a Drupal 6 database, unless you follow the recommended upgrade procedure. (And even then, if you've customized any modules or written your own modules or templates, you will have some work to do to fully convert the application over.)

That said, no, you don't *have* to upgrade, at least not now. You are fine sticking with Drupal 6 up until Drupal 8 comes out, as others have pointed out. You could run a parallel Drupal 7 server on a MAMP or WAMP install on your own hard drive, and use it to practice porting your application to Drupal 7. Once Drupal 8 comes out, you should be ready to upgrade your application to Drupal 7 (and any other modules you've installed should have caught up with D7 by then).
> 1 votes

---
Tags: 6, security, upgrading
---


# Question
Title: Correct way to validate config entities?
In Drupal 8, how do I validate a ConfigEntity? I tried adding constraints, but then I found out this only works for ContentEntity, not ConfigEntity.

My ConfigEntity has 2 fields, and the options of the second field should be limited based on what's selected in the first.

Through Drupals #ajax mechanism I can limit the items in the second dropdown - that all works. However, with Javascript disabled or when creating the ConfigEntity programmatically, someone can still select a wrong value for the second dropdown, that doesn't work with the first dropdown selection. I checked ConfigEntityBase but couldn't find anything related to validation.

# Answer
> 5 votes
It depends on how your config-entities are created. If the only way to create them is via a form, then you could just override the `validateForm` method in your form to ensure the entity is valid. In this context the entity should be available by running this code

```
$form_state->cleanValues();
$this->entity = $this->buildEntity($form, $form_state);

```

This is what content entity forms do (see `\Drupal\Core\Entity\ContentEntityForm::validateForm`).

However if you expect your entities to be added programatically or via REST and you need lower-level validation, then you could add a `validate` method to you entity and call this from the preSave method. Having it available as a public method (`validate`) would allow other consumers of your API to check if the entity was valid before they called `save`, thus avoiding the exception.

In terms of the contents of the `validate` method, you have lots of options. You could try and piggy-back onto core's constraint system - which uses plugins to define constraints. Or you could keep it simple and just return an array of errors. Finally you could keep use a middle-ground and just integrate with the validator component in the Symfony way, which would at least keep your `validate` return consistent with those for Content entities - something like so:

```
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Component\Validator\Context\ExecutionContextInterface;
use Symfony\Component\Validator\Mapping\ClassMetadata;
use Symfony\Component\Validator\Validation;

/**
 * Validates my config entity.
 *
 * @return \Symfony\Component\Validator\ConstraintViolationList
 *   List of violations. Empty if valid.
 */
public function validate() {
  $validator = Validation::createValidator();
    ->addMethodMapping('loadValidatorMetadata')
    ->getValidator();
  return $validator->validate($this);
}

/**
 * Defines validation rules for this config entity.
 */
public static function loadValidatorMetadata(ClassMetadata $metadata) {
  // Same validator rules.
  // Add your own as required.
  // Note this is static, so you don't have $this in scope.
  $metadata->addPropertyConstraint('someProperty', new Assert\NotBlank(['message' => 'Some property cannot be blank']));
  // But if you add a validation callback, you can operate in the context
  // of an instance.
  $metadata->addConstraint(new Assert\Callback(['methods' => ['someValidationCallback']]));
}

/**
 * Validation callback for some field.
 */
public function someValidationCallback(ExecutionContextInterface $context) {
  if ($this->something === 'something it should not be') {
      $context->buildViolation("Can't let you do that Dave.")
      ->atPath('something')
      ->addViolation();
    }
}

```

---
Tags: 8, entities, forms
---


# Question
Title: Set a data value for a content field with rules
I am able to create a new content with rules whenever a user has been flagged as 'satisfied'. However, i need to fill in the fields as well with the flagged username, and some other fields in the flagged user profile. This i tried to do with 'set a data value' but the parameters doesn't seem to be available. Only 'site' and 'node' is available in d data selection field. Is there a way to 'fetch' the user profile of the flagged user and use it in the fields of the newly created contents?

# Answer
Solved by myself.

under the same rule (after a user has been flagged, )and after "create a new entity", I added 'set a data value' and chose 'entity-created:'. This then followed by the value "flagged-user:...".

If you understand my question, then you should understand my answer.lols
> 2 votes

---
Tags: rules
---


# Question
Title: How to add product details to Drupal Commerce order confirmation email
Default email that is sent when user completes the checkout process contains order number and other details. I want to include additional product details and product type in this email. How can I do that?

# Answer
> 1 votes
you can do that by using `php` code inside text message body.

```
$wrapper = entity_metadata_wrapper('commerce_order', $commerce_order);
    $line_items =  $wrapper->commerce_line_items->value();
    foreach($line_items as $line_item){
        $product = commerce_product_load($line_item->commerce_product['und'][0]['product_id']);
            echo "Product Title :".$product->title;
            echo "Product Title :".$product->type;
     }

```

# Answer
> 0 votes
You want the Commerce Message module and it's dependencies. It includes customer emails with a full order details, including customer profiles and all the products purchased.

---
Tags: commerce, rules
---


title: Find legacy id of newly created node

text:
# Question
Title: Find legacy id of newly created node
I have 3 non-drupal tables : items, item\_actions, actions.

```
 items(id, title, body, published_at);
 item_actions(item_id, action_id);
 actions(id, name);

```

I were able to migrate items to drupal 7. Now i want to migrate actions but since i don't know the node\_id of the newly migrated `items` just the `legacy id` it is throwing an error.
How do i find the node\_id knowing the legacy\_id so that it finds the right node and migrate related content.

```
$query = Database::getConnection('default', 'for_migration')
  ->select('actions', 'actions')
  ->fields('actions', array('id', 'name'))
  ->orderBy('id', 'DESC');
// Join values from the action_items.
 $query->leftJoin('action_items', 'ai', '(actions.id = ai.action_id)');
 $query->addField('ai', 'item_id', 'item_list');

```

Here is the error:

```
The referenced entity (node: 123456) is invalid.

```

**update**
The migration was done with the migration module. So i had to write class migration and use queries like the one above to migrate to D7 the items table.
Can i create a table in the drupal DB and add the ids(old and new) for example: migrate\_nodes(legacy\_id, drupal\_node\_id) .
How do you capture the node\_id?
I am new to drupal so this is still a learning process, thanks.

# Answer
How did you migrate the content from the nond-drupal tables to nodes? Module or custom code?

I would suggest a 'custom' migration routine/module (if it is a lot of data you can do this as a cron and/or batch job - that is a separate discussion).

Any case, in your custom routine, when you migrate each record (so read a record form your table and create a new node) from items and actions - you will be able to 'capture' the node id (nid) if the new node. Save this value to your 'old' items/actions tables (new field required). Now when you step through your item actions table you can use the nid saved in items and actions as reference values.
> 0 votes

---
Tags: 7, entities, migrations
---


# Question
Title: How to dynamically create Drupal 7 tables based on form API input values?
I have an array with the data below:

```
arr_fields[0] = 'a bigint'
arr_fields[1] = 'b bit'

```

I want to structure it just like the array structure below:

```
$fields = array(
            'a' => array(
                'type' => 'bigint',
            ),
            'b' => array(
                'type' => 'bit',
            )
);

```

Below is the rest of the code and it's working fine.

```
$schema = array(
    'description' => t ('Contains a particular templates data inputted from the MyID Inputting System'),
    'fields' => $fields,
);

db_create_table('myid_template_' . $template_id, $schema);

```

I tried the code below to structure it like the above, but it throws an error

```
foreach ($arr_fields as $value) {
    $arr = explode(' ' , $value);
    $fields[$arr[0]] = array('type' => $arr[1]);
}

$schema = array(
    'description' => t ('Contains a particular templates data inputted from the MyID Inputting System'),
    'fields' => $fields,
);

db_create_table('myid_template_' . $template_id, $schema);

```

An error says:

```
<em class="placeholder">PDOException</em>: SQLSTATE[42601]: Syntax error:  7 ERROR:  syntax error at end of input
LINE 4: )
     ^: CREATE TABLE {myid_template_489} (
a ,
b
); Array
(
)
in <em class="placeholder">db_create_table()</em> (line <em class="placeholder">2720</em> of <em class="placeholder">C:\xampp\htdocs\drupal-7.34\includes\database\database.inc</em>).

```

How should I structure it?

```
foreach ($arr_fields as $value) {
    $arr = explode(' ' , $value);
    $fields[$arr[0]] = array('type' => $arr[1]);
}

```

UPDATE 1:

Here's my form input pass through AJAX POST method:

# Answer
> 1 votes
As I read the output of the error message, I suppose the values you are trying to parse do not contain the type of the database field.

Did you check your PHP error log as well? There might be PHP warnings, stating that $arr\[1\] is not set.

Verify your parsed values and make sure they contain the type information.

An additional note: I do not know your special use case. But creating a new table on each template might easily bloat your database structure. Maybe you find a better solution to store your information within one dedicated table, using your template ID as identifier and serialized arrays holding the information?

---
Tags: 7, forms, database
---


title: Grouped exposed filter is not available

text:
# Question
Title: Grouped exposed filter is not available
I'm trying to create a filter within a view, which has multiple ranges;

i.e.

* 0-99
* 100-399
* 400-699
* 700-1000

I have seen this before when you *Add filter criteria*, you can select *grouped exposed filter* and I can set up the ranges in there. But in this instance, this option is not there and I'm not sure why not.

In the drupal code I found Drupal API which counts the options in `$this->operator_options()` \- But I don't know what `$this->operator_options()` is meant to contain, or how you go about adding items to it through the back-end.

# Answer
> 0 votes
Did you try Facet API filters? check the Facet API module

> The Facet API module allows site builders to easily create and manage faceted search interfaces. In addition to the UI components that come out of the box, themers and module developers can build their own widgets that can optionally be contributed back to Drupal.org. Facet API works with the core Search, Search API, and Apache Solr Search Integration modules (including Acquia Search) meaning that code and configuration can be reused as-is with the most popular search solutions available to Drupal. Refer to the documentation for more details.

---
Tags: 7, views
---


# Question
Title: Is there a module that can "lazy load" content, not just images?
Utilizing the JAIL module I can lazy load images. Is there any module that lets me do this for content as well (i.e. only load portions of the page that are in the current viewport)?

# Answer
You can try out infinite scroll. It (lazy)loads the content as you scroll through the page.
> 1 votes

# Answer
I recently made a jQuery plugin that will "lazy load" anything you want. When the jQuery selector elements come into view of the browser viewport it will for a load event which you can stuff full of jQuery/Javascript goodness.

https://github.com/shrimpwagon/jquery-lazyloadanything
> 1 votes

# Answer
You can try Node Lazy Loader which lazy loads all nodes in site with multiple nodes in a site.
> 0 votes

---
Tags: 7
---


title: How do I implement georeferencing?

text:
# Question
Title: How do I implement georeferencing?
I must make a website with geo-referenced content. And I would like to add POI and the possibility to download this POI for GPX, KML\KMZ (Google Earth), etc.

Do you have any tip or idea on how to implement this somehow?

# Answer
> 2 votes
Have a look at the IP Geolocation Views & Maps module. Partial quote from its project page:

> Despite what the name may suggest, IP Geolocation Views & Maps (IPGV&M) is first and foremost a mapping engine.
>
> The module makes it very easy to create Views-based mapping solutions using the map renderer of your choice (**Google**, **OpenLayers** or **Leaflet**) with any location storage module of your choice, e.g.:
>
> This allows you to bring together modules and feature sets that without IPGV&M you would not be able to combine.
>
> Like beautiful animated marker clustering on Google or Bing or Mapbox ... any of various map providers.
>
> But more importantly IPGV&M adds some features you won't find as conveniently packaged elsewhere.
>
> These include marker differentiation based on field values or ranges (2nd screenshot) with or without font icons, various centering options, super-imposing the current visitor's location, allowing multiple content types to be displayed on the same map, full screen button and mini-map inset (bottom screenshot), polygon support (Geofield), marker tags and tool tips and cross-highlighting of associated content on the page when markers are hovered (and vice versa).

Head over to its (impressive) project page for even more information about it which also includes various screenshots.

# Answer
> 2 votes
If you want to use an existing module - something like GMap is probably the easiest place to start.

That being said, the Google Map API is fairly easy to use, so nothing preventing you from writing a module that does exactly what you want.

---
Tags: 7, location, google-maps
---


# Question
Title: How to programmally add nodes with next nid?
i want to create multiple nodes (from csv file) the csv is loaded well, and my table `node` contains many old records (with `nid` from 1 to 170) what i want is to record the csv's new nodes with nid strating from the last one on table `node` (the new nodes would start from 171 on nid) I've tried `db_last_insert_id()` with no success.

This is my `db_merge` part :

```
 $nodes = db_merge('node')
        ->key(array('nid' => last_insert_id()))
        ->fields(array(
            'type' => 'livre',
            'uid' => 1,
            'status' => 1,
            'comment' => 1,
            'promote' => 0,
            'title' => $new_array['titre_csv']<===from csv
        ))
        ->execute();

```

# Answer
Try this way:

```
  $node = new stdClass();
  $node->title = $new_array['titre_csv'];
  $node->type = "livre";
  node_object_prepare($node); // Sets some defaults. Invokes hook_prepare() and hook_node_prepare().
  $node->language = LANGUAGE_NONE; // Or 'fr' in your case
  $node->uid = $user->uid;
  $node->status = 1; //(1 or 0): published or not
  $node->promote = 0; //(1 or 0): promoted to front page
  $node->comment = 1; // 0 = comments disabled, 1 = read only, 2 = read/write
  $node = node_submit($node); // Prepare node for saving
  node_save($node);
  //save the other table

```

If you want to save it in your custom table you can do a db\_insert or EntityFieldQuery.
In that case $node-\>nid value will be taken after you do the node\_save (so do it after you save it with node\_save).
You could also use a hook\_schema for your table.
> 7 votes

---
Tags: 7, nodes, database
---


# Question
Title: Getting the value of a taxonomy term reference field
I have a content type (*Movie*) with a taxonomy reference (*Movie rating*) for which can get multiple values. I would like to use the template node--movie.html.twig and get the first value inserted in the taxonomy term.

I tried using the following code, but it doesn't give any value.

```
{{ content.field_rating['#items'].getValue()|first.value }}

```

What am I doing wrong? In which way do I reference the taxonomy term value?

# Answer
I got the answer of my problem.

Actually first i wanted to show only label or title of term just in my node template. To get the title of first term is like below -

```
{{ content.field_rating[0]['#title'] }}

```

OR

```
{{ node.field_rating.0.entity.label }}

```

But I got to know that I have to show entire term (comma separated ) with link of term as well. The code below works -

```
{{ content.field_rating[0] }}
{% for key, value in content.field_rating %}
       {% if key > 0 %}
           {{ ' , ' }}
           {{ content.field_rating[key] }}
        {% endif %}
{% endfor %}

```
> -1 votes

# Answer
You get the first item out of \['#items\] with a "0":

```
{{ content.field_rating['#items'].0 }}

```

To get a field from the taxonomy term, I would use the node object, because you don't know how the render array in content will change if you configure the view mode differently:

```
{{ node.field_rating.0.entity.term_field.value }}

```
> 7 votes

---
Tags: theming, 8
---


title: Editable webform fields in views

text:
# Question
Title: Editable webform fields in views
I'm using drupal 7.41 and have used Webform for my leave applicaiton form and there are such approvals fields that I've displayed in views, I'd like to make it editable in views by checking multiple records and it can be approved on views list page, can anybody please suggest some hints?

# Answer
> 1 votes
```
function hook_views_post_execute(&$view) {
  // If there are more than 100 results, show a message that encourages the user
  // to change the filter settings.
  // (This action could be performed later in the execution process, but not
  // earlier.)
  if ($view->total_rows > 100) {
    drupal_set_message(t('You have more than 100 hits. Use the filter settings to narrow down your list.'));
  }
}

```

---
Tags: views, webforms
---


# Question
Title: When does the computed field get calculated?
I don't understand when a computed field computes. Does it compute when the fields it draws on are updated or when someone views the node it's used in?

# Answer
From Computed Field Module:

Computed Field is a very powerful CCK field module that lets you add a custom "computed fields" to your content types. These computed fields are populated with values that you define via PHP code. You may draw on anything available to Drupal, including other fields, the current user, database tables, you name it. (Feeling the power yet? :) ) **You can also choose whether to store your computed field values in the database with other content fields, or have them "calculated" on the fly during node views.** (Although you should note that Views use requires database stored values.) This field is literally the Swiss Army knife of CCK fields. So start cooking up your PHP based values!

In the documentation page ( http://drupal.org/node/126522 ) it also says:

**When is the field actually computed?**

If you wish to store the values in the database then you have to update or re-submit the node to compute the value of the field.

If it is not stored in the database then the value computes when the node loads and only when the node is loaded. The field will not work in views nor will it function properly if it depends on other non-stored computed fields.

More information from drupal.org and what appears to be a good page of snippets is http://drupal.org/node/149228
> 2 votes

# Answer
These days (more then 3 years after this question was asked), there is a NOT commonly known/used alternative available for the Computed Field module, i.e. the (fairly new) Math Field module (for D7). Some more details about this module (from its project page), which also details when the calculations actually happen:

> The Math Field module defines a new field type to dynamically calculate values on entity forms. **This is an alternative to Computed Field that does not require the use of PHP Filter.**
>
> Math expression fields are dynamically updated via ajax on the entity form as soon as all necessary fields are populated. If JavaScript is disabled, the field will be evaluated when the form is submitted. The result is stored in the database when the form is submitted.

For more details (step-by-step instructions), refer to either of these links:

**Known issues**

As this is a fairly new D7 module, there are still a few (known) issues with it, as mentioned also on its project page:

**Bonus**: you would not need the "PHP filter" (IMO only that should be a valid reason to investigate this alternative) ...
> 2 votes

---
Tags: entities
---


# Question
Title: How to get devel content generate module to only include one image per dummy content creation
I'm using devel generate and it randomly adds multiple images to articles.

I can limit the number of words in the title.

Is there an option to limit number of images or text lenght?

# Answer
> 1 votes
you can set the image upload limit in field setting itself.

-Anas

---
Tags: debugging
---


# Question
Title: I need a way to automatically make Panel layouts responsive
Before I asked this question I did a humble Google research for several times but I really couldn't find any efficient solution for this problem. I consider a working answer to be a grace with the community:

Until now, I haven't had many panels in my sites (say no more than 1-2 mini Panels + 1 panel page, per site). I made each Panel responsive by per block elements. I must say that could take some time and it's surly not an efficient solution when you have many panels in your site...

Therefore, I am looking for a way to automize this process - Instead of making any panel layout responsive manually, I need a way (maybe even a **general CSS** code piece if not a **module**) just to ensure my panel layouts will be responsive, and an example would be:

instead of width: 50%+50% or 33%+33%+33% float\text-align: right\left, all will be centered).

So, how can you to "Auto-responsify" all existing panels, including all panels to come, in a site?

# Answer
I think the closest you're going to get to out of the box is Panels Extra layouts, which ships with a bunch of adaptive layouts.

Other than that, your best bet is just to create a bunch of custom layouts by yourself, with their respective templates. The documentation is not bad for that; you can find it here: Panels 3: Creating a custom layout in your theme. Alternatively, just look in the Panels codebase for their implementations.
> 3 votes

# Answer
The Zen5 base theme ships with ZenGrids, which is a responsive mobile friendly grid system and I think it has it's own panels layouts.

Actually I've taken a look at the current release and it does have one panels layout but it's not what you're looking for. It also has some theme overrides for panes and panels pages.

It's not the role of the Panels module to have responsive layouts. The Panels builtin layouts are based on concepts of 'rows'. Your theme should pick up the HTML and turn those rows into stacks. Zen is a good place to start. And it might stack those rows out of the box. For example check out the `responsive.scss` file in `zen/STARTERKEIT/sass/layouts`.
> 0 votes

# Answer
There is a way by using Panels bootstrap layouts module. Module adds Bootstrap layouts to Panels. It uses Bootstrap grid as a base and you can define your own settings for columns.
> 0 votes

---
Tags: panels, theming
---


# Question
Title: Why is the drupal.org site not using the more recent Drupal version?
Seems to me that if drupal.org is encouraging people to use Drupal 8, that they should be leading by example and migrate their own site to Drupal 8.

On drupal.org:

```
<meta name="Generator" content="Drupal 7 (http://drupal.org)">

```

Is there a reason why they've released Drupal version 8 but they themselves are still using Drupal version 7? Should the fact that *they* have not migrated give us any suspicious reasons why we shouldn't quite yet?

# Answer
> 19 votes
Drupal.org is huge website the migration can take some time. The migration from Drupal 6 to Drupal 7 was finally done 2 years ago and it took forever. Moving forward to Drupal 8 is going to take a lot time. I do not see that happening like in 3 to 4 years.

Moving to Drupal 8 is not a higher priority right now for Drupal.org, compare to adding new features and improving the current website.

Drupal.com is a smaller website is been running Drupal 8 since Beta.

# Answer
> 10 votes
There is a lot of infrastructure and dependencies on the drupal.org site, which also exist outside of the core drupal code base. Such as git integration, issue queues, testbot, project hosting. These contrib modules aren't all yet updated to drupal 8 to my knowledge.

For an idea of what is going on with the drupal.org site I recommend reading: https://groups.drupal.org/drupalorg

# Answer
> 3 votes
# About drupal.org

Here is a quote from the Drupal.org Roadmap:

> ... Each year Drupal.org and its sub-sites serve millions of visitors, and thousands of active contributors. It is one of the largest continuously operating Drupal sites in the world. And because of that, it has 15 years of legacy content and features. At this scale, it's impossible to make real improvements to Drupal.org without a prioritized roadmap, focusing on a few, high impact features at a time. ...

To understand what the D8 "*upgrade challenge*" would be about, have a look at these **drupal.org projects** (quotes are from the links):

* Webmasters

> A project with issue tracker that you can use to report spam, broken links, or user account problems on Drupal.org website.
* Content

> A project with issue tracker for Drupal.org non-documentation content organization and moderation. This is a place for issues about marketplace listings (services, training and books), case studies, front page promotion requests, planet drupal feeds, etc.
* Documentation

> This is the main project for all Drupal documentation. To learn more about helping with documentation efforts, start with the Contribute to documentation section of the handbook.
* Customizations

> Customizations used on drupal.org itself. It is not meant to be useful to other sites, except as an educational example of the kinds of modifications you can make via a site-specific module.
>
> More information about the state of planned work on Drupal.org can be found on the Drupal.org Roadmap.
* Theme

> Bluecheese is the redesigned Drupal.org theme ... This theme is only for use on official Drupal.org sites. Do not use this for businesses, local groups and other sites, which should have their own brand and identity. Questions and comments about use of this theme should go to the Drupal Association ...
* Infrastructure

> An issue tracker for everything related to the Drupal.org servers. This includes the Apache and MySQL installation, the Mailman mailing lists, the Git repositories, and the various Drupal installations on the drupal.org domain.
* Testbots

> This project is a place for issues to be filed or questions to be asked about the Drupal.org testbots and all the projects related to them. Since there are so many d.o projects involved it seems that most people just need a one-stop shop for issues. They can be moved out from here.
* Groups

> This project has two purposes.
>
> 1. It is like the drupal.org customizations project to hold site specific code.
>     2. It is like the Infrastructure and Webmasters queues but is specific to groups.drupal.org. So, where people used to enter things into those queues with a Component of groups.drupal.org they can now enter them here.

# About the upgrade challenge

With the above in mind, I think there are dozens of reasons which Drupal.org is not using D8 yet, here are just a few of them (in a random order):

* This site is **mission critical** for quite a few of us, so *failure is not an option*.
* There must be quite a few **contributed modules** that are needed, but for which the D8 release isn't there yet. Not sure if they use/need all of them, but I bet these are some of those modules: Project, Organic groups, Migrate (D7 to D8), something for charting, maybe Rules, Flag, etc ... True, modules like Views, etc are in D8 core now, and you can get pretty far already only using Drupal core, but I doubt drupal.org doesn't need some of the modules like the ones above.
* You need the **manpower** for it, with appropriate skills (D8 is a bit different from D7, right?).
* You need **infrastructure** to run D8 sites (PHP version, memory, etc).
* I bet there is "*some*" **custom code** involved for running Drupal.org, and upgrading custom code has never been easy.
* And there is a need for things like **QA-testing**, or **documentation**, etc.
* From my quote above it seems there are other priorities, so upgrading to D8 seems to be like **not a priority**.
* I bet there are other things that have a higher priority, e.g. "The forums need improving".
* Even if none of the above were blocking it all, think about the purely **accounting** part of it (I can't imagine the yearly write-offs for the *recent* D7 upgrade are finished already).

# What's next

For all these reasons, I think at this very moment the best we can do is "***Hope for George to do it***" (the one from the keynote from Dries at DrupalCon Amsterdam 2014 when the very first beta1 version of D8 was announced).

**PS**: One never realizes what **has been done**, only what **remains to be done**.

---
Tags: community-official-site
---


# Question
Title: Delete query is called while updating the value of node
Delete query is called while updating the cck field value of node.

After debugging i find following code in

> var/www/drupal-7.40/modules/field/modules/field\_sql\_storage/field\_sql\_storage.module

in field\_sql\_storage\_field\_storage\_write($entity\_type, $entity, $op, $fields)

we have following code

```
// Delete and insert, rather than update, in case a value was added.
if ($op == FIELD_STORAGE_UPDATE) {
  // Delete languages present in the incoming $entity->$field_name.
  // Delete all languages if $entity->$field_name is empty.
  $languages = !empty($entity->$field_name) ? $field_languages : $all_languages;
  if ($languages) {
    db_delete($table_name)
      ->condition('entity_type', $entity_type)
      ->condition('entity_id', $id)
      ->condition('language', $languages, 'IN')
      ->execute();
    db_delete($revision_name)
      ->condition('entity_type', $entity_type)
      ->condition('entity_id', $id)
      ->condition('revision_id', $vid)
      ->condition('language', $languages, 'IN')
      ->execute();
  }
}

```

May be someone explain why ? And also can i use update Query instead of delete, insert ?

# Answer
As the comment at the top states: Delete and insert, rather than update, in case a value was added.

So to make sure all old data is cleared, the records are deleted and re-added with new data (as you can see on line `481: $query = db_insert($table_name)->fields($columns);`.

Of course you could use the update query, but this query would need to contain all fields because it is impossible to know which fields are added, modified or deleted. A simple delete and add solves that problem.
> 1 votes

---
Tags: 7, entities, database
---


# Question
Title: Is there an easy way to move nodes into a language section?
I have a site in English, with few nodes in Arabic, Aramaic, and Hebrew.

Is there a way to move each group of nodes into a language section, from the user interface?

All the nodes are created in the same site and they could share their content type.

# Answer
> 4 votes
You can do this only using the Pathauto module

Use as replace pattern in admin/config/search/path/patterns:

```
[node:language]/[node:title]

```

Then go to admin/config/search/path/delete\_bulk and delete all the aliases

And go to generate the new aliases at admin/config/search/path/update\_bulk

# Answer
> 4 votes
From your comments I understand that you want to display URLs based on languages.You can achieve that by simply editing each node and edit URL alias (under URL path settings) for each node.

If you have bunch of nodes and want to change the all URL aliases at once, follow the steps

1) Install and Enable Pathauto and Views Bulk Operations (VBO) modules.

2) Define Path alias patterns in URL alias settings (admin/config/search/path/patterns)

3) Create a view with Views Bulk Operation field and select "Update node alias" option.

From the View output you can generate Auto paths for selected nodes in one click action.

# Answer
> 1 votes
I suggest to install rules and views bulk operation. Make a component in order to change language of your selected nodes. (you must configure your component)

And then make a view with vbo checkbox and run your component for all selected node in a views result.

---
Tags: 7, nodes, i18n-l10n
---


# Question
Title: Webform multipage - different page.tpl for different page
Is it possible to use specific `page.tpl` for webform pages?

For example: `page--form1.tpl` for page 1 and `page--form2.tpl` for page 2.

I wanted to do this via URL but it's same on all pages.

Any ideas?

# Answer
> 0 votes
I don't think you can do this on page level. Can't you use form templates? In that case you could add your own theme functions. Here's an example:

```
/**
 * Implements hook_theme().
 */
function YOUR_TEMPLATE_OR_MODULE_theme() {
  // Add our own webform theme function, copied from
  // webform_form in webform.module.
  $theme = array(
    'webform_form_page' => array(
      'render element' => 'form',
      'template' => 'templates/webform-form',
      'pattern' => 'webform_form_[0-9]+_[0-9]+',
    ),
  );
  return $theme;
}

/**
 * Implements hook_webform_form_webform_client_form_alter().
 */
function YOUR_TEMPLATE_OR_MODULE_webform_form_webform_client_form_alter(&$form, &$form_state) {
  // Check if we are on another page then 1 in a webform.
  if (isset($form_state['storage']['page_num'])) {
    // Add our own theme including the page number.
    $form['#theme'][] = 'webform_form_' . $form['#node']->nid . '_' . $form_state['storage']['page_num'];
  }
}

```

You should now be able to create your own tpl file per form page. It would look something like this: **webform-form-626-2.tpl** where 626 is the node id and 2 is the page number. For the first page you should just use **webform-form-626.tpl.php** so it also functions as a fallback template.

I haven't tested this so you might need to tweak it a bit but I hope this puts you on the right way.

---
Tags: theming, webforms
---


title: Show blocks based on parent URL context

text:
# Question
Title: Show blocks based on parent URL context
We are looking for a way to show banners on pages based on their URL parent. There are multiple banners in use, and each page should display a banner based on its parent page. We want to build this into the theme, if at all possible.

So, for the Programs section, the Programs banner should display. However, within Programs there are named Programs with their own banners, such as "Great Program" and "Program For Winners" which each have their own sub-pages. When on those sub-pages, we want only the banner for the specific program to show.

**/programs** \- Show Programs banner (top-level parent)

**/programs/all** \- Show Programs banner

**/programs/great-program** \- Show Great Program banner (second-level parent)

**/programs/great-program/about-great-program** \- Show Great Program banner

**Note**: I'm using D7, and probably using blocks, maybe Views. Open to all suggestions.

# Answer
If you'd implement those banners via blocks, then you might be able to get it to work using the Rules block visibility module. Here is a quote from its project page:

> The Rules block visibility module allows Rules components to be used to control block visibility. This provides Drupal administrators and developers extreme flexibility in controlling when blocks should be displayed on their websites, in addition to the default visibility options provided by Drupal.
>
> The general idea is that if you can do it with Rules, you can use it to control block visibility, so the possibilities are limitless.
>
> Need to show a block only for users registered more than a month ago?
>
> Perhaps you have a block that must be shown only between 8am-5pm on weekdays?
>
> What about displaying or hiding a block based on current weather conditions?
>
> All of this can be done by using Rules block visibility.

With that, and as per the "*if you can do it with Rules, you can use it to control block visibility*" above, you've reduced your question to making Rules intercept the various URLs corresponding to each of those banners.

If you're not familiar with how to do that with Rules, then have a look at my answer to the question "How to make the permissions of a module more granular?" (and pay attention to the regex-expression included in the sample rule I included there).
> 0 votes

---
Tags: 7, blocks
---


# Question
Title: HELP! Can't make glossary using taxonomy term name
I'm using Drupal 8.0.2 and I'm trying to create a glossary of taxonomy terms by name. I have setup the view as follows:

* Unformatted list
* Fields: Taxonomy term: Name
* Filter: Taxonomy term: Vocabulary (= Fruit Name)
* Sort: Taxonomy term: Name (asc)

Stopping here the preview shows all Fruits by name (a-z) as expected.

Now when I add the following Contextual Filter:

* Taxonomy term: Name
* Type: Fixed
* Fixed value: a
* More: Glossary mode
* Character limit: 1

The preview is empty, and the page returns a 500 error. I have done this successfully many times using Content: Title, but it never works using Taxonomy: Name. Can anyone tell me why this won't work using taxonomies?

# Answer
> 0 votes
This appears to be a bug in D8 core. Here is a link to the issue:

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

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


# Question
Title: Context Module - not triggering menu active
I need the menu called "Questionários" to be active/visible (and styled in different color) only for the node 115.

I've installed the **context module** and tried to use the path pointing to my node but it didn't work.

Here's a print (some things are in Portuguese but I hope you can understand):

Thank you!

# Answer
> 0 votes
The patch is here: https://www.drupal.org/files/issues/context-fix-menu-reaction-2374445-16.patch

It will fix the issue for the main menu set as a block.

---
Tags: 7
---


# Question
Title: /admin/* pages "The website encountered an unexpected error"
After two clean installs of Drupal 8.0.2 without issues on my server (Debian 7.1 / PHP 5.6.17 / MySQL 5.5.31) I can log in and out fine and view my user profile page, but that's it.

Any /admin/\* pages returns the following error:

> The website encountered an unexpected error. Please try again later.

I'm a little stuck as effectively I can't do anything and this wasn't an issue locally on WAMP. Can someone offer me guidance please? I've had a look for error logs on the server but unless I'm looking in the wrong places I'm not seeing anything.

Database watchdog shows the following error. (The serialized array has been edited to show the relevant parts.)

> GuzzleHttp requires cURL, the allow\_url\_fopen ini setting, or a custom HTTP handler.
> GuzzleHttp\choose\_handler()
> /var/www/virtual/mysite.info/drupaltest/htdocs/vendor/guzzlehttp/guzzle/src/functions.php"; line 116

As suggested in other similar posts I have tried increasing `max_allowed_packet`.

# Answer
> 0 votes
Just to get this marked off as answered (with thanks to Clive).

First of all was understanding how to make use of the database watchdog table to find the errors. You have to download and view the variables column... the error's in there. In my case it was that cURL was not installed.

It was as simple as installing cURL and restarting the Apache service.

```
apt-get install php5-curl

```

Thanks again to Clive!

---
Tags: 8
---


# Question
Title: How do I call a controller function in a module?
I am trying to access a static method of a controller class from a module, but my code doesn't work.

This is the controller class.

```
namespace Drupal\content_statistics\Controller;

use Drupal\Core\Controller\ControllerBase;

class ContentStatisticsCount extends ControllerBase {

  public static contentStatisticsCount() {
    $value = $this->t('hi');
    return $value;
  }

}

```

This is the module code.

```
use Drupal\Core\Controller\ControllerBase;
use Drupal\content_statistics\Controller;

/**
 * Implements hook_node_view().
 */
function content_statistics_node_view($node, $display, $view_mode, $langcode) {
  $value = ContentStatisticsCount::contentStatisticsCount();
  print_r($value);
  die;
}

```

This is giving me the following PHP error:

> PHP Fatal error: Class 'ContentStatisticsCount' not found in /home/qbuser/Projects/test/modules/custom/content\_statistics/content\_statistics.module on line 15

# Answer
If you want to define a controller, then don't use a static method:

```
namespace Drupal\content_statistics\Controller;

use Drupal\Core\Controller\ControllerBase;

class ContentStatisticsController extends ControllerBase {

  public function count() {
    $value = $this->t('hi');
    return $value;
  }

}

```

The use statement should import the class, not the namespace. But this is not the only problem.

If you want to use a controller class in a hook, create an instance of the controller and use the method of that instance:

```
use Drupal\content_statistics\Controller\ContentStatisticsController

$statistics = new ContentStatisticsController;
$value = $statistics->count();

```

Your class and method had the same name, I split the name in a controller class name and the method count().
> 10 votes

---
Tags: 8
---


# Question
Title: Implementing a search and results page in the admin interface
I'm trying to implement a search and results form in the admin interface but I am having trouble getting the search function and pager working.

\[1\] The pager is not showing at all. I've got this working using db\_select for the query but I'd like to use a solr query. How can I get a pager to display?

\[2\] The form submission is not working as expected either. On submission the page is redirect to the correct url but an error message is displayed: The requested page `'/admin/monitor/custom/search/?q=foobar'` could not be found. Do i have to declare a separate menu route /admin/monitor/custom/search/% to handle searches?

Many thanks,

```
function custom_menu(){
    $items['admin/monitor/custom/search'] = array(
      'title' => 'Custom',
      'description' =>'Custom search form',
      'page callback' => 'drupal_get_form',
      'page arguments' => array('custom_form'),
      'access arguments' => array('administer site configuration'),
    );
    return items;
}

function custom_form($form, &$form_state){

    $table = build_results_table();

    $form['keyword'] = array(
      '#type' => 'textfield',
      '#description' => t('Search database by keyword'),
    );

    $form['submit'] = array(
      '#type' => 'submit',
      '#value' => 'Go!'
    );

    $form['results'] = array(
      '#markup' => $table,
    );

    return $form;
  }

function build_results_table($search_term){

    // perform query using Solr Search API
    // page number from $_GET('page')
    // search limit from a variable set by another module
    $results = query_database();

    $header = array('Firstname', 'Middlename', 'Surname');

    $rows = //... build rows from $results ...;

    $table = theme('table', array(
      'header' => $header,
      'rows'=>$rows,
    ));

    pager_default_initialize($table);
    $table .= theme('pager');

    return $table;
}

function custom_custom_form_submit($form, &$form_state){

    $keyword = $form_state['values']['keyword'];
    drupal_set_message(t('Showing results for %keyword',
    array('%keyword' => $keyword)));

    $form_state['redirect'] =
    '/admin/monitor/custom/search/?q='. $keyword;

}

```

# Answer
> 1 votes
1. Drupal only has only pager implementations for DB queries, but you can use the pager system manually for data in external sources. There are a couple of examples on the `pager_default_initialize()` docs that should get you started.
2. Anything other than `q` as the param name should work - Drupal uses `q` as the path param in its rewrites, so it's probably trying to find a route of `foobar` in your example.

---
Tags: 7, forms, search, paging
---


# Question
Title: 8 autocomplete pass current value to function
I am trying to use autocomplete in a custom form, but I don't know how to pass the current value of the field to the autocomplete function.

This is my form element:

```
  $form['gs_name'] = [
    '#type' => 'textfield',
    '#title' => $this->t("Name"),
    '#autocomplete_route_name' => 'gseight_autocomplete',
    //'#autocomplete_parameters' => array(),
    '#required' => TRUE,
  ];

```

Route:

```
gseight_autocomplete:
  path: 'gseight_autocomplete'
  defaults:
    _controller: '\Drupal\gseight\Controller\GsEightAutoComplete::content'
    _title: 'Autocomplete Results'
  requirements:
    _permission: 'access GS simple page'

```

Inside GsEightAutoComplete

```
public function content($q = '') {

    //get user
    $userCurrent = \Drupal::currentUser();
    $uid = $userCurrent->id();

    $selectthree = db_select('gs_plans','g');
    $selectthree->addField('g','gs_name');
    // Filter only current user".
    $selectthree->condition('g.uid', $uid);
    $selectthree->condition('g.gs_name', '%' . db_like($q) . '%', 'LIKE');

    $currentone = $selectthree->execute()->fetchAll();

    $jsonarray = array();

    foreach($currentone as $eachcurrentone) {
        $jsonarray[] = $eachcurrentone->gs_name;
    }

    return new JsonResponse($jsonarray);

    }

```

The array fills with items from the database that belong to the current user when i have `$q = ''`at the start. But how do I pass the current value of the field to q?

# Answer
> 3 votes
The form value is automagically added as a query parameter so it is not necessary to pass the current value. This is accessible in the Request object. The controller class method should be:

```
public function autocomplete(\Symfony\Component\HttpFoundation\Request $request) {
  $value = $request->query->get('q');
}

```

---
Tags: 8, ajax
---


# Question
Title: is there any way to load commerce_products into a collection in rules configuration
I need to load all commerce products that their status is "active" into a collection in rules configuration.

I searched in internet and also I tried rules bonus pack but the didn't help me.

Is there any way to load commerce products into a collection and iterate collection via loop ?

# Answer
> 1 votes
I found that VBO (Views bulk operation) give me ability to load views result into a collection in rules.

Just install VBO and make a view and use it.

---
Tags: commerce, rules
---


# Question
Title: How to create a catalog site with views and taxonomy?
I'm trying to setup a site where users can download pdfs that are sorted into different categories based what type are. I've coded out what I want in a html version (which is currently live here) but I need to make this into a CMS (first time for me in Drupal, I've been using other CMSs such Wordpress).

Here's the structure I'm after (also would like to have the URL aliases mention below):

Displayed on Main Download Page (url: domainname/downloadpage):

(Probably a block)

* First Top Category
    + First Sub Category
    + Second Sub Category
    + Third Sub Category

(Also a block)

* Second Top Category
    + First Sub Category
    + Second Sub Category
    + Third Sub Category

Displayed on Top Category Page (url: domainname/downloadpage/firsttopcategory):

(A block but doesn't have to be)

* First Top Category
    + First Sub Category
    + Second Sub Category
    + Third Sub Category

Displayed on Sub Category Page \[already worked this out- just trying to link/incorporate it\] (url: domainname/downloadpage/firsttopcategory/firstsubcategory):

* First Sub Category
    \[in a table\] + Download Name Field1 Field2 Download Link
    + Name Field1 Field2 Download Link

I've already worked out how to create a content type for this, all I need to get this structure into place. This has been a good help but I can't seem to get the way I need it with what I'm after. If you could point me in the right direction in order to archive this, it would be very much appreciated.

# Answer
Have a look at either of these modules, both have an official D7 version (quotes included are from their project pages):

* Taxonomy Menu Block

> Taxonomy Menu Block allows you to make blocks containing unordered lists that represent the structure of your vocabularies, creating a menu out of your taxonomies (without using Drupal's menu system).
>
> Taxonomy Menu Block combines the idea of Taxonomy menu with the workings of Menu block:
>
> + Make multiple menus per vocabulary.
>     + "Split" the taxonomy into different menus. This allows, for example, the creation of one menu with only the top items (parents) of a vocabulary and another menu with only the sub-items (children).
>     + Make a menu out of a specific branch of your vocabulary only.
>     + Follow the active trail, also for nodes coupled to a term with a term reference field.
>
> Taxonomy Menu Block also comes with its own theme function and a few hooks (see the .api.php file) that allows you to alter the generated data to your needs.
* Taxonomy Block

> This module displays a list of taxonomy terms in a block from a single vocabulary.
> 0 votes

---
Tags: views, taxonomy-terms, blocks, uri
---


# Question
Title: Adding create, edit, delete link of referenced entity in same content type
How could we interconnect referenced entity in one content type so that we can search, create, edit, delete the referenced entity on the same content page. In drupal 7 "references\_dialog" module was fulfilling the requirement but now in drupal 8 what is alternative of that module.I think references\_dialog is now no more maintained by developer for Drupal 8. I already know that inline\_entity\_form is there but i want some module which open every thing in modal window pope up like reference dialog does.

Any module or code suggestion will be great.

# Answer
> 1 votes
You want a combination of inline\_entity\_form and Entity browser.

It's possible to create different browsers that consist of one or multiple views, dropzonejs upload forms (with the dropzonejs module), you could also integrate it with a create form I guess but there's no integration for that yet I think (within the entity browser, which is why you can use Inline Entity Form for that part directly in the widget9.

Entity browser doesn't have a UI yet to create browsers, but you can look at the provided demo module and adjust it to your neeeds.

Another example is the File Browser project. That uses an inline iframe, and not a dialog. And it's specifically for managing files/images.

---
Tags: 8, entities
---


# Question
Title: How to show user info in DIV based on link click?
I'm currently trying to make a 'biography' block with Drupal profile pictures and when you click on them more information (user fields that has been filled in by the Drupal user) will dynamically display in a block. To be more specific, this is what I want:

https://css-tricks.com/forums/topic/change-content-in-div-based-on-link-click

I tried to make a Views block displaying the profile pictures. These pictures will function as thumbnails. The things is, I have no idea how it will show more information when you click on them (without going to the profile page). Is there a Views trick, Jquery way or any other method I can try?

# Answer
Have a look at the Colorbox module. Some more details about it (from its project page):

> Colorbox is a light-weight customizable lightbox plugin for jQuery. This module allows for integration of Colorbox into Drupal.
>
> Images, iframed or inline content etc. can be displayed in a overlay above the current page.
>
> Features
>
> * Works as a Formatter in entities and in views.
> * Excellent integration with core image field and image styles and the Insert module
> * Choose between a default style and a number of other styles that are included.
> * Style the Colorbox with a custom Colorbox style in your theme.
> * Drush command, drush colorbox-plugin, to download and install the Colorbox plugin in sites/all/libraries.

**Credits**: rooby (in a comment below the question).
> 1 votes

---
Tags: views, blocks, users, javascript
---


# Question
Title: Product attribute price based on quantity
I'm here with a tricky question about Drupal Commerce. Here's my need:

1. I have a group of products that have a variable price based on quantity.
2. Each product has specific (only for that product) attributes that can modify the price.
3. \[The real problem\] Each attribute price is variable based on the original product quantity.

A real example: 0-300 pieces -\> 0.75€ 300+ pieces -\> 0.52€

OptionA 0-300 pieces -\> 0.07€ OptionA 300+ pieces -\> 0.05

So if I buy 400 pieces + OptionA i pay 0.52+0.05 each, but if I buy 200 pieces I pay 0.75+0.07.

Basically what I want to achieve is to have the attribute price dinamically changed depending on the quantity.

How could I achieve such result? I can't really find a way. Thank you in advance!

# Answer
> 0 votes
You may decrease price by setting up the rule on "After product added to cart" event, checking up the quantity added and calculate discount in a way you want to, for example.

# Answer
> 0 votes
Instead of applying a discount after they added it to the cart as described in another answer, this is exactly why prices are calculated every time they are displayed.

There's a great little module called Commerce Price Table that can give you the ability to change the base price based on quantity, and display this price to the user as well.

Video walking you through set up.

---
Tags: commerce
---


# Question
Title: Is there any way to show a progress bar during loop iteration in a rules?
I have made a rule set and in my rules I load a collection of nodes into a list and by iterating, I perform some modifications in each node.

Sometimes the number of nodes is more than 500.

I want to know is there any solution in order to show a progress bar during loop processing ?(such as one when we update a module)

# Answer
I found the solution.

At first I must appreciate Eyal who gave me key point .

I used module named "rules\_batch" in https://www.drupal.org/project/rules\_batch and it solved my problem.
> 1 votes

---
Tags: rules
---


title: Drill-down contextual filtering

text:
# Question
Title: Drill-down contextual filtering
I've created a view called "Upcoming Events" that presents upcoming events in chronological order at the url `/upcoming-events/all`. Each event has associated tags. Currently my contextual filter is set so that replacing `all` in the url with a valid tag will present just events with that tag. Tags are set up as links with the url `/upcoming-events/[field_tags]`.

My question is two-fold. How do I set up the contextual filter so that adding more tags on the end of the url (`/upcoming-events/happy-hours/drupal/` for example) will further narrow the results presented to the user? Also, how do I set up the tag links to append the field tag to the end of the url rather than replace it?

# Answer
> 1 votes
If you click on **More** link under the contextual filter settings, there is an option to **allow multiple values**.

Enabling this option, you can use URLs like `/upcoming-events/happy-hours,drupal` to show events having both `happy-hours` **and** `drupal` tags.

---
Tags: views
---


# Question
Title: Display blog posts from Wordpress to my Drupal site and filter it by taxonomy terms
I am new to Drupal and need some help. I have a Wordpress blog and a Drupal (version 7) website. I want to display a few blog posts from Wordpress onto my Drupal site. The problem is that I want to select/filter the blog posts based on taxonomy terms I've created in Drupal (blog posts will have corresponding tags for filtering). How can I do this?

# Answer
This is a bit complicated. You'll need to fetch the data somehow from WordPress and make it Drupal data. Fortunately, there's the Feeds module that can help you getting data from your WordPress and transforming it into Drupal nodes. You'll need to configure the Feeds to also parse WordPress categories and create taxonomy terms from it.

I recommend you to read the Feeds documentation before start using it.
> 0 votes

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


# Question
Title: Have module .install create a table in a non-default DB
I have constructed a module that, using the .install file, creates a table on a database different than the default. The module installs fine and functions fine – just a hello world example in the controller. However, when I uninstall the module I get: “The website encountered an unexpected error. Please try again later.” and the reports log there is: DatabaseExceptionWrapper: SQLSTATE\[42S02\]...

Here is the .install file code:

```
function hello_world_schema()
{
    db_set_active('notTheDefaultDB');
    $schema['create_table'] = array(
      'fields' => array(
        'id' => array('type' => 'serial', 'not null' => TRUE,),
        'name' => array('type' => 'varchar', 'length' => 40, 'not null' => TRUE,),
        'last_name' => array('type' => 'varchar', 'length' => 40, 'not null' => TRUE,),
        'message' => array('type' => 'varchar', 'length' => 250, 'not null' => TRUE,),
        'boogie' => array('type' => 'varchar', 'length' => 20, 'not null' => TRUE,),
      ),
      'primary key' => array('id'),);
    return $schema;
}

```

I do realize that I'm tell hook\_schema to switch to notTheDefaultDB and don’t switch it back – if it is switched before the return statement the table is created in the default.

As I said, the module seems to function as intended, but blows up when uninstalled.

Is there a way to write the module so it doesn’t blow up on uninstall or perhaps an entirely different way to do what I’m after?

# Answer
> 3 votes
To my mind, the entire purpose of hook\_schema is to build the Drupal schema. If you need/want to create tables outside of Drupal, it seems like just using PDO in a hook\_install() and hook\_uninstall() implementation might be the way to go. Can you explain your use case a little bit more?

All that said, I don't see an obvious reason for your code to fail.

# Answer
> 2 votes
The Schema API is tailored to declare/manipulate/alter your Drupal project's schemas. Instead of using it to create and delete tables, use raw PHP with synchronous calls. No need to use Schema API when you're no manipulating your Drupal schema.

---
Tags: database, hooks
---


# Question
Title: How to use hook_form_alter to target a specific drupal commerce form?
I have a fairly basic question I think. I've written a module that uses `hook_form_alter` to alter the fields in a product form.

But now I'd like to change the fields in the form for a different product and I was thinking of using my custom module to do so.

However, when I use the Devel module to try and find the specific `$form_id` for each of my created product forms I see they ALL have the SAME name: `commerce_checkout_form_checkout`. Soooo, I'm not sure how to target a specific form.

Moreover, I've used `dpm()` to check the variables in the forms and they all have the exact same values for everything. Even across product types. The only value that is different is `#build_id` but this changes for every form load so it can't be targeted.

Anyone know how to do this?

# Answer
To add or alter the pane forms on the checkout page, for maximum compatibility, you should use the Commerce API.

Define new panes in:

`hook_commerce_checkout_pane_info`

Alter existing panes:

`hook_commerce_checkout_pane_info_alter`

For example, you could alter the `checkout_form` callback for a checkout pane to add your customizations.

> `checkout_form($form, &$form_state, $checkout_pane, $order)`: returns form elements for the pane’s checkout form fieldset

You could also add your own custom checkout pane for your custom design there.

You can refer to the existing pane callback to first include or replicate the checkout pane.

Note: I posted a similar answer for adding a custom validate handler to a checkout pane a while ago here: https://drupal.stackexchange.com/a/87061/7153
> 3 votes

# Answer
The information you are looking for is available inside the order object of the form\_state parameter.

To figure out, from inside a hook\_form\_alter implementation, which product you are dealing with each time, and assuming that you are only looking at one product per checkout (very weak assumption), the following code would reveal the product:

```
function raks_form_commerce_checkout_form_checkout_alter(&$form, &$form_state, $form_id) {
  $line_item = commerce_line_item_load($form_state['order']->commerce_line_items[LANGUAGE_NONE][0]['line_item_id']);
  $product = commerce_product_load($line_item->commerce_product[LANGUAGE_NONE][0]['product_id']);
  if($product->sku == XX && $product->product_id == XX){
    // Alter form accordingly, only for this product
  }
}

```

N.B.: This is very frail code, it only serves to show how you can identify the product each time you use hook\_form\_alter. You may need to change the value index for the line item, in the code above I am simply picking the first one.
> 2 votes

# Answer
If you can know in a easy way the form id you can use the Devel form debug module, I use this module in all my projects.

> This module adds a contextual link to every form that lets you easily find out form's ID, name of `hook_form_FORM_ID_alter()` hook and print out form's variables.
>
> **Usage:**
>
> By hovering over any form you will see a contextual link available. By expanding the link you will see the form ID. Click on the link and you will see a modal window with copyable form id and hook\_form\_FORM\_ID\_alter() hook suggestion.
> 1 votes

---
Tags: 7, commerce
---


title: Taxonomy exposed filter

text:
# Question
Title: Taxonomy exposed filter
I am working with Drupal 7.
How do I limit a taxonomy drop-down exposed filter to only display the terms used by nodes in view results?

I understand that the list is populated before the views takes place, but this means that I am often left with tags that display nothing ( since they are hidden with my view).

# Answer
Views Hacks does this with Views Selective Exposed Filters:

> **Views Selective Exposed Filters**
>
> On list and checkbox exposed filters, you can specify the filter option "Limit list to result set" to only display values that are actually returned in the view's results. The filter option "Further limit list to active filters" restricts the displayed values to view results obtained by applying exposed filter values.
> 3 votes

# Answer
Now we have Views Selective Filters

From the module page:

> This module allows to have an exposed filter only show options that belong to result set.
>
> The options are calculated real-time with the current View's configuration, including the filters selected by the user so you get dynamic dependent filters, that is, when the value of one filter is changed, the list of options of the selective filters are updated accordingly to the trimmed down result set.
> 0 votes

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


title: Import RSS Feed Programatically

text:
# Question
Title: Import RSS Feed Programatically
I have content in an RSS feed that I'm looking to import into separate nodes. I set up a feed importer, and when I run manually, all works as designed (content is imported, fields mapped properly, etc.).

That said, I need to be able to import from the RSS feed on a regular basis. Unfortunately, Elysia Cron won't work, as I don't have access to the crontab on the server. Can this be done programmatically, and on a regular basis?

Thanks!

# Answer
Use

### Ultimate Cron

> The Ultimate Cron handling for Drupal. Runs cron jobs individually in parallel using configurable rules, pool management and load balancing.

It lives up to its name.
> 0 votes

# Answer
There is an option in feed import module settings (admin/config/services/feed\_import/settings), where you can set to import your RSS when the cron runs ("Cron import" checkbox).

If you do not have access to crontab, you cannot schedule cron from server side, but if you set cron interval at admin/config/system/cron, cron will be also triggered on, when the time elapses and there will be site visitors on your page (cron will be triggered by one of the site visitors).

Source here.

**Edit**: If you would like to run cron each 5 minutes (or other custom interval), you will need custom module and implement hook\_init(), which is executed on every page load, when the module is active. See the example:

```
function mymodule_init(){
  //get variable content (last cron run time), if not exists, return 0
  $last_cron_run = variable_get('mymodule_cron_run', 0);

  //if it was more than 5min before
  $five_minutes = 5 * 60;
  if($last_cron_run + $five_minutes < time()){
    //run cron
    $result = drupal_cron_run();

    //do with $result what needed

    //set last cron run time to variable
    variable_set('mymodule_cron_run', time());
  }
}

```
> 0 votes

---
Tags: 7, feeds
---


title: Is this a possible attack on database?

text:
# Question
Title: Is this a possible attack on database?
In the logs (Drupal 7), I have seen the next entry (I have edited some compromised info). It seems a failed (only I hope it actually failed) attempt to access the login account. I have tried to replicate the error, but cannot have the same error entry with failed login/password, so I am very worried that it originated in some possible breach of Drupal 7 security.

```
PDOException: SQLSTATE[42000]: Syntax error or access violation: 1064
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '
'Crap' AND status = 1' at line 1: SELECT * FROM {users} WHERE name = :name_0, :name_1 AND status = 1; Array ( [:name_0] => FcUk
 [:name_1] => Crap )
in user_login_authenticate_validate() (line xxxx of /[HOME_ROOT]/[PUBLIC_HTML_PATH]modules/user/user.module).

```

# Answer
> 0 votes
There is indeed a very serious vulnerability in 7.35. Strongly recommended to upgrade. The hack attempt can be reproduced by using Chrome navigator, F12 and inspect element on the field name of the Drupal web login page. We copy the line of the input name, we set the name of the HTML elements to name\[0\] and name\[1\], respectively, and with any value filled, we submit. Potentially extremely serious and a shame of biblical proportions that this bug survived until 2015.

# Answer
> 3 votes
I asked a member of the Drupal security team about this and he referred me to https://www.drupal.org/drupalsa05FAQ#comment-9255523.

This points to a user attempting to exploit SA CORE 2014 005, but failing due to the site being patched. Cesar's attempt to reproduce triggers the PDOException, but does not (and cannot) result in actual SQL injection.

---
Tags: users, security
---


# Question
Title: Why so many "page not found" for statistics.php?
In my Drupal sites, there are many "page not found" for `modules/statistics/statistics.php` recorded in the log ("Recent log messages" or `/admin/reports/dblog`). Many of them were accessed by the admininistrator in the record. The file exists, of course.

That seems strange to me. Why is it so?

Note the core `statistics` module (Ver.7.32) is enabled, and all the three options (access log, Count content views, Use Ajax to increment the counter) in its configuration are enabled.

**\[Description added\]**
In the Report page `/admin/reports/dblog` when I click the links `modules/statistics/statistics.php` in the Message part, I see (for TYPE: `page not found`) the LOCATION of `http://MyHost/en/modules/statistics/statistics.php` or alike, that is, path with the language prefix. My websites use the path-prefix-based i18n feature.

# Answer
> 3 votes
If file exists, but Drupal still captures calls to it, it may mean one of few things:

1. Obviously this happens if filename is misspelled in one place (request or filesystem) but not the other (or misspelled differently in both).
2. As above, sometimes this happens when paths are (slightly) different.
3. Path you see in your address bar and path your server use to test for file existence are not the same thing. May look the same, but may not, depends on your .htaccess, nginx.conf or whatever you use to control that.
4. Language prefixes may break things. If file `/sites/default/files/example.jpg` exists, server may fail to find `en/sites/default/files/example.jpg`. If that's the case, and for any reason you can't fix broken code, you can try setup like this in your htaccess:

```
RewriteCond %{REQUEST_FILENAME} ^(en|de|fr)/(.*)$ [NC]
RewriteCond %2 -f
RewriteRule ^(en|de|fr)/(.*)$ $2 [NC,QSA,L]

```

Notice, I didn't test it. OP preferred to use *`%{DOCUMENT_ROOT}%{REQUEST_URI}` instead of `%{REQUEST_FILENAME}` to deal with the potential dependencies on the environment/timing etc* \- that are implementation details beyond the scope of this site, I believe. The **logic behind it** is, line by line:

1. Test if request filename contains one of the specified prefixes (should match your site's languages.
    2. Test if file without prefix (second regex group) is there, and really is a file.
    3. If so, rewrite request to remove language prefix.

Apply this logic and you should be good. Actual implementation may vary, but logic you want is just that.

# Answer
> 3 votes
There is a bug report for this @ https://www.drupal.org/node/2172871

A temporary fix available @ https://www.drupal.org/node/2172871#comment-10247397

No need to hack the core. Just add the below function in your theme or module.

```
/**
 * Implements hook_url_outbound_alter().
 *
 * Fix statistics path when i18n path prefix enabled
 * see: https://www.drupal.org/node/2172871
 */
function YOUR_THEME_OR MODULE_url_outbound_alter(&$path, &$options, $original_path) {
  if ($original_path === 'modules/statistics/statistics.php' && isset($options['prefix'])) {
    $options['prefix'] = '';
  }
}

```

---
Tags: 7, nodes
---


# Question
Title: Access Functions Attach in Drupal Behaviors From Global Scope
I have this Drupal Behaviors Javascript code:

```
Drupal.behaviors.myid_templates = {
    attach: function(context, settings){
        function local_function(){
            alert('local_function');
        }
    }
}

function global_function(){
    //I want to call local_function here. Is that possible?
    local_function();
}

```

I was wondering I could do something like `Drupal.behaviors.myid_templates.local_function()` to access local functions from global functions? Any idea? Thanks.

# Answer
> 4 votes
You would need to add it to `Drupal.behaviors.myid_templates` and not inside of your attach function.

```
Drupal.behaviors.myid_templates = {
  attach: function(context, settings){
    // Code to run on DOM ready, each AJAX request finish.
  },
  local_function: function (){
    alert('local_function');
  }
}

```

---
Tags: 7, javascript
---


# Question
Title: How can I send a Privatemsg using Rules and have the name of the site as the sender?
I am using the Privatemsg and Rules module and I am trying to set up an automatically generated welcome message to new members registering on the site. This message will go into the new member's inbox.

I do not see a token that would allow the site's name to be the sender. All I see is the token for the logged in user. As expected, this doesn't trigger the message.

I have toyed with the \[account\] token. So when John creates an account, the message comes from John himself. This would be acceptable but it isn't consistent: Sometimes it works, sometimes it doesn't.

I know some tokens exist that are not always displayed. Does anyone have the name of the mysterious token? Or the magic to get this to work?

# Answer
You could create an account for sending the messages and in rules, use direct input and enter its user id. That way, you could also see replies to welcome message.
> 2 votes

# Answer
Here's the site name token: \[site:name\]

Full list of tokens: https://www.drupal.org/node/390482
> 0 votes

---
Tags: 7, rules, privatemsg
---


# Question
Title: How to call limited data items per page?
I am using one custom module, which is getting data from the database, with the following code.

```
function rs_get_doors() {
  $doors = array();
  $doors_nids =  db_select('node', 'n')
  $doors_nids = $door_nids->extend('PagerDefault')->limit(10);
    ->condition('n.type', 'vivarium_door')
    ->fields('n', array('nid'))
    ->orderBy('n.title', 'ASC')
    ->execute()
    ->fetchCol();

  foreach ($doors_nids as $nid) {
    $wrapper = entity_metadata_wrapper('node', $nid);
    $doors[$nid] = array(
      'name' => $wrapper->title->value(),
      'fee_nid' => $wrapper->field_fee_category->value()->nid,
    );
  }

  uasort($doors, 'rs_doors_natural_sort');

  return $doors;
}

```

it is getting thousands of nodes at time in a single page and it takes too much time to load.

So I think I need to paginate the query. How can I achieve this?

# Answer
> 0 votes
```
$doors_nids = db_select('node', 'n')

->condition('n.type', 'vivarium_door')

->fields('n', array('nid'))

->orderBy('n.title', 'ASC')

->extend('PagerDefault')->limit(10)

->execute()

->fetchCol();

```

Hopes this will helps you.

# Answer
> 0 votes
You are using the wrong method: It's not `limit()`, but `range()` that you should use.

```
  $query = db_select('node', 'n')
    ->condition('n.type', 'vivarium_door')
    ->fields('n', array('nid'))
    ->orderBy('n.title', 'ASC')
    ->range(0, 10);

  $result = $query->execute(); // Add here the call to fetchCol().

```

Notice that dynamic queries are slower than static queries; you should use them when you want other modules to dynamically alter your query. In the other cases, you should use static queries (i.e. use `db_query()` or `db_query_range()`).

```
$query = db_query_range("SELECT n.nid FROM {node} n WHERE n.type = 'vivarium_door' ORDER BY n.title ASC", 0, 10);

```

### Reference

---
Tags: nodes, database, paging
---


# Question
Title: How to update Geofield using a custom form and DrupalGap's node_save?
The code below successfully updates the title, but does not update the Geofield. The node\_save function is provide by DrupalGap and described here http://api.drupalgap.org/node.js\_.html

```
        var node = {
            'nid': nid,
            title : 'New Title', // THIS WORKS!!
            'field_geocoordinates[und][0][geom][lat]':tripchi.geocoordinates.coords.latitude.toString(), // NONE OF THESE DO
            'field_geocoordinates[und][0][geom][lon]':tripchi.geocoordinates.coords.longitude,
            'field_geocoordinates[und][0][geom][lat]':tripchi.geocoordinates.coords.latitude,
            'field_geocoordinates[und][0][geom][lat]':tripchi.geocoordinates.coords.latitude.toString(),
            'field_geocoordinates["und"][0]["geom"]["lat"]':tripchi.geocoordinates.coords.latitude.toString(),
            'field_geocoordinates["und"][0]["geom"]["lon"]':tripchi.geocoordinates.coords.longitude.toString(),
            'field_deal_count[und][0][value]' : 3, // simpler structure also does not update
            "field_geocoordinates": {
                "und": [
                    {
                        "geom": "POINT (2 1)",
                        "geo_type": "point",
                        "lat": tripchi.geocoordinates.coords.latitude.toString(), // I've tried this as strings and integers
                        "lon": tripchi.geocoordinates.coords.longitude.toString(),
                        "left": "2.000000000000",
                        "top": "1.000000000000",
                        "right": "2.000000000000",
                        "bottom": "1.000000000000",
                        "geohash": "s01m"
                    }
                ]
            }
        };
        node_save(node, {
            success: function(result) {
                console.log(result);
                utils.mAlert("Pinpointed Location to Latitude:" + tripchi.geocoordinates.coords.latitude + ' - Longitutde:' + tripchi.geocoordinates.coords.longitude);
            }, error: function(result) {
                utils.mAlert("UPDATE ERROR: " + result);
                console.log(result);
            }
        });

```

How should i be targeting custom fields in custom html forms / ajax update requests?

**UPDATE:** @Jimajamma is correct in the comment below, but this only works when the property to update is value. It is not working on the Geofield module object shown in my code above.

# Answer
From this example it looks like the syntax is along these lines:

```
var node = {
  type:"donation",
  title:"Donation",
  field_donation_amount: {
    und: {
      0: {
        value: form_state.values.amount,
      },
    },
  },
};

```

Addition:

So have you looked at something like this then? Nesting things further, eg:

```
var node = {
  field_geocoordinates: {
    und: {
         0: {
            geom: {
                  lat: FOO,
            },
         },
    },
  },
};

```

(I think I have the correct number of `}`s :) Perhaps a js version of php's print\_r (here is an example) of a valid node object from node\_load() would help out?
> 0 votes

# Answer
The solution to create geofield by lat and lot

include\_once(drupal\_get\_path("module", "geophp") . "/geoPHP/lib/geometry/Geometry.class.php"); include\_once(drupal\_get\_path("module", "geophp") . "/geoPHP/lib/geometry/Point.class.php");

$node-\>field\_current\_location\['und'\]\[0\]\['geom'\] = new point((float)$lat, (float)$lot);
> 0 votes

---
Tags: 7, entities, theming, location
---


# Question
Title: Drupal commerce email order notification not sending properly
On the rule of sending email order notification I just changed the "*FROM:*" of the send mail, instead of the email of the website I want the email of the anonymous customer from a custom field of billing information I created then this will be sent to the admin.

This is my current rule:

```
{ "commerce_checkout_send_an_order_notification_e_mail_admin" : {
"LABEL" : "Send an order notification e-mail ADMIN",
"PLUGIN" : "reaction rule",
"WEIGHT" : "4",
"OWNER" : "rules",
"TAGS" : [ "Commerce Checkout" ],
"REQUIRES" : [ "rules", "commerce_checkout" ],
"ON" : { "commerce_checkout_complete" : [] },
"IF" : [
{ "entity_has_field" : { "entity" : [ "commerce-order" ], "field" : "commerce_customer_billing" } },
{ "entity_has_field" : { "entity" : [ "commerce-order" ], "field" : "commerce_line_items" } },
{ "entity_has_field" : {
"entity" : [ "commerce-order:commerce-customer-billing" ],
"field" : "field_email"
}
}
],
"DO" : [
{ "entity_fetch" : {
"USING" : {
"type" : "commerce_customer_profile",
"id" : [ "commerce-order:commerce-customer-billing:profile-id" ]
},
"PROVIDE" : { "entity_fetched" : { "customer_profile" : "customer_profile" } }
}
},
{ "mail" : {
"to" : "[site:mail]",
"subject" : "[customer-profile:field-full-name] - Event: [customer-profile:field-event-name]",
"message" : "Customer Name: [customer-profile:field-full-name]\r\nCustomer Email: [customer-profile:field-email]\r\nCustomer Contact Number: [customer-profile:field-contact-number]\r\nEvent Date: [customer-profile:field-event-date-no-end-date:event_date]\r\n\r\nPackages Selected:\r\n[commerce-order:commerce_line_items]\r\n\r\nOverall Total: [commerce-order:commerce_order_total]",
"from" : "[customer-profile:field-email]",
"language" : [ "commerce-order:state" ]
}
}
]
}
}

```

When I checked the **log report** of the website it says **"Successfully sent email"** but I never received the email. but whenever I change the "*FROM:*" to blank or \[site:mail\] I will receive the email notification. Why is that? The token I used for the "*FROM:*" is exactly the same as on the message and it's correct.

# Answer
> 0 votes
Your issue is due to server email blocking. Please configure SMTP module for sending emails from the website. This will add appropriate headers in the mail, and your email will not get blocked.

Hope this will help you.

Thanks

---
Tags: 7, commerce, rules, emails
---


# Question
Title: copy content-profile elements to another page
In my content profile page, I have a set of three elements: a search field, a set of checkboxes with data, a text area that shows the chosen options. I also have a number of onclick and keyup functions defined in a .js file, that fills the checkbox options, makes sure that entering values in the search field scrolls to the nearest checkbox, and when user checked a value it appears in the text area. So far so good.

How do I "copy" these elements and their functions to a separate page? I want a new page called "update my data" that has the exact same elements and functions, and I would just need to change the submit function. I am new to Drupal and Javascript, so sorry if this is a stupid question...

I tried using the content-profile update page and it doesn't copy the event handlers. Also, it allows the user to update all their data and I want only these elements.

I am using Drupal 6 and Content Profile module.

Thanks!

# Answer
> 0 votes
In the end I used the content-profile edit page, with the following modifications:

1. It did copy the event handlers but the ajax call was calling the wrong url becasue of relative path problems. Using an absolute path instead fixed this issue and the event handlers worked perfectly.
2. Used JavaScript to add a css class to the elements I wanted hidden, and styled in css that this class should have display:none.
3. I needed to install a patch on the CCK module to solve an issue with a hidden on/off checkbox.

Thanks!

---
Tags: 6, javascript, users
---


# Question
Title: How to use file_save to store pictures into a folder on server?
what i want to perform (globally) is to import a `csv` file that contains data such as book\_title, author, and the cover image of the books. The csv file is loaded, book\_title and author are stored in their respective tables but for pictures, what i want is to put them manually (ftp for example) on a folder (doesn't matter if it's my default public folder or a new one) and store data in tables like : `file_managed` and `field_data_field_cover_picture` etc In my csv file, and for pictures column i just write filenames of every picture.

At the moment, i'm confused and this is my actual code :

```
$filename_cover = $get_filename.'.jpg'; <===from csv

        $add_cover_file = db_insert('file_managed')
        // ->key(array('fid' => rand()))
        ->fields(array(
            'uid' => $user->uid,
            'filename' => $filename_cover ,
            'uri' => 'public://couvertures/'.$filename_couv,<==my file
            'filemime' => 'application/octet-stream',
            'status' => 1,
            'timestamp' => time()
        ))
        ->execute();

```

Now adding on the pictures covers table : (how to put the `fid` ?)

```
  $add_couverture = db_merge('field_data_field_photo_de_couverture')
        ->key(array('entity_id' => $newNode->nid, 'field_photo_de_couverture_fid'=>$add_couv_file->fid ))
        ->fields(array(
            'field_photo_de_couverture_fid'=>$get_fid ,
            'entity_id' => $newNode->nid,
            'delta' => 0,
            'bundle' => 'livre',
            'entity_type' => 'node'
        ))
        ->execute();

```

# Answer
> 1 votes
Try this:

```
$file = file_save((object)array(
    'filename' => $file_name,
    'uri' => $destination_uri,
    'status' => FILE_STATUS_PERMANENT,
    'filemime' => file_get_mimetype($destination_uri),
  ));
//at that point you can use the $file->fid
//do the magic on your custom table field_data_field_photo_de_couverture

```

---
Tags: 7, files
---


# Question
Title: Remove label Search terms from Views exposed form
On this site in the sidebar i have a `views_exposed_form` to search. I need this search functionality to show my search results for restricted pages.

* How do i remove the label 'Search Terms'. Is it possible within `template.php` with a hook?
* How do i add a placeholder to the input field?

# Answer
```
function views_exposed_form($form, &$form_state) {

if ($info = $handler->exposed_info()) {
          $form['#info']["$type-$id"] = $info;
          /**enter your code here  *****/

        }
/**for place holer**/

if (isset($form['title'])) {
        $form['title'][] = array('#placeholder' => t('Gemeente...'));
}

}

```
> 2 votes

# Answer
> **Remove label :** In exposed form settings there is a label text if you will not add any value on that it will not display any label

```
    /* for placeholder */

    function hook_form_alter(&$form, &$form_state, $form_id) {
     if ($form_id == 'views_exposed_form') {
                    $form['title']['#attributes']['placeholder'] = t('Place holder');

    }
    }

```
> 0 votes

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


# Question
Title: Comment Forms - place label inside the inputs
I'm theming a comments section on a page in a D7 site. What I want is for the label for the forms items to show as a `placeholder` attribute rather than above the element.

I've used a `hook_form_alter` to add the placeholder attributes, e.g.

```
$form['comment_body']['#attributes']['placeholder'] = t('Add comment here');

```

…but don't seem to be able to hide the label. In a normal form I can set the label to hidden but there's no option under 'manage display' for the comment form.

Is there something I can do in my hook to do it instead? I know I can hide it with CSS but would like to know The Drupal Way™

# Answer
> 1 votes
Right, answered my own question with a bit of help from the Form API Docs!! https://api.drupal.org/api/drupal/developer!topics!forms\_api\_reference.html/7

`'#title_display' => 'invisible'`

was what I needed!

---
Tags: 7, forms, comments
---


# Question
Title: how to add multiple style values in attribute in drupal form
I have form element like as follows :

```
$form['precio'] = array(
  '#type' => 'textfield',
  '#title' => t('Price'),
  '#default_value' => $precio,
  '#size' => 20,
  '#attributes' => array(
    'style'=>'background: none repeat scroll 0 0 #EAEAEA;'
  ),
  '#description' => t('Change the price'),
);

```

how i add more style attributes to 'precio' ?

# Answer
> 2 votes
You can nest the style attributes as follows :

```
$form['precio'] = array(
  '#type' => 'textfield',
  '#title' => t('Price'),
  '#default_value' => $precio,
  '#size' => 20,
  '#attributes' => array(
    'style'=>'background: none repeat scroll 0 0 #EAEAEA;
              margin: 0 3 4;
              color:red;'
  ),
  '#description' => t('Change the price'),
);

```

---
Tags: forms, 6
---