# Question
Title: How to access data from external MS SQL database tables in a Drupal site running on MySQL
I am currently working a academic medical department that uses a lot of MS SQL databases because faculty set them up - making us the maintainers :(

We also recently launched **Drupal 6** site on LAMP, with the goal to move from what was supposed to be a .NET shop to PHP and MySQL ... go open-source!

**My problem:** Fetch data from *external* MS SQL database tables into Drupal which runs on MySQL, more specifically integrating *Views 2* with this external data and dynamically show it on the site.

What I have found out so far:

* People have tackled this problem since Drupal 4, but no one is owning it and so ... no stable solution.
* Drupal can only run one *type* of db driver per site. Either MySQL/PostgreSQL/etc ... given you have the driver.
* The MS SQL drivers that are there are not stable and still only solve the problem if my site would already run on MS SQL.
* The are interesting modules that rely on the schema module to build table definitions and enable access to external MySQL data. (Table Wizard, Data API)

Right now: Looking into how the Data API module can be used for my purpose by creating a plugin for it for instance.

Any thoughts that would help me in how to access external MS SQL tables would be very appreciated.

# Answer
As pointed in the question, Views is currently unable to do it. It relies on Drupal's DB Layer which is currently unable to query different DB engines and doesn't support MS-SQL. Views 3 (currently in alpha) provides pluggable query backend so it must be possible to write a backend on top of PDO ODBC or an other mean to reach the MS-SQL DB. Queryin the MS-SQL DB from PHP will probably be a performance issue. Views' caching will certainly be needed to avoid unnecessary repeated queries to the server.

In order to work around this and avoid diving into Views 3, you may use Views (2) to query the Drupal's database, or another one on the same engine. And simply import the needed data into this database. This is what I recently did on a project with a small amount of daily updated data. I used PDO ODBC (with unixODBC and FreeTDS) to periodically import data from a MS SQL Server database into MySQL tables. The tables were then exposed to Views using Views' API. The Data module could also have been used for this purpose.

Another option may be to import the data from MS-SQL as Drupal's nodes. If the data are imported as nodes using a custom content-type with the needed fields (using CCK), you get Views integration as well as the tons of existing modules to leverage Drupal's nodes.

One easy solution to import external data into Drupal is the Feeds module. While initialy build as a rewrite of the Feed API to import RSS and Atom feeds, Feeds is actually a powerful framework to import data into Drupal. It can easily be extended through plugins and hooks to support different data sources, formats and processors.
> 5 votes

# Answer
It will most likely be easier for you to custom code pages and blocks than it will be to use views to access an external MS SQL database. It's hard enough to get views to access an external database, making it a MS SQL database only makes a hard thing harder.

Now I haven't gone through the Views query builder, bit I'm pretty sure that it will create queries with LIMIT in them. IIRC MS SQL can't handle LIMIT in queries, so not only will you need to switch database while views execute it's queries and switch back after wards, you will need to extend it's query builder to handle a MS SQL database and patch Drupal to add support for making queries to a MS SQL database.

All of this isn't impossible, but it will be a lot easier to import the data into the MySQL database instead. Drupal 6 performance on MS SQL wont be too good either.
> 2 votes

# Answer
Drupal for windows does exsist. But I can't imagine that many modules will work on it. You could however share a theme accross two sites one lamp and one windows. Saving trying to connect to MS SQL from a lamp drupal instance.
> 1 votes

# Answer
For anybody still asking the same question these days: ***there is a module for it***, it's called Forena. It can be used to query (not update) any MySQL database.

For more details about Forena, 2 types of documentation are available:

* Community documentation.
* Documentation that comes with Forena, which you can access right after install and enable of the module. Checkout the demo site for an online example of the current:

+ **Forena documentation** \- use the link 'Reporting documentation' or visit relative link /reports/help.
    + **Forena samples** \- use the link 'Reporting samples' or visit relative link /reports/samples (these samples are fully functional, so make sure to experiment a bit with it, such as the drill downs available on the SVG Graph sample).

The newest 7.x-4.x version also includes an amazing (I think) UI for either creating your reports (the WYSIWYG report editor) and/or for creating your SQL queries (the Query Builder).

Here are some variations of the **mysql database** part in the questions:

1. Using a **SQLite** instead of MySQL database: the Forena samples actually get shipped including a (Tiny) SQLite database. Go check it out in the demo site: the data shown there are data contained in the sampledb, which is in SQLite format.
2. Forena comes with a full suite of Supported database connections ... such as My SQL, MS SQL, Oracle, Postgress or any PDO compliant variation.

Enough reasons for considering giving Forena a try? While doing so, use it's issue queue for any type of support/docu requests you may have.

Be aware: I'm a co-maintainer of Forena.
> 1 votes

---
Tags: database, views
---


# Question
Title: Responsive jcarousel doesn't resize images
Im using the jcarousel module and its responsive setting:

http://smartpeopletalkfast.co.uk/carousel/

Below you can see screenshots of how it works. When I resize the browser and the final image doenst fit it is then hidden.

This is working however the original jQuery plug in also resizes the remaining images so they take up the full available width:

http://sorgalla.com/jcarousel/examples/responsive/

How can I get my Drupal site to behave the same way? The only solution I can think of is pretty hacky. I could run javascript on page load and window resize which measured the images and the container, and then resized the images to take up the full width.

# Answer
Since there is not an official jcarousel release that uses v0.3.x you have limited options if you want to use jCarousel.

There is a jCarousel 7.x-3.x version being worked on that will use jCarousel 0.3.x but it is in development still and should only be used for testing purposes. With some good testing, I would imagine that you could use this version without much worry.

Personally, I would not use the development version or try to hack v0.3.x into the current release. I ran into this issue a while back and ended up using OwlCarousel. This module offers very similar functionality and seems a bit ahead of jCarousel as far as responsive settings go. If you're not locked into using jCarousel, I'd give OwlCarousel a shot.
> 0 votes

# Answer
I think JCarousel still uses 0.2.x version of the JCarousel library and the example you're refering uses version 0.3.3 of the library which brings wider responsive support. Since 0.2.x and 0.3.x are not compatible as one can read here https://github.com/jsor/jcarousel, I think it will be difficult to achieve the features of the 0.3.x library in the drupal module. Look at the roadmap on https://www.drupal.org/project/jcarousel
> 0 votes

---
Tags: javascript
---


# Question
Title: How to create a custom table containing data to be rendered using the Views module
I have a module which is pulling in some remote data. this is only temporary as long as page is opened i dnt want to store the data on my drupal site. is there a way i can create a custom data table in order to render my data results using the views module. i looked into hook\_views\_data()but it seems this only works with database table in the drupal system

# Answer
> 1 votes
Data module helps you model, manage and query related sets of tables. The Data module provides

* an API for dynamically allocating tables for single-row records.
* an API for insert/update/delete operations and describing how tables join to each other.
* **automatic views integration.**
* a way to export table definitions to code.

Also next patch in "Describe and use external database tables using Data." allow use external DB tables to show on Views.

# Answer
> 1 votes
Module Forena can be used to query (not update) any MySQL database table.

For more details about Forena, 2 types of documentation are available:

* Community documentation.
* Documentation that comes with Forena, which you can access right after install and enable of the module. Checkout the demo site for an online example of the current:

+ **Forena documentation** \- use the link 'Reporting documentation' or visit relative link /reports/help.
    + **Forena samples** \- use the link 'Reporting samples' or visit relative link /reports/samples (these samples are fully functional, so make sure to experiment a bit with it, such as the drill downs available on the SVG Graph sample).

The newest 7.x-4.x version also includes an amazing (I think) UI for either creating your reports (the WYSIWYG report editor) and/or for creating your SQL queries (the Query Builder).

Here are some variations of the **MySQL database** part in my answer:

1. Using a **SQLite** instead of MySQL database: the Forena samples actually get shipped including a (Tiny) SQLite database. Go check it out in the demo site: the data shown there are data contained in the sampledb, which is in SQLite format.
2. Forena comes with a full suite of Supported database connections ... such as MS SQL, Oracle, Postgress or any PDO compliant variation.

Enough reasons for considering giving Forena a try? While doing so, use it's issue queue for any type of support/docu requests you may have.

Be aware: I'm a co-maintainer of Forena.

---
Tags: views
---


title: Views on custom data source

text:
# Question
Title: Views on custom data source
I have an app that has a front end in tons of custom AJAX and fancy JS controls.

These controls all pull from URL which return JSON in a specific format.

I would like to remove all the selection code from the existing system and integrate with drupal:

1. Can views be linked to tables which are not directly managed by Drupal?
2. Can Views have their output overridden to support JSON instead of HTML?

I have googled and found a few projects but none seem to be very active -- I am using D7 maybe D8 for this project :)

Any pointers, hook suggestions, etc?

# Answer
After using `hook_views_data()` to declare your custom tables/fields, use a custom Views handler to override or reformat the output.
> 2 votes

# Answer
Answers:

> Can views be linked to tables which are not directly managed by Drupal?

This is done by the data module - here is a heads up.

> Can Views have their output overridden to support JSON instead of HTML?

Install the views datasource project, then enable the views\_json module. This outputs the view fields as JSON. You set the output format to JSON, configure it, and all fields are outputted as JSON:

Take care to uncheck views api mode if you simply want a JSON file.

Add a path to the new 'page'-type display, and you will see the JSON output.

For me it was somewhat limited, since I you can't change the field names (only hide them). Maybe you have a solution?
> 2 votes

# Answer
Module Forena can be used to query (not update) any MySQL database table. And Forena can be used as a views style. So the combination of these 2 Forena features should perfectly address the 1st part of the question.

For more details about Forena, 2 types of documentation are available:

* Community documentation.
* Documentation that comes with Forena, which you can access right after install and enable of the module. Checkout the demo site for an online example of the current:

+ **Forena documentation** \- use the link 'Reporting documentation' or visit relative link /reports/help.
    + **Forena samples** \- use the link 'Reporting samples' or visit relative link /reports/samples (these samples are fully functional, so make sure to experiment a bit with it, such as the drill downs available on the SVG Graph sample).

The newest 7.x-4.x version also includes an amazing (I think) UI for either creating your reports (the WYSIWYG report editor) and/or for creating your SQL queries (the Query Builder).

Here are some variations of the **mysql database** part in the question:

1. Using a **SQLite** instead of MySQL database: the Forena samples actually get shipped including a (Tiny) SQLite database. Go check it out in the demo site: the data shown there are data contained in the sampledb, which is in SQLite format.
2. Forena comes with a full suite of Supported database connections ... such as MS SQL, Oracle, Postgress or any PDO compliant variation.

Enough reasons for considering giving Forena a try? While doing so, use it's issue queue for any type of support/docu requests you may have.

Be aware: I'm a co-maintainer of Forena.
> 1 votes

---
Tags: 7, views, database
---


# Question
Title: publish article to home page and secondary page
I am a joomla convert. With my old website on Joomla I could publish an article to a specific page as well as the home page. It would remain on the home page until it was "pushed down" by new articles, but would always be on the specific page in a back up sort of way. I want to do that here are well.. Let me be a bit more specific...

I have officers at my work place that want to put reports on the website on occasion. When the President posts a report it will post on the front page but also the president page. I have created a President page on Drupal (7) yet I can't get an article to post to it AND the front page. I asked this question on another forum and I was rudely directed to look up Taxanomy, which I did and I'm still lost.

Can someone please just direct me to what I need to do to have an article appear on the president page and the home page?

Thank you...

# Answer
> 1 votes
Drupal has a "Promoted to front page" check box under Publishing options when you create a new node.

To use this feature, visit `/admin/config/system/site-information` and make sure that the field under "Default front page" is empty. This will enable your front page to show all content with "Promoted to front page" checked. Anything you promote to the front page will be both on the front page and also have it's own individual page.

If you have a "President" page that needs to show all the president's articles/reports, you should take a look at Views. This will be one of your best friends and you will want to take the time to learn how to use it properly. In short, you would use views to create a block that displays articles authored by the president. You would be able to display the block wherever needed.

---
Tags: taxonomy-terms
---


# Question
Title: French accented characters not saving to database
I have created a module that reads in a csv file that has french accented characters in it to create nodes from. The creation of the nodes seems to work fine but when I execute the node\_save() command I get the following error:

```
An AJAX HTTP error occurred. HTTP Result Code: 500 Debugging information follows.
Path: /batch?id=55&op=do StatusText: Service unavailable (with message)
ResponseText: PDOException: in field_sql_storage_field_storage_write()
(line 494 of /var/www/html/modules/field/modules/field_sql_storage/field_sql_storage.module).

```

The special character I am having problems with is é character (however I am sure other accented characters will cause me grief as well).

I thought this was an encoding issue and checked the database encoding on the tables - all tables are set to UTF8. I believe that this is the correct encoding and should work (however I am no database expert).

I tried using the following code:

```
$encodedval = mb_check_encoding($val, 'UTF-8') ? $val : utf8_encode($val);

```

Which seems to help but still gives the same error after 300 items are read in (there are 3000 items that need to be imported). During the importing, I am Geo-referencing the nodes, so could this be Google killing the look-ups after so many hits?

I am at a loss and would appreciate if anyone could shed some light as to what might be the issue.

# Answer
Both suggested solutions above are good things to check when trying to solve this problem.

In my particular case, using the fgetcsv command. It silently chokes on files that are not UTF-8 encoded and contains accented characters. To fix this problem I had to implement the file read function as follows:

```
while (($line = fgets($file_handle)) !== FALSE) {
  // Ensure the line we read is encoded properly
  $value = mb_check_encoding($line, 'UTF-8') ? $line : utf8_encode($line);
  $data = str_getcsv($value);
  // process the data as normal
}

```

This fixed my issue.
> 1 votes

# Answer
Have you tried to save your module file in another encoding format?

I'm usually having the same issues as my files are default to AINSI. After converting the file to UTF-8 I have no more issues.

By doing so you will have to remove your utf8\_encode() calls to avoid double encoding.
> 0 votes

# Answer
I've imported thousands of Spanish-language nodes using the Feeds module; so I would indeed suspect that something is going wrong in the georeferencing, especially with the "Service unavailable" message. Does Google return something human-readable? If so, I suggest writing out the responses to a log file somewhere, and see if something goes wonky after 300 requests.
> 0 votes

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


# Question
Title: Create a printable document from template
I am fairly new to Drupal. I have a Microsoft Word Document template and would like to allow users to fill in fields and insert an image and then print the document. I am not stuck on using the Word template if that is not feasible.

We have been using a document that is a fillable form. We fill out the fields and then have to add an image to the form in a particular position. I would like, if possible, to have Drupal do this. I would like it so a use goes to the site, fills out the information and uploads the image. Once that is done they would need to print the document and have it retain a specific layout.

Possible? Please point me in the right direction. I am using Drupal 7.x

thanks

# Answer
This use-case is perfectly normal for Drupal, but you're better off not using Word at all.

* Create a content type (let's call it `fillable`) that contains all of the fields you require including an Image field which requires the ImageField module.
* Give your users the '`fillable`: Create new content' and any of the other relevant permissions for that content type that you wish them to be able to do.
* Edit the content type and go to the `manage display` tab, determine how you want the fields to show (with labels? as links?). If you need to group fields you can use the Field collection module.
* Use your theme to make the node page layout how you want it to be
* Put a print.css file in your theme and use that to fine-tune how the document prints

If you want to make other changes to the output of the node (like extra text in certain places, or complicated formatting), you can create a node template for that specific content type by giving it a name such as node--fillable.tpl.php
> 2 votes

---
Tags: views
---


# Question
Title: Multiple user-selected front page layouts
I would like my site builders to be able to select from three unique front page layouts. The selection can be made either through config or through theme settings, but not require any coding. The three pages have different pieces of content consisting mostly of fields. I've looked at panels but I would prefer to use something a little lighter as panels seems like a lot for this one piece of functionality. Has anyone here solved a similar problem?

# Answer
> 0 votes
You could add a checkbox in the theme settings and adjust the page template accordingly in a page preprocess.

Something similar to this would go in the theme-settings.php file in your theme...

```
function THEMENAME_system_theme_settings_alter(&$form, $form_state) {
    $form['front_layout'] = array(
      '#type'          => 'radios',
      '#title'         => t('Front Page Layout'),
      '#options'       => array(
        'layout_1' => t('Layout 1'),
        'layout_2' => t('Layout 2'),
        'layout_3' => t('Layout 3'),
      ),
      '#default_value' => theme_get_setting('front_layout'),
    );
}

```

Add new page template suggestions in a page preprocess ...

```
function THEMENAME_preprocess_page(&$variables) {
  if ($is_front) {
    $layout_setting = theme_get_setting('front_layout');
    $variables['theme_hook_suggestions'][] =  'page__' . $layout_setting;
  }
}

```

This would allow you to have separate page templates for each layout. An example being `page--layout-3.tpl.php`.

If it's merely css changes you need, you could add a body class in an html preprocess ...

```
function THEMENAME_preprocess_html(&$variables, $hook) {
  if ($is_front) {
    $layout_setting = theme_get_setting('front_layout');
    $variables['classes_array'][] = drupal_html_class($layout_setting);
  }
}

```

In this example you would have a "layout-1", "layout-2" or "layout-3" class on the body element.

---
Tags: 7
---


# Question
Title: How to make a link type of a news automatically?
I made a content type what called *news*, and I have created a **list(text)** field type to grab the type of news and name it **news\_type** and it's value is **Sport, Health, Technology, Economic** and others.

I want each of this type comes to a block as a link to all of that type news. Something like below:

and How to make each news type a link?

Some people say you should use View, How to use view for this?
Please describe step by step.

# Answer
> 1 votes
1. Create a View named "xyz" & select content of type "news"
2. Select page or block
3. Add fields what you want to show or if you need filtration then you can filter your content.
4. & save.

---
Tags: views, 7
---


# Question
Title: How to use Drupal for managing a public website together with an intranet and an MSSQL database?
I'm new to Drupal and I've been digging through the documentation to find out most of the features and possibilities of this software.

I'm asking you an advice in evaluating if Drupal could be the case for a CMS for a client of ours.

The client is an Italian public administration; right now they've got two sites: internet and intranet. The two sites feature different layouts and different content (some content is mirrored in both sites, some is only on internet and some is only on intranet). Right now everything is managed manually with classic xHTML and some programming.

In an effort to switch to a CMS (don't consider content migration right now) we have to deal with different infrastructure problems, such as:

* the intranet site is behind a private LAN not accessible from outside
* the internet site is on a DMZ with no link with the private LAN (and they want to stay it that way)
* the client database option is SQL server (they could provide access on a shared database from both sites, this is ok, but it is the only link they could give)

So I have some trouble to find a good software that could solve most of their problems. How to:

1. Let them have only one administration panel (content is managed only once)
2. Let them choose if the content added has to appear on one of the two or on both sites
3. How to sync the files uploaded on both sites (if files are stored in the db it shouldn't be a problem)
4. Is there some module that can let editors to insert images directly in articles (let's suppose they have wysisyg editors for content) and save those attachment in the db (same problem as n. 3)
5. Manage different layouts on sites and also different content organization (menù, views, blocks etc.)

What do you think about it?

# Answer
> 1 votes
Drupal can most of this very well.

Someone with more experience can address how it can be set up for Intranet and Internet. It can handle multiple sites linked with data from same database (Not sure if this is what you want).

User permissions can be defined effectively down to the smallest content level so restricting access based upon any user categories you choose is not a problem.

Drupal works from a database (MySQL), apache, and php. Transferring data will not be a problem for an experienced DB manager.

Images are stored as separate files on the site with references in the DB. Images can be handled in a variety of ways on any page display including direct insertion.

Page layouts can be handled either through layout themes that handle HTML and CSS management and are fully customizable.

Drupal is exceptionally flexible and can do just about anything you can imagine. There are hundreds of modules to choose from (all free and open source).

Having said all that, doing sophisticated site features is not for beginners and there is a steep learning curve for new site developers. Getting a sophisticated site up and running requires an experienced Drupal developer. Some of them are on this site and you can find others at Drupal.org.

# Answer
> 1 votes
Maybe using a multi site setup could already get you fairly far? Such setup also has some pros and cons that would have to be investigated first of course.

Consider using Module Forena to address part of the infrastructure problem related to MS SQL. It can be used to query (not update) the data in MS SQL databases.

For more details about Forena, 2 types of documentation are available:

* Community documentation.
* Documentation that comes with Forena, which you can access right after install and enable of the module. Checkout the demo site for an online example of the current:

+ **Forena documentation** \- use the link 'Reporting documentation' or visit relative link /reports/help.
    + **Forena samples** \- use the link 'Reporting samples' or visit relative link /reports/samples (these samples are fully functional, so make sure to experiment a bit with it, such as the drill downs available on the SVG Graph sample).

The newest 7.x-4.x version also includes an amazing (I think) UI for either creating your reports (the WYSIWYG report editor) and/or for creating your SQL queries (the Query Builder).

Here are some variations of the **MS SQL database** part in the questions:

1. Using a **SQLite** instead of MS SQL database: the Forena samples actually get shipped including a (Tiny) SQLite database. Go check it out in the demo site: the data shown there are data contained in the sampledb, which is in SQLite format.
2. Forena comes with a full suite of Supported database connections ... such as MS SQL, Oracle, Postgress or any PDO compliant variation.

Enough reasons for considering giving Forena a try? While doing so, use it's issue queue for any type of support/docu requests you may have.

Be aware: I'm a co-maintainer of Forena.

---
Tags: 7, theming, multi-sites, database
---


# Question
Title: How to use URL as a filter in view module?
I asked a question here and now I am going to create a view that the view take the URL and use it as a filter.

and I want to have a the view by a **dynamic filter** use the URL path and show the result by different type something like sport, economy, etc.

Pathauto: **news/\[node:news\_type\]/\[node:title\]**

I want to use \[node:news\_type\] in my filter

# Answer
You need to add a Contextual filter under the Advanced pane in your view's edit page.

1. Look for your field, it would probably be *Content: News type* then add the field
2. Under ***WHEN THE FILTER VALUE IS NOT IN THE URL*** select Provide default value
3. Choose Raw value from URL for **Type**
4. Choose 2 for **Path component**
5. Check **Use path alias**
> 1 votes

---
Tags: 7, views, nodes
---


title: Display Drupal taxonomy tree

text:
# Question
Title: Display Drupal taxonomy tree
I sucessfully printed the whole taxonomy tree using this code.

```
$voc = taxonomy_vocabulary_machine_name_load('product_sub_categories');
$tree = taxonomy_get_tree($voc->vid, 0, NULL, TRUE);
foreach ($tree as $key => $term) {
  print $term->name."</br>";
}

```

Now I want to separately print parent and child in order to custom theme them, because I already have a mark-up in which parent has separate `<p class="parent_class"> Parent terms</p>` and children has separate `<ul class="child_class">Child terms</ul>`.

How should I do this?

---

I have done it using `taxonomy_get_children()`, but it is giving me the children of parent of the taxonomy whose ID is 1.

* child1
* child2
* child3

This is what I need, but now I want to get the children of parent `child1`. I tried to get them by reusing the above function but it give me this.

* child1
    + children of child1
* child1
* child2
* child3

# Answer
> 2 votes
Use nested foreach like below.

```
$terms = taxonomy_get_children(1);
foreach ($terms as $term) {
  $items[] = $term->name;
  $child_term = taxonomy_get_children($term->tid);
  if (!empty($child_term)) {
    foreach ($child_term as $child) {
      $items[] = $child->name;
    }

  }
}
return theme('item_list', array('items' => $items));

```

---
Tags: taxonomy-terms
---


# Question
Title: new submit button to node form not displayed?
When i try to add a new node of type article for example i want to add a new submit button with new submit function so i did like this in hook\_form\_alter :

```
function MYMODULE_form_alter(&$form, &$form_state, $form_id){
  switch ($form_id){
        case "article_node_form" :
            $form['submit_delegate'] = array(
                '#type' => 'submit', // I tried also '#type' => 'button'
                '#value' => t('Delegate'),
                '#submit' => array('MYMODULE_form_submit_article_delegate'),
            );
            dpm($form);
            break;
  }
}

```

this is the dpm result of the new form element :

> submit\_delegate (Array, 3 elements)
>
> # type (String, 6 characters ) button
>
> # value (String, 8 characters ) Delegate
>
> # submit (Array, 1 element)

Thanks in advance.

# Answer
> 1 votes
It will be displayed somewhere between the node form elements. May be you didn't notice that. Try appending this form element under actions like this. Then You can see the button along with save and preview button.

```
$form['actions']['submit_delegate'] = array(
  '#type' => 'submit', // I tried also '#type' => 'button'
  '#value' => t('Delegate'),
  '#submit' => array('MYMODULE_form_submit_article_delegate'),
);

```

---
Tags: 7, forms
---


# Question
Title: How to show each type of content-types just one time?
I have news content type and it has title, body, image and type. The type is a **list(text)** and have these values:

1. sport
2. Economy
3. Health
4. ...

And now I need to have these types in a **view (block)**. in view module the field is **type** *(means the news type)* I just want each of them shows one time not showing by each published news content.

**For example**: in that block that I made I have 3 sport news and 2 health news and one Economy!

# Answer
> 0 votes
I hope I understand your question. Do you want to use the Type of the node as header for a collection of nodes? So:

**Sport** Node 1 Node 2 Node 3

**Health** Node 4 Node 5

**Economy** Node 6

What I would do is use the Views field view module. First make a view for all three groups, so you have three views one for Sport, one for Health and one of Economy. Give them all a header with the Type name. Then add all these views to one view with this module.

---
Tags: views, nodes
---


# Question
Title: How to create hook for altering every node form?
I tried:

> mymodule\_form\_node\_alter
>
> mymodule\_form\_node\_form\_alter

and global hook:

```
function mymodule_form_alter(&$form, $form_state, $form_id) {
  if ($form['#id'] == 'node-form') {
      #set message
  }
}

```

None from above works for me.

I need to create hook that invokes on every node form. if it possible.

# Answer
> 11 votes
```
function yourmodule_form_alter(&$form, &$form_state, $form_id) {
    if (strpos($form_id, '_node_form') !== FALSE) {
      // ...
    }
}

```

# Answer
> 25 votes
```
/**
 * Implements hook_form_BASE_FORM_ID_alter().
 */
function MYMODULE_form_node_form_alter(&$form, &$form_state) {
  // Do stuff.
}

```

It could be that it didn't work because you have to clear the cache after adding the hook.

# Answer
> 2 votes
Use `hook_form_BASE_FORM_ID_alter()` to provide a form-specific alteration for shared forms. For your example this would be:

```
function yourmodule_form_node_form_alter(&$form, &$form_state, $form_id) {
  // code that runs on every node form
}

```

https://api.drupal.org/api/drupal/modules!system!system.api.php/function/hook\_form\_BASE\_FORM\_ID\_alter/7

# Answer
> 1 votes
I find better solution:

```
if (isset($form['#node'])) {

}

```

Another solution is to use: hook\_form\_BASE\_FORM\_ID\_alter()

---
Tags: 7, forms
---


# Question
Title: URL aliases and Entity Translation (menu name replacement pattern)
I am using entity translation (Field translation) for my nodes, and set the menu name on each 'page'. The menu itself is arrange to basically have a duplicate tree in the same menu each with a different language, for example:

```
main-menu
-item 1 english
--sub item 1 english <node/23>
-item 1 german
--sub item 1 german <node/23>

```

Now when i want to make URL aliases based on the menu it does not translate.

```
[node:menu-link:parents:join-path]/[node:menu-link]

```

Keeps the URL as english. i assume this is because of "node".

What replacement patterns could i use to make the URL aliases compatible with my entity translation?

# Answer
Instead of using `[node:menu-link]`, use `[node:title]` instead.
> 0 votes

---
Tags: path-aliases, i18n-l10n
---


# Question
Title: How to specify English path alias for Chinese?
I created a node of type `Post` in English, and translated it using Entity Translation to Chinese, Traditional. I then set the path alias for the content type to be `[node:menu-link:parents:join-path]/[node:title]`, so it will create an URL alias based on the menu trail and the node title.

However, for Chinese, it is coming up with the Chinese node title, is there anyway to make it display the English title instead? Possibly using Tokens?

I am aware of the Transliteration module, but I am not looking to transliterate, but use the English title altogether.

# Answer
Instead of using `[node:title]`, use `[node:menu-link]` instead.
> 0 votes

# Answer
Use `[node:source:title]` instead of `[node:title]` as shown below in all translated languages:

`[node:menu-link:parents:join-path]/[node:source:title]`
> 0 votes

---
Tags: i18n-l10n, tokens, path-aliases
---


# Question
Title: Taxonomy fields in node default display using display suite
I have a content type called "product" and a taxonomy called "producer". On each product, I can select a producer. The producer has some fields I need: "country", "area", "district".

I need to display those 3 fields from the producer on the product default display. How can I do that?

---

Some things I tried that don't work:

* Created a view pane with a contextual filter for term id, then selected the argument input to be "From context" and selected the producer field from the product.
* Created a dynamic field in ds and selected the view pane and selected "No being viewd" as the argument.

# Answer
> 0 votes
In Manage display of Product content type, select **Rendered taxonomy term** for term reference producer, then create `taxonoy-term--producer.tpl.php` to change style of the taxonomy.

---
Tags: views, display-suite
---


# Question
Title: Text Resize but with defined font sizes?
I am using the Text Resize module to dynamically change the font size of my page content. However, instead of having two buttons which increases and decreases font size, I need, instead, to have three buttons so when the user clicks on one, the font size will be set to a preset value. This value should be able to be changed by the client themselves.

Is there a module which is similar to Text Resize but with defined font sizes?

# Answer
> 1 votes
You can use **Text Size**. It provides 3 buttons and also has settings for increment/decrement step.

step 1: go to admin/config step 2: User interface -\> Text Resize click step 3: tick Add Reset Button then save

---
Tags: 7, theming
---


title: My New Site admin approval

text:
# Question
Title: My New Site admin approval
I'm planning to build a website with Drupal (having very little experience in building sites and none with Drupal). Through my webhost I managed to install Drupal on my site and I tried to create a drupal account immediately. I got an email "Account details....(Pending Admin Approval)", but then nothing. Maybe I'm just too eager and should just wait longer :-), but it could also be that I did something wrong. So my question: is it normal for an account to take more than 3 days getting My New Site admin approval? And can I do something to speed up the process?

I'm following some tutorials and wish I could play around a little while learning. THanks for the info! Hetty

# Answer
> 2 votes
When you installed Drupal you should have had to setup a main account:

That is the login you should be using, if you don't know that password go to /user and click Forgot Password and you can retrieve your login if you remember username or email you used. Since you got (Pending Admin Approval) it should be that email that is registered as main account.

(Pending Admin Approval) emails are sent when someone else tries to register an account on your site.

---
Tags: installation, users
---


# Question
Title: How to log in to Drupal 7 website with jmeter
I am trying to set up an load test using jmeter. As part of the test I want to be able to log in as the site administrator and then go to admin page.

For some reason the test is not able to login as the adminstrator. I followed the instructions in this tutorial. That tutorial was written for D6 so I did make some changes for D7 (e.g. changed the regex used to get the form\_build\_id). However it is still not working. I would be very grateful for any suggestions on why this is occurring.

```
<?xml version="1.0" encoding="UTF-8"?>
<jmeterTestPlan version="1.2" properties="2.7" jmeter="2.12 r1636949">
  <hashTree>
    <TestPlan guiclass="TestPlanGui" testclass="TestPlan" testname="API test" enabled="true">
      <stringProp name="TestPlan.comments"></stringProp>
      <boolProp name="TestPlan.functional_mode">false</boolProp>
      <boolProp name="TestPlan.serialize_threadgroups">false</boolProp>
      <elementProp name="TestPlan.user_defined_variables" elementType="Arguments" guiclass="ArgumentsPanel" testclass="Arguments" testname="User Defined Variables" enabled="true">
    <collectionProp name="Arguments.arguments"/>
      </elementProp>
      <stringProp name="TestPlan.user_define_classpath"></stringProp>
    </TestPlan>
    <hashTree>
      <ThreadGroup guiclass="ThreadGroupGui" testclass="ThreadGroup" testname="Authenticated user" enabled="true">
    <stringProp name="ThreadGroup.on_sample_error">continue</stringProp>
    <elementProp name="ThreadGroup.main_controller" elementType="LoopController" guiclass="LoopControlPanel" testclass="LoopController" testname="Loop Controller" enabled="true">
      <boolProp name="LoopController.continue_forever">false</boolProp>
      <intProp name="LoopController.loops">-1</intProp>
    </elementProp>
    <stringProp name="ThreadGroup.num_threads">1</stringProp>
    <stringProp name="ThreadGroup.ramp_time">1</stringProp>
    <longProp name="ThreadGroup.start_time">1425852247000</longProp>
    <longProp name="ThreadGroup.end_time">1425852247000</longProp>
    <boolProp name="ThreadGroup.scheduler">false</boolProp>
    <stringProp name="ThreadGroup.duration"></stringProp>
    <stringProp name="ThreadGroup.delay"></stringProp>
      </ThreadGroup>
      <hashTree>
    <ConfigTestElement guiclass="HttpDefaultsGui" testclass="ConfigTestElement" testname="HTTP Request Defaults" enabled="true">
      <elementProp name="HTTPsampler.Arguments" elementType="Arguments" guiclass="HTTPArgumentsPanel" testclass="Arguments" testname="User Defined Variables" enabled="true">
        <collectionProp name="Arguments.arguments"/>
      </elementProp>
      <stringProp name="HTTPSampler.domain">d6.dev</stringProp>
      <stringProp name="HTTPSampler.port"></stringProp>
      <stringProp name="HTTPSampler.connect_timeout"></stringProp>
      <stringProp name="HTTPSampler.response_timeout"></stringProp>
      <stringProp name="HTTPSampler.protocol"></stringProp>
      <stringProp name="HTTPSampler.contentEncoding"></stringProp>
      <stringProp name="HTTPSampler.path"></stringProp>
      <stringProp name="HTTPSampler.concurrentPool">4</stringProp>
    </ConfigTestElement>
    <hashTree/>
    <HTTPSamplerProxy guiclass="HttpTestSampleGui" testclass="HTTPSamplerProxy" testname="Home page" enabled="true">
      <elementProp name="HTTPsampler.Arguments" elementType="Arguments" guiclass="HTTPArgumentsPanel" testclass="Arguments" testname="User Defined Variables" enabled="true">
        <collectionProp name="Arguments.arguments"/>
      </elementProp>
      <stringProp name="HTTPSampler.domain"></stringProp>
      <stringProp name="HTTPSampler.port"></stringProp>
      <stringProp name="HTTPSampler.connect_timeout"></stringProp>
      <stringProp name="HTTPSampler.response_timeout"></stringProp>
      <stringProp name="HTTPSampler.protocol"></stringProp>
      <stringProp name="HTTPSampler.contentEncoding"></stringProp>
      <stringProp name="HTTPSampler.path">/</stringProp>
      <stringProp name="HTTPSampler.method">GET</stringProp>
      <boolProp name="HTTPSampler.follow_redirects">true</boolProp>
      <boolProp name="HTTPSampler.auto_redirects">false</boolProp>
      <boolProp name="HTTPSampler.use_keepalive">true</boolProp>
      <boolProp name="HTTPSampler.DO_MULTIPART_POST">false</boolProp>
      <boolProp name="HTTPSampler.image_parser">true</boolProp>
      <boolProp name="HTTPSampler.monitor">false</boolProp>
      <stringProp name="HTTPSampler.embedded_url_re"></stringProp>
    </HTTPSamplerProxy>
    <hashTree>
      <HTMLAssertion guiclass="HTMLAssertionGui" testclass="HTMLAssertion" testname="HTML Assertion" enabled="true">
        <longProp name="html_assertion_error_threshold">0</longProp>
        <longProp name="html_assertion_warning_threshold">0</longProp>
        <stringProp name="html_assertion_doctype">omit</stringProp>
        <boolProp name="html_assertion_errorsonly">true</boolProp>
        <longProp name="html_assertion_format">0</longProp>
        <stringProp name="html_assertion_filename"></stringProp>
      </HTMLAssertion>
      <hashTree/>
      <ResponseAssertion guiclass="AssertionGui" testclass="ResponseAssertion" testname="Response Assertion" enabled="true">
        <collectionProp name="Asserion.test_strings">
          <stringProp name="49586">200</stringProp>
        </collectionProp>
        <stringProp name="Assertion.test_field">Assertion.response_code</stringProp>
        <boolProp name="Assertion.assume_success">false</boolProp>
        <intProp name="Assertion.test_type">1</intProp>
      </ResponseAssertion>
      <hashTree/>
    </hashTree>
    <OnceOnlyController guiclass="OnceOnlyControllerGui" testclass="OnceOnlyController" testname="Once Only Controller" enabled="true"/>
    <hashTree>
      <CookieManager guiclass="CookiePanel" testclass="CookieManager" testname="HTTP Cookie Manager" enabled="true">
        <collectionProp name="CookieManager.cookies"/>
        <boolProp name="CookieManager.clearEachIteration">false</boolProp>
      </CookieManager>
      <hashTree/>
      <HTTPSamplerProxy guiclass="HttpTestSampleGui" testclass="HTTPSamplerProxy" testname="login page" enabled="true">
        <elementProp name="HTTPsampler.Arguments" elementType="Arguments" guiclass="HTTPArgumentsPanel" testclass="Arguments" testname="User Defined Variables" enabled="true">
          <collectionProp name="Arguments.arguments"/>
        </elementProp>
        <stringProp name="HTTPSampler.domain"></stringProp>
        <stringProp name="HTTPSampler.port"></stringProp>
        <stringProp name="HTTPSampler.connect_timeout"></stringProp>
        <stringProp name="HTTPSampler.response_timeout"></stringProp>
        <stringProp name="HTTPSampler.protocol"></stringProp>
        <stringProp name="HTTPSampler.contentEncoding"></stringProp>
        <stringProp name="HTTPSampler.path">/user</stringProp>
        <stringProp name="HTTPSampler.method">GET</stringProp>
        <boolProp name="HTTPSampler.follow_redirects">true</boolProp>
        <boolProp name="HTTPSampler.auto_redirects">false</boolProp>
        <boolProp name="HTTPSampler.use_keepalive">true</boolProp>
        <boolProp name="HTTPSampler.DO_MULTIPART_POST">false</boolProp>
        <boolProp name="HTTPSampler.monitor">false</boolProp>
        <stringProp name="HTTPSampler.embedded_url_re"></stringProp>
      </HTTPSamplerProxy>
      <hashTree>
        <RegexExtractor guiclass="RegexExtractorGui" testclass="RegexExtractor" testname="get form id" enabled="true">
          <stringProp name="RegexExtractor.useHeaders">false</stringProp>
          <stringProp name="RegexExtractor.refname">form_build_id</stringProp>
          <stringProp name="RegexExtractor.regex">id=”(form-.{43})”</stringProp>
          <stringProp name="RegexExtractor.template">$1$</stringProp>
          <stringProp name="RegexExtractor.default"></stringProp>
          <stringProp name="RegexExtractor.match_number">1.0</stringProp>
        </RegexExtractor>
        <hashTree/>
      </hashTree>
      <HTTPSamplerProxy guiclass="HttpTestSampleGui" testclass="HTTPSamplerProxy" testname="Send login" enabled="true">
        <elementProp name="HTTPsampler.Arguments" elementType="Arguments" guiclass="HTTPArgumentsPanel" testclass="Arguments" testname="User Defined Variables" enabled="true">
          <collectionProp name="Arguments.arguments">
            <elementProp name="name" elementType="HTTPArgument">
              <boolProp name="HTTPArgument.always_encode">false</boolProp>
              <stringProp name="Argument.value">CCA_Web</stringProp>
              <stringProp name="Argument.metadata">=</stringProp>
              <boolProp name="HTTPArgument.use_equals">true</boolProp>
              <stringProp name="Argument.name">name</stringProp>
            </elementProp>
            <elementProp name="pass" elementType="HTTPArgument">
              <boolProp name="HTTPArgument.always_encode">false</boolProp>
              <stringProp name="Argument.value">XXXXXXXXXX</stringProp>
              <stringProp name="Argument.metadata">=</stringProp>
              <boolProp name="HTTPArgument.use_equals">true</boolProp>
              <stringProp name="Argument.name">pass</stringProp>
            </elementProp>
            <elementProp name="form_build_id" elementType="HTTPArgument">
              <boolProp name="HTTPArgument.always_encode">false</boolProp>
              <stringProp name="Argument.value">${form_build_id}</stringProp>
              <stringProp name="Argument.metadata">=</stringProp>
              <boolProp name="HTTPArgument.use_equals">true</boolProp>
              <stringProp name="Argument.name">form_build_id</stringProp>
            </elementProp>
            <elementProp name="form_id" elementType="HTTPArgument">
              <boolProp name="HTTPArgument.always_encode">false</boolProp>
              <stringProp name="Argument.value">user_login</stringProp>
              <stringProp name="Argument.metadata">=</stringProp>
              <boolProp name="HTTPArgument.use_equals">true</boolProp>
              <stringProp name="Argument.name">form_id</stringProp>
            </elementProp>
            <elementProp name="op" elementType="HTTPArgument">
              <boolProp name="HTTPArgument.always_encode">true</boolProp>
              <stringProp name="Argument.value">Log in</stringProp>
              <stringProp name="Argument.metadata">=</stringProp>
              <boolProp name="HTTPArgument.use_equals">true</boolProp>
              <stringProp name="Argument.name">op</stringProp>
            </elementProp>
          </collectionProp>
        </elementProp>
        <stringProp name="HTTPSampler.domain"></stringProp>
        <stringProp name="HTTPSampler.port"></stringProp>
        <stringProp name="HTTPSampler.connect_timeout"></stringProp>
        <stringProp name="HTTPSampler.response_timeout"></stringProp>
        <stringProp name="HTTPSampler.protocol"></stringProp>
        <stringProp name="HTTPSampler.contentEncoding"></stringProp>
        <stringProp name="HTTPSampler.path">/user</stringProp>
        <stringProp name="HTTPSampler.method">POST</stringProp>
        <boolProp name="HTTPSampler.follow_redirects">true</boolProp>
        <boolProp name="HTTPSampler.auto_redirects">false</boolProp>
        <boolProp name="HTTPSampler.use_keepalive">true</boolProp>
        <boolProp name="HTTPSampler.DO_MULTIPART_POST">false</boolProp>
        <boolProp name="HTTPSampler.monitor">false</boolProp>
        <stringProp name="HTTPSampler.embedded_url_re"></stringProp>
      </HTTPSamplerProxy>
      <hashTree>
        <ResponseAssertion guiclass="AssertionGui" testclass="ResponseAssertion" testname="Response code 200" enabled="true">
          <collectionProp name="Asserion.test_strings">
            <stringProp name="49586">200</stringProp>
          </collectionProp>
          <stringProp name="Assertion.test_field">Assertion.response_code</stringProp>
          <boolProp name="Assertion.assume_success">false</boolProp>
          <intProp name="Assertion.test_type">1</intProp>
        </ResponseAssertion>
        <hashTree/>
        <ResponseAssertion guiclass="AssertionGui" testclass="ResponseAssertion" testname="Login details correct" enabled="true">
          <collectionProp name="Asserion.test_strings">
            <stringProp name="-1477566849">unrecognized username or password</stringProp>
          </collectionProp>
          <stringProp name="Assertion.test_field">Assertion.response_data</stringProp>
          <boolProp name="Assertion.assume_success">false</boolProp>
          <intProp name="Assertion.test_type">6</intProp>
        </ResponseAssertion>
        <hashTree/>
      </hashTree>
      <HTTPSamplerProxy guiclass="HttpTestSampleGui" testclass="HTTPSamplerProxy" testname="admin page" enabled="true">
        <elementProp name="HTTPsampler.Arguments" elementType="Arguments" guiclass="HTTPArgumentsPanel" testclass="Arguments" testname="User Defined Variables" enabled="true">
          <collectionProp name="Arguments.arguments"/>
        </elementProp>
        <stringProp name="HTTPSampler.domain"></stringProp>
        <stringProp name="HTTPSampler.port"></stringProp>
        <stringProp name="HTTPSampler.connect_timeout"></stringProp>
        <stringProp name="HTTPSampler.response_timeout"></stringProp>
        <stringProp name="HTTPSampler.protocol"></stringProp>
        <stringProp name="HTTPSampler.contentEncoding"></stringProp>
        <stringProp name="HTTPSampler.path">/admin</stringProp>
        <stringProp name="HTTPSampler.method">GET</stringProp>
        <boolProp name="HTTPSampler.follow_redirects">true</boolProp>
        <boolProp name="HTTPSampler.auto_redirects">false</boolProp>
        <boolProp name="HTTPSampler.use_keepalive">true</boolProp>
        <boolProp name="HTTPSampler.DO_MULTIPART_POST">false</boolProp>
        <boolProp name="HTTPSampler.monitor">false</boolProp>
        <stringProp name="HTTPSampler.embedded_url_re"></stringProp>
      </HTTPSamplerProxy>
      <hashTree>
        <ResponseAssertion guiclass="AssertionGui" testclass="ResponseAssertion" testname="! response code 403" enabled="true">
          <collectionProp name="Asserion.test_strings">
            <stringProp name="51511">403</stringProp>
          </collectionProp>
          <stringProp name="Assertion.test_field">Assertion.response_code</stringProp>
          <boolProp name="Assertion.assume_success">false</boolProp>
          <intProp name="Assertion.test_type">6</intProp>
        </ResponseAssertion>
        <hashTree/>
      </hashTree>
    </hashTree>
    <ResultCollector guiclass="TableVisualizer" testclass="ResultCollector" testname="View Results in Table" enabled="true">
      <boolProp name="ResultCollector.error_logging">false</boolProp>
      <objProp>
        <name>saveConfig</name>
        <value class="SampleSaveConfiguration">
          <time>true</time>
          <latency>true</latency>
          <timestamp>true</timestamp>
          <success>true</success>
          <label>true</label>
          <code>true</code>
          <message>true</message>
          <threadName>true</threadName>
          <dataType>true</dataType>
          <encoding>false</encoding>
          <assertions>true</assertions>
          <subresults>true</subresults>
          <responseData>false</responseData>
          <samplerData>false</samplerData>
          <xml>false</xml>
          <fieldNames>false</fieldNames>
          <responseHeaders>false</responseHeaders>
          <requestHeaders>false</requestHeaders>
          <responseDataOnError>false</responseDataOnError>
          <saveAssertionResultsFailureMessage>true</saveAssertionResultsFailureMessage>
          <assertionsResultsToSave>0</assertionsResultsToSave>
          <bytes>true</bytes>
          <threadCounts>true</threadCounts>
        </value>
      </objProp>
      <stringProp name="filename">/home/bgunn/dev/load tests/CCA.jtl</stringProp>
    </ResultCollector>
    <hashTree/>
      </hashTree>
    </hashTree>
  </hashTree>
</jmeterTestPlan>

```

# Answer
Quickest way to start is to use https://github.com/jacobSingh/Drupal-Performance-Testing-Suite

1. Download DrupalStress.jmx
2. Open up the jmx file
3. Enable either Drupal-6 or Drupal-7 config sections (not both).
4. Edit the config section and change the host to reflect your target machine
> 1 votes

---
Tags: 7, testing
---


# Question
Title: Find out which nodes use a specific filter
How could I find out which nodes actually use a specific filter?

My nodes use an input format that has the Bbcode filter enabled. Now I need to know which (of the several thousand) nodes use BB code, to decide if I still need this filter (in which case I’d switch to Extensible BBCode, and for that I’d like to have a list of nodes to test if everything works correctly).

# Answer
Create a view for nodes & add **Content: Body (body:format)** in Filter Criteria, then set the text format value as `bbcode`.
> 1 votes

---
Tags: 7, input-formats
---


# Question
Title: How to create active menus for the content type in drupal 7?
I want to create a simple content type with menus ,on clicking each menu the content will be shown on the same block but of the respective menu item.

In this image ,i am having 3 menus a,b ,c with a content .On clicking 'a' menuitem respective content of 'a' will be shown ,on clicking 'b' respective content of 'b' will be shown and so on.

Can anyone help me with this issue!.

# Answer
> 0 votes
If you're just about tabs in a content type you could try this.

---
Tags: nodes, routes
---


title: Theme expanded menu item?

text:
# Question
Title: Theme expanded menu item?
Does anyone know how I can theme the entire li output for an expanded menu item?

For instance, the output is

I want to change the output to:

Is there a way to theme this output, like there is a way to theme specifically the expanded menu item output, like there is to theme other li outputs, such as below...?

```
function theme_menu_tree__main_menu_link($variables) {
  return '<li class="menuitem">'.$variables['tree'].'</li>';
}

```

My current code

```
function theme_menu_link__main_menu(array $variables) {
  $element = $variables['element'];
  $sub_menu = '';

  if ($element['#below']) {
    foreach ($element['#below'] as $key => $val) {
      if (is_numeric($key)) {
        $element['#below'][$key]['#theme'] = 'menu_link__main_menu_inner'; // 2 lavel <li>
      }
    }
    $element['#below']['#theme_wrappers'][0] = 'menu_tree__main_menu_inner';  // 2 lavel <ul>
    $sub_menu = drupal_render($element['#below']);
  }
  $output = l($element['#title'], $element['#href'],     $element['#localized_options']);
  return '<li' . drupal_attributes($element['#attributes']) . '>' . $output .
  $sub_menu . "</li>\n";
}

```

# Answer
You can get the complete (main) menu tree with this in your THEME\_preprocess\_page

```
  // Get the entire main menu tree
  $main_menu_tree = menu_tree_all_data('main-menu');

  // Add the rendered output to the $main_menu_expanded variable
  $vars['main_menu_expanded'] = menu_tree_output($main_menu_tree);

```

Then you can pass that to a theme function in your page template:

```
<?php print theme('links__system_main_menu', array(
  'links' => $main_menu_expanded,
  'attributes' => array(
    'id' => 'main-menu',
    'class' => array('nav', 'navbar-nav'),
  ),
)); ?>

```

I've been using the function below to create a Bootstrap ready dropdown menu - you can clearly see how the submenus are themed by checking the `$link['#below']` part of the array.

```
    /**
     * Implements hook_links__system_main_menu().
     *
     * @param array $vars
     * @return string
     *  Themed HTML for bootstrap 3 ready main menu.
     */
    function YOURTHEME_links__system_main_menu($vars) {
      // Get the active trail
      $menu_active_trail = menu_get_active_trail();
      // Initialise our custom trail.
      $active_trail = array();

      // Get current path
      $dest = drupal_get_destination();
      if (is_string($dest['destination'])) {
        $paths = explode('/', $dest['destination']);
        // Loop through and add all active paths
        foreach ($paths as $path) {
          // Read previous element added to active trail (using array values
          // preserves original array).
          $safe = array_values($active_trail);
          $previous = array_pop($safe);
          if ($previous) {
            $active_trail[] = $previous . '/' . $path;
          }
          // Or this is the first one
          else {
            $active_trail[] = $path;
          }
        }
      }

      // UL classes
      $class = implode($vars['attributes']['class'], ' ');
      $html = '<ul class="' . $class . '" id="' . $vars['attributes']['id'] . '">';

      // Iterate links to build menu.
      foreach ($vars['links'] as $key => $link) {

        // Check this is a link not a property.
        if (is_numeric($key)) {
          $sub_menu = '';
          $li_class = array();
          $a_class = array();

          // Check if link is in active trail and add class.
          if (in_array($link['#original_link']['link_path'], $active_trail)) {
            $li_class[] = 'active-trail';
          }
          if ($link['#original_link']['link_path'] == end($active_trail)) {
            $li_class[] = 'active';
          }
          // Check if last element in list and see if LI contains actual link
          $link['#attributes']['class'][] = strtolower(str_replace(array('& ', ' '), array('', '-'), $link['#title']));
          $link_title = $link['#title'];

          if (isset($link['#localized_options']['attributes'])) {
            $link['#attributes'] = array_merge($link['#localized_options']['attributes'], $link['#attributes']);
          }

          // Check if we have a submenu.
          if (!empty($link['#below'])) {
            // Check if lvl 1, if higher do other stuff
            if ($link['#original_link']['depth'] < 2) {
              $li_class[] = 'dropdown';
              $link_title .= '<b class="caret"></b>';
              $link['#attributes']['class'][] = 'dropdown-toggle';
              $link['#attributes']['data-toggle'] = 'dropdown';
            } else {
              $li_class[] = 'dropdown-submenu';
              $link_title .= '<b class="caret"></b>';
            }
            // Theme submenu
            $sub_menu = theme('links__system_main_menu', array('links' => $link['#below'], 'attributes' => array('class' => array('dropdown-menu'))));
          }
          // Build classes string
          $classes = '';
          if (!empty($li_class)) {
            $classes = ' class="' . implode($li_class, ' ') . '"';
          }
          $html .= '<li' . $classes . '>' . l($link_title, $link['#href'], array('html' => 'true', 'attributes' => $link['#attributes'])) . $sub_menu . '</li>';
        }
      }
      $html .= '</ul>';
      return $html;
    }

```
> 1 votes

# Answer
use hook\_theme and create the menu theme registry. see the below example code

function yourthemename\_theme() {

return array(

'custom\_menu\_theme' =\> array(

```
  'template' => 'custom_menu',
),

```

}

the above code custom\_menu is template file name.

this registry print using theme function in drupal.
> 0 votes

---
Tags: routes, theming
---


# Question
Title: How to set properties for a specific chart only using the views integration of the Charts module?
I'm creating charts using the charts module and its integration with the Views module.

I want to set options for only some charts and found that in charts.api.php:

```
/**
 * Alter an individual chart before it is printed.
 *
 * @param $chart
 *   The chart renderable. Passed in by reference.
 * @param $chart_id
 *   The chart identifier, pulled from the $chart['#chart_id'] property (if
 *   any). Not all charts have a chart identifier.
 */
function hook_chart_alter(&$chart, $chart_id) {
  if ($chart_id === 'view_name__display_name') {
    // Individual properties may be modified.
    $chart['#title_font_size'] = 20;
  }
}

```

It seems perfect for what I want because it has the `if ($chart_id === 'view_name__display_name') {` line for specific views but I wonder if I directly add some settings code such as `$chart['#title_font_size'] = 10;` here (to charts.api.php) or is there any other way to do this?

**I mean overriding the charts.api.php inside of the charts module is OK or do I have to write and run these codes anywhere else?**

**EDIT**:

Based on rooby's comments, these are the **two** ways that I tried to set the properties for each charts (created with views module):

# 1. Custom Module

I created a custom module called **benim**.

This is the benim.info file:

```
name = Benim
description = Override charts properties.
package = Other
core = 7.x

```

And this is the benim.module file:

```
<?php

function benim_hook_chart_alter(&$chart, $chart_id) {
  if ($chart_id === 'chartim__block_1') {
    // Individual properties may be modified.
    $chart['#title_font_size'] = 50;
    $chart['subtitle'] = array(
    '#text' => 'Source:',
    );
    $chart['xaxis'] = array(
    '#type' => 'chart_xaxis',
    '#allowDecimals' => 'true',

    );

  }
}

function benim_hook_chart_definition_alter(&$definition, $chart, $chart_id) {
  if ($chart['#chart_library'] === 'highcharts') {
  if ($chart_id === 'chartim__block_1') {
    $definition['title']['style']['fontSize'] = 100;
  }
}
}

```

# 2. Template.php

I added the lines below to the theme's **template.php**.

```
function mytheme_hook_chart_alter(&$chart, $chart_id) {
  if ($chart_id === 'chartim__page') {
    // Individual properties may be modified.
    $chart['#title_font_size'] = 150;
    $chart['subtitle'] = array(
    '#text' => 'Source:',
    );
    $chart['xaxis'] = array(
    '#type' => 'chart_xaxis',
    '#allowDecimals' => 'false',

    );

    $chart['yaxis'] = array(
    '#type' => 'chart_yaxis',
    '#allowDecimals' => 'false',

    );

  }
}

function mytheme_hook_chart_definition_alter(&$definition, $chart, $chart_id) {
  if ($chart['#chart_library'] === 'highcharts') {
  if ($chart_id === 'chartim__page') {
    $definition['title']['style']['fontSize'] = 100;
  }
}
}

```

*(above mytheme is the name of the actual theme)*

Unfortunately, both two ways didn't work for me. I wondered if the $chart\_id parameter is correct and checked for different views but the result didn't change.

**Note**: I also tried clearing caches, and trying inside another theme.

# Answer
No, not in the charts module, in a custom module of your own.

It is also possible for you to use drupal alter hooks from your theme's template.php file however you should be careful what you put in your theme. You should only put code relating to visuals in the theme, if you are doing more functional code it should go in a module.

A good rule of thumb is whether or not you would want to keep that functionality if you ever changed themes. If you would want to keep it then that is a possible indicator that it is functional, not visual, and should be in a module.

.api.php files are files that give developers information on the function and hooks that a module makes available to others.

It is basically just documentation so you editing it will do nothing (except for then making that documentation incorrect, which is bad if anyone else wants to use it).

Some reasons why it is generally not a good idea to modify the module itself can be found at Why don't we hack core? (it is talking about drupal core but the same goes for other contrib modules and themes). One of the main reasons we have drupal hooks is so you don't have to modify the original module if you want to make changes.

So you would create a custom drupal module and then in that module implement the hook like this (changing MODULENAME to the name of the module and the chart ID to match the ID of your specific chart):

```
/**
 * Alter an individual chart before it is printed.
 *
 * @param $chart
 *   The chart renderable. Passed in by reference.
 * @param $chart_id
 *   The chart identifier, pulled from the $chart['#chart_id'] property (if
 *   any). Not all charts have a chart identifier.
 */
function MODULENAME_chart_alter(&$chart, $chart_id) {
  if ($chart_id === 'view_name__display_name') {
    // Individual properties may be modified.
    $chart['#title_font_size'] = 20;
  }
}

```

There are lots of other drupal module development resources besides drupal.org docs too. There are some good affordable textbooks and some paid training type websites, as well as a scattering of blog posts in random corners of the internet.

Here is a more functional example of using the definition alter hook.

```
/**
 * Alter an individual chart's raw library representation.
 *
 * This hook is called AFTER hook_chart_alter(), after Charts module has
 * converted the renderable into the chart definition that will be used by the
 * library. Note that the structure of $definition will differ based on the
 * charting library used. Switching charting libraries may cause your code
 * to break when using this hook.
 *
 * Even though this hook may be fragile, it may provide developers with access
 * to library-specific functionality.
 *
 * @param $definition
 *   The chart definition to be modified. The raw values are passed directly to
 *   the charting library.
 * @param $chart
 *   The chart renderable. This may be used for reference (or read to add
 *   support for new properties), but any changes to this variable will not
 *   have an effect on output.
 * @param $chart_id
 *   The chart ID, derived from the $chart['#chart_id'] property. Note that not
 *   all charts may have a $chart_id.
 */
function THEMENAME_chart_definition_alter(&$definition, $chart, $chart_id) {
  // For the portfolio charts.
  if ($chart_id == 'MY_CHART_ID') {
    $definition['legend']['borderRadius'] = 0;
    $definition['legend']['borderColor'] = NULL;
    $definition['legend']['style']['fontFamily'] = 'Helvetica,Arial,"Nimbus Sans L",sans-serif';
    $definition['legend']['backgroundColor'] = 'transparent';
    $definition['legend']['layout'] = 'vertical';
    $definition['legend']['verticalAlign'] = 'top';
    $definition['legend']['padding'] = 0;
    $definition['legend']['margin'] = 0;
    $definition['legend']['itemStyle']['color'] = '#555555';
    $definition['legend']['itemStyle']['fontSize'] = '12px';
  }
}

```
> 2 votes

# Answer
Interesting question, and an even more interesting answer (from Rooby ... again! Thank you!).

Just to be aware, and to take this answer maybe even a little step further): you may want to checkout issue #2347721, titled '**Pass view info to chart (for further processing)**', which I recently committed to the most current DEV version. So now you also know which view/display you're actually processing when building the chart. Challenge (for Rooby?): create another sample (variation) that illustrates a good use case for this also?

Disclosure: I'm a co-maintainer of the Charts module.
> 1 votes

---
Tags: 7, views, charts
---


title: getting line breaks in tinymce wysiwyg

text:
# Question
Title: getting line breaks in tinymce wysiwyg
On a new drupal 7 installation, I'm trying to get line breaks to show up correctly when saved. I have wysiwyg and tinymce installed through using the panopoly distribution. When I try to do more space after a paragraph (by hitting enter twice), it will generate two empty paragraph tags, such as `<p></p><p></p>`. This however won't provide the needed space as they are empty. In an earlier (drupal 6) project, when I tested this behavior it would insert paragraphs with ` ` in them which correctly displayed the line breaks. For example: `<p> </p><p> </p>`

Is there any way to get this behavior back in Drupal 7?

I've played around with the wysiwyg settings, and text formats, but I can't find a combination of settings that will work.

# Answer
It turns out this has something to do with the "WYSIWYG filter" under text formats (admin/config/content/formats). Disabling this gave my non-breaking space back. You would probably want to adjust the configuration rather than just turning it off.
> 1 votes

# Answer
The followin setup works in my Drupal 7 TinyMCE configuration:

1. Turn off the WYSYWIG filter on the admin/config/content/formats page.
2. Configure the 'Limit Allowed HTML tags' filter to allow for

and
tags.

Note: Filters are configured at admin/config/content/formats/MY\_FILTER\_NAME
> 0 votes

# Answer
Problem:

Drupal 6: Removed the CHARACTER REPLACEMENT "?" FOR NON-BREAKING-SPACE TAG in P tags from wysiwyg. The empty p tags were formerly placed to denote a change of line, however Drupal wysiwyg automatically adds a NON-BREAKING-SPACE TAG which thereby fail to display properly and thus be replaced with the CHARACTER REPLACEMENT "?"

Drupal 7: No nbsp tag but empty p tags

Working Solution:

```
$to_filter = array('bloc_1_delta', 'bloc_2_delta', 'bloc_3_delta', 'bloc_4_delta');
if (in_array($vars['block']->delta, $to_filter)) {
    $vars['block']->content = str_replace("<p></p>", "<br/>", mb_convert_encoding($vars['block']->content, 'HTML-ENTITIES', 'UTF-8'));
}

```
> 0 votes

---
Tags: wysiwyg
---


# Question
Title: How to generate a resume after an applicant submitted an online resume?
I'm currently building a recruitment system using Drupal 7. In my system, an applicant who wants to apply for a job, needs to complete an online resume (one time only).

Question: Are there any modules that can generate a simple resume after the applicant finishes (saves) the online resume, similar to this Online resume example?

# Answer
> 3 votes
I would create a profile type using Profile2 module and call it something like 'Resume'. So that every user can create a Resume profile for themselves.

Then I would install Print module and enable Print PDF and set it to show up on Resume profile pages.

You must play with the permissions so that only the owner of the profile can access the profile page and the PDF version. You may have to write some custom code to make PDF version accessible only once. You may achieve this writing an access callback function for the PDF path.

# Answer
> 1 votes
As an alternative to the profile2 based approach, you may want to consider the Forena module. Reason why I think so, is because the question was tagged with the tag.

It would probably take a bit of time to achieve perfection, but you'd have all of Forena's xHTML-power available to finetune the ultimate result (CV?), for things such as:

* look-and-feel (styling/theming).
* granularity of who is allowed to see what subset of data contained in the CV (what forena calls data blocks, and the related permissions that can be added to each block).
* maybe add some charts to it also (using selected data stored in the CV).
* saving the ultimate output (CV) in formats such as PDF, DOC, etc.
* creating eMail campaigns about selected CVs.
* puling in information stored in other databases related to this CV.

For more details about Forena, 2 types of documentation are available:

* Community documentation.
* Documentation that comes with Forena, which you can access right after install and enable of the module. Checkout the demo site for an online example of the current:

+ **Forena documentation** \- use the link 'Reporting documentation' or visit relative link /reports/help.
    + **Forena samples** \- use the link 'Reporting samples' or visit relative link /reports/samples (these samples are fully functional, so make sure to experiment a bit with it, such as the drill downs available on the SVG Graph sample).

The newest 7.x-4.x version also includes an amazing (I think) UI for either creating your reports (the WYSIWYG report editor) and/or for creating your SQL queries (the Query Builder).

Here is some more info about the **other databases** in mentioned above:

1. Using a **SQLite** instead of MySQL database: the Forena samples actually get shipped including a (Tiny) SQLite database. Go check it out in the demo site: the data shown there are data contained in the sampledb, which is in SQLite format.
2. Forena comes with a full suite of Supported database connections ... such as MySQL, MS SQL, Oracle, Postgress or any PDO compliant variation.

Enough reasons for considering giving Forena a try? While doing so, use it's issue queue for any type of support/docu requests you may have.

**Be aware**: I'm a co-maintainer of Forena.

# Answer
> -1 votes
You can try with Recruiter Module

> Recruiter is a Drupal distribution for building Drupal based e-recruitment platforms. Users can register either as recruiter and post job classifieds or they can register as applicants and fill out their resume. A faceted search helps users to find jobs and possible job candidates.

---
Tags: 7, nodes, log-messages
---


# Question
Title: settings and switching to external pgsql db
I am working with Drupal 7.3.4 and attempting to follow the instructions of changing settings.php so that I can switch to a pgsql DB within a module and then switch back to the default mysql after doing a query.

I have set up in the settings.php file with the following format:

```
$databases = array (
  'default' =>
  array (
    'default' =>
    array (
      'database' => '',
      'username' => '',
      'password' => '',
      'host' => 'localhost',
      'port' => '',
      'driver' => 'mysql',
      'prefix' => '',
    ),
  ),
  'custom_db' =>
  array (
    'default' =>
    array (
      'database' => 'custom_db',
      'username' => 'dbuser',
      'password' => 'pass',
      'host' => 'urltoservice',
      'port' => '5432',
      'driver' => 'pgsql',
      'prefix' => '',
    ),
  ),
);

```

Now I am trying the process of switching to this DB in a module and verifying that the driver is changing.

```
db_set_active('custom_db');
//Get the currently active DB driver
drupal_set_message(db_driver());
db_set_active();

```

But, when I print the driver it is not switching to pgsql as expected. I am pretty sure it is still pointing to the default mysql db. Any ideas of what I may be doing wrong here would be greatly appreciated.

Thanks, Derek

# Answer
> 0 votes
first check whether you are executing your query before doing `db_set_active();` because this function call will set your db to default drupal db.

so you should go like this:

```
db_set_active('custom_db');

```

// execute your query related stuff here

then at last switch to your default db by `db_set_active();`

---
Tags: database
---


# Question
Title: How to run commerce_order_save() without triggering any rules?
I need to run `commerce_order_save()` on several Orders in loop but without triggering any Rules.

Is that possible ?

# Answer
> 5 votes
It's possible, but the change would need to be sitewide (not just in the context of rules). You'd need to override the entity controller class used for commerce\_product (which you could do with `hook_entity_info_alter()`), and re-implement its `save()` method so it doesn't invoke the entity hooks.

If that is undesirable (probably is), and you just need to update field values, you can use `field_attach_update()` instead, which will bypass the entity save process altogether:

```
$order->some_field[LANGUAGE_NONE][0]['value'] = 'foo';
field_attach_update('commerce_order', $order);

```

Other than those I don't think there's any way to accomplish it using the API.

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


# Question
Title: Add a new configurations block to admin/config
I'm trying to add a new configurations block to `admin/config` (just like "People", "Media" and "System").

I tried copying and modifying the relevant lines from `modules/user/user.module` but my block doesn't show and directly going to the link `admin/config/mysite` results in an access denied message.

The sub pages appear directly under the `Administration > Configuration` menu in the Administration module (but not in the page `admin/config`.)

Any idea how to fix this?

```
$items['admin/config/mysite'] = array(
  'title' => 'My Site',
  'description' => 'Configure My Site settings.',
  'position' => 'left',
  'weight' => -20,
  'page callback' => 'system_admin_menu_block_page',
  'access arguments' => array('access administration pages'),
  'file' => 'system.admin.inc',
  'file path' => drupal_get_path('module', 'system'),
);

$items['admin/config/mysite/page1'] = array(
  'title' => 'Sub page 1',
  'page callback' => 'drupal_get_form',
  'page arguments' => array('mysite_admin_1'),
  'access arguments' => array('access administration pages'),
);

$items['admin/config/mysite/page2'] = array(
  'title' => 'Sub page 2',
  'page callback' => 'drupal_get_form',
  'page arguments' => array('mysite_admin_2'),
  'access arguments' => array('access administration pages'),
);

```

# Answer
I have solved my own problem. The reason the links appeared where they did and not under my new block is that I've moved existing items to a new location, which means they were still in the original location in the menu configuration screen. Moving them manually to their correct location solved the problem.
> 2 votes

# Answer
if we don't specify the `access callback` property in `hook_menu()` we get a notification as below:

```
Notice: Undefined index: access in _menu_translate() (line 778 of includes/menu.inc).
Notice: Undefined index: access in menu_get_item() (line 464 of includes/menu.inc).
Notice: Undefined index: access in menu_execute_active_handler() (line 499 of includes/menu.inc).
Notice: Undefined index: access in menu_tree_page_data() (line 1167 of incldes/menu.inc).
Notice: Undefined index: access in menu_tree_page_data() (line 1167 of includes/menu.inc).
Notice: Undefined index: access in menu_local_tasks() (line 1845 of includes/menu.inc).
Notice: Undefined index: access in menu_tree_page_data() (line 1167 of includes/menu.inc).
Notice: Undefined index: access in menu_tree_page_data() (line 1167 of includes/menu.inc).
Notice: Undefined index: access in menu_tree_page_data() (line 1167 of includes/menu.inc).

```

To avoid this the above code should be edited a bit by adding an `access callback` property

```
$items['admin/config/mysite'] = array(
 'title' => 'My Site',
 'description' => 'Configure My Site settings.',
 'position' => 'left',
 'weight' => -20,
 'page callback' => 'system_admin_menu_block_page',
 'access callback' => 'user_is_admin'
 'access arguments' => array('access administration pages'),
 'file' => 'system.admin.inc',
 'file path' => drupal_get_path('module', 'system'),
);

$items['admin/config/mysite/page1'] = array('title' => 'Sub page 1',
 'page callback' => 'drupal_get_form',
 'page arguments' => array('mysite_admin_1'),
 'access callback' => 'user_is_admin'
 'access arguments' => array('access administration pages'),
);

```

And the notice is removed. :)
> 0 votes

# Answer
I fixed it using below code.

```
$items['admin/config/myblk'] = array(
'title' => 'Title of the block',
'description' => 'description',
'position' => 'left',
'weight' => -25,
'page callback' => 'system_admin_menu_block_page',
'access arguments' => array('access administration pages'),
);

$items['admin/config/myblk/myblk-setting'] = array(
'title' => 'Link to settings',
'description' => 'Description about link',
'page callback' => 'drupal_get_form',
'page arguments' => array('call_your_setting_form'),
'access arguments' => array('administer authentication'),
'weight' => 10,
);

```
> 0 votes

# Answer
The easiest way we can add the module link to Admin config page by menu management. Here is the below link to access the menu management.

http://yoursite.com/admin/structure/menu/manage/management

Thank you!!!
> 0 votes

---
Tags: 7, routes
---


title: Drupal Language Switcher menu item

text:
# Question
Title: Drupal Language Switcher menu item
I am using D 7.28 with Boostrap theme (https://www.drupal.org/project/bootstrap). I am using the theme's 'Main menu' to display my links. The language switcher works well for me (changing homepage, Hero banner block and navigation into the appropriate language).

I would like to move the language switcher to the 'Main menu' and display it as an item only showing the inactive language.

Could anyone please provide instructions how to do it?

# Answer
> 1 votes
I have a small module hosted on GitHub that does just that:

Locale Menu

From the README file:

> ## Overview
>
> Alters the href of any menu item whose title is "English" or "Español" to point to the translated version of the current menu item. If no translation exists for the current menu item, the link will point to the translated version of the homepage.

You'll need to tweak Lines 6, 15, and (especially) 21 of the localemenu.module file to match the name and language code of your language.

# Answer
> -1 votes
I have created a module that provides a language switcher dropdown for Bootstrap-enabled themes. It is available as a sandbox module here: https://www.drupal.org/sandbox/pascalanimateur/2493639

---
Tags: routes, i18n-l10n
---


# Question
Title: How to change line-wrap length on Drupal 6 Blog?
I'm currently managing a Drupal 6 website which has a blog displaying about 155 characters per line. I'd like to set that to under 85 if possible. Is this buried somewhere in the menus or it is something I'm going to have to find in some php file?

# Answer
> -1 votes
hi you can use the module maxlength to achieve it, it can be used to set the charecter limit to any of the cck field like body, summary, title etc.

---
Tags: nodes
---


title: Region doesn't show the blocks content

text:
# Question
Title: Region doesn't show the blocks content
I can't see a content of custom block (making by clicking on "Add new block").

I try to add block in region, but region doesn't show the block content. I use different kinds of block("Search form", "Powered by Drupal", etc.) and it doesn't help.

What should i do?

# Answer
Add new block then yo have to specify whether the block should be visible in all pages or specific pages in the **Show block on specific pages** save it. also while assigning the block to any particular region you need to save the block by clicking on save blocks button at the bottom of the blocks page.
> 0 votes

---
Tags: 7, theming
---


# Question
Title: How to fetch HTML created via a Forena report and store it as a node?
I'd like to automatically (Rules) copy some HTML into a node . The HTML comes from a Forena report (already as an HTML document), created by the Forena module. In the Rules module I couldn't find anything exactly fitting.

It might be possible to develop a small module that fetches the Forena report (using some of the available Forena hooks) and create a node from it.

But is this the easiest way to go? It feels a bit like a detour, maybe I'm just overlooking some module or feature which can do that task?

# Answer
You can have a look to the module "Feeds". It's aim is to provide a way to import content (node, term...) from CSV File, XML...

You can also specify interval between two importation. So you won't need rules.
> 3 votes

# Answer
From the Forena project page: use Feeds to create nodes using **Forena data blocks** and/or **reports**. In other words: Forena can be used as a feeds importer (= to enable Feeds to go read from al kinds of database tables, **external databases**, etc. which Feeds out-of-the-box does not support). And Forena comes with various hooks to use Forena from within another module.

For more details about Forena, 2 types of documentation are available:

* Community documentation, which includes a child page Video demos and tutorials containing a link also about using Forena to import data and reports based on data as drupal nodes (that video even demonstrates the creation of charts, so not just tabular reports).
* Documentation that comes with Forena, which you can access right after install and enable of the module. Checkout the demo site for an online example of the current:

+ **Forena documentation** \- use the link 'Reporting documentation' or visit relative link /reports/help.
    + **Forena samples** \- use the link 'Reporting samples' or visit relative link /reports/samples (these samples are fully functional, so make sure to experiment a bit with it, such as the drill downs available on the SVG Graph sample).

The 7.x-4.x version also includes an amazing (I think) UI for either creating your reports (the WYSIWYG report editor) and/or for creating your SQL queries (the Query Builder).

Here are some variations of the **external databases** part mentioned above:

1. Using a **SQLite** instead of MySQL database: the Forena samples actually get shipped including a (Tiny) SQLite database. Go check it out in the demo site: the data shown there are data contained in the sampledb, which is in SQLite format.
2. Forena comes with a full suite of Supported database connections ... such as MySQL, MS SQL, Oracle, Postgress or any PDO compliant variation.

**Disclosure**: I'm a co-maintainer of Forena.
> 1 votes

---
Tags: rules, log-messages, forena
---


# Question
Title: how to add 'OR' operator in views sort criteria
How to add `'OR' operator` in views sort criteria?

Is there any ui setting or have to do some custom work?

Any suggestion?

# Answer
> 0 votes
What do you mean add OR? There is no such condition in sorting. You can have different sorting levels. Add multiple values in the view's ui sorting criteria and then re-arrange properly.

---
Tags: views
---


# Question
Title: Cache + random + hook_form_user_register_form_alter
for a captcha purpose, I'm trying to set a random number in the `hook_form_user_register_form_alter`

For example :

```
function my_module_form_user_register_form_alter(&$form, &$form_state) {
    $random_case = rand(0, 3);
    $form["random"] = array(
        "#type" => "textfield"
        , "#title" => ""
        , "#disabled" => 0
        , "#value" => $random_case
        , "#description" => null
        , "#weight" => -2
    );
}

```

When cache is disabled it's working as intended.

when I enable the cache the random number is always the same until I flush all caches. I tried to flush cache programmatically, but it doesn't seem to work. What can I do ?

if I put a

```
die($random_case);

```

It's working but I think it's because drupal can't put the hook inside the cache.

Best regards.

# Answer
> 1 votes
When the forms cached, it caches the original, unprocessed `$form` array, and the builder functions are not called again.

you can explicitly set cache off by setting `$form_state['no_cache'] = TRUE;`. Note that this has potential to break Ajax forms.

---
Tags: hooks, caching, users
---


# Question
Title: hook_views_pre_render() to override results of a view
I have a view used on a site to show the latest 4 nodes (in teaser mode) of a content type of 'article'.

On some Article pages the administrator can override some or all of the 4 nodes to be shown in this view.

I have an entity reference field in this content type where they can optionally select up to 4 nodes to feature instead, then in my template.php I have the following code:

```
function adaptivetheme_subtheme_views_pre_render(&$view) {
    if($view->name == "related_articles") {

        if ((arg(0) == 'node') && is_numeric(arg(1))) {
            $node = node_load(arg(1));
        }

        if(isset($node) && $node->type == 'article') {

            foreach($node->field_related_articles['und'] as $key=>$override) {
                if(!empty($override)) {
                    $view->result[$key]->nid = $override['target_id'];
                }
            }

            dsm($view);
         }

       }
}

```

I can see in the DSM output that the values in the results array of the view are changed correctly, but the actual rendered view has blank spaces in place of the inserted nodes.

Where am I going wrong?

# Answer
> 1 votes
Per the first two comments here you should probably use hook\_views\_post\_execute. If you have paged data this will cause issues.

---
Tags: views
---


# Question
Title: How to populate the select option using select index
-- Modifying my previous question --

This really got me. This is what I am doing right now with my module. I created a menu\_hook which creates a form using a theme to create data. Another menu link which displays the saved records. When the user clicks on the Name, it should display the form with all fields populated with the corresponding data but with form fields disabled. To attain this, my module file looks like this.

```
<?php
  function agents_menu(){
    $items=array();
    $items['enquiryform']=array(
      'title'=>'New Enquiry',
      'description'=>'Add new enquiries form',
      'page callback'=>'agents_form',
      'access callback'=>TRUE,
      'access arguments'=>array('access content'),
      'type'=>MENU_NORMAL_ITEM,
    );
    $items['enquirylist']=array(
      'title'=>'View Enquiries',
      'description'=>'Lists all the enquiries',
      'page callback'=>'show_enquirylist',
      'access callback'=>TRUE,
      'access arguments'=>array('access content'),
      'type'=>MENU_NORMAL_ITEM,
    );
    items['enquiry_details']=array(
      'title'=>'New Enquiry',
      'description'=>'Add new enquiries form',
      'page callback'=>'enquiry_details',
      'access arguments'=>array('access content'),
      'type'=>MENU_CALLBACK,
    );
    return $items;
  }

  function agents_form(){
    $form = drupal_get_form('enquiries_form');
    return render($form);
  }
  function agents_theme(){
    return array(
      'enquiries' => array(
        'render element' => 'form',
        'template' => 'customTemplate',
      ),
    );
  }

  function enquiries_form($form, &$form_state){
    $form = array();
    $form['#theme'] = 'enquiries';
    $form['efname'] = array(
      '#type' => 'textfield',
      '#title' => 'First Name',
      '#size' => 28,
      '#maxlength' => 100,
      '#required' => TRUE,
  );
  $form['elname'] = array(
    '#type' => 'textfield',
    '#title' => 'Last Name',
    '#size' => 28,
    '#maxlength' => 100,
    '#required' => TRUE,
  );
  $form['edob'] = array(
    '#type' => 'date',
    '#title' => 'Date of Birth',
    '#date_format' => 'Y-m-d',
    '#required' => TRUE,
  );
  $options = array('0'=>'Male','1'=>'Female');
  $selected = '0';
  $form['egender'] = array(
    '#title' => t("Choose Gender"),
    '#type' => 'select',
    '#options' => $options,
    '#default_value' => $selected,
  );
  $form['submit_btn'] = array(
    '#type'=>'submit',
    '#value'=>'Submit',
  );
  return $form;
}
function enquiries_form_validate($form, &$form_state){}

function enquiries_form_submit($form, &$form_state){
  $dobarr = $form_state['values']['edob'];
  $dob = $dobarr['year'].'-'.$dobarr['month'].'-'.$dobarr['day'].' 00:00:00';
  db_insert('enquiries')->fields(array(
    'efname'=>$form_state['values']['efname'],
    'elname'=>$form_state['values']['elname'],
    'edob'=>($dob),
    'egender'=>$form_state['values']['egender'],
    'active' => 1,
    )
  )->execute();
  drupal_set_message($form_state['values']['efname']);
}

function enquiry_details(){
  $query = db_query("SELECT * FROM {enquiries} WHERE eid='".$_GET['vars']."'");
  $form = drupal_get_form('enquiries_form');
  foreach($query AS $result){
    $form['efname']['#value']=t($result->efname);
    $form['efname']['#attributes']['readonly'] = 'readonly';
    $form['efname']['#attributes']['class'][] = 'readonly';

    $form['elname']['#value']=t($result->elname);
    $form['elname']['#attributes']['readonly'] = 'readonly';
    $form['elname']['#attributes']['class'][] = 'readonly';

    $form['egender']['#default_value'] = '1';
    $form['egender']['#disabled'] = TRUE;
    $form['egender']['#attributes']['readonly'] = 'readonly';

    $form['edob']['#value'] = date($result->edob, '00:00:00');
  }
  return $form;
}

```

No matter what I do, select drop-down doesn't populate "Female". I checked the value of $form\['egender'\]\['#default\_value'\] before and after setting it to 1. Though the value is returned, select drop-down won't change as per the default\_value. My understanding is that the form element is not refreshed after setting the value. Tried using the same approach in hook\_form\_alter but of no use. Same way, date is also not getting populated. What and where am I doing wrong?

# Answer
If you are trying to set the default value, you need to set:
`$form['egender']['#default_value']`.
setting it to 1 will make female the default value.
HERE is a page that shows you the relevant form array values that an be set.
> 0 votes

# Answer
The problem is solved now and this is what I did, exactly what 2pha has suggested me to do.

```
$form['egender']['#default_value'] = t($result->egender);

```

The key is, clear the cache as much as you can. I tried to see the result by clearing the cache, but nothing happened. Finally I ended up restart the server and try again, and it worked. Thanks to 2pha
> 0 votes

---
Tags: forms
---


# Question
Title: Menu links duplicated on node/%node/edit pages
I've a strange problem. I've a multilingual site with many menus configures as "Translate and localize".

Everything works, every menu link has his language, but ONLY when I go to a node/%nid/edit page the system prints all links, on both language (on every language)

This behaviour there is on every theme. I've i18n modules enabled.

What's wrong?

# Answer
> 0 votes
The problem is the function \_i18n\_menu\_link\_process of i18n\_module.

```
<?php
    /**
     * Check whether this link is to be processed by i18n_menu and start processing.
     */
    function _i18n_menu_link_process(&$link) {
      // Only visible links that have a language property and haven't been processed
      // before. We also check that they belong to a menu with language options.
      if (empty($link['i18n_menu']) && !empty($link['language']) && !empty($link['access']) && empty($link['hidden']) && i18n_menu_mode($link['menu_name'])) {
        // Mark so it won't be processed twice.
        $link['i18n_menu'] = TRUE;
        // Skip if administering this menu or this menu item.
        if (arg(0) == 'admin' && arg(1) == 'structure' && arg(2) == 'menu') {
          if (arg(3) == 'manage' && $link['menu_name'] == arg(4)) {
            return FALSE;
          }
          elseif (arg(3) == 'item' && arg(4) == $link['mlid']) {
            return FALSE;
          }
        }
        // Skip if administering this menu item through the node edit form.
        elseif (arg(0) == 'node' && arg(2) == 'edit') {
          return FALSE;
        }
        return TRUE;
      }
      else {
        return FALSE;
      }
    }
?>

```

This function returns TRUE or FALSE when checking if a menu link should be "hidden" (and so not displayed). At the end this value "hidden" is TRUE for link of a language different from current user language.

This function EXCLUDES this "hidden =\> TRUE" value when the request page is node/%nid/edit, and I don't understand way.

So there are two solutions:

* apply a patch to this function
* declare in a custom module the hook\_translated\_menu\_link\_alter, force this hook to run AFTER i18n\_menu and apply my "logic"

And, obviously, ask on drupal.org the reason of this behaviour.

# Answer
> 0 votes
I'm not sure i fully understand the question, but please take a look to this post:

https://drupal.stackexchange.com/a/96963/30465

It seems related to your question.

I this it will be related to the language configuration fallback (since there is no language suffix inlcuded)

You could for example try

http://www.example.com/en/node/%nid/edit

if that works correctly (and only shows the engish menu links), you know that it will be a problem with language fallback.

Hope this helps, feel free to let me now if you need more!! :)

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


title: how to alter a hook_field_insert

text:
# Question
Title: how to alter a hook_field_insert
I am trying to find a way of altering the output of a hook\_field\_insert. In my exact example, I'm trying to hook into the link\_field\_insert hook, in the Link module:

```
/**
* Implements hook_field_insert().
*/
function link_field_insert($entity_type, $entity, $field, $instance, $langcode, &$items) {
  foreach ($items as $delta => $value) {
    _link_process($items[$delta], $delta, $field, $entity);
  }
}

```

and make a modification to the \_link\_process function, without actually having to hack the Link module. Is thi possible?

Just to have some background, what my end goal is to add a new form field on the node page for the user to enter link classes, and these classes would be autmatically applied to the link. I have already overridden the theme\_link\_field to add this form field and its value shows up in the $items array in the above function, so I just need to know how to override the above function.

# Answer
you don't need to alter the hook. You can implement the hook. But in your case maybe you want to use theme\_menu\_link() instead Customizing menu link output

also check https://api.drupal.org/comment/55298#comment-55298
> 0 votes

---
Tags: hooks, entities
---