# Question
Title: Putting items in multiple places in a menu
I'm trying to set up a menu layout which has two links to `/biblio`; one under "Researchers", and one under "Staff". This is for convenience, as if you are looking under "Staff", the "Researchers" submenu is closed, and the "Staff" submenu isn't available to unregistered users. The problem I'm running into is that although I can have two links in different parts of the menu, when looking at the page it will always try to open the menu to only one of them. This means that if you are looking under "Staff", and you go to publications, suddenly you're in what seems to be a different location of the site. Any suggestions for how I can fix this?

# Answer
You can use the Multiple Node Menu module.
> 3 votes

# Answer
The issue here is that you have one page, and two ways of getting to it. Suppose you went straight to /biblio on your site, from a bookmark or something. Drupal would have no idea if you intended to be "Staff" or a "Researcher".

In this situation, you might be able to do something like /staff/biblio and /researchers/biblio, which would be the same page, but this would enable Drupal to tell which version of the menu to display.

An alternative might be to say "if the user is logged in (or has a specific role), assume that he or she has used the 'staff' menu, and if not logged in, assume the 'researchers' menu".
> 1 votes

# Answer
The real problem here is that Core is inconsistent when handling two menu items with the same path. It says one thing in the UI and does another in reality.

The result of which is that the menu link added most recently, the one with the highest menu link ID, is the one whose menu trail will be active.

If that's not your preference, delete your preferred duplicate menu item, and then re-add it. It will then have the highest ID number so when you land on the internal URL path, that menu item's trail will be active.

I don't believe there's a way to have have multiple trails active at the same time; you have to select one.
> 1 votes

# Answer
To have two different URLs that point to /biblio should be sufficient to create two path aliases that alias /biblio. The exact path aliases to use depend from the menu URLs.
> 0 votes

# Answer
The **Menu Position** module allows you to configure rules that apply to items placed in menus.

You can restrict the active menu item depending on the page, content type, language, taxonomy, or user role.

Using this, you'd create two *Menu Position Rules* within your menu, at different spots, and use them to set the active menu trail by the user role.
> 0 votes

---
Tags: 7, routes
---


# Question
Title: Issue with content access and multilingual system
I have a multilingual website using English, Arabic and French. 2 days ago I noticed that anytime when I clicked on `node/add/*` for the English section, it returns an access denied page. And that is just for English (the other languages are fine and nothing wrong with them).

I use the Content Access module but even after I uninstalled it the issue remains the same.

I'm using Drupal version 7.32 and I18n 7.x-1.11.

Does anyone have an idea about this issue?

# Answer
> 0 votes
I see 2 possible explanations for your issue, as further detailed below. Consider checking both of them to see if either one of them apply in this case.

## Cookie problem

It is possibly an issue with a cookie. So try the same scenario usiing another browser. If with that browser the problem does not occur, then it is probably a cookie problem. In that case, just delete the session cookie in the browser where the problem occurs. Then check if the issue is resolved.

## Site may be hacked

Since the version of this Drupal site is **7.32**, it might simply be that your site was hacked. Refer to SA-CORE-2014-005 (posted a week before this question was asked ...) for some more details.

For way more details about that, and possible approaches to do more research on that, refer to Drupal SA-CORE-2014-005 - How to tell if my server / sites were compromised?, which also suggests to use the Drupalgeddon module.

---
Tags: users, i18n-l10n
---


# Question
Title: How to implement module dependencies in a theme and package modules with a theme?
If you're making a theme and associated custom modules designed for that theme and no other theme. Is there a way to package the modules with the theme so that when the theme is activated the modules will show up in the module list ready to be activated? The custom modules are build for the theme and so if they can be packaged with the theme that would make it simple to distribute.

I would like to avoid the problems of the user not being able to fully use the theme due to a missing library or module.

If a theme and collection of modules that are packaged in a single zip file, when passed to the drupal installer, permit Drupal the ability to extract the theme and modules to the correct locations? Can it determine the themes dependencies and then install the modules from a url?

Some examples that I can think of is having color pickers for a theme so you can select different colors for the theme in the settings area. I could make custom modules for this and have the modules show up if the theme is active. Maybe also have it alert the user to activate the modules one theme activation. If the theme has a custom slideshow should this be built into the theme or maybe as a packaged module inside the theme that shows up as a module in the modules list to be activated.

Maybe inside the theme package it could have a modules folder that Drupal could then extract the modules and install them into the module directory. On uninstall could prompt the user if they would like to also uninstall the associated modules. If this is possible (or soon to be) this would make managing complex themes clean and simple. It would also keep the module list clean as well. maybe some dependency in the theme info file?

Other thoughts would be if a theme was active maybe it could find said modules and inject rendering options into the modules configurations options.

As of right now this is just a curiosity of mine and I wonder if it could be done. This idea came about after setting up many Drupal sites and making custom modules and themes. Then it hit me what if I could do more with my custom themes by knowing it can only run if all the needed modules where there. Then I wouldn't have to worry about a bad user experience.

# Answer
Up to Drupal version 7, themes do not allow to have the typical directive for module dependencies in their info files. Because themes are supposed to be module independent.

However, for D8, there is the issue about dependencies\[\] for themes, so they can depend on modules (created back in 2009 ... current status = needs work).

For D7, Comment #3 in (Drupal core) issue 647014 contains a possible work around that you may want to consider, something like so:

```
<?php
function mytheme_preprocess_page(&$vars)
{
  ...
  if (!module_exists('needed_module'))
  {
    // No needed_module means we need to add it, let everyone know.
    //
    print "<h1>"  . t( 'mytheme requires that module needed_module is installed')
        . "</h1>"
        . "<h6>"  . t( 'warning generated in file: %f', array ( '%f'=>__FILE__ ))
        . "</h6>";
  }
  ...
}
?>

```
> 2 votes

---
Tags: 7
---


# Question
Title: Block form send email to recipients from a view
We have a view which can be filtered. We need a block which can be used to send a message with the recipients coming from the view. Ideally this would be on the same page. This would be used by anonymous users so the interface needs to be simple. We have tried views send but the form is too complex to present to anonymous users.

Possibly an entity form where we can define the fields, user selects the recipients from the view, fills the simple block form and send.

Any ideas much appreciated.

# Answer
> 0 votes
You can use Views Send module for that.

> Views Send enables you to send mass mailing from a View.

# Answer
> 0 votes
You can use Views Contact Form module

> A new Views style which display a contact form, in a block, a page or an attachment. Recipients are taken from a field you define.

# Answer
> 0 votes
Add the "Send email" field to your Fields list

---
Tags: views, forms, blocks, emails
---


# Question
Title: Functional testing without using simpletest
I have recently joined a Drupal project at work that is approx 50% finished. Functional testing was never part of the project. The site has about 8 custom modules and they are not going to be used anywhere but with this client. I tried implementing the testing module in D7 but the modules were not created in a way that allows the modules to install cleanly. I tried to get them installable but I don't think there will be enough time to devote.

So, I need a solution that will allow me to test the new features we are building without having to fix the previously built portions.

I looked at Selenium but to my knowledge it requires the feature to be built before the script can be recorded. I'd like to use it Test Driven Development style. I have also been looking at Behat but honestly, I don't get it.

This question is more specific than "what is your favorite functional testing framework?". It is more specifically, "What functional testing framework works well with Drupal and works with our site as it is currently developed?".

# Answer
I ended up working with Behat (http://docs.behat.org/en/latest/) and Mink for Behat (http://mink.behat.org/en/latest/) to write tests that emulated a user using a browser on my website.

However, I still needed Drupal integration for quick access to nodes, users, and roles. I found this project (https://www.drupal.org/project/drupalextension) which incorporates Behat, Mink, and the Drupal API. This allows me to write tests like this:

```
@api
Scenario: Logged out user can access the custom Landowner registration page
    Given I am not logged in
        And I am on the homepage
    When I click "Register here"
        And I am on "/register"
        And I click "Register as a Landowner"
        And I am on "/register/landowner"
    Then I should see "Landowner Registration"

```

Now I can test a Drupal site without the issues involved with Simpletest.
> 2 votes

---
Tags: 7, testing
---


# Question
Title: Error when trying to extend a db_select query
I'm trying to add a field to my query by using addField(). However, whenever I add this to the query I get a whitescreen and an apache error message on the line after. Any help in resolving this would be much appreciated.

Apache error log:

`PHP Fatal error: Call to a member function extend() on a non-object`

db\_select query:

```
$query = db_select('z_revision', 't')
    ->fields('t', array('drupal_user_id'))
    ->addField('t', 'z', 'category')
    ->extend('PagerDefault') # error on this line
    ->extend('TableSort')->orderByHeader($header)
    ->limit(30)
    ->execute();

```

Ideally this would give me a two column table with headers 'drupal\_user\_id' and 'category' - all the rows in the category column having 'z' as a value.

# Answer
`addField` returns the alias of the field that's added, not the query object. You just need to break your code up a bit:

```
$query = db_select('z_revision', 't')
  ->fields('t', array('drupal_user_id'));

$query->addField('t', 'z', 'category');

$result = $query->extend('PagerDefault')
  ->extend('TableSort')
  ->orderByHeader($header)
  ->limit(30)
  ->execute();

```
> 3 votes

---
Tags: 7, database
---


title: EntityFieldQuery and "legacy" nodes

text:
# Question
Title: EntityFieldQuery and "legacy" nodes
Here's the situation, which I suspect is pretty common:

* A site is deployed where a node type has no fields added.
* Lots of nodes are added.
* The site is changed and a new field is added to the node type.

At this point, I've got my original nodes that do not have a value for the new field. There aren't even any field value records in the database for these nodes.

I now need to query for the nodes where this field is set to a certain value (a new or updated node) **OR** where it's one of the original nodes. So I'm thinking something like this (note the NULL in my array of possible values):

```
$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'node')
  ->entityCondition('bundle', 'my_content_type')
  ->fieldCondition('field_myfield', 'value', array('myvalue', NULL));

```

Unfortunately, this doesn't work, and I suspect it's due to the nature of the join. Is it possible to return results where the field is a certain value OR where there is no record of a value at all?

ps: how do I see/debug the resulting query?

# Answer
Although EFQ is a good tool, it starts with the assumption that you are querying about a field value. It does not do the join because it is more efficient to get what you want the way it does it. For you legacy nodes, I think you should do a legacy Dynamic Query. This way you can specify a Left Join to get a result set that includes nodes with NULL/absent entries in the field table.

```
$query = db_select('node', 'n');
$query->leftJoin('field_data_field_myfield', 'f', 'n.nid = f.entity_id');
$query->condition('f.value', array('myvalue', NULL), 'IN')
  ->condition('n.type', 'my_content_type');

```

Joins in the dynamic query method.
> 0 votes

---
Tags: 7, database
---


title: Pagination Not Tied to database queries

text:
# Question
Title: Pagination Not Tied to database queries
I would really like to:

* to create a paginated table of nodes, displaying only those that the user has 'update' permission to; displaying title, content type, and path alias
* the path for nodes may be different depending on the content type. More specifically, I have created a content type 'file' to wrap an uploaded file; I would like to display the url alias associated to the actual file, rather than the url alias of node that wraps it.

There are a few approaches that I have considered,

1. Creating views. However, the above behavior seems to require merging two views --- one for nodes of type file, one for node of content type not equal to file. I have no idea how to merge two views. Also, this method seems to create a dependency of the output of the view on the content type 'file'.
2. Use database query + pagination. In many of the examples that I have seen, if I want to add pagination to a table, I can do the following (see this very excellent tutorial):

* run a database query using either `pager_query` or the `extend` method for the `SelectQuery` object
    * theme the query results, and use theme to generate the pager based on the query

The problem with this approach is making theme('pager') play well with filtering the database entries by node\_access. For example, for an user with relatively few nodes that she can edit, the table displays many empty pages.
3. Database query, filter into array, then use pagination on array as suggested by this post. This does get the table to work correctly. However, it is really expensive, because the entire query is run at this point, and the pager is purely for aesthetic purposes; seems a bit wasteful.

Now (thank you for bearing with me so far), is there a some way to create this table this without using views, but faster than method 3? I can also accept 'no' for an answer; in this case, it would be nice to know why not.

# Answer
I realise the question is more than a year old...

Create a view with no content type filter. Add fields for Title, Type, Link, and File field in that order. In the Link field settings, check the Exclude from Display box. In the File field settings, under No Results Behavior, use the token of the Link field in the Rewrite Output space. The available tokens will be listed in an expandable space below the text field. Tokens include all fields listed before the current field, which is why the order matters. Set display to a table and turn on paging.

Views will automatically check access permissions, so this should do what you want. This will pull in all nodes, filter by access, look for the file and use that link if it finds it, and then in the cases where that field is empty (content of another type) it will use the node link instead.
> 1 votes

---
Tags: database, paging
---


# Question
Title: Why does Drupal have both "sid" and "ssid" field in the session?
Learning more about Drupal core so I can be a better contributor, understand security better, etc.

I noticed that on creating a session Drupal uses both an "sid" and "ssid" field. The code seems to indicate they are both the same (the little code I've been able to decipher so far), `'sid' && 'ssid' = session_id()`, and looking at the DB only the sid is set in my own session.

Why do both columns exist? Is it a security measure? If so what does it do? Is it a legacy field from an old system?

Looking at Drupal 7 code.

# Answer
> 2 votes
Yes it is a security measure; `sid` is the session id for HTTP traffic & `ssid` is the session id for HTTPS traffic. The idea here is that secure parts of your website (e.g. **https://www.example.com/user/\*/edit** ) can't be compromised by session hijacking the `sid` that occurs with HTTP traffic.

---
Tags: 7, sessions
---


title: how to add "new" or "updated" on a view

text:
# Question
Title: how to add "new" or "updated" on a view
In my administration content editing page (drupal 7), I have a little red "new " or "updated" next to some items. How can I make these red labels come out in my views listing?

# Answer
You may use field "Content: Has new content" in views to display "updated" text
> 1 votes

---
Tags: views
---


# Question
Title: Why didn't the Drush command bam-restore work?
I'm a new admin of a Drupal site (core 7.38 on an OpenSUSE 11 server). Yesterday I ran `Drush up` to update VBO to 7.x-3.3 and suddenly I could no longer access the site. The homepage displayed the site's header/logo with the generic error message "The website encountered an unexpected error. Please try again later." I tried accessing /?q=user and some of the other pages via their clean URLs, but nothing worked. The server was working fine and I was able to access the tar.gz archive created that morning through the Backup & Migrate module. So I followed instructions I found online for restoring from a Backup & Migrate archive (using `bam-restore`) but it failed. Drushcommands.com says bam-restore accepts three arguments: source, destination, backup id. I entered the parameters but got another ambiguous error message. Subsequently I found different instructions that avoided the `bam-restore` command and opted for mysql commands.

Why didn't the `bam-restore` work?
Is there a way to get more specific error message or access what's actually going on with Drush in a specific circumstance?

# Answer
First, I would have run **drush up drupal**, updates only Drupal core, no third party themes or modules. To do a restore, try **drush archive-restore**
> 0 votes

---
Tags: drush, views, backups
---


# Question
Title: Edit panel not showing up (Gear -> Edit Panel -> NOTHING??)
If I go to a custom panel and click the gear, then click edit panel, the link changes as if a popup appeared, but nothing else shows up. I cleared my cache on my browser, computer, on the website, and even tried it on my coworker's computer but it still doesn't work. I also tried it on Chrome, Firefox, and Safari and still no success. Any thoughts?

# Answer
You or one of the modules you installed is loading latest version of jQuery. In the latest version of jQuery code like

```
if (jQuery.browser.msie && parseInt(jQuery.browser.version, 10) < 8) {}

```

does not work.

This code is in one of the Drupal core files. You can find it in modules/overlay/overlay-parent.js file on line 932, 975 and 985.

I do not recommend editing this file, but you can test this change on your localhost to make sure it is the latest version of jQuery which is causing this issue.
> 0 votes

---
Tags: panels
---


title: excessive "access denied" logs?

text:
# Question
Title: excessive "access denied" logs?
I've setup a Drupal site and had to turn off user registration because of the amount of bogus accounts being created. Now when I check the logs I see loads of access denied messages, usually for pages node/add user/register

Is this normal for a drupal (possibly any) site, and something to be expected? It seems excessive to me, so I'd like to understand if this is a normal problem for websites, drupal or otherwise?

# Answer
> 1 votes
Yes, this is a common problem. A spam bot has crawled your site, realizes it's a Drupal site, and it going through its functions to spam content (e.g. user register & node posting). This isn't exclusive to Drupal; there many kinds spam bot software that target specifics CMSes and any other comment/content submission forms.

You should look into various Drupal spam prevention modules like CAPTCHA, Botcha, etc.

---
Tags: users
---


# Question
Title: rules autotag module, bulk retagging existing nodes
I am using the rules autotag module. It's working fine for adding new nodes. But what would I do for retagging existing nodes (approx. 40,000)?

# Answer
> 2 votes
According to this autotag issue on d.o, titled "How to re-tag all content":

> * Use Views Bulk Operations (VBO).
> * Create a bulk view with the 'Save post' operation
> * In the view, select the nodes you want to re-autotag and execute (which will resave all the nodes)

Note the different autotag modules:

* autotag uses your existing taxonomies, can be used with VBO.
* rules autotag doesn't have the UI of autotag, it's possible to use this one with VBO as well.
* autotagging uses 3rd party services

# Answer
> 1 votes
Just wanted to share a solution without the use of VBO but only the Rules module:

Say, you are using the Basic page with your field “MyField” for tags in the vocabulary “MyTags”

Add new component as a rule and call it “MyComponent”

Select Node as datatype, “Node” as label, “node” as machine name and keep it as a parameter

Add condition, choose Entity has field, type “node” as data selector and select field\_myfield as field

Add action, choose Actionset: Autotag to terms list, type \[node:body\] as text for extracting terms, select MyTags as the vocabulary, switch to data selection under target list and type node:field-myfield

Now, add a new rule and call it MyRule

For an event to react on you can choose anything. I have all my nodes updated when I create a new term so I would choose After saving a new term and restrict it by selecting MyTags as vocabulary

Add action, choose Fetch entity by property, select Node as entity type and Content type as property. Because of a bug in Rules you cannot choose the content type right away but if you press Switch to data selection under Limit result count and then press Switch to the direct input mode you can now choose Basic page as value. Switch to the direct input mode for Limit result count and choose a number higher than you nodes. Hit save.

Add a loop and type entity-fetched under list and hit continue. Add an action inside the loop, choose Rule: MyComponent, type list-item as node and hit save.

Now all your nodes should be updated every time you save a term to your vocabulary.

Code to import MyRule:

```
{ "rules_myrule" : {
"LABEL" : "MyRule",
"PLUGIN" : "reaction rule",
"OWNER" : "rules",
"REQUIRES" : [ "rules", "taxonomy" ],
"ON" : { "taxonomy_term_insert--mytags" : { "bundle" : "mytags" } },
"DO" : [
  { "entity_query" : {
      "USING" : {
        "type" : "node",
        "property" : "type",
        "value" : "page",
        "limit" : "10000"
      },
      "PROVIDE" : { "entity_fetched" : { "entity_fetched" : "Fetched entity" } }
    }
  },
  { "LOOP" : {
      "USING" : { "list" : [ "entity-fetched" ] },
      "ITEM" : { "list_item" : "Current list item" },
      "DO" : [ { "component_rules_mycomponent" : { "node" : [ "list-item" ] } } ]
    }
  }
]}}

```

Code to import MyComponent:

```
{ "rules_mycomponent" : {
"LABEL" : "MyComponent",
"PLUGIN" : "rule",
"OWNER" : "rules",
"REQUIRES" : [ "rules" ],
"USES VARIABLES" : { "node" : { "label" : "Node", "type" : "node" } },
"IF" : [
  { "entity_has_field" : { "entity" : [ "node" ], "field" : "field_myfield" } }
],
"DO" : [
  { "component_rules_autotag_tag" : {
      "text" : "[node:body]",
      "vocabulary" : "mytags",
      "target_terms" : [ "node:field-myfield" ]
    }
  }
]}}

```

Morten

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


# Question
Title: jQuery scripts not working on my Drupal theme
This script from JSFiddle that works: https://jsfiddle.net/ryXFt/704/

Does not work in my Drupal theme (yes, it does load, I can see it via Firebug). All I do is just wrap up the code to match Drupal rules.

```
(function ($) {
  Drupal.behaviors.yourBehaviorName = {
    attach: function (context, settings) {
        $("#block-menu-menu-mobile ul li .nolink").click(function() {
            $('html,body').animate({
                scrollTop: $(".region-front-calander").offset().top},
                'slow');
        });
    }
  };
})(jQuery);

```

When clicked, console gives `TypeError: $(...).offset(...) is null` for line that contains `scrollTop: $(".region-front-calander").offset().top},`

HTML

```
<html>
    <body>
        <div id="page">
            <div id="main">
                <div id="content" class="column" role="main">
                    <div class="region region-highlighted">
                        <div id="block-menu-menu-mobile" class="block block-menu first odd" role="navigation">
                            <ul class="menu">
                                <li class="first leaf">
                                    <span class="nolink" title="">Calendar</span>
                                </li>
                            </ul>
                        </div>
                    </div>
                    <div class="region region-front-calendar"></div>
                </div>
            </div>
        </div>
    </body>
</html>

```

# Answer
Looks like your classes aren't matching up. I'm guessing that the ideal action you want is when you click on the calendar link, it brings the region-front-calendar up.

The issue looks like your js isn't doing anything to that region, rather it's attempting to pull up a class called "second" which dosn't exist in the html snippet you posted.

If you switch that to the region-front-calander, that might be the answer your looking for.

```
(function ($) {
  Drupal.behaviors.yourBehaviorName = {
    attach: function (context, settings) {
        $("#block-menu-menu-mobile ul li .nolink").click(function() {
            $('html,body').animate({
                scrollTop: $(".region-front-calander").offset().top},
                'slow');
        });
    }
  };
})(jQuery);

```
> 1 votes

---
Tags: 7, theming, javascript
---


# Question
Title: Display different time from one field value
I have field to display event start date and time. This field uses date module's widget. I need display time of event start for different time zones. For example:

Eventname - starttime for Tallin: 05.07.2015 01:54

Eventname - starttime for Boston: 05.07.2015 09:54 (+8 Hours)

How can I add +8 hours to date field value and display result on node?

# Answer
Well you are better off writing a custom module or using a function that can swap out a timezone variable instead of manually calculating by adding 8 hours... But if that's what you want here is one way of achieving this..

Create a node template for that content type or specific node (whichever suits your scenario).

In the template file you can use:

```
 <?php
    // Your date field. note the appended 'field_' at the start of the machine name.
    $date = new DateTime($content['field_YOUR_FIELD_MACHINE_NAME']['#items'][0]['value']);

    // Boston date field
    $boston_date = $date;
    $boston_date ->modify("+8 hours");
    $boston_date ->format("d.m.Y H:i");

    //Outputs your date field with 8 hours added to it.
    print 'Eventname - starttime for Boston: ' . $boston_date;
 ?>

```
> 0 votes

---
Tags: datetime
---


title: How to Install two version of Drush?

text:
# Question
Title: How to Install two version of Drush?
I installed in my PC drush 8 for develop on Drupal 8, but I need drush 7 for connect with my sites on remote servers. I download manually drush 7 but when I try to open said me:

> Unable to load autoload.php. Drush now requires Composer in order to install its dependencies and autoload classes. Please see README.md

Then, How I install two versions of Drush in my PC?

# Answer
Drush 8 should work just fine with remote sites running Drush 7.

To get around the error message you are seeing, run `composer install` from the Drush directory.

If you want to install multiple versions of Drush to run locally, the easiest way to do it is to manage your Drupal site with Composer, and add a 'require drush' line in your composer.json. If your global Drush is at least version 7, then you will find that Drush automatically dispatches to the site-local Drush whenever you target it.

One really good use-case for doing this would be to run Drush 7 stable as your global Drush, but use Drush 8 with any Drupal 8 site.

See also:

https://github.com/drupal-composer/drupal-project https://github.com/pantheon-systems/example-drupal7-composer
> 2 votes

---
Tags: drush
---


title: How to find the base table of view?

text:
# Question
Title: How to find the base table of view?
A view is just an SQL query on a table - in the UI how can I find what table an existing view is based on?

# Answer
> 6 votes
Not exactly. But, you may find it helpful to goto `Views -> Settings -> Advanced Settings` from `admin/structure/views` and check the `Show SQL Query` in your View Preview.

Then goto a view and generate a preview and you will see the SQL statement Drupal is using to generate a query. Some parts of the Views lifecycle to render a `views display` though are fulfilled by PHP and not SQL. For example drupal Fields are inserted into each row of the the resultset if your display mode is either Fields or Rendered Entity. By this I mean the raw SQL does not perform a JOIN upon every `field_data_*` table used by your content type -- this is handled in PHP, and not SQL. All of this is also dependent on the Storage mechanism being used by Drupal (the default is SQL, but other backends exist such as NoSQL backends).

I'm just saying the SQL preview will show you ~70% of what Drupal is doing to generate your view. But there is some behind the scenes processing with sql `metadata` and hook processing going on too.

---
Tags: views
---


# Question
Title: Making user reference field in Drupal 7?
I have searched in Google with queries like "User reference drupal 7" or "User taxonomy vocabulary drupal" "user field drupal 7" "cck drupal 7" but I couldn't find any way to make a field that links for a user profile page... Do you know how to make this as a simple field can be done with CCK in Drupal 6? thanks.

# Answer
> 3 votes
You may look into References module

> This project provides D7 versions of the 'node\_reference' and 'user\_reference' field types, that were part of the CCK package in D6, at functional parity with the D6 counterparts.

# Answer
> 4 votes
Another alternative to References is the Entity Reference module. It can do user reference fields as well.

---
Tags: entities
---


title: extend site information with fields

text:
# Question
Title: extend site information with fields
How can one add fields to site information section?

Maybe explaining the purpose can lead to an other approach. Building a template site for Hotels/B&B's wich needs to feature simple re-usablity. For example the address data, contact data, location etc centralized to make it easy to setup an new instance of the template. Sure I can use something like this, but I don't know I can use special fields like location or address fields. .

'checkbox', '#title' =\> t('Use my setting'), '#default\_value' =\> variable\_get('extended\_siteinfo\_extra\_setting', TRUE), ); } } ?\>

Maybe creating a content type site-information and creat one node with the info, is an easier approach but it feels very wrong...

# Answer
> 1 votes
What I do is create a content type for storing this data and use Views to display/output the attached fields as a block.

Views itself natively supports importing and exporting (if I'm not mistaken through Chaos tool suite (Ctools)), and to copy the content type you could use Bundle copy.

This allows me to easily reuse parts of website structures in other projects.

# Answer
> 1 votes
The easiest solution can be like you said using nodes , creating a content type , storing data and then viewing them in right positions.

You also can add them as features to your theme and then make some facilities to change this data using theme settings , just like how logo is added to theme ,

Using variable\_get is not my taste in this situation cause I have an imagination of settings for variable\_get function , but it is not wrong .

There always could be more options , even you can have all data in an xml file or a key=\>value file (like .info file) and write a custom module to read/modify them

---
Tags: entities
---


# Question
Title: Knowing if the currently logged-in user has seen the list of nodes shown in a view
I use the Views module to show a list of specific nodes. Is there a way to know if the currently logged-in user has seen the list of nodes?

# Answer
I think that the best option for you is to write a mini module with a simple DB table. If you need designing it i will help you.

Also try the checklist module

Maybe it could help you
> 0 votes

# Answer
add a list of users to your node type , create a new rule on node view event , add user to that list , this list can be hidden using field permission

it is easy , and fast because you don't need any sql search to check who has seen it.
> 0 votes

---
Tags: views
---


# Question
Title: How can I integrate a stemmer with Search API?
Exactly what the question says - I'm using Search API with Database Search. I also have the Porter Stemmer module, but my understanding is that it only works with the Drupal built-in search.

Any help with this would be greatly appreciated.

# Answer
> 1 votes
It is possible to use the Porter Stemmer module with other modules besides the Drupal standard search. I have done it before (with Views exposed filters).

In your module, you could either invoke the `porterstemmer_search_preprocess()` function or just copy its contents into your own function. And then pass your search terms to this function. E.g.:

```
function your_function_for_preprocessing_text($text) {
   // Include porterstemmer (change accordingly).
   module_load_include('module', 'porterstemmer');

  // Convert text to lower case, and replace special apostrophes with regular
  // apostrophes.
  $text = drupal_strtolower(str_replace('’', "'", $text));

  // Split into words
  $words = preg_split('/(' . PORTERSTEMMER_BOUNDARY . '+)/', $text, -1, PREG_SPLIT_DELIM_CAPTURE);

  if (!count( $words )) {
    return $text;
  }

  $has_pecl_stem = _porterstemmer_pecl_loaded();

  // Process each word, skipping delimiters.
  $isword = !preg_match('/' . PORTERSTEMMER_BOUNDARY . '/', $words[0] );
  foreach ($words as $k => $word) {
    if ($isword) {
      if ( $has_pecl_stem ) {
        $words[$k] = stem_english($word);
      }
      else {
        $words[$k] = porterstemmer_stem($word);
      }
    }
    $isword = !$isword;
  }

  // Put it all back together (note that delimiters are in $words).
  return implode('', $words);
}

```

As I said, I have used the Porter Stemmer to stem all the terms entered in a Views exposed search. However, you'll still need to find the right hook in the Search API module to pre-process the text before the search query is run against the database.

---
Tags: 7, search
---


# Question
Title: Google web font imports breaking with advagg
I'm trying to pass Google Page Insights, and they keep saying we have render blocking CSS. When I try and inline the CSS, it breaks my fonts I'm importing from Google Fonts. I've tried a million combinations, but the inline is the culprit for some reason.

Here is the CSS code from one of the aggregated files:

```
@import url("http://fonts.googleapis.com/css?family=Pontano+Sans");@import url("http://fonts.googleapis.com/css?family=Roboto");

```

I tried it with and without quotes.

For the time being, to keep my client happy, I moved the $styles variable below in my html.tpl.php template, right before the close of the body. It works fine, but there is a nasty flicker on the page load before the CSS loads, so inlining makes the most sense to me.

I use Omega 4 and use @import in my SASS.

# Answer
You'll want to follow this issue https://www.drupal.org/node/2396609 Inline critical css

I'm guessing you're using the "Inline CSS on specific pages" setting on the AdvAgg: Modifications page. If the imports and not working correctly when everything is inlined, please open up a bug report explaining this with a good way for me to reproduce the issue locally.

Also noted that you can use the Adjust CSS location and execution setting to load the css async without having to mess with the tpl file.
> 1 votes

---
Tags: 7, caching, theming, performance
---


# Question
Title: Can't install modules in a sub site --- Seeing Ajax error
## Background

I have a Drupal 7.38 **folder subsite** (i.e `yoursitesname.com/test`). The site was installed with softaculous, and has only few core modules enabled. When I come to install the last version of Views, or alternatively, References, I get this error:

You can see from the first screen that the error tells me to continue to the "errors page" and this is what I see when I continue

## Already tried and didn't help

Some of the solutions were found in Google search:

* Flushed all caches.
* Installing from a downloaded file, instead of a link in Drupal.org.
* giving 755 permissions to all the homefolder files (including .HTaccess and all files in sites/default folder).
* Changing PHP version for main folder (i.e `yoursitesname.com`) from PHP 5.3.29 to PHP 5.5.26

Any suggestions?

# Answer
The site was installed via Softaculous platform (Cpanel software). The original isntallation included some non-core modules and I removed all of them to the situation I had only core-modules... Yet, for some unkown reason, it prevented me from installing modules by the aforementioned error. But now... After I deleted the Softaculous install and installed Drupal 7.38 in the traditional "manual" way, the sub-site worked fine... It might be a bug in the current release of Softaculous, that prevents installation of modules in sub-sites.
> 1 votes

# Answer
Here is a list of items to check:

* Clear all caches (it doesn't hurt, and occasionally helps solving various issues): if you get a WSOD while doing so, it indicates memory shortage.
* Try running `update.php` (by typing an URL like `http://www.yourdomain.com/update.php`): if you get a Fatal error like "Allow memory size of ... bytes exhausted", it indicates memory shortage.
* Verify if it is a memory shortage issue by increasing the memory a bit to check if there is any difference.

Assuming this is NOT a multi site, consider editing your `/sites/default/settings.php`, and change the line to set the memory limit. If it is a multi site, then edit the `settings.php` file related to the site where you are experiencing the problem.

That line in settings.php should look similar to this:

`ini_set('memory_limit', '100M');`

The '100M' in it might be some other number. Whatever the number is, try to increase it with like 50%, or maybe even double it to see what happens after you do so (of course do not forget to save the file after increasing that number).

If needed, refer to https://www.drupal.org/node/207036 for more details, eg if such 'ini\_set' is not yet included in your `settings.php` file. As mentioned in that link: "*Locate the PHP settings section and add that line at the end of that section*".
> 1 votes

---
Tags: ajax
---


title: login user after form submit

text:
# Question
Title: login user after form submit
I have a form that one of fields is `mail` field, when form submit I check that email if not belongs to any user I create a user and assign that node to the created user, Then I want logged in that user automatically after user create a node.

I have below solution but not work.

```
function mymodule_form_node_form_alter(&$form,&$form_state,$form_id)
  {
 if($form_id=="my_content_type")
 {
if($user->uid==0){
        array_unshift($form['#submit'], '_tgdev_ss_submit');
   $form['actions']['submit']['#submit'][]= '_tgdev_listing_suserlogin';
  }

   }
}

function _tgdev_ss_submit(&$form, &$form_state)
{
        $mail=form_state['values']['field_mail']['und'][0]['mail'];
    if(!user_load_by_mail($mail)){
        $account = new stdClass;
        $account->is_new = TRUE;
        $account->name = _tgdev_username_pattern_generate();
        $account->pass = user_password(8);
        $account->mail = $form_state['values']['field_email']['und'][0]['email'];
        $account->init = $form_state['values']['field_email']['und'][0]['email'];
        $account->status = TRUE;
        $account->roles = array(DRUPAL_AUTHENTICATED_RID => TRUE);
        user_save($account);
        $op = 'register_no_approval_required';
        $status = _user_mail_notify($op, $account);
        $form_state['values']['uid'] = $account->uid;
        $form_state['values']['name'] = $account->name
        }
 }

function _tgdev_listing_suserlogin($form,$form_state)
{
//$user_obj = user_load_by_mail($form_state['values']['field_email']['und'][0]['email']);
$form_state['uid'] = $form_state['values']['uid'];
user_login_submit(array(), $form_state);
// ym($form_state,'message');
 $form_state['redirect']='node/'.$form_state['nid'];
 }
}

```

**appreciate any help or suggestion**

# Answer
You could use something like auto\_login\_url and generate a url then redirect the user to that URL before you go to the node. This is mainly an API module that allows you to generate URL login links so you will have to code the solution. There are a couple of other URL login modules out there but this one has a pretty easy API to handle with no large learning curve.

From the module page:

> Creates auto login URLs on demand and through tokens.
>
> This is mostly a developer's module. The better use for me is to convert all links of a specific text to auto login links.

Similar module urllogin
> 0 votes

---
Tags: forms
---


# Question
Title: Colorbox not working in new content type
I have Colorbox and the plugin installed, and enabled.

The module is in the `sites/all/modules` folder, and the plugin is in the `sites/all/libraries` folder.

I've created a new content type and called it *Image Gallery*.

I've created a new field for that content type also called *Image Gallery*

The display format for my Image Gallery field is set to *Colorbox*.

I can create an image gallery, but the images are not opening in Colorbox. I'm stuck, the console isn't showing any errors, as far as I know everything is configured right but it's not displaying properly. What am I missing?

# Answer
> 1 votes
As per the comments:

JQueryUpdate Module solved the problem.

> It Upgrades the version of jQuery in Drupal core to a newer version of jQuery.

# Answer
> 1 votes
This problem might occur because the path to library is incorrectly set. It is typically like so:

```
libraries\colorbox\jquery.colorbox-min.js

```

Though via /admin/config/media/colorbox it is possible to set some other path for it (within 'advanced settings').

There was a time (some older version in colorbox) that the solution was to correct the path to the Colorbox plugin directory, so that after unpacking it looked like so:

```
sites/all/libraries/colorbox/colorbox/jquery.colorbox-min.js

```

Refer to issue #1906156 for more details on this.

If that doesn't help, then check if there are any other modules that use Colorbox that are trying to find it on this path.

Of course, make sure also that the "permissions" to the plugin are set correctly (if no read access is granted, then that is probably what is causing the problem).

---
Tags: javascript
---


# Question
Title: How do I get the correct URL of an image field?
I'm trying to print out the URL of an image field using the following code.

```
<img src="<?php echo $field_company_logo['und'][0]['uri']; ?>" alt="<?php echo $company[0]['#markup']; ?>" />

```

The code gives me a URI like public://company-logos/image.png when I would need sites/default/files/company-logos/image.png.

What code should I use to print the image path (i.e. sites/default/files/company-logos/image.png)?

# Answer
> 21 votes
You want to use the drupal\_realpath() function to convert the URI into the actual filesystem path.

```
echo drupal_realpath($field_company_logo['und'][0]['uri']);

```

You could also use file\_create\_url() to get the actual URL to the image, as opposed to a local filepath.

And the correct way to render an image is to run it through `theme_image()`:

```
echo theme('image', array(
  'path' => file_create_url($field_company_logo['und'][0]['uri']),
  'alt' => check_plain($company[0]['#markup']),
));

```

Also, accessing field data the way you're doing it isn't the preferred method. Have a look at field\_get\_items() and the detailed example in the Rendering Drupal Fields (the right way) blog entry.

# Answer
> 11 votes
If you literally just want to transform a URI into an actual URL, then you want the file\_create\_url() function, which is used like this:

```
$url = file_create_url($uri);

```

But you might find it easier to use a theme function, like Yuriy Babenko suggests:

```
$image_vars = array(
  'path' => $field_company_logo['und'][0]['uri'],
  'alt' => $company[0]['#markup'],
);
echo theme('image', $image_vars);

```

You can easily adapt this to use theme\_image\_style() instead, if you want a sized derivative of your image.

# Answer
> 2 votes
You can use the Image URL Formatter module. It allows to change the field format in order to get only the URL:

Bonus: it works with Views as well:

---
Tags: 7, entities, media
---


title: Different aspect on different browsers

text:
# Question
Title: Different aspect on different browsers
I'm using Drupal 7, Webform module, and Bootstrap Sub-Theme.

I'm facing a browser problem and an admin/end-user problem.

As a French speaker I would like to have my error messages in French.

In **Safari** (as admin), it shows errors in red box as in this example:

This is my result in **Chrome** (as admin):

And this is my result in **Firefox** (as anonymous):

Chrome (as admin) is working with translation automatically (as shown in the example above), but not Firefox (as end-user).

Safari and Chrome (as admin) use a different way to display errors. Safari got red box for every errors.

Chrome uses a red box just for web form validation (module) errors.

I would like to have errors in French and in red box for end-user as well.

End-user have to answer a Captcha.

Any suggestions to resolve these issues?

# Answer
Even though you didn't mention it, this is clearly a multilingual site. Which implies that "language detection" is involved (to decide each time in which language a page (or webform) needs to be displayed.

Your problem related to the usage of French or English language might be because of the "language detection" configuration.

So check this configuration via *Configuration -\> Languages -\> detection and selection*: experiment a bit with the correct order that should be used. Often times, this should be changed to something like 'URL, Default, User', and not something like 'Default, URL, User' (which I assume you're currently using, and which might explain the difference in the language used in different browsers).

The browser differences to display the errors (red boxes, etc) might be some browser dependency and/or something in your sub-theme (custom or not?). With the few details provided it is hard to tell what might help to resolve that part of your question. I recommend you move that part to a different (new) question, or enhance your question to provide more details about the sub-theme.
> 0 votes

---
Tags: webforms
---


title: Hide hybridauth tab from user page

text:
# Question
Title: Hide hybridauth tab from user page
I want to hide hybridauth tab in user page. I have used `$items['user/%user/hybridauth']['access callback'] = FALSE;` in `hook_menu_alter()` which gives the result, but hides for all user. In my case I Want hybridauth tab to hide for all user except admin.

# Answer
The module uses the following definition for that menu item.

```
  $items['user/%user/hybridauth'] = array(
    'title' => 'HybridAuth',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('hybridauth_user_identity', 1),
    'access callback' => 'user_edit_access',
    'access arguments' => array(1),
    'file' => 'hybridauth.pages.inc',
    'type' => MENU_LOCAL_TASK,
  );

```

Simply changing the access arguments, as suggested by Andrew, doesn't work because the access callback used by that module is expecting an user object as argument, while with his solution you would give that callback a string, with all the effects.

To answer your question, it all depend from what you mean by admin user.

If you mean the user whose ID is 1, then use the following code.

```
$items['user/%user/hybridauth']['access callback'] = 'user_access';
$items['user/%user/hybridauth']['access arguments'] = 'administer user hybridauth';

```

I used a permission none of the other modules defines, so that nobody will have it assigned. Don't assign that permission, and only the user #1 will be able to see that menu item.

If you mean a user with a specific role, then use the same code I already shown, but assign that permission to the role the admin user has.

In both the cases, the module needs to implement `hook_permission()` too, since the code I shown uses a new permission.
> 0 votes

# Answer
Can you try this solution?

`$items['user/%user/hybridauth']['access arguments'] = array('administer site configuration');`
> 0 votes

---
Tags: users, authentication-authorization
---


# Question
Title: How to get rid of Re geocode and delete radio boxes on Location module?
How can I remove the ReGeocode and Delete checkboxes from the Location module? I don't need these functions and there is no settings to delete them.

Where is the PHP or html file located so I can manually delete the lines of code? I searched for it but can't find it anywhere.

```
<label for="edit-locations-0-re-geocode-location">Re geocode </label>

<label for="edit-locations-0-delete-location">Delete </label>

```

I think these are the lines I need to delete?

# Answer
> 1 votes
There isn't a template to edit the location module's form elements. You'll need to alter its form element. You can drop the following functions into a custom module to alter the form element so that it doesn't display the Recode/Delete checkboxes.

```
function MYMODULE_element_info_alter(&$type) {
  if(isset($type['location_element'])) {
    $type['location_element']['#after_build'][] ='MYMODULE_location_element_post_render';
  }
}
function MYMODULE_location_element_post_render($element, &$form_state) {
  $element['delete_location']['#access'] = FALSE;
  $element['re_geocode_location']['#access'] = FALSE;
  return $element;
}

```

---
Tags: 7, location
---


# Question
Title: Feeds Soap - importing items but can only add 1 item at a time?
I'm having problems with using this API to get my details from:

http://api.tradera.com/v3/PublicService.asmx?op=GetSellerItems

It imports almost all fields and create nodes as it should however the "LongDescription" is not beign imported or displayed in their reponse it is only displayed as without any content

For testing I tried to use this public service to see where is the problem:

http://api.tradera.com/v3/PublicService.asmx?op=GetItem

Using this allows me to import all single item details but it uses the parametr as the Item ID (Auction Number) and allows only 1 item at a time to be imported

But it imports the Long description as it should

So I was trying to:

1) Import all items I want with "GetSellerItems" 2) Map ItemID into Import ID 3) Use Item ID as parametr that would be passed to "GetItem" feed parametr \<-- but this part I dont know how to make

If anyone have some suggestion why the "LongDescription" may not be beign displayed in response that would be great

If not then I would need to find a way to use GetItem to import descriptions of 500 items on schedular basis

# Answer
I managed to solve my question by my self, In order to do that I had to create simple module

```
<?php
function feedspop_node_presave($node) {
  if($node->type == 'ubrania_a') {
      $numeraukcji = $node->field_import_id['und'][0]['value'];
      $node->feeds['FeedsWSClientFetcher']['operation_arguments']['parameters']['itemId'] = $numeraukcji;
      dpm($node, $name = NULL);
  }
}
?>

```
> 0 votes

---
Tags: 7, importing-exporting
---


# Question
Title: Restrict pagination using entity field query
I have pagination using entity field query:

```
$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'node');
$query->entityCondition('bundle', 'content_type');
$query->pager(3,0);
$result = $query->execute();
$pager=theme('pager');
print render ($pager);

```

and it is successfully displayed like below,

I need to restrict them to display to number 6 then ... like below
: `1,2,3,4,5,6....next,last`

# Answer
It's very easy. Just use

```
$pager=theme('pager', array('quantity' => 6));

```
> 1 votes

---
Tags: 7, database
---


# Question
Title: Newbie Question - How do I add content to this page?
I'm very new to drupal, and I've been put on this project.

So I wanted to create a custom page to display the privacy conditions, which is just a word file I have to copy (so just plain text).

I created the custom page, used the template they gave me and now I want to add the plain text, however I have no Idea where I can do that. Normally I should be able to do it on this page they told, but I can't figure out why I can't change the Main Content.

Sorry for this very silly question, but I can't find anything about this on the internet.

# Answer
> 0 votes
Am not clear about your requirement, right now you are trying to display it using a panels. If your requirement is just to show a custom page with custom text.. then just add a basic page as a content and place the text in body field. Then call the page using the given path.

# Answer
> 0 votes
You should be using "Add content" link to create a new "node". If you don't have such link (yet), then it must be that you have no permission (yet) to add content ...

---
Tags: panels, 7, nodes
---


title: Views Bulk Operation alternative?

text:
# Question
Title: Views Bulk Operation alternative?
As VBO for Drupal 6 is outdated due to a security issue, is there an alternative to this module?

# Answer
> 1 votes
Trying to find an alternative / replacement for VBO is similar to trying to do so for a module like Views, or other (popular) modules.

To my knowledge there is no other "contributed" module that can do the same as VBO to replace it. Your only alternatives to consider, I think, is either of these options:

1. Carefully review the D6 security issue and check if you can find a way to prevent that issue from happening in your site (do not allow it to be used in any way that might cause the security issue to arise).
2. Spend time to create a fix to actually resolve the D6 security issue in VBO, and optionally consider contributing that back to the VBO module (so that others may help to continue to "maintain" that fix).
3. Similar to "2.", but "hire somebody" to do it for you.

PS: Writing your own "custom" module to replace VBO entirely is another option, but of course "the toughest one" also ...

---
Tags: 6, views
---


title: Views, taxonomy and content type

text:
# Question
Title: Views, taxonomy and content type
I have a content page called **Book**, to which I also added an image field and a "term reference" to a **Book** taxonomy which has Book A, Book B, Book C, Book D, Book E as available terms in it.

I created 5 'Book' pages, inserted images and selected taxonomy terms (each taxonomy value are different).

I have another content page called **List Book**, to which I added a "term reference" to a **Book** taxonomy as well.

When I create a 'List book' page, I have to select a term from the **Book** taxonomy. If I select the terms 'Book A' and 'Book C', two images (related to Book A and Book C) will display.

Lastly I created a **view** with as a field the image field. As the filter, I added:

* 'publish = yes'.
* 'content type = Book' and 'List Book'.
* taxonomy field from 'List Book'.

Field: image from **Book**

There is no result.

What is the correct way?

# Answer
> 0 votes
What I'm getting here from your question is, you want to search on the basis of category. I think, you can use exposed filter in the views to get your desired result.

You can find exposed filer in views Under "Filter Criteria".

Hope it will help you.

# Answer
> 0 votes
About the **There is no result** you added (in your latest edit): that is probably because of the "and" in the 2nd bullet of your views filter ... a content type can only have 1 value, but with the "and" you can never find any hit. So remove the "and", and see if you get a "better" result (at least not empty anymore.

**If** that views filter in the 2nd bullet is supposed to be an "OR" instead of "AND", **then** refer to my answer in OR condition in Views Contextual Filters ...

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


# Question
Title: Edit Drupal Form in "popup" just like it is done in Drupal Views Edit form
I am making replica of **views** module. We when navigate to view in admin/list/structure, we **add new view**. Here we type name of our view and content type. After clicking "**save and continue**", it is redirected to **view edit page**.

On the top, there is, ***Title title:None*** And when we click on "None", a popup box will appear to edit title of the view and replaces "None" with the title given by us.

I need to have this **edit in popup functionality**. Can anyone please help doing it.

# Answer
> 0 votes
I think what you are looking for is the ctools modal functionality. Without further digging into that - because I think the following tutorial is comprehensive, easy to understand and complete - here is a link that will help you: https://www.deeson.co.uk/labs/insert-form-pop-modal-ctools-and-drupal-7

Some important things you should not forget:

1. Add the ctools module as dependency.
2. Add the callback to the menu.
3. Include the ctools js files on the page where the link to the title popup is.

ctools modal helped me a lot! Give it a try!

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


# Question
Title: How to configure date facet filter with year granularity, when click it should show months
I am using Facet api with Search api.

I have enabled the facet for the node created date with Granularity set to "Year".

On the search page when I click on Year then it should show the months of that year and when click on month then it should display days of that month?

I didn't see any configurations for this in the facet configurations.

How will I achieve this functionality? Any contributed module?

# Answer
I have found the solution.

Just select the Granularity to "Days" instead of "Year" in the facet configurations.
> 1 votes

---
Tags: 7, search
---


title: Populate a select box with a vocabulary

text:
# Question
Title: Populate a select box with a vocabulary
I have a select box that I want to populate with a particular taxonomy programmatically. If i was was to use a taxonomy vocabulary how would i populate a particular select box in my form. My form is generated using the from api and not using content types. If for example I was to have a vocabulary called countries. I have a select box which currently is configured like this

```
 $form['status']['currentstatus'] = array (
 '#values' => array(t('red'), ('green'))

 );

$form['status']['currentStatusList'] = array (
    '#title' => 'current status',
    '#type' => 'select',
    '#options' => $form['status']['currentstatus']['#values']
);

```

Instead of just adding the values I would like to pass a vocabulary.

I have manged to get the vocabulary data but a zero is placed before the terms.

the code I figured out for the box is the same as yours. I even pass the id for the vocabulary. I will have a play with it thanks for your help

# Answer
> 6 votes
You should be able to use the `taxonomy_get_tree` function to get all the children of the term, and then just run a `foreach()` on that.

Example:

```
function mymodule_blah($vocabulary) {
  $terms = taxonomy_get_tree($vocabulary);

  foreach ($terms as $data) {
    $output[$data->tid] = $data->name;
  }

  return $output;
}

```

This should return an array keyed by Term ID, although you could put whatever you want where it says `$data['tid']` to put a different key in.

Example output:

```
[1] => ['My First Term']
[2] => ['My Second Term']
...
[15] => ['My Fifteenth Term']

```

Then pass this to your `'#options'` on your select box.

EDIT:

Forgot to mention that the helper function will need the vocabulary ID passed to it - should have added in the clarification just for completeness' sake.

EDIT 2 (full implementation):

```
function mymodule_myform($form) {
//The rest of your form stuff is in here
$form['status']['currentStatusList'] = array (
    '#title' => 'current status',
    '#type' => 'select',
    '#options' => mymodule_selectbox_contents(PUT THE NUMERIC VOCABULARY ID HERE)    ,
);
//The rest of your form stuff is in here
}

function mymodule_selectbox_contents($vid) {
  $terms = taxonomy_get_tree($vid);

  foreach ($terms as $data) {
    $output[$data->tid] = $data->name;
  }

  return $output;
}

```

# Answer
> 1 votes
See Chapabu's answer; if you want to make it more dynamic, you can use taxonomy\_vocabulary\_machine\_name\_load to load the vocabulary id.

Here's a addition to Chapabu's implementation:

```
  function mymodule_myform($form) {
    //The rest of your form stuff is in here
    $voc = taxonomy_vocabulary_machine_name_load(your_machine_name);
    $form['status']['currentStatusList'] = array (
        '#title' => 'current status',
        '#type' => 'select',
        '#options' => mymodule_selectbox_contents($voc->vid),
    );
    //The rest of your form stuff is in here
  }

    function mymodule_selectbox_contents($vid) {
      $terms = taxonomy_get_tree($vid);

      foreach ($terms as $data) {
        $output[$data->tid] = $data->name;
      }

      return $output;
  }

```

---
Tags: 7, taxonomy-terms, forms
---


# Question
Title: What can not be done by the Panels module without using the Panelizer module?
Is there anything that can not be done by the Panels module without the Panelizer module?

I'm just starting to learn Panels module and I faced Panelizer.

**Note**: I installed and applied this module but the `Edit in-place` that was selected has gone. Is there any conflict?

# Answer
> 3 votes
To answer your question, as in the 'title' of your question, consider reviewing the article about Creating Specialized Layouts with Panelizer. Here is part of what is written in it, and which I think are key features of Panelizer that you can't do with only the Panels module:

> Many users of **Panels** have taken advantage of the **Panel Nodes** sub-module to create customized layouts for nodes. **Panelizer** does that and takes things a giant step further; by integrating with Drupal 7's entity system, it can create custom layouts for any entity item.
>
> Panelizer was initially created to allow for one node to be displayed differently than any other node on the system. This allows content creators to be just about as creative with the look and feel of each unique piece of content as they would like.

Some more suggestions about tutorials that you may want to checkout:

Regarding the Edit-In-Place (IPE, or In-Place-Editor), refer to what's mentioned also in Working with Panelizer combining panels and node displays, i.e.:

> Panelizer fully supports the IPE (In Place Editor) meaning that panelized nodes can enable the alternative directly editable panel.

The question about "Enabled Panels In-Place Editor module but cant see the edit icon" may contain other interesting information about IPE, with topics related to:

* Clearing the cache.
* Renderer mode.
* Permissions.

---
Tags: nodes, panels
---


# Question
Title: Drupal 7 and Ubercart - admin approve sale before payment
Drupal 7.36 & Ubercart 3.0-rc4.

My client needs to vet users purchasing products from an Ubercart shop. The idea is that when the user completes the checkout, the user does not go to a payment gateway - but instead, the admin receives an email notification saying someone wishes to make a purchase. the admin then goes on to the site and authorizes the sale, sending an email to the user telling them they can now return to the site and complete the purchase and pay.

I've looked at rules, but it appears for fall slightly short of what i need.

Are there any contrib modules, or and know workarounds for this?

# Answer
I think you can do this by using Rules module.

> The Rules module allows site administrators to define conditionally executed actions based on occurring events (known as reactive or ECA rules). It's a replacement with more features for the trigger module in core and the successor of the Drupal 5 workflow-ng module.

* You need to create a rule with below condition :

> **Condition** : Data comparison for the order state "Approved by admin" with a Negate option (checkbox in bottom).

So if you change the order state to "Approved by admin" this rule will not trigger anymore because this condition will return FALSE.
> 0 votes

---
Tags: 7, ubercart, notifications
---


# Question
Title: Create a block Most popular content using google analytics
Can anyone explain how to create a block of most popular contents using google analytics. I know about the modules Google Analystics Statistics and Most Popular but there is no good documentation about this.

How can I get any of these module to work?

# Answer
> 1 votes
Consider looking (also) at the Google Analytics Reports module. Here is an excerpt from its project page:

> ... provides graphical reporting of your site's tracking data. Graphical reports include a dashboard widget for admins, a small path-based report in blocks, and a full path-based report.

# Answer
> 0 votes
You may try this documentation from Lullabot team

---
Tags: google-analytics, authentication-authorization
---


# Question
Title: How to render comments at the top and the comment form at the bottom?
I'm trying to display the comments on a node at the top of the page. I've edited `node.tpl.php` in my theme to be:

```
<article id="article-<?php print $node->nid; ?>" class="<?php print $classes; ?> clearfix"<?php print $attributes; ?>>

  <?php print $unpublished; ?>
  <?php print render($content['comments']); ?>
  <?php print render($title_prefix); ?>
  <?php if(!empty($user_picture) || $title || (!empty($submitted) && $display_submitted)): ?>
    <header class="clearfix<?php $user_picture ? print ' with-picture' : ''; ?>">

      <?php print $user_picture; ?>

      <?php if ($title): ?>
        <h1<?php print $title_attributes; ?>>
          <?php if ($page): ?>
            <?php print $title; ?>
          <?php elseif (!$page): ?>
            <a href="<?php print $node_url; ?>" rel="bookmark"><?php print $title; ?></a>
          <?php endif; ?>
        </h1>
      <?php endif; ?>

      <?php if ($display_submitted): ?>
        <div class="submitted">
        <?php
            //By:   Mike Ghen
            //Date: 5/21/2012
            //Description: This Modifies the submitted user and date info.
            //             Code from: http://drupal.org/node/1072640
            if ($submitted) {
                echo "Submitted on " . date( "F j, Y",$node->created);
            }
        ?>
        </div>
      <?php endif; ?>

    </header>
  <?php endif; ?>
  <?php print render($title_suffix); ?>

  <div<?php print $content_attributes; ?>>
  <?php
    hide($content['comments']);
    hide($content['links']);
    print render($content);
  ?>
  </div>

  <?php if ($links = render($content['links'])): ?>
  <?php endif; ?>

</article>

```

I moved `<?php print render($content['comments']); ?>` to the top of the page but, it makes the form to fill out a comment appear at the top of the page as well. Is there a way to render the comments at the top and the comment form at the bottom?

# Answer
> 1 votes
you attack this line in file :

```
<?php
    // Remove the "Add new comment" link on the teaser page or if the comment
    // form is being displayed on the same page.
    if ($teaser || !empty($content['comments']['comment_form'])) {
      unset($content['links']['comment']['#links']['comment-add']);
      unset($content['links']['comment']['#links']['comment-comments']);
            unset($content['links']['comment']['#links']['comment_forbidden']);
    }
    // Only display the wrapper div if there are links.
    $links = render($content['links']);
    if ($links):
  ?>
    <div class="link-wrapper">
      <?php
      hide($content['links']['comment']['#links']['comment-comments']);
      print $links;
      ?>
    </div>
  <?php endif; ?>

```

# Answer
> 0 votes
You are editing a node template , in this situation you are not able to change an element itself , but you can go to comments module , there you can find a template file inside which generates the comment output , copy it to your theme folder/templates then modify it there and changes will be applied. An easier solution could gain by using Panels and page manager . it will take you just some mouse clicks.

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


# Question
Title: HTML in square brackets -> output as normal HTML
We do import (using Feeds\_ex) some data into Drupal (we do not control data-source we use to import data) and these data contains HTML in a brackets.

so far I have found these 3 brackets:

```
 1. [b]bla bla bla[/b]
 2. [i]my text[/i]
 3. [url=http://www.google.com/[/url]

```

I'm wondering if there is a good approach to deal with these values:

```
 - Convert them during import?
 - Somehow define in Drupal that these tag are equal to <b>, <i> or <a
   href>?

```

At the very end I want to output these data as HTML.

I would be happy to get any suggestion.

Thanks.

# Answer
That's BBCode.

One option would be to simply install the BBCode module, which contains a BBCode filter. You can then apply that filter to the text format you're using for the body field, and it'll be converted to HTML automatically when rendered.
> 3 votes

---
Tags: feeds, theming, input-formats
---


# Question
Title: How to change fields permission using some action in the Rules module?
I installed the Field Permissions module to grant access of the individual fields to the roles.

I need to change the permission of some fields when an event occurs. How do I can add the field edit permission to the *Action* component of the Rules module?

# Answer
To my knowledge, there is no way you can "*add the field edit permission to the Action component of the Rules module*" (as in your question), which is somehow confirmed in the Post installation Support forum via the issue about "Field Edit Permissions Based on Rule?" also.

However, in one of the comments of that link, there is an interesting work around that might work in your case also:

> Create a user role that has editing permissions for the field, then assign that user role to a user with Rules when the conditions you require are met.
>
> You'd then possibly need to remove that role after updating the content depending on your workflow.

PS: I'm assuming this question is about D7.
> 4 votes

---
Tags: entities, rules, users
---


# Question
Title: Generate 1D bar code based on user defined input
My requirement is to generate 1D bar code based on user defined input in the text box. for example if user give 10 as input in the text box then he should able to generate 10 bar code with different serial number after saving the content .... so far, I have used bar code module to generate the bar code and serial module for different serial number and I am able to generate single bar code on saving the content.

now my problem is how to generate series of bar code based on the number which we give as input.

I am not getting how to map the input text box field to content and call multiple time.can any one help on this.

# Answer
> 0 votes
You have content of type A and it contains a field called B , B is your serial fieldneedrst of all your field B must get multiple values , this can be set through Field UI. If you are going to collect more than 10 values per each content you can select unlimited values , but this has some DB overhead , after that drupal itself will create the form with multiple value , if you have chosen a specific number for that field for example 3 values , there will be 3 widget to get values , else if it is unlimited you will have an ajax add element button . If this is not what you want and you want to enter the number of barcodes at the beggining then you must alter the form using hook\_form\_alter (you must write a module) , inside that hook add a counter element to your form (it gets the repeatation s count) and then use ajax to add widget to your form . Each widget must be added to your field in your form , so drupal will understand that all the data inserted in these widgets relates to your field. If you want to do it by writing a module and need some code ,I can add some code later.

# Answer
> 0 votes
I tried Barcode module and there were no problem for having multiple values , so I recommend you to use this module , off course it is not exactly what you wanted but it can do the job ,

1. first create a test content type using Structure
2. add a new field using manage fields to this content
3. add a field of type Barcode
4. in the first setting screen choose any type of barcode you wish
5. in second screen down below you can see Number of values
6. change it to Unlimited
7. save and try adding new content

---
Tags: media
---


title: roles for non-authenticated users?

text:
# Question
Title: roles for non-authenticated users?
I'm looking at making a site that provides a different 'experience' (to use the marketing term) depending on who the visitor says they are, without authentication. The functionality I'm thinking of using is to programmatically change the role from anonymous to something else.

So the from the launch page, client wants the site to look different depending on whether the visitor clicks "I'm a floor manager", "I'm a purchaser", "I'm a decision maker" and a perhaps few other choices. They are going to see different promotional material and copy depending on which link they choose, and the client wants it to appear that the whole site is geared towards them -- in other words, menus, pages, and promotional material not 'for' that user will be absent when they make that choice. It should look like several different sites, after they click out of the initial page.

So I thought that a way to do this would be to make all the content, menus, images, pdfs, and then assign access by role. That way, if you're looking at the site as that role, you only see the things relevant to you. But we don't want the users logging in -- they just click on a button to declare what role they are, and if they are tricking us, we really don't care.

Will I be able to do this in the way I am imagining?

# Answer
Roles can be added to users who are authenticated users, which means they logged in. Anonymous users are only anonymous users; no other role can be added to them.

If you are just trying to show a page differently basing on the what selected from the anonymous users, then you can use a cookie to store a value that is used to alter the user interface. In Drupal 7 there are two helper functions that can be used to delete and save a cookie containing values for an anonymous user: user\_cookie\_delete(), and user\_cookie\_save().
> 3 votes

# Answer
There are a couple of ways you could approach this without programmatically logging people in. A cookie is one. Another would be by taxonomy term - you can use the Contexts, Panels and/or ThemeKey modules to build out a custom look or even change the theme for a specific path or term.

Another way you could do this is through Organic Groups. Novell uses OG to define "user communities" (which sounds a lot like what you are talking about). Check out http://www.novell.com/communities/ and you'll see each group can have quite different information and look/feel.

If you anticipate these groups of users will eventually connect with the company online using OG may be the best choice.
> 1 votes

# Answer
I've tackled something similar to this in a different way using Domain Access module. Set up subdomains for each variation of the site you want, have a splash screen to let the visitor make their initial choice which then directs them to the appropriate URL. Then use content/block visibility to control what is displayed on each subdomain.
> 0 votes

---
Tags: users
---


# Question
Title: How to insert data into node and other tables at the same time?
I create a Drupal module which install database tables during module installation, table is created using Drupal way. The tables are created perfectly and now i have to insert data into those tables.

Example table structure where i want data to be inserted in sequence :

1. Node (insert product name)
2. myproduct\_category (take the inserted node id and save the product category and nid at the same time in this table)
3. myproduct\_price (take the inserted node id and save the product price and nid at the same time in this table)

Once data are inserted into database, the site admin will retrieve those saved data and show it in front-end.

here's my current code to insert data into node, i just can't get the last inserted id and continue insert data into other tables :

```
            $node   = new stdClass();
            $node->title    = $val['ADDRESS_1'];
            $node->type     = 'basil_veco';
            node_object_prepare($node);
            $node->language = LANGUAGE_NONE;
            $node->uid      = $user->uid;
            $node->status   = 1;
            $node->promote  = 0;
            $node->comment  = 0;
            $node->created  = timestamp;

            $node = node_submit($node); // Prepare node for saving
            node_save($node);

```

Please tell me the way to go about if my approach is not the right way.

Thank you.

# Answer
> 1 votes
Why you are using custom code to store the records in the node table. Are you calling any API service or you creating form yourself?

If you have created content type, then just go with drupal way and call custom submit function to store products and price values in a separate table by using db\_write\_record() or db\_insert() function to insert the record in the database.

Just go through the below link

https://api.drupal.org/api/drupal/includes!common.inc/function/drupal\_write\_record/7 https://www.drupal.org/node/310079

---
Tags: 7, database
---


title: How to use hook_entity_presave?

text:
# Question
Title: How to use hook_entity_presave?
I have a product type called package. It is a package of another product type which is called applications; when a user wants to create or update a package , I want to calculate the price of the package by adding the price of all applications in that package . I want to use **hook\_entity\_presave()**. but it doesn't work. I have put my function here.

My question: what should I check exactly against the `$entity->type`? My node type? Or my product type? It doesn't work either way.

```
function itunesdev_entity_presave(&$entity, $type) {
  if($entity->type == 'package') {
    $product_ids = array();
    foreach($entity->field_products[LANGUAGE_NONE] as $key => $pid)
      $product_ids[] = $pid['target_id'];
    $products = entity_load('commerce_product', $product_ids);
    // reset default price
    $entity->commerce_price[LANGUAGE_NONE][0]['amount'] = 0;
    foreach($products as $pid => $product) {
      $entity->commerce_price[LANGUAGE_NONE][0]['amount'] += $product->commerce_price[LANGUAGE_NONE][0]['amount'];
    }
  }
}

```

# Answer
> -3 votes
> Function hook\_entity\_presave acts on an entity before it is about to be created or updated

Code:

```
  function hook_entity_presave($entity, $type) {
    $entity->changed = REQUEST_TIME;
  }

```

source : Drupal API

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


title: Tableselect with columns of checkboxes

text:
# Question
Title: Tableselect with columns of checkboxes
I've a simple tableselect with 4 columns, in the 3 last columns a want to populate all the columns with checkboxes, anyone can help me to do that ?

here is my actual code :

```
function liste_sections($form, &$form_state){
$form = array();

$header = array(
        'sections' => t('Sections'),
        'affichable'=>t('Affichable'),
        'new'=>t('New'),
        'online'=>t('Online'),
);

$resultat = db_select('taxonomy_term_data','tax');
$resultat->fields('tax',array('tid','name'));
$res = $resultat->execute();

$rows = array();
    foreach($res as $sql){
        $rows [] = array(
            'sections' => $sql-> name,
          // Time to put checkboxes for other columns
            );
    }

$form['liste_sec'] = array(
        '#type' => 'tableselect',
        '#header' => $header,
        '#options' => $rows,
        '#empty' => t('empty ! '),
);

$form['ok'] = array(
    '#type' => 'submit',
    '#value' => t('submit'),
    );
return $form;
}

```

Thank you all

# Answer
I got it, in my liste\_sections($form, &$form\_states)

```
$checkbox_col1 = array(
    '#type' => 'checkbox',
    );

$checkbox_col2 = array(
    '#type' => 'checkbox',
    );

$checkbox_col3 = array(
    '#type' => 'checkbox',
    );

```

after that, add those variables to the rows :

```
$rows = array();
    foreach($res as $sql){
        $rows [] = array(
            'sections' => $sql-> name,
            'affichable' => array('data'=>$checkbox_col1),
            'News' => array('data'=>$checkbox_col2),
            'online' => array('data'=>$checkbox_col3),
            );
    }

```
> 0 votes

---
Tags: forms
---


title: How to load data from db with ajax?

text:
# Question
Title: How to load data from db with ajax?
I am new to ajax so my question might be a basic one, but I have not found an answer anywhere so I ask here.

I am building eshop website on D7 with Commerce. On page where products are displayed I have 2 custom php scripts included - one that echoes menu(filter) and one that echoes products. The menu is implemented as a filter, users can select multiple checkboxes to display multiple categories of products. These categories are passed in URL, for example /eshop?filter=category1+category2. There are about 20 products in each category, but because user can select a lot of categories, there can be quite a lot of products to fetch from db and the page load is slow. So I would like to ajaxify this process so the behavior is like this: display whole page, including menu. Display loading gif for each category while it is fetched from the database. When data are ready, display the category(replace loading gif) and continue with the next category, until all categories are displayed.

```
function loadCategory(filter){

if (window.XMLHttpRequest) {
        // code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp = new XMLHttpRequest();
    } else {
        // code for IE6, IE5
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlhttp.onreadystatechange = function() {
        if (xmlhttp.readyState == 4 && xmlhttp.status==200) {
            document.getElementById(filter).innerHTML = xmlhttp.responseText;

        }
    }
    xmlhttp.open("GET","my_php_file.php?filter="+filter,true);
    xmlhttp.send(null);
}

```

I am calling the above function(taken from w3schools) on jQuery(document).ready() event multiple times for each category(filter) and it works fine. The problem is that in my\_php\_file.php I need to have access to drupal functions - not only db\_query(), but also some commerce functions since I am building custom add to cart forms. I have tried bootstraping drupal as hinted here, but it does not work as drupal shows site telling me that drupal is already installed.

How do I achieve this? Or am I taking wrong approach? Thanks a lot.

# Answer
I suppose your list is implemented with views (if not you can easily do this), to load a view via Ajax use the following code; I supposed your view's name is `VIEW_NAME` and it's display machine name is `block_0` and there is a contextual filter to get `filter`

```
$.ajax({
    url: Drupal.settings.basePath + 'views/ajax',
    type: 'POST',
    dataType: 'json',
    data: 'view_name=VIEW_NAME&view_display_id=block_0&view_args='+filter,
    success: function(response) {
        var output = response[1].data;
        $("#filter").html(output);
    },
   error: function(data) {
        alert('An error occured!');
    }
});

```

The Ajax call in Drupal framework is different to the one you usually see on non-Drupal websites.
> 0 votes

---
Tags: commerce, ajax
---


# Question
Title: How do I get Rules to see my custom entity?
From what I've read in the past few days, Rules will gather all information it needs from hook\_entity\_info. I still can't get my custom entity to appear in the data selector to make things work though. Here is my implementation of hook\_entity\_info:

```
function badge_entity_info() {
  $info = array();

  $info['badge'] = array(
    'label' => t('Badge'),
    'base table' => 'badge',
    'class' => 'DrupalDefaultEntity',
    'controller class' => 'DrupalDefaultEntityController',
    'entity keys' => array(
      'id' => 'bid',
      'label' => 'name',
    ),
    'module' => 'badge',
    'access callback' => 'badge_access',
    'admin ui' => array(
      'path' => 'admin/structure/badge',
      'file' => 'badge.admin.inc',
    ),
    'uri callback' => 'badge_uri',
  );

  return $info;
}

```

Everything else is working perfectly, I just need to understand how to make Rules recognize my custom entity.

# Answer
> 0 votes
Individual rules can have a `type` associated with them. Most rules work with `Nodes` but an `Entity` is 1 object up in the type hierarchy of Drupal. therefore rule(s) defined with the Rules module must be made aware that they are compatible with your custom entity type.

You would do this with an alter hook for Rules, or providing property information for your Entity: I can't set a data value using rule on a custom entity

---
Tags: rules, entities
---


# Question
Title: How do I migrate from Rhythmyx to Drupal?
I am working on migrating a site from Rhythmyx to Drupal 7, and since they are so different I was wondering if anyone has done that and how they did it.

# Answer
Rhythmyx is proprietary software. You're likely to find very little, if at all, people in the Drupal community that have experience migrating from it.

The first thing to know is what technology stack it's built on so you can evaluate tools to pull out content. The vendor's website is scarce on tech details. From what I could find, the language is perhaps Java. It's also supposed to have a static content export & pluggable API so that should be able to assist in pulling out data.

On the Drupal side, there's Feeds & Migrate. Feeds is best for mostly static content migration where there isn't fresh content coming into the site on day-to-day basis (and thus an ongoing need to sync both the existing site and new site while development/testing is happening). Migration is a best when you have many different custom content types, taxonomy, users, and other custom data that needs to synced regularly while development is occurring.

Whatever means you find to pull out data from Rhythmyx will affect what import tools you use. If you have static structured data (e.g. CSV, XML, RSS Feed) Feeds is the better choice here. If you have an API that PHP can interface with, Migrate will be more useful.
> 1 votes

---
Tags: migrations
---


# Question
Title: Set default text format for a content type
At "Home » Administration » Configuration » Content authoring" I added a custom text format (news).

Now when I trie to enable this for a certain content type "Newsmessage" "Home » Administration » Structure » Content types » Newsmessage » Manage fields"

I only see "Plain text" or "Filtered text (user selects text format)" as options. How do I set the "news" text format as a default for my "newsmessage" content type?

# Answer
If the field is Wysiwyg, so you might want to configure the "Wysiwyg" profile settings, then it will be available in the Structure » Content types » contentType name » Manage fields.
> 1 votes

# Answer
use the Better formats module to do this
> 1 votes

---
Tags: nodes
---


# Question
Title: What are Hooks in Drupal and can I learn and use them if I've yet to learn PHP?
Whenever I try to read about what are Hooks in Drupal, and how to manipulate forms or content with them, the text seem not to deal with the **UI** at all, but mostly with coding... Maybe I did not encounter the right reading material about **UI-Hook** relationship?

Can someone please detail in simple words and a simple example?

1. What are Hooks?
2. Do you use them via UI or only through Coding?
3. Do I need to know PHP to use a module such as Hook form-alter?

# Answer
> 2 votes
1. Hooks are a system to allow you to extend and alter Drupal's functionality. Specifically, a hook is a PHP function that follows a specific naming convention, so that Drupal can find them and call them appropriately.
2. You use them only through code.
3. You need to know PHP to write hooks. They are PHP functions that use Drupal's API and conventions. For `hook_form_alter()`, you at least need to understand PHP arrays and HTML form elements.

To answer your titular question, "Can I learn the Drupal Hooks issue if I've yet to learn PHP?", I suppose you can learn both at the same time, if you have past programming experience, or if you are especially dedicated.

# Answer
> 5 votes
> Hooks can be thought of as internal Drupal events. They are also called callbacks, but because they are constructed by function-naming conventions and not by registering with a listener, they are not truly being called back. Hooks allow modules to “hook into” what is happening in the rest of Drupal.

Suppose a user logs into your Drupal web site. At the time the user logs in, Drupal fires hook\_user\_login.

That means that any function named according to the convention module name plus hook name will be called. For example, comment\_user\_login() in the comment module, locale\_user\_login() in the locale module, node\_user\_login() in the node module, and any other similarly named functions will be called.

If you were to write a custom module called spammy.module and include a function called spammy\_user\_login() that sent an e-mail to the user, your function would be called too, and the hapless user would receive an unsolicited e-mail at every login.

> The most common way to tap into Drupal’s core functionality is through the implementation of hooks in modules.

You have to use coding to implement hooks and you need to know PHP.

> For more details about the hooks Drupal supports, see the online documentation at http://api.drupal.org/api/7, and look under Components of Drupal, then “Module system (Drupal hooks).”

# Answer
> 2 votes
Hooks allow modules to interact with the Drupal core. A hook is a PHP function which is used to extend Drupal functionality.

Basically your modules understands hooks. Read Here about hooks.

You can use hooks through coding part only and you should at least be able to read PHP code. Soon you'll be writing it too. You don't need a lot of PHP knowledge to implement hooks. After a little practice, you will find it is much easier to work with hooks than it looks.

You can find API on the API page on drupal.org.

Watch videos and ask here for any kind of assistance you need.

---
Tags: hooks
---


# Question
Title: How to sync content title with "synchronize translations" module?
The synchronize translations module, part of the Internationalization module (i18n), allows us to sync content between two languages.

It works very well with node configurable and standard fields. But I can't configure it to sync also the node title.

Is there a way to force it to sync also the title, or any alternative to do this work?

# Answer
> 0 votes
Possibly this is because titles do not get translated in a site using the i18n module. And that is most often because of the Title module that has not been enabled. From the module's project page (bold markup added here):

> After enabling the module as usual, visit the Manage fields page of the content type, taxonomy vocabulary or "comment type" which you wish to replace fields of and click the replace link. That's all.

---
Tags: i18n-l10n
---


title: Page not getting redirected properly

text:
# Question
Title: Page not getting redirected properly
I'm only using i18n and not Entity Translation.

I've an English version of page set as front page( node/page1).

I've restarted working on my multilingual site after 2 months and previously it was working fine. Earlier I had added French, German, etc translated version of this page.

So if I go to mysite.com/de or mysite.com/fr those translated pages are shown automatically(in short existing translated pages are getting redirected correctly).

But now (after 2 months) when I add translation for untranslated languages like "it" then mysite.com/it does not redirect to the Italian version of the home page.

I've Global Redirect, Translation Redirect enabled. I've also tried clearing all cache several times.

What could be the problem?

# Answer
> 0 votes
Your problem might be because of the "language detection" configuration.

So check this configuration via *Configuration -\> Languages -\> detection and selection*: the order should be 'URL, Default, User', and not something like 'Default, URL, User'.

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


# Question
Title: How to get the name of the current page view
I'm trying to find a way to check the view name of the current page.

```
$views_page = views_get_page_view();
if (is_object($views_page)) {
    //get the view name
}

```

I haven't found any function that gives that information. Any suggestions?

# Answer
> 6 votes
views\_get\_page\_view() returns a View object. The name should be stored in `$views_page->name`.

# Answer
> 1 votes
Once you have a view object, call view::get\_title().

# Answer
> 0 votes
Use below code in your module file

```

function MYMODULE_views_api() {
  return array(
    'api' => 2,
    // might not need the line below, but in any case, the last arg is the name of your module
    'path' => drupal_get_path('module', 'MYMODULE'),
  );
}

```

Use below code in your MYMODULE.views.inc
```

function MYMODULE_views_query_alter(&$view, &$query) {
   echo $view->name; exit;
 }

```

Relpace MYMODULE with your module name.

---
Tags: 7, views
---


title: Edit specific menu items in template

text:
# Question
Title: Edit specific menu items in template
In my theme I'd like to have complete control over my menus. I'd like to apply specific classes and wrap the menu however I like. I was thinking I could do this within a template. I see that you can print the menu with this:

```
<?php
$menu = menu_navigation_links('menu-your-custom-menu-name');
print theme('links__menu_your_custom_menu_name', array('links' => $menu));
?>

```

But I'm not sure how to edit the individual items within the menu.

# Answer
> 2 votes
Menu attributes module is for what you want. Some details from its project page:

> This simple module allows you to specify some additional attributes for menu items such as id, name, class, style, and rel.

---
Tags: theming, routes
---


title: Mail not going from SMTP

text:
# Question
Title: Mail not going from SMTP
I have configured the smtp for drupal , as said in this link `https://www.drupal.org/project/smtp` and my smtp module folder lies in **`/sites/all/modules/smtp`** and phpmailer library lies in **`/sites/all/libraries/phpmailer`** . But am getting the following error on sending the test mail from the drupal admin `SMTP authentication support` .

**2015-07-09 14:37:30 Connection: opening to ssl://smtp.gmail.com:465, timeout=300, options=array ( ) 2015-07-09 14:41:45 SMTP ERROR: Failed to connect to server: Network is unreachable (101) 2015-07-09 14:41:45 Connection: opening to ssl://:465, timeout=300, options=array ( ) 2015-07-09 14:41:45 SMTP ERROR: Failed to connect to server: php\_network\_getaddresses: getaddrinfo failed: Name or service not known (0) 2015-07-09 14:41:45 SMTP connect() failed. https://github.com/PHPMailer/PHPMailer/wiki/Troubleshooting**

And these are my smtp parameters ,

Any help is appreciated . Thanks .

# Answer
Your host cannot reach *smtp.gmail.com* on port *465*. It sounds like a network connectivity problem, not a Drupal problem. Run the command `nc -zv smtp.gmail.com 465` to confirm.

You may need to talk your hosting provider if they have restrictions in place. My guess, if they are blocking it, is they are blocking SMTP access to GMail to prevent spam.
> 1 votes

---
Tags: 6, emails
---