# Question
Title: basic difference between Date, Date(ISO format), Date(Unix timestamp) to create a field
I have created a field as field type Date(Unix timestamp).

When i edit a content with some input value in the above created field it shows an error like below:-

```
PDOException: SQLSTATE[01000]: Warning: 1265 Data truncated for column 'field_reprisal_date_value' at row 1: INSERT INTO {field_data_field_reprisal_date} (entity_type, entity_id, revision_id, bundle, delta, language, field_reprisal_date_value) VALUES (:db_insert_placeholder_0, :db_insert_placeholder_1, :db_insert_placeholder_2, :db_insert_placeholder_3, :db_insert_placeholder_4, :db_insert_placeholder_5, :db_insert_placeholder_6); Array ( [:db_insert_placeholder_0] => node [:db_insert_placeholder_1] => 258985 [:db_insert_placeholder_2] => 245170 [:db_insert_placeholder_3] => embedded_video [:db_insert_placeholder_4] => 0 [:db_insert_placeholder_5] => und [:db_insert_placeholder_6] => 2015-03-02 ) in field_sql_storage_field_storage_write() (line 494 of /www/d7yourtango/modules/field/modules/field_sql_storage/field_sql_storage.module).

```

But after deleting above field again i create another field as field type Date and i process same, it work.

So my question is why it happening so for 1st case?

And what are basic difference between field types of Date, Date(ISO format), Date(Unix timestamp) to create a field.

# Answer
Below explains three field types in details

**Date**

* Called a 'datetime' field type in techno database speak. This format type is recomended for most installs because it takes advantage of the database's date handling functions without any conversion, which means faster queries.
* Stores the date in the database's native date format (YYYY-MM-DD HH:MM:SS).
* The data is in a human-readable form.
* You can use it for incomplete dates, i.e. only a year or only a year and a month, and pad the other values with zeros, so it does not appear to be any more precise than it really is.

**Date (ISO Format)**

* Stores the date in an ISO format (YYYY-MM-DDTHH:MM:SS).
* The data is in a human-readable form.
* List You can use it for incomplete dates, i.e. only a year or only a year and a month, and pad the other values with zeros, so it does not appear to be any more precise than it really is.
* It is a format that is internationally-recognized, and it is used as-is on many web sites and in many applications.

**Date (Unix Timestamp)**

* Stores the date as an integer.
* Takes up less room in the database because it's smaller.
* Often easier to use for date calculations because you can increase or decrease it just by adding or subtracting seconds.
* It is the format used by php date functions.
* It must be filled with a complete date -- year, month, day, hour, minute, second, so you sometimes have to arbitrarily set some of these values even if they are not applicable.

Taken Reference from Here
> 9 votes

---
Tags: datetime
---


title: Product price formatter

text:
# Question
Title: Product price formatter
In my shop site, on each of the products listed can we please just list the dollar amount i.e. $80.00(for eg.) - and remove the default currency(eg. AUD) and (GST (exc) )text that follows? How to formatting the price?

# Answer
> 1 votes
You can use module Commerce Currency Settings for formatting of currency.

---
Tags: commerce
---


# Question
Title: With Drush, what's the correct procedure to install Commerce Kickstart, Drupal, and the sample store data as a new site?
In my opinion, the install documentation is a bit lacking when answering this question.

http://www.drupalcommerce.org/commerce-kickstart-2/install

I want to avoid the browser all together and install commerce\_kickstart and configure the sample store all via the command line with Drush.

What's the correct way to do this? Download Drupal; Download commerce\_kickstart which creates a profile directory, and then 'drush si commerce\_kickstart ... ' ?

# Answer
> 1 votes
Commerce Kickstart differs from the standard core installation profile, by having extra installation steps. These steps are illustrated in the offical Commerce installation docs - they ask questions about store features and whether or not to install the sample store data.

Installation via drush does indeed work, however it does NOT offer these extra-step choices to the user. Instead it assumes you want the sample store.

So installation via drush is straight-forward. Assuming you have downloaded and unpacked the distribution archive file, just `cd` to the Drupal root, and run `drush site-install commerce_kickstart`.

Take some time to review the options described by `drush help site-install`. Most likely you will need to pass in a few more options, such as database credentials. A typical installation command will look something like this:

`drush site-install commerce_kickstart --account-pass=admin --account-name=admin --db-url=mysql://root:pass@localhost/db_name --notify`

Note that the Commerce Kickstart takes a lot more time than the standard core install profile. It sets up over 100 modules, several content/product types, and imports the sample store data. `drush site-install` will tell you "This takes a few seconds...", but it took 10 minutes on my machine :-)

# Answer
> 0 votes
You don't have to install Drupal and commerce kickstart separately. Commerce Kickstart distribution itself contains the latest Drupal.

Only command that you need is drush dl commerce\_kickstart

---
Tags: commerce
---


# Question
Title: Possible to join different entity type on using EntityFieldQuery?
I am wondering whether I can use EntityFieldQuery to fetch all entities belonging to a specific content type. This entity type has a reference to another entity type. Is it possible to check against the refereed entities fields in the same query?

# Answer
No.

An `EntityFieldQuery` allows you to run queries based on field and property conditions, but it has no way to query the fields or properties of a referenced entity.

Such a thing would involve some pretty full on logic, and it probably wouldn't even be possible to provide a programmatic interface to it that made sense.
> 2 votes

# Answer
What you would need to do is run a query against the referenced type first so you have all the node ids that apply, then use them in a second query with a field condition like:

```
->fieldCondition('YOUR_REFERENCE_FIELD', 'target_id', $nids, 'IN')

```

This may not be practical if your database is very large.
> 0 votes

---
Tags: entities, database
---


# Question
Title: Storing data for every country for an interactive chart
I need to store one and possibly more values for each and every country so that I can populate an interactive SVG world map. This data will be updated often by hand by one of the content moderators. So it should be easy to maintain by someone with basic drupal content editing knowledge.

So far I have tried:

* My initial work had me use a Field Collection, in which I had a dropdown field with all the countries, and another dropdown to select which data point to use for that specific country. This works, but gets extremely memory intensive as the country goes up. It becomes exceptionally difficult to find a country as well since they are not in alphabetical order. I attempted to create each Field collection item prefilled for each country upon creating the node create form. but I would constantly run out of execution time, with it taking more then 4 minutes to get to 200 countries, and getting exponentially slower as the country count went up. Never managing to get to 250.
* I then tried to use TableField, and import the data from a CSV, with one column for the iso2 code, one for the name, and one with the numerical value for the value on the chart. This was okay, but nearly always crash when trying to import an updated version of the csv. It also was difficult to ensure the integrity of the country codes and names, since anyone could easily make a inadvertant change when modify data. This would then break either the map, or the translation of the names.

So my question is, how can I go about structuring a content type, so that I can list all the countries and set a value for them which I can choose from a select list, that allows me to view the data, sorted by country, and doesn't bring the browser to a standstill?

*Note*: I'm using Ammaps to display the data on the front.

# Answer
I did something similar sometime ago.
My svg had a path per country with each path being identified by a unique id (namely the country name camelcased). These were stored directly in the template.
I created a taxonomy with all the country ids, and a content type for the user-contributed country data, with a reference to the country-ids taxonomy.
After that I used EntityFieldQuery to get the list of country-ids with published data, so as to display them highlighted in the map.
Then on click of a country I'd retreive the country data via an AJAX request and display it besides the map using jquery.

Beyond my original implementation you could probably load all data via EntityFieldQuery and then just handle it via javascript without further requests.

Does that make sense to you ?
> 1 votes

---
Tags: nodes, entities
---


# Question
Title: Changing value of a field before rendering in Drupal 7
I am trying to change the value of a field. I need to add a dynamic class on-the-fly, based on some complext context, and I need to warp the text value with the span-class-stuff. But I haven't been able to alter the value, even if I am able to read it. I use MYTEMPLATE\_preprocess\_page(&$variables, $hook), MYTEMPLATE\_preprocess\_field..., even some hooks in my modules, but to no avail. I am unable to change it. What would be the best and effective approach?

# Answer
I suppose you're not actually trying to change the value of a field – but instead change one of its attributes? It would probably be useful to see how you're trying to rewrite the classes inside those theme functions so far. Basically that should already be the right location to do this.

I recently just had a very similar problem, wanting to rewrite classes of a node. I know it's not exactly what you're asking – but the approach should be very similar. Inside your preprocess funtion first you should extract the already existing classes for later use:

```
$variables['classes_array'][] = drupal_html_class('node-' . $node->type);

```

Then you could add classes to the classes\_array according to your conditions:

```
if ($variables['promote']) {
    $variables['classes_array'][] = 'node-promoted';
}

```

Find full example code and further details on this page or also over here.
> 1 votes

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


title: Upload Image impossible

text:
# Question
Title: Upload Image impossible
I just migrated a website, and I can't upload any files now. I checked the file path , it's ok I checked the files and tmp permission , its ok (775)

When I try to upload an image, it does the 'ajax loading' and then boom everything's gone. It's like I just came and didnt try to upload anything. I have no js , php or ajax error.

I really don't know what to do, have someone already face this ?

Thank you.

# Answer
Ok, I've found the answer. Files and tmp folders were owned by root, so I changed in www-data ( web user ) and everything works now.
> 0 votes

---
Tags: migrations, media
---


# Question
Title: how to insert image inside an existing image
hi i'm working on my sample site.in that I've done the background image blue sky into the respective region how can i add one more image in center of that like below ? and more over I've to add an web form in that center image i'm going to add? how can i achieve this?

# Answer
It depends on your theme which you're using. Normally you've to create a block with image in its content and assign to the right region.

If you don't have the right region to assign to, try changing the existing content, or expand your theme and add new region based on your needs, or use Panels and replace your current page with custom layout (e.g. by using a flexible layout).
> 0 votes

---
Tags: theming, media
---


# Question
Title: How To Upload Image From Media Library Programmatically?
I enabled latest version of media module to upload images in wysiwyg. It is working fine. There is no problem. I want to upload images programmatically from media library.
Below is my code.

```
function test_form_upload_form_alter(&$form, $form_state) {
 $form['settings']['apply_now_image'] = array(
  '#type' => 'media',
  '#title' => 'Image for apply now',
 );
 $form['#submit'][] = 'test_upload_form_submit';
}

function test_upload_form_submit(&$form, $form_state) {
    global $user;
    if (!empty($form_state['values']['apply_now_image'])) {
    $file = file_load($form_state['values']['apply_now_image']);
    // Change status to permanent.
    $file->status = FILE_STATUS_PERMANENT;
    // Save.
    file_save($file);
    file_usage_add($file, 'user', 'user', $user->uid);
    $apply_now_image_path = file_create_url($file->uri);
    variable_set('rgit_apply_now_image', $apply_now_image_path);
    variable_set('rgit_apply_now_image1', $file->fid);
  }
}

```

But it didn't give correct answer. This is only work if the '#type' is managed\_file'. It didn't work if the '#type' is media. Is any solutions there to upload images from media library.

# Answer
> 0 votes
Not sure what you are trying to achieve here, but files uploaded via media are already permanent managed files once you get to the submit stage, I believe.

The value in the form\_state array you need is `$fid = $form_state['values']['apply_now_image']['fid']);`

You can then use that in a file\_load: `$file = file_load($fid);`

So your code becomes

```
$file = file_load($form_state['values']['apply_now_image']['fid']);
file_usage_add($file, 'user', 'user', $user->uid);
$apply_now_image_path = file_create_url($file->uri);
variable_set('rgit_apply_now_image', $apply_now_image_path);
variable_set('rgit_apply_now_image1', $file->fid);

```

---
Tags: media
---


# Question
Title: how to display labels of empty profile fields
I have enabled profile2 module. There is profile type called personal information and it has related manage fields.I want to display the labels for empty profile fields on profile page. The fields are visible when it contains information but how to display the labels of empty profile fields to prompt the user to fill out empty fields. Does anyone have the solution? Please help. Thank you.

# Answer
> 1 votes
Use the Empty Fields module. With this you can place custom text as filler until content has been entered. This will have the labels show up.

# Answer
> 1 votes
You should have searched on google ! visit this page

---
Tags: users
---


# Question
Title: Why are my prices showing up as unformatted (minor units) in a view on a search index?
Bit of an odd one here, I am experimenting with the Search API, Search DB and Views. I have a view based on Commerce Products. The view works, along with most of it's facets (but that's another story).

I'm running into a strange issue. I have a view based on a search index using Search API and Search\_DB. I have access to all the fields that I indexed, but price is presented as the unformatted price in minor units. It is pulled in as "Indexed Commerce Product Price\>\> Amount (Price \>\> Amount)"

The issue I'm having is that it's displaying price as 98,000 rather than $980

Why is the formatting changing? and what's the right way to pull that info into my search view? D-Commerce wants the prices in minor units for it's own internal formatting. I have a regular non-search view which has the correct price...

# Answer
> 0 votes
To start, if it's a Views view, check you field formatter within the view admin page. You could also hook into it somehow (I'm not entirely sure how, possibly alter the query), to divide the price by 100, but only for formatting.

---
Tags: commerce, search
---


# Question
Title: Array Field for a Content Type. Is it possible?
I'm new in drupal and I'm about to use drupal for my expanding site. This is my issue: I have some documents which segmented to sentences and words and each word has a tag for example:

Document: This is a test text to show what I say. This is the second sentence. This is the third. Sentences: 1. This is a test text to show what I say 2. This is the second sentence and so on.

Tagged words: This =\> ABC is =\> DEF a =\> EE test =\> NME and so on.

I would like to make a node for each document not each word or sentence and store sentences and words as fields. This data is stored in a mysql database and I can export it in any form. How can I implement this structure in Drupal? Is there any module for it? or I should develop a new module? or any other solution?

Thank you all so much

# Answer
In case you want to store complete array as a single input in a field, you can do so by serialize the array.

Create a long text field and serialize the array before input by calling hook\_node\_submit().
> 1 votes

# Answer
Create a new content type (at /admin/structure/types/ in D7). Add the fields you want within it. Then write a template or create a view to output the fields in the order you desire.
> 0 votes

# Answer
Create a text field with multiple possible values and programatically save your datas as $i number values

```
 $node = new stdClass ();
 $node->type = 'our content type';
 $node->your_field ['und'] [$i] ['value'];
 ...

node_save ( $node );

```

for associative array , field collection module could do
> 0 votes

---
Tags: entities
---


# Question
Title: User Registration Disable Email Verification
The issue is for non admins to only view a particular part of the user section. The current password and email address fields need to be hidden. I've tried the field permissions but that doesnt give an option.

Writing the hook makes sense to hide both the fields but the validation is what I'm having issues with. If I add optional mail or the mail control modules, I'm thinking its going to throw a few other things off.

# Answer
You need to do a lot more than just unsetting the field if you want to change the way registration works. Out of the box, Drupal expects a valid email unique address for every user. This is why there are contributed modules for this purpose: it needs a fair amount of code to achieve.

Take a look at https://www.drupal.org/project/optional\_mail for example.
> 1 votes

# Answer
To disable the user Registration e-mail verification you can use the mailcontrol module.

> Have full control over the default mails sent by Drupal 7 out of the box.
>
> ## Description
>
> This small module extends original Drupal 7 account settings page with the ability to globally turn ON/OFF all standard mails. By default Drupal 7 provides no option to globally disable the following mails:
>
> * Welcome (new user created by administrator)
> * Welcome (awaiting approval)
> * Welcome (no approval required) Password recovery
>
> ## Use cases
>
> This module may come in handy when:
>
> * you don't want to send those emails for some reason
> * or you are sending them through some other means
> * or to get rid of the PHP Mail error message when you’re working on localhost
> * or other development purposes

Also this question have been ask already at - Disable register email notification
> 0 votes

---
Tags: forms, users, emails
---


# Question
Title: How to generate stats or reports for multi-sites?
We've a large deployment of multi-sites, each site with its own database, and I am looking at generating reports from these sites and making those available online in some format.

For e.g., our sites implement many redirects. I want to be able to pull a report on what redirects are in use by which site. I can readily do this via drush and shell scripts, but it would be nice to have a "stats site" to do the generating of these kinds of reports for all sites in a multi-site setup.

# Answer
Here's how I do this:

I created a "meta" site and database in the system where I added a new table called "databases". In that table I store the access info of all the DBs in the system.

Then loading an array from a query to that table, query the other DBs individually using the methods outlined here: http://drupal.org/node/18429
> 1 votes

# Answer
The Forena module seems to me like a pretty perfect fit to address this requirement. No PHP coding involved, just add your custom SQL queries to fit your requirements for getting the data you need, and then use your XHTML / CSS skills to beef up your output (report). Eventually adding some charts to it also, which even support drill-down links.

Here is the intro near the top of that linked page (use the link for more details, and its child pages):

> Forena Reports is built of the idea of using SQL to get data out of a database and use XHTML and CSS to format it into web reports.
>
> It is designed to leverage existing knowledge of HTML, CSS, SQL and JavaScript to help you create rich interactive web reports.

Its Supported database connections you'd want to take advantage of in this case would be either "Drupal" or "PDO" ... done! Don't believe me (yet), just try it in your own environment).

Be aware: I'm a co-maintainer of forena, and created most of the community docu for it.
> 1 votes

---
Tags: multi-sites, log-messages
---


# Question
Title: How to inject a product field to product display?
I have added a field on a product.I want the same field to appear on the product display that is being referenced.I need to do this with code. How can I do this? thanks

# Answer
I would personally be using views to either override the product page, or I would hide the fields on the manage display page of the product, and show all the fields using a view in a block with a contextual filter to get the content by ID.

However, you can override the product using a template like node--product.tpl.php and use something like...

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

```

To print your chosen field.
> 0 votes

---
Tags: commerce
---


# Question
Title: Replace date by text in date_popup default value (or in-field label)
I am desperately trying to display a date\_popup field in my form with a text eg("please select date") as default value and not a date. Can someone help? Thanks a lot.

# Answer
Try using the placeholder html5 attribute by removing the #default\_value from the array.

So, take out....

```
'#default_value' => $date,

```

and replace with

```
'#attributes' => array('placeholder' => t('Please select date')),

```

or, as you already have attribute, add it to that
> 0 votes

---
Tags: datetime
---


# Question
Title: How to use Open Atrium 2 for document managment
In the past I have used Open Atrium 1 as an intranet site making use of the document management system.

I can't work out how to do something similar in OA2. From the documentation I have found:

> News section - for document management, wikis, or articles

So I have created a News section. It looks like I can create a Document Page and add attachments to it. Do I no longer have the options to create files and folders. Just document pages and attachments?

# Answer
The 2.30 version of Open Atrium supports folders out-of-the-box through the oa\_folders module.

On earlier versions I have used a customized news section type and calling it Folders or Filesharing. With a clear workflow established with the people working on it, you can then have each document page being a folder, where all space members can add or remove further documents. It was obviously a limited solution, but made the purpose. Now we have a better OA world :)
> 1 votes

---
Tags: 7, distributions
---


# Question
Title: Giving custom argument value in 'q' variable
We want to use a custom template page when a specific value is given for the `q` variable in url .

For example if we give `http://localhost/drupal/?q=xyz/123` , we want to use a custom template page say `page-xyz.tpl.php` ..

Have a hunch that hooks and template.php file may be the key components here but not sure what to exactly do.

# Answer
> 1 votes
Your question seem a little bit unclear to me. But my understanding is that you are having problems with theme template.

You should try it out using the node in your url. There is an example...

If you had the following path:

```
/node/99/edit

```

PHPtemplate looks for the following templates, in descending order:

```
page-node-edit.tpl.php
page-node-99.tpl.php
page-node.tpl.php
page.tpl.php

```

---
Tags: theming, hooks
---


title: Customizing a Views HTML

text:
# Question
Title: Customizing a Views HTML
I'll start off saying I'm pretty new to Drupal. I'm trying to customize the way a view displays. I want it to look like the Industry News section on this page: http://www.silverfishdevelopment.com/clients/maafs

However I'm confused as to what I want to actually edit. Do I want to create a custom views-view.tpl.php file? Or style output, or row style, etc?

And if I create a new tpl file, what are the variables I can use?

I was trying to follow this: http://www.wdtutorials.com/2011/06/29/drupal-7-how-create-custom-template-view#.VPXOIXXN9cY but couldn't get it to print out the $fields data.

Or am I approaching this all wrong?

If you know of a great tutorial too I'd appreciate that as well. I'm a little overwhelmed with all of it. Thanks for any help you can give.

# Answer
I found that Semantic Views worked best for me in this situation. It cuts down on the amount of HTML outputted by Drupal Views and allows you to define the HTML tag that wraps each field as well as add a CSS class.
> 1 votes

# Answer
The bulk of your HTML can be controlled via the Manage Fields section of your content type that you are displaying.

To add a bit more flexibility and configuration option to your content type, you can install Display Suite.

After installing DS and DS extras, you can enable "Field Templates" in DS settings. This will allow you to change the HTML for each of your fields.

This way, views just simply displays your data rather than controlling its appearance. You would set your view to show "Display Suite" with whatever view mode you choose. I think this is a better route when new to Drupal.

If you'd rather go the views template route, you can see a couple starting points by going to "Advanced \> Theme: Information" in your view settings. You can also check out This LInk that explains what template names to use.
> 0 votes

---
Tags: views, theming
---


# Question
Title: Replacing an existing image via the admin interface
Have access to a Drupal 6 admin and attempting to replace a single image via the admin interface. My understanding is that to just replace an existing image that I'll need to access the sever directly. Is there any way to edit (aka replace) an existing image via the admin interface?

Might be worth noting that one reason I want to replace the image, and not just upload a new one is due to the fact that the image is referenced via template, and not in a block, page, etc.

# Answer
> 1 votes
If the image is referenced via a template, there is no (easy) way to replace it via the CMS. You will need access to the file system, like FTP access.

Otherwise, you could look at finding or writing a module that gave you full access to the filesystem via the Drupal CMS. This would be.. difficult and dangerous.

---
Tags: 6, media
---


# Question
Title: Suggestions for Adding Documentation to a Drupal Application
I've built a pretty robust application using Drupal and currently have documentation available for the end users via a simple link to a pdf document. I wondered if anyone had suggestions on how to integrate a more robust help system in a Drupal application, perhaps with search etc. I've searched around on this topic but everything that comes up assumes I am talking about Drupal help documentation.

# Answer
Interesting question, I've been asking myself about the same thing. Read on for details ...

1. From your last phrase, I get the impression that you don't seem to like the "Drupal Help documentation", or that for some reason it doesn't fit your needs. I'm assuming that your talking about the Advanced Help module. If not please add an hyperlink to what exactly you mean. I've been considering actually starting to USE the Advanced Help module, e.g. in the modules I maintain, such as chart, charts and visitors. E.g. because of it's integration with Drupal searches in a site, and because it's basically HTML formatted content, which should be straightforward to use for building actual tutorial contents.

I researched a bit within some of the typical modules (in core or contrib) that do come already with such 'Advance Help' tutorial pages (like 'trigger' back in D6 I believe). It took me a while to figure out what exactly to go look for where (= "what does this 'advance help' module actually add to such module that uses it?"). After I got that, I wondered "how do they do that, or what am I supposed to do in my own module to get something similar, and what kind of options/features do I have?". I didn't quite get it at first, so then I started to just scan the code of those contribute modules (using a string that I saw in the help docu from that module). Then I figured out, as often is the case in Drupal, it is a matter of knowing how to call which hook in the advanced\_help module.

Next step I started to look around for "Advanced Help" about the "Advanced Help" module (makes sense I think, no?). Too bad, couldn't find any info about "how" to get this magic to work. Now 6 to 12 months later, and rather by accident, I discovered '1' (only!) community documentation page about the advanced help documentation. But you know what: on the project home page there is no (repeat: no) Read documentation link. After I discovered it, I did 2 things:

a) create issue #2445025 . More then 1 day later now ('only?' one might say ...), no reaction at all from any of it's maintainers. Last commit to this project is from late 2013. It makes me wonder about the health of this module (sorry). Haven't checked the health of the issue queue yet ...

b) While filing that issue, I was trying to understand the available docu in that (1) community docu page. I perceived it as fairly hard to read / understand, partially because of it's poor formatting. So I did as described in my PS in that issue. There is still lots of docu about that advanced help to be added. At least (I think) for a target audience like "technical writers" who might not have the skills to go figure out how to use the available hooks (something for drupal developers, but not for site builders or something similar). Yes producing docu might be boring for the experts who wrote a module (or it's most experienced users), but it is really important for a module to be successful, i.e. lots of reported installs and as few support / docu requests as possible
2. OK, enough about the 'help' module (wrong name! That's another module not at all related to it), I really do want to give it a try soon to get started with it in my own modules I maintain ... How about a completely different approach (which might only fit for some modules), which is "eat your own dogfood". Which is what we did in the forena module. It's a module for reporting (and charting) in Drupal, whereas it uses XHTML to actually 'develop' your custom report (report writer if you want). Here are some sample "help" pages for that module, shipped as part of the module, which you can see at work by just following the links to this demo sample:

* Forena Help: if you check it out, make sure to also experiment with that "Refine Table of contents" pull down menu near the top, and see what happens if you change the (default) value for "show chapter extract" (from no to yes).
    * FrxTitle: That's just one (out of many) of the links you can follow on the page in the previous bullet. After visiting that link, scroll to the top of that page where it says "Including". That's (obviously) the TOC for the subitems on the selected page. With some CSS (not shown in this sample), you could eg move that "including" to the upper right corner (to make it look more wiki style).
3. Voilà (oeps), here you have 2 alternatives to consider. But you know what, while writing this answer I came to realise this: for somebody who is NOT looking for a module that forena is originally designed for (= reporting about all sorts of databases), forena might ALSO be consider as a possible alternative for the "advanced help" module. To proof my point: the entire set of "help pages" I described in the previous bullet, is just a matter of some (what is called) 'FRX' files. Go checkout the forena GIT repository to go look at them to see the "source" files (in FRX format) of those tutorial pages.

What was the original question again? Did I answered it?

PS 1: For anybody wondering now "how did he do that forena tutorial?", please contact me (or 'hire us and we'll teach you') ... or just read that tutorial ...

PS 2: I actually contributed most of the work for these forena tutorials as included in the most recent version 7.x-4.x. It is a complete rework of the preio release version, in which I added tons of extra content (features that were undocumented), and introduced this new navigation links, etc. When I first shared it with the module owner (David), he asked me something like ... "How did you do that! Can't believe I never thought of that myself".
> 1 votes

---
Tags: 7
---


title: Custom module fails to install on db

text:
# Question
Title: Custom module fails to install on db
This is my first custom module to use Drupal for its data storage. So I've wired up the .info, .module and .install file as you'll see below. The .info, .module make it show up in Drupal but when I enable the module I see no table instantiated in mysql, and no warning, either.

What I did was copy the hook\_schema from here and modified it as you'll see below.

/sites/default/modules/custom/issueTracker/issueTracker.module

```
function issueTracker_init() {
  // drupal_set_message(t('hell, jars'));
}

function issueTracker_menu() {
  $items = array();
  $items['issueTracker/custom'] = array(
    'title' => 'New issue',
    'description' => "Create new issue",
    'page callback' => 'drupal_get_form',
    'access arguments' => array('access content'),
    'page arguments' => array('issueTracker_form'),
    'access callback' => TRUE
    );
  return $items;
}

function issueTracker_permission() {
  return array(
    'custom path' => array(
      'title' => t('Access the custom path'),
      'description' => t('Allow users access to the custom path'),
    ),
  );
}

function issueTracker_help($path, $arg) {
  switch ($path) {
    case 'admin/help#issueTracker':
      return '<p>' . t('Form to capture user issues') . '</p>';
      break;
  }
}

function issueTracker_block_info(){
  $blocks['current issues'] = array(
    'info' => t('Current issues'),
    'cache' => DRUPAL_CACHE_PER_ROLE,
    );
  return $blocks;
}

function issueTracker_form($form, &$form_state) {
  $form['issueDescription'] = array(
    '#type' => 'textfield',
    '#title' => t('Issue Description'),
    '#size' => 255,
    '#maxlength' => 255,
    '#required' => TRUE,
    );
  $form['submit_button'] = array(
    '#type' => 'submit',
    '#value' => t('Click here'),
    );
  return $form;
}

function issueTracker_form_validate($form, &$form_state) {

}

function issueTracker_form_submit($form, &$form_state) {

}

function issueTracker_helper() {
  return '<p>Hell, jello</p>';
}

```

And my /sites/default/modules/custom/issueTracker/issueTracker.install

```
function issueTracker_schema() {
  $schema = array();
  $schema['domIssues'] = array(

    // Example (partial) specification for table "node".
    'description' => 'Tracking issues.',
    'fields' => array(
      'issueID' => array(
        'description' => 'The primary identifier for an issue.',
        'type' => 'serial',
        'unsigned' => TRUE,
        'not null' => TRUE,
      ),
      'issueDate' => array(
        'description' => 'Date issue created.',
        'mysql_type' => 'DATETIME',
        'unsigned' => TRUE,
        'not null' => TRUE,
      ),
      'issueDescription' => array(
        'description' => 'Issue details.',
        'type' => 'varchar',
        'length' => 255,
        'not null' => TRUE,
        'default' => '',
      ),
      'lastModified' => array(
        'description' => 'Issue last touched.',
        'mysql_type' => 'DATETIME',
        'not null' => TRUE,
      ),
    ),
    // 'indexes' => array(
    //   'issue_changed' => array('changed'),
    //   'issue_created' => array('created'),
    // ),
    // 'unique keys' => array(
    //   'nid_vid' => array('nid', 'vid'),
    //   'vid' => array('vid'),
    // ),
    // 'foreign keys' => array(
    //   'node_revision' => array(
    //     'table' => 'node_revision',
    //     'columns' => array('vid' => 'vid'),
    //   ),
    //   'issue_author' => array(
    //     'table' => 'users',
    //     'columns' => array('uid' => 'uid'),
    //   // ),
    // ),
    'primary key' => array('issueID'),
  );
  return $schema;
}

```

And the output of my drush status:

```
 Drupal version                  :  7.32
 Site URI                        :  http://default
 Database driver                 :  mysql
 Database username               :  dbo
 Database name                   :  db
 Database                        :  Connected
 Drupal bootstrap                :  Successful
 Drupal user                     :  Anonymous
 Default theme                   :  velocity
 Administration theme            :  seven
 PHP executable                  :  /home/sam/.phpbrew/php/php-5.4.34/bin/php
 PHP configuration               :  /home/sam/.phpbrew/php/php-5.4.34/etc/php.i
                                    ni
 PHP OS                          :  Linux
 Drush version                   :  6.2.0
 Drush configuration             :
 Drush alias files               :
 Drupal root                     :  /media/psf/Home/apps/umhef
 Site path                       :  sites/default
 File directory path             :  sites/default/files
 Temporary file directory path   :  sites/default/files/tmp

```

I would expect that when I enable this module, either by drush or through the UI that there would be a table created called 'demises' based on my reading of the tutorials.

Knowing my history, it's likely some goof on my part and I asked myself, how do I know that I'm writing to the db as I expect. Looking on Stack I can see the module is listed in the system table and is enabled so it's likely I am writing to the same database, just get no info that I haven't written to the db.

What else can I use to troubleshoot this? thx, sam

# Answer
> 2 votes
The install file will only be executed the first time the module is enabled. Try disabling and un-installing (drush dis issueTracker && drush pm-uninstall issueTracker) and then enable again.

---
Tags: 7
---


# Question
Title: Import a PDF from within a page (Feeds / Mailhandler)
I am using Mailhandler to import quite a bit of content. The one piece I'm not able to get is a pdf.

The email body contains five links. The last link goes to a page that has an iframe with a source of the pdf I want. Example:

```
<iframe src="/files/20394.pdf">

```

However, the link in the email does not seem to have "20394" anywhere in it, so I can't even generate the link to the pdf myself.

At the end, then, I would have the importer import that link as a file.

Is there any other way to grab that pdf?

# Answer
I was able to do this using curl to get the source code then preg\_match to pull the URL. I haven't actually gotten the pdf, though, because it's using a form to generate the pdf. However, that's a different issue, so this question is answered.
> 0 votes

---
Tags: files, feeds
---


# Question
Title: Salesforce API module encryption warning
I started working on a legacy Drupal 7 site that uses the `salesforce_api` at version `7.x-2.0-alpha3` (yes, it's ancient). I noticed in the status report page the following warning:

There is a link on the warning that goes to the Salesforce module configuration page, but no real direction what to change to encrypt this properly.

Does anyone know what could be missing from the Salesforce configuration to throw this warning? Is it because the module is so old? That's my suspicion, but after googling around, nothing came up on that warning at all.

# Answer
> 2 votes
This is most likely related to AES encryption on your Salesforce credential data, not the connection itself. From the relevant doc page:

> By default, all Salesforce credentials are stored in the variables table, unencrypted. If this is a problem for you, this module supports encryption via the AES module

When you have the AES module enabled (which it seems like you do), the message you see in your site status report is:

> Salesforce encryption is enabled but not configured securely.

And if AES is not enabled, you see this instead:

> Encryption is unavailable. Using encryption is recommended in order to better secure your data.

Check out `salesforce_api_requirements()` and `salesforce_api_encryption_available()` for more. From the logic in the latter it looks like there was an attempt to return more useful information (specifically about the AES module) along with that generic "salesforce encryption" message, but for whatever reason that text never propagated up to what was printed to the screen.

---
Tags: crm
---


# Question
Title: Can Panels provide a panels context based on the URL string or URL query?
I need to know if Panels can provide a panels context based on the URL string or URL query. This context may then be used to set in the panel pane settings.

Background info: I have panels that contain panel views panes. The panels pane settings use the available panel context.

I therefore want to create a panel context based on the current URL string or URL query. Is that possible?

Note: if that is not possible, I would have to create new views panes that get their contextual filter directly from the URL instead of the available panel contexts. Using panels contexts would allow me to re-use views more efficiently.

# Answer
Page Manager can take arguments from the URL and provide them as context.

For instance if you create a path in Page Manager lik `foo/%bar/%baz` both 'bar' and 'baz' will be automatically available as Arguments. You just need to tell Page Manager what it is looking for (i.e. should it be a taxonomy term id? a node number? maybe just a plain string...)
> 2 votes

---
Tags: panels, views, uri
---


# Question
Title: Returning a variable from a rules action
I am trying to create a variation on Fetch Entity, and I'm having trouble returning an entity. I'm just grabbing the data using db\_query, and trying to return an array of nodes that are loaded, but that doesn't seem to be the data structure needed to allow me to publish them.

Basically I want to return an entity (which will always be a node in this case), and then publish it.

```
    'MY_MODULE_actions_pseudo_fetch' => array(
      'label' => t('Fetch entity by Project Request field'),
      'parameter' => array(
        'type' => array(
          'type' => 'text',
          'label' => t('Entity type'),
          'options list' => 'MY_MODULE_gen_node_list',
          'description' => t('Specifies the type of the entity that should be fetched.'),
          'restriction' => 'input',
        ),
        'value' => array(
          'type' => 'unknown',
          'label' => t('Value'),
          'description' => t('The property value of the entity to be fetched.'),
        ),
      ),
      'base' => 'MY_MODULE_actions_pseudo_fetch',
      'provides' => array(
        'entity_fetched' => array('type' => 'list', 'label' => t('Fetched entity')),
      ),
      'group' => t('Entities'),
    )

function MYMODULE_actions_pseudo_fetch($type, $value) {

  $nid = $value->nid;

  $results = db_query("select pr.entity_id from {field_data_field_project_req} pr where pr.field_project_req_target_id = :nid", array(':nid' => $nid));

  $node_array = array();
  foreach($results as $result) {
    $node_array[] = node_load($result->entity_id);
  }
    return $node_array;
}

```

# Answer
> 0 votes
Since a Rule action can provide multiple variables, an array should be returned providing the value(s) belonging to the keys defined in hook\_rules\_action\_info() hook.

In your case your function `MYMODULE_actions_pseudo_fetch($type, $value)` should `return array('entity_fetched' => $node_array);`

---
Tags: nodes, rules, entities, actions
---


# Question
Title: Why I'm getting MySQL error that server has gone away?
I'm running: Drupal 7.34, PHP 5.4.16, MySQL 15.1 Distrib 5.5.41-MariaDB, for Linux

I am getting a WSOD on just the module page after a move of server, everything else seems to be running ok.

I've added:

```
error_reporting(E_ALL);
ini_set('display_errors', TRUE);
ini_set('display_startup_errors', TRUE);

```

to `index.php` and see the below errors:

> Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE\[HY000\]: General error: 2006 MySQL server has gone away' in /public\_html/includes/database/database.inc:2171 Stack trace:
>
> #0 /public\_html/includes/database/database.inc(2171): PDOStatement-\>execute(Array)
>
> #1 /public\_html/includes/database/database.inc(683): DatabaseStatementBase-\>execute(Array, Array)
>
> #2 /public\_html/includes/database/database.inc(2350): DatabaseConnection-\>query('SELECT expire, ...', Array, Array)
>
> #3 /public\_html/includes/lock.inc(167): db\_query('SELECT expire, ...', Array)
>
> #4 /public\_html/includes/lock.inc(146): lock\_may\_be\_available('theme\_registry:...')
>
> #5 /public\_html/includes/theme.inc(449): lock\_acquire('theme\_registry:...')
>
> #6 /public\_html/includes/bootstrap.inc(455): ThemeRegistry-\>set(Array) #7 \[internal function\]:
>
> DrupalCacheArray-\>\__destruct() #8 {main} thrown in /public\_html/includes/database/database.inc on line 2171
>
> Fatal error: Access to undeclared static property: Database::$activeKey in /public\_html/includes/database/database.inc on line 1466

# Answer
> 2 votes
A couple of things to try:

First, it's potentially one of your contrib modules causing the problem, so option 1 would be to use Drush to disable all non core modules:

`drush pml --no-core --type=module --status=enabled --pipe | xargs drush -y dis`

After running this, there is a good chance that you can access your modules page again and be able to start enabling modules one by one to pinpoint the culprit.

Option 2 would be to check mysql's `MAX_ALLOWED_PACKET`. You can check this by running `SHOW VARIABLES LIKE 'max_allowed_packet'` in your mysql console. If it is set at 1MB, you can try raising it to 16M by running `SET GLOBAL max_allowed_packet=16777216;`. Try loading your page again to see if that was the issue.

# Answer
> 2 votes
It's problem with your database configuration.

You need to increase your `max_allowed_packet` value in your MySQL configuration file to at least 8MB or more depending on your site/database complexity.

---
Tags: 7, wsod
---


title: Reasons to run Drupal on PostgreSQL

text:
# Question
Title: Reasons to run Drupal on PostgreSQL
What would be the strongest reasons for running Drupal on PostgreSQL, in terms of available features and performance? I.e. what postgres features of *that are supported by Drupal* are not available on mysql? For example, postgres is known for ACID conformance and transactions; does Drupal core take advantage of these or other features in any way?

This question is not about which is a better DB in general, rather whether there are any specific reasons why one might choose postgres over mysql. One obvious trade-off is that many contrib modules will be buggy running on postgres.

I am working with D6, but feel free to direct answers to any major version.

# Answer
Personally, I think the only reason for choosing PostgreSQL over MySQL is if you (or your client) is already a PostgreSQL shop and have DBAs that know PostgreSQL well and know the ins-and-outs of babysitting it. I would also say the same also applies for choosing MySQL over PostgreSQL, assuming you aren't using any contrib modules with MySQL-only functions in them.
> 8 votes

# Answer
Some of our clients insist on using PostgreSQL because that's the only database they can support in house.

After implementing a couple of complex Drupal projects using Postgres I would say Postgres is generally faster and I would consider it if the site needs lots of rather complex views. MySQL has only one join algorithm (nested loop) whereas Postgres provides a few so when Views have lots JOINs Postgres may be more advantageous. This is more true if those views also have lots of exposed filters. However Views (both 2.x and 3.x) may experience issues with Postgres that some views with DISTINCT may not work very well if at all.

At the end of the day, if your client insists on using Postgres, and/or performance is a priority, give it a shot but be very cautious that some popular modules or some features may not function well. Or stick with MySQL if you don't have an appetite for risk.
> 2 votes

# Answer
Personally, I am using Drupal on Postgres because I need the PostGIS extension, but I reckon this is not a need many applications have.
> 1 votes

---
Tags: 6, database
---


title: Adding validation to commerce pane form

text:
# Question
Title: Adding validation to commerce pane form
I want to add validation to the user's details form.

I've tried to use the #validate to add validation function, but nothing happens.

This is the Code:

```
function hotphone_checkout_form_commerce_checkout_form_checkout_alter(&$form,&$form_state)
{
 $form['#validate'][] = 'mymodule_validate_check';
}

function mymodule_validate_check(&$form, &$form_state)
{
  dpm('hererere', $form_state);
  die();
}

```

What am i doing wrong??

# Answer
> 7 votes
The current way to do this, as per Commerce API is, instead of adding a validate handler to the complete checkout form you extend the checkout pane definition and specify your own validate handler.

If your custom validation passes, fallback to the default pane validation handler.

In this example, to add a custom validation handler to the shipping pane:

```
/**
 * Implements hook_commerce_checkout_pane_info_alter
 */
function MODULE_commerce_checkout_pane_info_alter(&$checkout_panes) {
  if(isset($checkout_panes['commerce_shipping'])){
    $checkout_panes['commerce_shipping']['callbacks']['checkout_form_validate'] = 'MODULE_commerce_shipping_pane_validate';
  }
}

/**
 * Checkout pane validation override to ensure valid shipping method for address
 */
function MODULE_commerce_shipping_pane_validate(&$form, &$form_state, $checkout_pane, $order) {

  // Do some validation tests here... omitted for brevity.
  if (!$valid) {
    drupal_set_message(t('Some validation error message'), 'warning');
    return FALSE;
  }

  // Fallback to default validator.
  if (function_exists('commerce_shipping_pane_checkout_form_validate')) {
    return commerce_shipping_pane_checkout_form_validate($form, $form_state, $checkout_pane, $order);
  } else {
    // Passed validation.
    return TRUE;
  }

}

```

> `checkout_form_validate($form, &$form_state, $checkout_pane, $order)`: validates data inputted via the pane’s elements on the checkout form and returns TRUE or FALSE indicating whether or not all the data validated

More info:

# Answer
> 0 votes
The "drupal commerce way" is the one of david thomas.

Please note that this seems also possible to use classical "hook\_form\_alter" if you don't want to declare new panes or alter existing panes (e.g, add a simple checkbox for terms and conditions), but you will have to create a custom validate function which set $form\_state\['rebuild'\] to TRUE; or you checkout will go to the next page even if an validation error have been throwed...

Here is an quick example of such a validation function :

```
function mymodule_terms_and_conditions_validate(&$form, &$form_state) {
  if (empty($form_state['values']['terms_and_conditions'])) {
  // do not go the next step of the checkout !
  $form_state['rebuild'] = TRUE;
}

```

}

# Answer
> 0 votes
Here is an alternative way that worked well for me:

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

    switch ( $form_id ) {

        case 'commerce_checkout_form_checkout':

            $form['buttons']['continue']['#validate'][]  =  'MODULE_customer_profile_billing_pane_validate';
            break;
    }
}

function MODULE_customer_profile_billing_pane_validate ( &$form, &$form_state ) {

    $needed_by_date  =  $form_state['input']['customer_profile_billing']['field_bill_date_needed_by']['und'][0]['value']['date'];
    $needed_by_time  =  strtotime( $needed_by_date );
    $time_now        =  strtotime( date( 'Y-m-d' ) );

    if ( $needed_by_time < $time_now ) {

        form_set_error(
            'customer_profile_billing][field_bill_date_needed_by',
            'The <b>Needed by Date</b> must not be in the past.'
        );
    }

```

}

# Answer
> 0 votes
Try this:

```
function hotphone_checkout_form_commerce_checkout_form_checkout_alter(&$form,&$form_state)
{
  $form['buttons']['continue']['#validate'][] = 'mymodule_validate_check';
}

//custom validation
function hotphone_checkout_form_validate_check($form, $&form_state) {
  //suppose you want to validate the field in customer profile billing
   $value = $form_state['values']['customer_profile_billing']['field_name'];
   if ($value == '') {
     form_set_error('customer_profile_billing][field_name', t('Please enter valid values'));
   }
}

```

---
Tags: commerce, forms
---


# Question
Title: Is there a way to add terms for the Spell Checker in editor to reference?
There are unique terms related to the industry that the spell checker might flag as incorrect.

We are looking for a solution for the client team to add the unique terms so they are not flagged as incorrect when spelt correctly and suggest this term for when it is spelt incorrectly.

Please help.

# Answer
Checkout the following modules:

Wysiwyg SpellCheck

> Wysiwyg SpellCheck module is a plugin for wysiwyg editor that enables TinyMCE spellchecker plugin.

Spell Checker

> This module supports spell checking of node content (including title, body and CCK fields).

Image from project page.
> 2 votes

---
Tags: 7, wysiwyg
---


# Question
Title: fetching taxonomy tree from database from query
I add a vocablary named "product sub categories" and I want to fetch the whole tree structure from datebase through query? Can anybody can help me?

# Answer
This is a way to do it!

```
$vocabulary = taxonomy_vocabulary_machine_name_load('Services');
$terms = entity_load('taxonomy_term', FALSE, array('vid' => $vocabulary->vid));

```
> 0 votes

---
Tags: taxonomy-terms, database
---


# Question
Title: Query Drupal User Table for: date created < $today - '100000'
I would like to select users from the Drupal users table where the date created was older than 1 day ago. Then delete those users. This code isn't correct but it will give you an idea of what I am trying to do I just don't know the right DB query. '

```
$users = db_select('user', 'created') //I know this is not the right DB query
$count = count($users);
if($count > 0){
  $users = user_load_multiple(array_keys($users['user']));
}
$today = getdate();
if ($users < $today - '100000' ) {
 user_delete($user->uid)
}

```

I am thinking about using user\_load\_multiple() to load the users in to an array to perform the delete action.

# Answer
> 3 votes
You can achieve this using `EntityFieldQuery` as shown below:

```
$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'user')
  ->propertyCondition('created', strtotime("-1 day"), '<')
  ->propertyCondition('uid', array(0,1), 'NOT IN');
$result = $query->execute();
if(!empty($result)){
    user_delete_multiple(array_keys($result['user']));
}

```

---
Tags: 7
---


# Question
Title: How to show the content type diffrent types in a block?
I have a news website, I have one content-type what named **news**, news has some fields like:

> news\_title
>
> news\_date
>
> images
>
> body
>
> news\_type

I want each news type shows in a block dynamically, my news\_types are **Sport, Economy, Political, Health** and some others. and I want each of this shows in one block, is there any way is view or even in content-type settings to do this?

# Answer
> 2 votes
Use Views module to create multiple blocks for different news types. Once you creates blocks using views, assign them to regions from Admin -\> Structure -\> Blocks.

---
Tags: views, 7
---


# Question
Title: How do I add managed images to the Media Module browser stored locally through a remote URL?
This question has been asked lots of other places and I was quite determined to make it happen. The use case is copy and paste a URL for an image on the web into the Media Module file browser. The Remote Stream Wrapper module does something similar except the images are not stored on the local server. Instead the metadata about the image is stored in the database while Image Cache stores images locally. I really wanted to import images I have access to onto my server.

# Answer
First, a form is built. Then the elements in the form array are expanded during `drupal_process_form()`. The default value of each element is set during this stage. The `file.module` has a callback hook added during the set element value stage which other form elements do not have, '#file\_value\_callbacks\`.

I simply added a textfield element to the upload form for the media browser and registered a callback. If there is an URL in the textfield, `drupal_http_request()` is used to pull the data / image and save it passing the file ID as the value of the upload widget element to finish processing the image.

It seems to work as expected. There are some gaping security holes which need to be cleaned up. Nonetheless, this implementation will greatly increase the efficiency of workflow for my next project.

Here is my solution:

```
/**
 * Implements hook_form_FORM_ID_alter()
 */

function helper_form_file_entity_add_upload_alter (&$form, &$form_state, $form_id) {
  // Keep the textfield clear if there is a file ID
  // We only have to upload the image once then who cares?
  if (!empty($form['upload'])){
    $form['upload']['#file_value_callbacks'][] = 'helper_file_value_callback';
    $form['url'] = array(
      '#type' => 'textfield',
      '#title' => 'Enter image URL',
    );
  }
}

function helper_file_value_callback (&$element, &$input, &$form_state) {
  global $user;

  // Make sure that there is a $url
  if (empty($input['fid']) && valid_url($url = $form_state['input']['url'])) {

    $upload_name = implode('_', $element['#parents']);
    $destination = $element['#upload_location'];
    $parsed_url = parse_url($url);
    $path = str_replace('///', '//', "$destination/") . drupal_basename($parsed_url['path']);

    // Make sure that there is a directory.
    if (isset($destination) && !file_prepare_directory($destination, FILE_CREATE_DIRECTORY)) {
      watchdog('file', 'The upload directory %directory for the file field !name could not be created or is not accessible. A newly uploaded file could not be saved in this directory as a consequence, and the upload was canceled.',
          array('%directory' => $destination, '!name' => $element['#field_name']));
      form_set_error($upload_name, t('The file could not be uploaded.'));
      return FALSE;
    }

    // Download file and make sure that return code is 200 or else abort!
    $result = drupal_http_request($url);
    if ($result->code != 200) {
      drupal_set_message(t('HTTP error @errorcode occurred when trying to fetch @remote.',
          array('@errorcode' => $result->code, '@remote' => $url)), 'error');
      return FALSE;
    }

    // Construct the $file object
    // file_save() adds the timestamp and filesize on save
    // file_unmanaged_save_data posts message on error
    if ($uri = file_unmanaged_save_data($result->data, $path, FILE_EXISTS_RENAME)){
      // Create a file object
      $file = new stdClass();
      $file->fid = NULL;
      $file->uri = $uri;
      $file->filename = trim(drupal_basename($parsed_url['path']));
      $file->filemime = file_get_mimetype($file->uri);
      $file->uid = $user->uid;
      $file->status = 0;

      if (file_save($file)){
        $input['fid'] = $file->fid;
      }
    }

  }
}

```
> 0 votes

---
Tags: media
---


# Question
Title: How to automatically link specific words in a node to other nodes?
Lets say i have a node with a body like:

" Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc cursus dapibus diam sit amet aliquet. "

I'm looking for a way to convert the **consectetur** (for example) word into a link to another node, when the node is displayed (**and not when is edited!**)

What is the best practices to define what node shuld be linked to that word (taxonomy? cck field?), and how to do that (theme\_preprocess\_node?).

Please note that, whatever hook/theme function i can use, the results **must** be cached (until the node get edited again): the site is for a no-profit cultural association with the lowest budget i've ever seen ;)

# Answer
I think the Glossary module does what you need?

You define a taxonomy and it will scan the text and provide links to the terms when a node is displayed.
> 0 votes

# Answer
I would definitely use taxonomy for the relation between node and word, I would then use hook\_node\_save to alter the value of the body and add the links with a preg\_replace. By adding a specific class to those links you can then remove those links with hook\_form\_alter before the body field is displayed for editing.
> 0 votes

# Answer
If you are looking for a Drupal 7 alternative, then the Glossify module is the way to go for this.
> 0 votes

---
Tags: navigation, nodes
---


title: Multiple Charts with Chart Module?

text:
# Question
Title: Multiple Charts with Chart Module?
I need to present multiple graphs in a single page. Is it possible to do this using the Charts module? Up until now I have been using the following to return a chart to the page.

```
return theme('chart', array(
                      'chart' => $chart,
                    ));

```

# Answer
After a while doing the following worked, I do not know why it did not work from the beginning :

```
return theme('chart', array(
              'chart' => $chart,
              )).theme('chart', array(
              'chart' => $chart,
              ));

```
> 2 votes

# Answer
I think you are using the chart module, not the charts module ... please add a link in your question to the module you're using.

It'd be interesting to know what result you get by only replacing `theme` by `echo` ... similar to what is shown in the D7 examples using theme() (using the chart-without-s module).

If that doesn't help then consider including the related coding for building the chart array in your question.
> 1 votes

---
Tags: 7, charts
---


# Question
Title: Drupal 7 not able to run cron after views/panels update
After an update of several modules to their latest versions (views, panels, ctools) it seems Drupal can no longer run cron, whether automatically or manual. It gives the error: "Cron run failed."

I have no idea what might be causing this and only discovered it some 10 days after performing the updates. The lightweight cron (for scheduled content) that I have set up externally in cpanel still runs.

Also a bit worrying is, when visiting mywebstie.com/cron.php (as an anon) it shows me my actual frontpage with some broken css. Which, I believe, is an unintended behaviour as it should show a blank page or a "content not found" page.

I believe the number 1 suspect is the views module, since immediately after the update I noticed that admin/content view no longer updates the "node views today" value and it just continuously increments this value without reinitialising every 24hours.

Any ideas of what might be the issue here?

Everthing was normal before the said updates: I have Unix server using Centos. BTW I have a local copy of the site using Xampp and it has the same cron problem as the live site. I am inclined to believe this is not a server problem.

PS: I have never used drush..

# Answer
> 0 votes
For troubleshooting cron.php problems found this:

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

Cron stopped running; logs say: "Attempting to re-run cron while it is already running."

I have been able to trigger cron using the ultimate cron module, which is in beta.

Still don't understand what was going and didn't find the faulty module but the "attempting to re-run cron while it's already running" error msg has gone away from the logs.

---
Tags: views, panels, cron, chaos-tool-suite
---


title: Cron Run error for drush update script

text:
# Question
Title: Cron Run error for drush update script
I have created a script drup.sh to update the site with security issues and placed it in the sites/default dir.

```
#!/bin/bash
drush up drupal --security-only -y

```

And on testing it by running bash drup.sh from the command line, as the user, in the sites/default dir. all works good

When I set up a cron to run it, as the user, I get the following errors

```
Command pm-update needs a higher bootstrap level to run - you will       [error]
need to invoke drush from a more functional Drupal environment to run
this command.
Command pm-update needs the following modules installed/enabled to       [error]
run: update.
The drush command 'up' could not be executed.                            [error]
A Drupal installation directory could not be found                       [error]

```

The command I use at the moment is

```
bash /home/user/public_html/sites/default/drup.sh

```

---

I have looked at the page you suggested, I had looked at it before but it did not make sense to me. I have tried various combinations, without success

The closest I can get to it not giving an error is

```
/usr/bin/env PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/root/bin COLUMNS=72 --username=/home/username/public_html/sites/default/drup.sh

```

the output is

```
SHELL=/bin/sh
USER=middlesex
LD_LIBRARY_PATH=
REMOTE_ADDR_PROTOCOL=4
PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/root/bin
SERVER_REALROOT=/usr/libexec/webmin
PWD=/usr/libexec/webmin/cron/
PERLLIB=/usr/libexec/webmin
REMOTE_ADDR=x.x.x.x
SHLVL=1
HOME=/home/username
LOGNAME=username
_=/usr/bin/env
COLUMNS=72
--username=/home/username/public_html/sites/default/drup.sh

```

But drush does not run or do anything

# Answer
> 0 votes
Take a look what is said here about running drush with crontab and pay especially attention to "Setting the PATH". Also you should specify the path to your drupal installation with the --root option.

---
Tags: cron
---


# Question
Title: Adding conditional statements as Math expression to custom text fields in views
I have created views in which i have added custom text and Math expression.
I displayed view in table format
I created one Math expression which is noticed below:

```
[Field 1] - [Field 2]

```

I have displayed this expression into another custom field in views.
Now i want to add some condition statements.
That is

```
If [expression] >= 0
 'display something'
else
 'other texts'

```

Is it possible to add conditional statement in Math expression views?

# Answer
Well you can override any of the output you have from views with a template override.

Goto your Views \> Display

on the right hand side in the box labelled 'other'

> click on information next to 'theme'

This will give you a list of template pages you can use to over write the section you need. A little trial and error maybe needed at first until you get used to what your being presented.

> on the left hand side of the page suggested you have a link to the code you need to use. Copy that code and paste it into the file name your targetting ( ie views-view-field--default.tpl.php ) and add in the theme/templates folder your using.
>
> from here on you can manipulate the code how you want using php

Hope this makes sense, as I wrote it real quick :)
> 0 votes

---
Tags: views, entities
---


title: Drush cannot connect to mysql

text:
# Question
Title: Drush cannot connect to mysql
I have a problem with Drush to enable or disable module. But downloading modules works perfect! However I want to use Drush in its full range.

Yesterday, I saw my Drush would not succeed in connecting to the database. I already tried to update the path in .bash\_profile to the AMPPS path. But after that, my bash cannot find the database any more. I already deleted the line but bash don't find mysql.

Anybody has an idea about what to do to resolve this?

**Below are the various messages I received:**

> Sams-MacBook-Pro:demo Sam$ drush en views -d
>
> Starting Drush preflight. \[0.01 sec, 1.82 MB\] \[preflight\]
>
> Cache HIT cid: \[debug\]
>
> 7.0-dev-commandfiles-0-9942ce60ec4ba1e3ca6f94d08d021773 \[0.01 sec, 1.88 MB\] Bootstrap to phase 0. \[0.09 sec, 5.75 MB\] \[bootstrap\]
>
> Bootstrap to phase 6. \[0.09 sec, 5.76 MB\] \[bootstrap\]
>
> Drush bootstrap phase : \_drush\_bootstrap\_drupal\_root() \[0.09 sec, \[bootstrap\] 5.76 MB\]
>
> Initialized Drupal 7.34 root directory at \[notice\]
>
> /Applications/AMPPS/www/demo \[0.1 sec, 6.09 MB\]
>
> Cache HIT cid: \[debug\] 7.0-dev-commandfiles-1-68c4337f6c538cdf6d3ca715c4afb7a3 \[0.1 sec, 4.17 MB\]
>
> Drush bootstrap phase : \_drush\_bootstrap\_drupal\_site() \[0.1 sec, 4.18\[bootstrap\] MB\]
>
> Initialized Drupal site default at sites/default \[0.1 sec, 4.18 MB\] \[notice\]
>
> Cache HIT cid: \[debug\] 7.0-dev-commandfiles-2-9518eda12b48158193bd617384d95a7d \[0.11 sec, 4.18 MB\]
>
> Drush bootstrap phase : \_drush\_bootstrap\_drupal\_configuration() \[0.11\[bootstrap\] sec, 4.18 MB\]
>
> sql-query: SELECT 1; \[0.11 sec, 4.3 MB\] \[status\]
>
> Executing: mysql --defaults-extra-file=/private/tmp/drush\_9NOj8N --database=demoDB --host=127.0.0.1 --silent \< /private/tmp/drush\_gIJn4w
>
> sh: mysql: command not found
>
> Bootstrap to phase 5. \[0.12 sec, 4.3 MB\] \[bootstrap\]
>
> Command pm-enable needs a higher bootstrap level to run - you will \[error\]
>
> need to invoke drush from a more functional Drupal environment to run this command. \[0.12 sec, 4.3 MB\]
>
> The drush command 'en views' could not be executed. \[0.12 sec, 4.3 \[error\] MB\]
>
> Drush was not able to start (bootstrap) the Drupal database. \[error\]
>
> Hint: This may occur when Drush is trying to:
>
> * bootstrap a site that has not been installed or does not have a configured database. In this case you can select another site with a working database setup by specifying the URI to use with the --uri parameter on the command line. See `drush topic docs-aliases` for details.
> * connect the database through a socket. The socket file may be wrong or the php-cli may have no access to it in a jailed shell. See http://drupal.org/node/1428638 for details.

**Drush was attempting to connect to:**

> Drupal version : 7.34
> Site URI : http://default
> Database driver : mysql
> Database hostname : 127.0.0.1
> Database port :
> Database username : demoDB
> Database name : demoDB
> PHP executable : /usr/bin/php
> PHP configuration :
> PHP OS : Darwin
> Drush version : 7.0-dev
> Drush temp directory : /tmp
> Drush configuration :
> Drush alias files :
> Drupal root : /Applications/AMPPS/www/demo
> Site path : sites/default
>
> \[0.17 sec, 6.42 MB\] Sams-MacBook-Pro:demo Sam$

# Answer
> -2 votes
Ok i solved that problem my own. I have deleted the Drush Version 7.x and installed the 6.x Version. it works like a charm.

---
Tags: drush
---


# Question
Title: How can I reuse translations from other contexts?
I know that in Drupal 7, **contexts** are used to provide multiple translations for the different meanings of the same string.

This works great for sentences that do have different meanings depending on the context. But for most of the cases, this means that I'll need to translate the same string twice or more times.

Is there a way to automatically reuse the translations from other contexts, when it's not already translated for the real context of the string?

If not, what is the best way to automatically import all the translations from one context to another?

# Answer
The problem is that the set of i18n modules set the context for strings automatically. For instance, suppose I reuse a taxonomy reference field in many content types. The vocabulary name and each of the field labels are exactly the same and have the same set of translations, but each one must be translated entirely independently. That field may also show up as an exposed filter in views and I have to translate it independently in each view as well.

Now suppose I mistranslated the vocabulary name for one of the languages and need to fix it. I have to change it everywhere, which is a ridiculously tedious process.

It would be REALLY nice to be able to translate a particular string such as this once and have it automatically update everywhere that string appears. I have been able to hack it by manipulating the locales\_target table in the database directly, but that is definitely not a good solution.
> 1 votes

# Answer
Article on localize.drupal.org says:

> Contexts are to be used for places where the string itself is too short to give enough context and could lead to mistranslation, or can have multiple translation in different uses. It is not to be abused wholesale for module strings, but only to be used after consideration.

It means you set the context only when the string itself is ambiguous. If it is, it's your responsibility to provide translations - all of them, because even if now that other translation is acceptable, it may cease to be if original context will call for a slightly different translation. If you have to much, well, it may be what first user of localize.drupal.org calls "abused wholesale" in his article.

API shows clearly - there is an option to set context, or not to. That's all there is.
> 0 votes

# Answer
Check out translation\_fallback module:

> This module enables fallback to the default context when a string has no translation in its own context.
> 0 votes

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


# Question
Title: Is there a way to conditional sort criteria in views
Is there a way to make a conditional sort criteria with views in D7?

I want to do the following stuff:

```
if node property = x
  use this sort criteria
else
  use this one

```

# Answer
You could achieve this using Views PHP.

Excerpt from the page:

> This module allows the admin account (user 1) to add fields, filters and sorts to views which use PHP code. It also supports additional accounts when the core PHP Filter module is enabled.
> 3 votes

# Answer
```
/**
 * Implements hook_views_query_alter().
 */
function HOOK_views_query_alter(&$view, &$query) {
  if ($view->name == 'view_name' && $view->current_display == 'page') {
    $query->orderby = array(
      array(
        'field' => 'CASE WHEN node.property = x THEN node.y ELSE node.z END',
        'direction' => 'ASC',
      )
    );
  }
}

```

https://www.drupal.org/node/2133879
> 3 votes

---
Tags: 7, views
---


title: Add help text to title D7

text:
# Question
Title: Add help text to title D7
How can I add Help text to the Title in D7?

Perhaps adding an 'edit' button similar to the other *normal* fields.

Ideally the solution integrates with Label Help.

# Answer
> 1 votes
'title' on a node is not a field, but a property, you can convert it into a field (with all it's goodness) with https://www.drupal.org/project/title .

# Answer
> 2 votes
This module can be used to add help text to node title https://www.drupal.org/project/node\_title\_help\_text

---
Tags: 7, nodes
---


title: Drupal 7.22 and Templating

text:
# Question
Title: Drupal 7.22 and Templating
I am developing a site using drupal. I need to create a template file for a specific page. For instance this is my site url http://www.dev.com. I created a basic page called documents which URL path settings alias is docs. So what I want to do is that whenever the user clicks on http://www.dev.com/docs drupal should use a specific template file. For that matter I create a tpl file called page--docs.tpl.php and put it inside my theme folder. However drupal seems not loading that file.

PLease assist me if I am missing something.

# Answer
> 2 votes
You need to use the non-aliased path for the template name.

For example if you are dealing with node 1 (node ID = 1) try naming the file `page--node--1.tpl.php` and clearing the cache again.

For more info see: https://drupal.org/node/1089656#page-suggestion

If you don't know what the node id is, go to the node edit page and it will be in the url /node/NODEID/edit.

# Answer
> 0 votes
To quickly and efficiently find the name to call your template add the following

```
$conf['theme_debug'] = TRUE;

```

to you your settings.local.php this will add a comment block before the rendering of your data

```
<!-- THEME DEBUG -->
<!-- CALL: theme('node') -->
<!-- FILE NAME SUGGESTIONS:
 * node--419.tpl.php
 x node--standard-content-page.tpl.php
 * node.tpl.php
-->

```

for example the above block tells me that if I want to just theme for that one object use the "node--419.tpl.php" for the filename but I chose to make the theme edit available for all objects of the type "standard\_content\_page"

Ado

# Answer
> 0 votes
You should try using the page theme module it does exactly what you're looking for using drupal configuration and there's a stable version for drupal 7.

# Answer
> -1 votes
you can also overwrite the template in template.php as well

```
function themeName_preprocess_page(&$vars, $hook) {
$vars['template_files'][] = 'page--docs';
}

```

---
Tags: theming
---


title: How to use hook_menu title arguments

text:
# Question
Title: How to use hook_menu title arguments
Reading hook\_menu it says this:

> "title": Required. The untranslated title of the menu item.
>
> "title callback": Function to generate the title; defaults to t(). If you require only the raw string to be output, set this to FALSE.
>
> "title arguments": Arguments to send to t() or your custom callback, with path component substitution as described above.

So how to use it? Right now i have this

```
function custom_gmap_neo_menu(){
    $item = array();

    $item['custom_gmap_neo/%/%/%'] = array( // hotel/origin/destination
        'title' => 'Get directions to @hotel',
        'title arguments' => array(1),
        'page callback' => 'custom_gmap_neo_show',
        'page arguments' => array(1,2,3),
        'access callback' => TRUE,
    );

    return $item;
}

function custom_gmap_neo_show($hotel, $origin, $destination){
    dpm($hotel);
    dpm($origin);
    dpm($destination);

    return '';
}

```

So knowing that default function for title callback is t() how to actually pass the @total wildcard to the t() function?

# Answer
When you define `title arguments` as an array, each array element will be passed as arguments in that sequence.

Now you have `title arguments` defined as `array(1)`, which means the actual call would mimic `t('something')` if the URL path was `custom_gmap_neo/something/something_else/something_else_1`.

If you want to call `t()` function as `t('Get directions to @hotel', array('@hotel' => 'something'))`, you need to define your own `title callback`, because automatic integer to path argument translations only happen in the root level array elements.

```
<?php
function custom_gmap_neo_menu(){
    $item = array();

    $item['custom_gmap_neo/%/%/%'] = array( // hotel/origin/destination
        'title arguments' => array(1),
        'title callback' => 'custom_gmap_neo_get_map_title'
        'page callback' => 'custom_gmap_neo_show',
        'page arguments' => array(1,2,3),
        'access callback' => TRUE,
    );

    return $item;
}

function custom_gmap_neo_show($hotel, $origin, $destination){
    dpm($hotel);
    dpm($origin);
    dpm($destination);

    return '';
}

function custom_gmap_neo_get_map_title($hotel) {
  return t('Get directions to @hotel', array(
      '@hotel' => $hotel
    ));
}
?>

```

However, if your first URL argument (hotel) is a node, consider using `%node` as the path wildcard, because it can load the node for you, and handles page not found errors automatically if `node_load` returns an empty result. Otherwise you will have to call `node_load` twice. `node_load` caches results, but there are many loader functions that do not cache results.
> 3 votes

---
Tags: 7, routes
---


title: Can not remove the Devel module

text:
# Question
Title: Can not remove the Devel module
While doing an upgrade to the Devel-module something went terrible wrong. Decided to remove the module through the "Uninstall"-tab. The module is however not listed there, while it's marked as active under the "Install"-tab. Removing the module manually (deleting the files) causes errors so I cannot do it this way either.

Ironically I need this module to be able to re-install other modules which are outdated. Anyone got any feedback how to cleanly remove the Devel-module without the Uninstall tab?

I do not have Drush for D8, need another way as I got D6 and D7 instances installed on the same environment aswell.

# Answer
> 2 votes
Can't you use the "normal" upgrade scenario for FTP servers? (I usume this still works btw. haven't tested it on d8 yet) \- Download your intended version of devel from d.o. \- Unpack the download \- Upload to the server in place of the old devel module (so same paths,permissions,etc) \- Run the "update.php" script to update the Database.(you need to be admin to do this, or change your settings.php to temp. allow anyone to do it). \- Devel should be updated now.

according to the docs this should work see d.o. D8 Update a module

# Answer
> 1 votes
Drush is the best solution IMHO.

You can install Drush 7 is compatible with D6, D7 and D8.

You can too (dirty way):

1. Uninstall Drush 6 or that you have.
2. Install Drush 7.
3. Uninstall Devel Module (`drush pmu devel`)
4. Uninstall Drush 7.
5. Install Drush 6 or whatever again.

---
Tags: 8
---


# Question
Title: Twitter feed on Drupal from multiple accounts
I want to add several Twitter profiles on my Drupal and create groups of them and show their tweet feeds. At the moment, I found a module which let me add only one Twitter profile. Here is an example:

* Group A: User 1, user 2, user 3
* Group B: User 4, user 5
* Group C: User 6, user 7, user 8, user 9

The create blocks (probably with Views?) and show all the tweets from each group. Another problem, I had with the module I have is that it needs the user to authorize his profile to get his tweets.

Is there any other way to do it without ask from user to authorize and with multiple profiles feature?

# Answer
> 2 votes
The twitter module allows you to get the tweets from various accounts and display them via views.

So you can have a view for your first 3 users and then another one for the other two and so on...

Now, you will have to provide an authenticated account via the twitter apps api. But then you'll be able to pull tweets from other non authenticated accounts.

---
Tags: social-network
---


# Question
Title: How to define custom messages in Drupal 7
I want to show a custom message to user after he/she adds a new content of a specific type in Drupal 7. If I change the '@type %title has been created' to what I want the message will change for all content types.

How can I do it? Is there any module to define messages for different actions?

# Answer
> 3 votes
I just did this the other day, it's a bit of a hack, but I couldn't find another way. The basic premise is to get and clear all current messages, loop through and call drupal\_set\_message() on all of them over again, changing the one you want:

```
<?php
/**
 * Submit function for the message node form.  Check for new message notification and change it.
 */
function mymodule_message_node_form_submit($form, &$form_state) {
  $node = $form_state['node'];
  $t_args = array('@type' => node_type_get_name($node), '%title' => $node->title);
  $replace_message = t('@type %title has been created.', $t_args);

  // This call will get all messages and clear them from $_SESSION
  $messages = drupal_get_messages('status');
  foreach ($messages['status'] as $message) {

    if ($message == $replace_message) {
      drupal_set_message(t('Thank you your message has been sent successfully.  We will be in touch shortly.'));
    }
    else {
      drupal_set_message($message);
    }
  }
}
?>

```

# Answer
> 1 votes
I am using this to replace an existing drupal message to my custom message.

```
function _exclude_message($mymessage, $mytype="status"){
$flag = false if ($messageArr = drupal_set_message()) {  foreach($messageArr as $type=>$messages) {
  if ($mytype==$type) {
    foreach($messages as $key=>$message) {
      if ($mymessage==$message) {
    unset($_SESSION['messages'][$type][intval($key)]);
       $flag = true;
      }
   }
  }
  if (count($_SESSION['messages'][$type])==0) unset($_SESSION['messages'][$type]);}} return $flag;}

```

`function my_theme_status_messages($display = NULL) {
 if (_exclude_message('Sorry, unrecognized username or password. Have you forgotten your password?',"error")) drupal_set_message("Sorry, unrecognized username or password.","error");
 return theme_status_messages($display);
}`

under template.php

this code will replace existing "Sorry, unrecognized username or password. " with my custom message "Have you forgotten your password?".

Hope this will help you.

# Answer
> 0 votes
I had to do that too. My solution is for error messages in validation hook. But should be quite the same for a confirmation message. You just have to find the id of the message (in my example the name of the field).

First I used a function to prevent the message from beeing sent.

```
function form_unset_error($name) {
   $errors = &drupal_static('form_set_error', array());
   $removed_messages = array();
   if (isset($errors[$name])) {
     $removed_messages[] = $errors[$name];
     unset($errors[$name]);
   }
   $_SESSION['messages']['error'] = array_diff($_SESSION['messages']['error'], $removed_messages);
   if (empty($_SESSION['messages']['error'])) {
     unset ($_SESSION['messages']['error']);
   }
}

```

So in my validation hook I unset the message and set a custom error message instead :

```
form_unset_error('field_name][und][0][value');
form_set_error('field_name', t('Custom error message translated'), $limit_validation_errors = NULL);

```

Hope it helps.

---
Tags: 7, status-messages
---


# Question
Title: How to add an URL link below the image in a custom content?
## Actual:

## Working content:

**My question**: How do I achieve adding URL link below my custom content images (i.e under those four images I need the URL links)?

# Answer
> 1 votes
If I understand the problem correctly: on a website page, you want to display images with some text underneath and possibly, have that text (and image) link somewhere?

Without knowing how are you collecting those images and text it may be difficult to answer it but here is what I would suggest:

1. Have a **content type** (let's call it "Highlight image") that will collect one image, text to appear underneath the image and a link you want that image and text to open.
2. Add the required images, text and links (4 in your case)
3. Create a **View \> Block displa**y with filter to display content of "Highlight image" type (or whatever you named it), published. Select fields for that view and change their settings:
    * **link** \- set to not display since we will use that link in image and text fields to link them to the URL from link field
    * **image** \- in **Rewrite Results \> Output this field as a link**: enter your link field value (check under Patterns to see what is your link field name and enter here, as a link to be used). It will be something like \[link\]
    * **text** \- do the same as for image field, in Rewrite Result options tell the view you want that text to appear as link
4. **Add the block to the page** where you want the images to appear.

If you don't want to use the Views, you may want to modify the custom content type, collect the link there (one for each image) and then modify the display of that content type to use the link - modify either using template functionality for that node or use Display options for that content type. I think the View implementation is more elegant and easier to maintain in the future.

---
Tags: media, uri
---


title: Batch deleting nodes breaks database

text:
# Question
Title: Batch deleting nodes breaks database
On my Drupal site, I have about 100 nodes that need deleting. I have deleted them via Views Bulk Operations.

When I do this, if I make a backup of my site MySQL database and then try to restore it via PHP My Admin, I get the following error:

```
INSERT INTO `cache_form` (`cid`, `data`, `expire`, `created`, `serialized`) VALUES
('form_state_form-0ry4vXadnLIroZBOuRNpM4WJWgNm0HNVumQ1bNHLEu4', 0x613a363a7b733a31303a226275696c645f696e666f223b613a333a7b733a343a2261726773223b613a323a7b693a303b4f3a343a2276696577223a35363a7b733a383a2264625f7461626c65223b733a31303a2276696577735f76696577223b733a31303a22626173655f7461626c65223b733a343a226e6f6465223b733a31303a22626173655f6669656c64223b733a333a226e6964223b733a343a226e616d65223b733a31313a2262756c6b5f64656c657465223b733a333a22766964223b733a313a2236223b733a31313a226465736372697074696f6e223b733a303a22223b733a333a22746167223b733a373a2264656661756c74223b733a31303a2268756d616e5f6e616d65223b733a31313a2242756c6b2044656c657465223b733a343a22636f7265223b733a313a2237223b733a31313a226170695f76657273696f6e223b4e3b733a383a2264697361626c6564223b4e3b733a373a2265646974696e67223b623a303b733a343a2261726773223b613a303a7b7d733a383a227573655f616a6178223b623a303b733a363a22726573756c74223b613a3130303a7b693a303b4f3a3[...]
MySQL said: Documentation

#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 '' at line 2

```

The error has been caused by deleting the nodes. If I go to an earlier back-up before the nodes were deleted, it works fine. However, everytime I delete the nodes, this error comes back.

How can I delete the nodes without the database becoming corrupt. I clear the cache after deletion and before backing up, but the problem still occurs.

Interestingly after deleting nodes, the size of the databse jumps from 16MB to 80MB. So I am not sure if the deletion is putting some bad data in the database.

# Answer
> 0 votes
When you delete a lot of Nodes in Drupal, the cache\_form table in the database becomes very large. You need to empty this before making a backup.

Steps:

1. Go to PHPMyAdmin and open your Database
2. Click on structure.
3. Look for the row "cache\_form:
4. Look at the MB value for the row. If it is a big value, that's the problem.
5. Click on Empty.

Now you can back up your database and can then be restored.

# Answer
> 0 votes
You need to increase `max_allowed_packets` in `my.cnf` file. to insert big data from cache tables. The best practice to avoid this is, never export cache prefixed tables data.

---
Tags: nodes, database
---


title: how to alter block subject html tag?

text:
# Question
Title: how to alter block subject html tag?
I am trying to change the `<h2>` tags that `block.tpl.php` uses to wrap `<?php print $block->subject ?>` to `<h3>` tags so that I can target them with jQuery UI Accordion. I've got the following code:

```
<?php
    function MYTHEME_block_view_alter(&$data, $block) {
        if($block->module == 'block' && $block->region == 'sidebar') {
            $data['subject']['#tag'] = 'h3';
        }
    }
?>

```

This doesn't work...I assume I'm screwing up the reference to the render element. Does `$data['subject']` contain an array where the HTML tag is stored? What is the correct way to target it?

Alternatively, should I look for a way to re-write block markup so that, in the `sidebar` region, it renders only the `<h3>` and `<div>` required by jQuery UI Accordion? Unless there's a fantastic module for turning blocks into Accordion-ready HTML already out there, I'd rather not install another module.

Many thanks for any help!

# Answer
You can override the block template for a particular block and can modify the html for block subject.

You can check theme suggestions for more reference.
> 2 votes

# Answer
You can rewrite the block output using HOOK\_BLOCK\_VIEW\_ALTER
> 0 votes

---
Tags: 7, theming, hooks, blocks, javascript
---


# Question
Title: Linking an individual term from a vocabulary with all terms from another vocabulary
I have two vocabularies/fields, one called Days that has all the days of the week (Mon, Tues, Wedn...) as terms, and another vocabulary/field called Time of Day that has terms (Morning, Midday, Afternoon, Evening, Night, Late).

I'm hoping to use these vocabularies/fields for a type of opening hours style tagging, e.g. X venue is open Monday: Morning, Midday, and Evening, Saturday: Evening, Night, Late, etc.

I'm imagining a situation when I check the box next to 'Monday' the terms in the Time of Day field will become visible and I'll be able to check the 'Morning', 'Midday', and 'Afternoon' boxes. Likewise for when I check any other box next to another Day term.

Can you guys think of a way I could set this up with my field structures?

Thanks in advance!

EDIT: Hey guys, new aspect of this question now. So I'd like to attach tags to different day and opening hour combinations, e.g. Monday Morning X Venue is good for coffee, breakfast, Saturday Night at X Venue is good for cocktails, dancing.

I've currently got a vocabulary of tags. How can I go about linking the tags and the opening hours/days? A heirachy would be an option, but that would make for a hell of a lot of repeated clicking for the user. Any thoughts?

# Answer
To do a hierarchical taxonomy, Use Taxonomy Manager and all you need to do is include the hyphen before the child terms, as shown in the answer above when you bulk add terms

You can also use the standard taxonomy manager, and use drag handles to inset children, like I have done below.
> 3 votes

# Answer
I would set this as a hierarchical taxonomy rather than two vocabs (hyphen indicates child term):

```
Monday
-Morning
-Midday
-Afternoon
Tuesday
-Morning
-Midday
-Afternoon

```

Simple Hierarchical Select will then give you the perfect widget for that too
> 1 votes

# Answer
I'm not sure if I see a value of somehow connecting those two vocabularies ("Day" and "Time of Day"). They don't have to be connected in any way for the display to work properly. Both vocabularies can be displayed on the content type for creator to enter both "Day" and "Time of Day". As for display, they can be made to display in one line, with - or something, so to site visitors they appear as one value. Another **reason I would keep those vocabularies separate** is that if you want visitors to be able to **find venue that is open any day of the week but only in the morning**, having two vocabularies makes is very easy in, for example, Views to have two separate filters. That way visitors can select "morning" only without having to select the day. Similarly other way, visitors can select a day without having to specify the time of day, when they looking for something that happens any time during that day.
> 1 votes

---
Tags: entities
---


# Question
Title: It's possible to create constants or similar and use them inside a node description or title in Drupal 7
Let's say we have a download page in a multilingual Drupal site, and we want to define the download version, for example '1.1.0' and a download URL 'http://myweb.com/setup\_1\_1\_0.exe', to use it on the distinct languages nodes for the download page, inserting them as a tag or similar on the tittle and body of the node.

How could it be done in Drupal 7?

# Answer
I'm not sure I fully understand your need. But I would try to set a `token` called `current_software_version` as `1.1.0`. Node titles and descriptions support the use of Tokens.

Tokens may also be supported within links, when using contributed modules or the redirect module I think.

You typically make custom tokens within a custom module you create. If you want an easier way to make the token value and name, I would look at the Variable module to build a UI and Admin Edit page for your `current_software_version` value. The Variable module will provide a `token` of the value for use throughout the site for you.
> 0 votes

# Answer
After fighting a little, and with the support of tenken ... first you need to install 'Token Filter' and then enable token replacement in the node body. After installed, go to '/admin/config/content/formats' and enable 'Replace tokens' in your preferred edit mode.

Then install 'Custom Tokens' v7.x-2.0 or greater (important!), flush all caches, and in Structure -\> Custom Tokens -\> Add token, define your custom token. For example, name: current-version, Token type: custom, ...

Finally in the editor you can insert the token typing something like \[custom:current-version\].
> 0 votes

---
Tags: i18n-l10n
---


# Question
Title: Drupal Views Date Views - Today in History (month, day)
I am using Drupal 7, Views, Date Views, and Date module.
My database uses a field named "release date" which contains the date that specific items were released (Month/Day/Year) I would like to customize my view to show only content with today's date (historically) basically showing all items that were released on this Month/Day in a block so that every day new content is displayed. Can someone lead me in the right direction to accomplish this? Thanks

# Answer
Add to your view a **contextual filter**: add your date field and select "**Provide default value: current date**". Then, in Granularity (in the same field settings, lower), **set the granularity to a "Day"** so that only content that was marked for that day is displayed.
> 1 votes

---
Tags: views, datetime
---


title: Imagecache Custom Actions - Imagemagick

text:
# Question
Title: Imagecache Custom Actions - Imagemagick
I cannot get my imagecache custom actions to work at all?

When returning $image in any way, it gives me an error, which can be resolved by adding in the first line here:

```
if (!$image_context['entity']) { return 'No referring entity'; }
$image->ops[0] = "-resize 1600x1600";
return $image;

```

That should simply just resize my images now?

Essentially, my end goal is to check the value of a field submitted with the node which also submitted the original image, and then based on its value, apply a watermark. I am just toying about with custom PHP right now... but I can't seem to get any custom actions to work right now... Any help would be great, thanks! :D

# Answer
Juste return "TRUE", not "$image", It is works for me.

```
 $image->ops[] = "-resize 1600x1600";
 return TRUE;

```
> 0 votes

---
Tags: media, actions
---