title: Drupal licensing/reselling

text:
# Question
Title: Drupal licensing/reselling
I am sure this has been answered somewhere, and I did read the licensing faq but it wasn't 100% clear to me so I thought I'd ask. I was curious as to the licensing/legal requirements of, well, using Drupal to make money.

Example 1: You are a free lance web designer. Business contacts you to have you build them a site. You meet with the client, discuss their needs, and eventually decide that their best option would be to make a Drupal site for them. You want to charge them for the initial setup and design, as well as possibly hosting it.

Example 2: You set yourself up more as a SaaS provider. People come to your site, click a big "Launch your site" button, pick their monthly plan and then a Drupal instance is generated for them that they can log into and edit just like any other Drupal site. Possibly includes some custom modules and themes pre-installed. You provide support and such for these instances. Kind of like Drupal Gardens.

What are the licensing/legal implications of those two situations? I.e., can you use them? And if so, are there legal restrictions you should be aware of (for example, do you have to put a giant 'Powered by Drupal' on the site, etc)?

# Answer
> 4 votes
The short answer is: Yes, both your examples are OK to use as a business model with Drupal. There is also no advertising requirement.

For a longer and more comprehensive answer, including the fine print, you'll find it all answered authoritatively in the Drupal licensing faq. I understand that you've read that, but didn't find it clear enough. I shall try to expand on it somewhat.

The most important bit is this:

> Drupal and all contributed files hosted on Drupal.org are licensed under the GNU General Public License, version 2 \[GPLv2\] or later. That means you are free to download, reuse, modify, and distribute any files hosted in Drupal.org's Git repositories under the terms of either the GPL version 2 or version 3, and to run Drupal in combination with any code with any license that is compatible with either versions 2 or 3, such as the Affero General Public License (AGPL) version 3.

GPLv2 basically says that you've free to use the licenced material in any way you like, *including* commercial use (i.e. where you make money). Unlike some other free software licences (e.g. the BSD license), there is no "advertising" clause, so you don't have to put up any "Powered by Drupal" signs.

However, there is *one* important legal restriction tied in with GPLv2 you need to be aware of: GPLv2 or later is a so-called "Copyleft" license.

"Copyleft", in brief, means that if you make any materials (i.e. the Drupal core and any custom development *you've* done to make it a fully functional website) available to a client, the materials *must* be made available to the client in *source form*, and under *the same \[Copyleft\] terms* (i.e. GPLv2 or later).

However, the requirement that any material you give your client has to be licensed under the *same terms* may in some situations be a problem. This means that your client is free to use the licenced material in any way your client like, *including* modifying and reselling it (also reselling it without giving you a cut of the proceeds).

I should add that usually, this is not a problem. Your client is probably not a Drupal developer (that's why they hired you), so they if they resold it, they would not have the skills to maintain it. But it is a real legal implication of GPLv2 or later you should be aware of.

Also, note at GPLv2 or later doesn't say you *have* to give you client access to the material. If you include hosting in the package you sell. And in particular, if you sell it as SaaS (your example 2), then no material changes hands and your client don't have access to anything they *can* resell.

Providing a website as SaaS without giving access to the material is *permitted* under GPLv2 or later.

Note that the Gnu Affero General Public License version 3 (AGPLv3) requires SaaS providers to give clients access to, and permission to resell, any material the service is based upon.

(AGPLv3 in not used by the Drupal core, but may be used by *some* contributed modules offered by third parties as it is upstream compatible with GPLv2 or later. However Drupal.org does not permit contributed modules that is under APGLv3 only to be hosted on Drupal.org)

# Answer
> 1 votes
It is free to use as per both of your examples.

You don't have to display the powered by drupal logo if you don't want to.

You may have already read it but check out the licencing FAQ

# Answer
> 1 votes
There is an excellent source of information on the legalities of using Drupal under a Saas model - you can find it here.

This legal analysis ( written by Theresa Gue, a Judicial law clerk with the U.S. District Court for the Eastern District of Pennsylvania) addresses most of the issues around what circumstances trigger copyleft, but the most succinct answer it provides is probably this:

"GPLv3 explicitly and unconditionally grants users permission to freely provide software as a service, with no trigger of copyleft. As a result, ASPs can freely modify GPL-covered software, provide the modified software as a service, and refuse to share the source code or license the new work under the GPL without fearing a lawsuit."

Hope this helps.

---
Tags: 7
---


# Question
Title: Need to sort views block by current node first
So what I'm doing is setting up a block with images that link to it's corresponding testimonial page. Each testimonials has it's own node, and I want to sort the block so that the first image in the block is the one that links to the current testimonial page that the user is on. For example:

I have testimonials from:

Student A
Student B
Student C
Student D

If I'm on the page for Student C then the order of the block should be:

Student C
Student A
Student B
Student D

Anyone have a good way to do this?

# Answer
> 3 votes
A quick solution might be using the module Views PHP.

As far as I understand your problem, you want to sort a list but have the current student at the top.

I used a Content Type name 'Students' with a integer field 'Rank', representing the field to sort the students.

Create your view and a block and set up your view as follows:

* Format: as you like, no grouping
* Show: Fields, no special settings
* Fields:

+ Content: Nid (exclude from display)
    + Content: Title
    + Content: Rank
* Filter Critera

+ Content: Published (yes)
    + Content: Type (= Student)
* Sort Criteria:

+ Content: Rank (asc)
    + Global: PHP (asc) -\> this is from the Views PHP module

Configure the Views PHP filter similar to this: Sort Code (no php tags!):

```
$nidFirst = arg(1);
return $row1->nid != $nidFirst;

```

That's it. Embed the resulting block on your students page and navigate to one of those pages.

Sort criteria 1 gets the result into the default order, e.g. best rank is on top. Sort criteria 2 fetches the current students node id (nid) from the url (assuminf it realy is the first argument), compares it to each row and returns true, if the rows nid is not equal to the current students nid. As the sort direction is ascending, all rows with a comparison result of true will be moved below the row with the result false, so the current student ends up at the top of the list.

---
Tags: views
---


# Question
Title: Multi country page - avoid repeating content
I have a site that has several pages, and it will be available in 2 primary languages: Spanish and English. However, in Spanish I'm creating other languanges:

* Spanish - Argentina
* Spanish - Colombia
* Spanish - Peru
* Spanish - Chile
* ...

The question is: I don't want to repeat all the content for the Spanish speaking countries, but change 2 or 3 pages instead: And mainly that's because I want to replace the country name in some pages.

What would be the best way to create country-specific versions of the site without duplicating all the content for each Spanish speaking country? Thanks!

**NOTE:** Would creating a 'language neutral' page a good idea? And then create the English version and the changed Spanish versions when necessary? Not yet sure what 'language neutral' is for.

# Answer
I think I've found the solution. It's not perfect, but better than having to repeat all the content 10 times :) Here's how:

1. Use Entity translations.
2. Create a page in a language that repeats several times, eg: Spanish - Colombia. Translate the content in the languages that you want, it could be only the English translation for example.
3. In Entity translations module, enable language fallback.
4. If you use Pathauto, then you will have the problem that the un-translated languages won't use the friendly URL and you will be forced to use /node/nnn. To solve this use the Synchronize Translations Path module. That way, when you edit a page, this module will enable the friendly page for all languages (either translated or not). Remember to check its settings to enable this module for each content type!
5. For the menus, if you set a menu item language to Language Neutral, then you will be able to translate it. If you create an item in, let's say English, you will have to create a new one in each dialect of Spanish. So you have the option to have the menu items repeated, or only once.

Some drawbacks:

* The URLs in all languages will look the same. You won't be able to create the following:
    + `www.example.com/en/test-page`, and
    + `www.example.com/es/pagina-prueba`
* The menu items will still need to be duplicated one time per language. If there are 10 spanish-speaking countries, you will end up with 10 menu items looking the same. ==\> **UPDATE:** To avoid this, set the menu item language to Language Neutral and problem solved!
> 0 votes

# Answer
With domain access module you can share content and set content to show on only one specific domain name

i.e Argentina.Spanish.com Colombia.Spanish.com Peru.Spanish.com Chile.Spanish.com
> 0 votes

---
Tags: i18n-l10n, navigation
---


# Question
Title: Create renderable nested tree array like Menu Tree or Taxonomy Tree
I am getting a nested array with children property from the WebSerice. I want to create the render able array so that I can use "drupal\_render" function to render final HTML. I looked at the 'menu\_tree\_output' and 'taxonomy tree" that Drupal generates, but there is not proper documentation that mention how to structure the array to make it render able nested list.

Lets make it short: How do I restructure the final array that I get from Webservice so that I can make it renderable using drupal\_render api. Final output is nested list(Folder tree).

# Answer
What you are trying to solve is a recursive problem.... See below code which solves problem..

```
function listArrayRecursive($array_name, $ident = 0){
  if (is_array($array_name)){
    foreach ($array_name as $k => $v){
      if (is_array($v)){
        for ($i=0; $i < $ident * 10; $i++){ echo " "; }
        echo $k . " : " . "<br>";
        listArrayRecursive($v, $ident + 1);
      }else{
        for ($i=0; $i < $ident * 10; $i++){ echo " "; }
        echo $k . " : " . $v . "<br>";
      }
    }
  }else{
    echo "Variable = " . $array_name;
  }
}

$ages = array(
        "ahmed" => "25",
        "mohamed" => "35",
        "group" => array("omar" => "15", "abdalla" => "20", "sub group" => array("john" => "10", "peter" => "20")));

listArrayRecursive($ages);

```

Output will be
> -1 votes

---
Tags: theming
---


# Question
Title: How to filter nodes by role (Content Access for nodes activated)?
I have activated content access per node, so that I can control the access of the node directly on the node. Now I want to create a view, with an exposed filter. The filter should contain the roles which are activated directly on the nodes. So that I can find nodes which have maybe role A and B activated but not C.

Matroschker

# Answer
Data related to access permissions per node settings are stored in content\_access table created by content access module along with acl module tables like ace and acl\_node

It is stored in serialized format.. For example

Content access doesn't have any views integration to list content filtered by roles based on settings...

I am afraid you need to read serialized array and then filter nodes using code...

To read values per node see per node settings page code below implemented in content access module..

```
/**
 * Per node settings page.
 */
function content_access_page($form, &$form_state, $node) {
  drupal_set_title(t('Access control for @title', array('@title' => $node->title)));

  foreach (_content_access_get_operations() as $op => $label) {
    $defaults[$op] = content_access_per_node_setting($op, $node);
  }

  // Get roles form
  content_access_role_based_form($form, $defaults, $node->type);

  // Add an after_build handler that disables checkboxes, which are enforced by permissions.
  $form['per_role']['#after_build'] = array('content_access_force_permissions');

  // ACL form
  if (module_exists('acl')) {
    // This is disabled when there is no node passed.
    $form['acl'] = array(
      '#type' => 'fieldset',
      '#title' => t('User access control lists'),
      '#description' => t('These settings allow you to grant access to specific users.'),
      '#collapsible' => TRUE,
      '#tree' => TRUE,
    );

    foreach (array('view', 'update', 'delete') as $op) {
      $acl_id = content_access_get_acl_id($node, $op);
      acl_node_add_acl($node->nid, $acl_id, (int) ($op == 'view'), (int) ($op == 'update'), (int) ($op == 'delete'), content_access_get_settings('priority', $node->type));

      $form['acl'][$op] = acl_edit_form($form_state, $acl_id, t('Grant !op access', array('!op' => $op)));
      $form['acl'][$op]['#collapsed'] = !isset($_POST['acl_' . $acl_id]) && !unserialize($form['acl'][$op]['user_list']['#default_value']);
    }
  }

  $form_state['node'] = $node;

  $form['reset'] = array(
    '#type' => 'submit',
    '#value' => t('Reset to defaults'),
    '#weight' => 10,
    '#submit' => array('content_access_page_reset'),
    '#access' => count(content_access_get_per_node_settings($node)) > 0,
  );
  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Submit'),
    '#weight' => 10,
  );

  // @todo not true anymore?
  // http://drupal.org/update/modules/6/7#hook_node_access_records
  if (!$node->status) {
    drupal_set_message(t("Warning: Your content is not published, so this settings are not taken into account as long as the content remains unpublished."), 'error');
  }

  return $form;
}

```
> 0 votes

---
Tags: users
---


title: Drush field-create with specified label

text:
# Question
Title: Drush field-create with specified label
I would like to add multiple existing fields to a content type using drush. Right now I'm using the following to create the fields:

```
drush field-create [content-type] [field-machine-name],[field-type]

```

Is there any way to do something like the following instead?

```
drush field-create [content-type] [field-label],[field-machine-name],[field-type]

```

# Answer
> 2 votes
I am afraid you need to edit drush files to achieve it.. Currently label support is not there if you see below code in contributions/drush/commands/core/field.drush.inc

```
function drush_field_create($bundle) {
  $entity_type = drush_get_option('entity_type', 'node');

  $args = func_get_args();
  array_shift($args);
  if (empty($args)) {
    // Just one item in this array for now.
    $args[] = drush_field_create_wizard();
  }

  // Iterate over each field spec.
  foreach ($args as $string) {
    list($name, $type, $widget) = explode(',', $string);
    $info = field_info_field($name);
    if (empty($info)) {
      // Field does not exist already. Create it.
      $field = array(
        'field_name' => $name,
        'type' => $type,
      );
      drush_op('field_create_field', $field);
    }

    // Create the instance.
    $instance = array(
      'field_name' => $name,
      'entity_type' => $entity_type,
      'bundle' => $bundle,
    );
    if ($widget) {
      $instance['widget'] = array('type' => $widget);
    }
    drush_op('field_create_instance', $instance);

    $urls[] = url(drush_field_ui_bundle_admin_path($entity_type, $bundle) . '/fields/' . $name, array('absolute' => TRUE));
  }
  drush_print(implode(' ', $urls));
}
?>

```

As you see above only field\_name and type is taken from args.. To create label also you need to change code to below

```
function drush_field_create($bundle) {
  $entity_type = drush_get_option('entity_type', 'node');

  $args = func_get_args();
  array_shift($args);
  if (empty($args)) {
    // Just one item in this array for now.
    $args[] = drush_field_create_wizard();
  }

  // Iterate over each field spec.
  foreach ($args as $string) {
    list($name, $label, $type, $widget) = explode(',', $string);
    $info = field_info_field($name);
    if (empty($info)) {
      // Field does not exist already. Create it.
      $field = array(
        'field_name' => $name,
        'type' => $type,
        'label' => $label,
      );
      drush_op('field_create_field', $field);
    }

    // Create the instance.
    $instance = array(
      'field_name' => $name,
      'entity_type' => $entity_type,
      'bundle' => $bundle,
    );
    if ($widget) {
      $instance['widget'] = array('type' => $widget);
    }
    drush_op('field_create_instance', $instance);

    $urls[] = url(drush_field_ui_bundle_admin_path($entity_type, $bundle) . '/fields/' . $name, array('absolute' => TRUE));
  }
  drush_print(implode(' ', $urls));
}
?>

```

and use command like

```
drush field-create [content-type] [field-machine-name],[field-label],[field-type],[field-widget-type]

```

---
Tags: entities, drush
---


title: Missing Fields When Adding Content

text:
# Question
Title: Missing Fields When Adding Content
When going to `node/add/my-content-type` there is only a field for editing the title. There are body and FileFields attached to this content type but they are not being displayed until *after* I click save.

The content type is an OG content type though I am not sure this has anything to do with the issue. I tried toggling `strict node access` but it didn't help.

Preview is disabled.

# Answer
> 0 votes
I disabled the **Organic Groups Field Access** module and the missing fields appeared.

Related to the OG issue: https://drupal.org/node/1743332

In summary, for some users, disabling/re-enabling this module while clearing the cache resolved the issue.

---
Tags: entities, nodes
---


title: How to expose age range in views?

text:
# Question
Title: How to expose age range in views?
I'm trying to add an exposed filter for an age range with the Views module.

I made a **select age field** for age 18 to 80, but I can't find how to add a **filter range** in views. For Example, I would add a filter saying "from age\_**_ to age\__**".

# Answer
* From the filter criteria choose the age field tick the exposed filter.
* Choose grouped filters from the filter type to expose.
* Choose the widget type. Then add values after changing the operator to 'is between'
> 3 votes

# Answer
If you tick 'Expose this filter...' then click **Grouped filters** then you will be able to input some custom filter options, for each option you can do a 'between' filter.
> 0 votes

# Answer
IN filter criteria just change the Operator from the default into "is between", It can give you ability to input the expose filter with min and max, eg. min =18 , max=80.
> 0 votes

# Answer
I would give this module a shot: Views Contextual Range Filter

Module Page Description:

> Views Contextual Range Filter is a simple plugin for Views that adds the option to contextually filter not just by a single value, but also by range.
>
> Numeric, alphabetical (string) and list ranges are all supported. Node ids, user ids and even taxonomy term ids are all special cases of numbers so will work also. Range-filtering on the "created" (posted) and "updated" (last modified) node properties is also supported, provided you use the correct format as dictated by Views. So, YYYYMMDD for full dates or one of the shorter formats, i.e. year+month, year-only, month-only, week-only or day-only.
>
> You may use the OR operator (i.e. +) and the negate operator. You negate by ticking the "Exclude" box on the Views Contextual filter configuration panel, in the "More" section.
> -1 votes

---
Tags: views
---


# Question
Title: How to make field on account only editable by admin?
How can I make it so that a certain field on the user profile/account is only editable by an admin? I added the "file" field to accounts, but I want admin's to be the only ones to be able to populate the field. I dont think there are permissions for this.

# Answer
You can use the Field Permissions module to set permissions for a single field.

> The Field Permissions module allows site administrators to set field-level permissions to edit, view and create fields on any entity.

Features:

* Enable field permissions on any entity, not just nodes.
* Role-based field permissions allowing different viewing patterned based on what access the user has.
* Author-level permissions allow viewing and editing of fields based on who the entity owner is.
* Permissions for each field are not enabled by default. Instead, administrators can enable these permissions explicitly for the fields where this feature is needed.
> 2 votes

---
Tags: users
---


# Question
Title: Directly adding data in MYSQL tables made through drupal
I have a simple three fielded (name, address, country) content in drupal. I have a csv containing 1,000,000 row lines of data. I need to fill up all drupal content type I made with the csv data.

First, I used FEEDS module but the importing is unacceptably too long. I tried to insert the data directly into MYSQL (ex: field\_data\_field\_name and field\_data\_revision\_name). It is successfully inserted into MYSQL but it does not show/update in the DRUPAL content.

How to make the Drupal synchronize with the newly added data in the table of MYSQL?

# Answer
Not sure but could you design your view fields \[name, address, country\] the way you want to use them. Then enter unique data.

Then look in the DB for the unique data to be sure you have the right fields.

After backup and site shut down you could import your csv right into mysql. With the db interface. Make sure you backup The tables before starting.

A bigger question perhaps is how will you work with the data.
> 0 votes

---
Tags: feeds, importing-exporting
---


# Question
Title: Can I get a upload progress bar when submitting the form with "submit"?
In D7, I've got some forms that are responsible for uploading potentially large video files via managed\_form fields. My server is properly set up for showing uploadprogress (or seems to be, according to phpinfo and Drupal's status report), but when I submit the form via the Submit button, I get no progress bar. Is this just "how it works"?

It's probably worth noting that I've hidden the "Upload" button after a long series of usability problems with my site's users, so that may be a blindingly obvious factor in my problem. But I'm still interested in getting some sort of upload indication in response to the Submit button; I'm not averse to bashing some stuff into the page via a jQuery .submit() handler or whatever if that's what it takes. Is there a way for me to have my cake and eat it too? Thanks!

# Answer
*Is this just "how it works"?* \- Yes, it's just how it works. This is a problem with HTTP protocol, if your site does not provide client-side implementation for that progress bar, it will not be shown. And Drupal forms are standard HTML / HTTP POST forms, so no implementation provided for traditional, old style POST.

What I do in such situations is:

# With plupload

```
uploader.bind('QueueChanged', function() {

```

to automatically start upload and disable form's submitting. Then

```
uploader.bind('StateChanged', function() {

```

to reenable form's submitting once upload is done.

# Without plupload

AutoUpload module has some good example code how to react on file selection and upload finish. I steal from it to do basically the same thing as above - disable form submitting when new file is added, enable it when it's uploaded. Alternatively, form submit behavior may start uploading files not yet uploaded, and only submit form when uploads finished.

# Without traditional POST

If you can give up traditional submit, and re-write it with AJAX, leaving traditional way in place for graceful degradation, you can have a progress bar for a whole form. But it is a quite big task, too broad to cover in Q&A format (at least for me).
> 5 votes

---
Tags: 7, forms
---


title: Custom Token + foreach not functionnal

text:
# Question
Title: Custom Token + foreach not functionnal
I want create a custom token to retrieve all parents with a specific type of a menu item.

I have created a custom module with that :

`function mytoken_token_info() {
 $info['tokens']['node']['team_url'] = array(
 'name' => t('Team URL'),
 'description' => t('Returns a custom url for team and team pages'),
 );
 return $info;
}
function mytoken_tokens($type, $tokens, array $data = array(), array $options = array()) {
 $replacements = array();
 if ($type == 'node' && !empty($data['node'])) {
 $node = $data['node'];
 $path = 'node/'.$node->nid;
 $mlid = db_select('menu_links' , 'ml')
 ->condition('ml.link_path' , $path)
 ->fields('ml' , array('mlid'))
 ->execute()
 ->fetchField();
 $menuParents = token_menu_link_load_all_parents($mlid);
 foreach ($menuParents as $itemParent_mlid => $original) {
 $item = menu_link_load($itemParent_mlid);
 $item_path = $item['link_path'];
 $item_path_args = explode('/', $item_path);
 $item_id = $item_path_args[1];
 $item_entity = entity_load('node', array($item_id));
 $item_type = $item_entity[$item_id]->type;
 $item_title = pathauto_cleanstring($item_entity[$item_id]->title);
 if ($item_type == 'type1' or $item_type =='type2') {
 $replacements[$tokens['team_url'] = $item_title;
 break;
 }
 }`

````
}
return $replacements;

````

`}`

With this code I get only one parent. The foreach seems not functionnal.

if I use $replacements\[$original\] = $item\_title I get no parent.

Can you help me ?

Thanks.

P.S. If i use a similar code in my node template I get all parent items. It's ok in my node.

# Answer
I have rewrited my code from an example of a custom token:

```
$replacements = array();

if ($type == 'node' && !empty($data['node'])) {

    $node = $data['node'];

    foreach ($tokens as $name => $original) {

        switch ($name) {

            case 'team_url':

            $path = 'node/'.$node->nid;

            $mlid = db_select('menu_links' , 'ml')
            ->condition('ml.link_path' , $path)
            ->fields('ml' , array('mlid'))
            ->execute()
            ->fetchField();

            $menuParents = token_menu_link_load_all_parents($mlid);

            foreach ($menuParents as $itemParent_mlid => $itemParent_title) {
                $item = menu_link_load($itemParent_mlid);
                $item_path = $item['link_path'];
                $item_path_args = explode('/', $item_path);
                $item_id = $item_path_args[1];
                $item_entity = entity_load('node', array($item_id));
                $item_type = $item_entity[$item_id]->type;
                if ($item_type == 'team' or $item_type == 'page_team') {
                    $itemParent[]= pathauto_cleanstring($itemParent_title);
                }
            }

            $itemsParents = implode("/", $itemParent);
            $replacements[$original] = $itemsParents;

        }
    }

}

return $replacements;

```

It's functionnal. Perhaps we can simplify this code and get a cleanly syntax.
> 0 votes

---
Tags: tokens
---


# Question
Title: Any module or way to add line item in existing order?
Is there any way so that admin or whoever permission can add the line item in existing order while editing the order?

Any module or custom code?

# Answer
It's available out of the box from commerce module...

See screenshot below of Edit Order
> 1 votes

---
Tags: 7, commerce
---


# Question
Title: selecting hierarchical select values during migration
I want to select the values of a taxonomy which is being shown by heirachical select. These values are to be selected while importing the data through csv by using migration module. right now i am passing the values but it not picking up the hierarchical select list. Any help would be useful.. thanks

# Answer
Dunno why my last message has been deleted but well I founded the answer alone : In order To make it work, you have to pass an array of values containing the terms tid values and their parent's tid. You might have to use a callback that retrieve the parent tid from the children one.

I am migrating contents from drupal 6 to 7, not from a csv, but I've declared a static function containing the mapping between the old tids and the new ones like so :

```
public static $hierarchicalThemesToTheme1TidsMap = array(
  '1'     => array('tid' => '13', 'parent' => '0'),
  '1797'  => array('tid' => '14', 'parent' => '13'),
  '14993' => array('tid' => '15', 'parent' => '13'),
  '1801'  => array('tid' => '16', 'parent' => '13'),
  '59'    => array('tid' => '17', 'parent' => '13'),
  '1795'  => array('tid' => '18', 'parent' => '13'),
  '1796'  => array('tid' => '19', 'parent' => '13'),
  '1798'  => array('tid' => '24', 'parent' => '13'),
  '1799'  => array('tid' => '23', 'parent' => '13'),
  '1811'  => array('tid' => '42', 'parent' => '0'),
  '1812'  => array('tid' => '42', 'parent' => '0'),
  '1813'  => array('tid' => '42', 'parent' => '0'),
  '1800'  => array('tid' => '20', 'parent' => '42'),
  '1802'  => array('tid' => '21', 'parent' => '42'),
  '1803'  => array('tid' => '22', 'parent' => '42'),
  '1804'  => array('tid' => '18', 'parent' => '13'),
  '1805'  => array('tid' => '18', 'parent' => '13'),
  '62'    => array('tid' => '25', 'parent' => '0'),
  '1806'  => array('tid' => '26', 'parent' => '25'),
  '1807'  => array('tid' => '27', 'parent' => '25'),
  '64'    => array('tid' => '28', 'parent' => '25'),
  '1808'  => array('tid' => '29', 'parent' => '25'),
  '1809'  => array('tid' => '30', 'parent' => '25'),
  '61'    => array('tid' => '32', 'parent' => '0'),
  '1723'  => array('tid' => '33', 'parent' => '32'),
  '1724'  => array('tid' => '34', 'parent' => '32'),
  '1725'  => array('tid' => '35', 'parent' => '32'),
  '1726'  => array('tid' => '36', 'parent' => '32'),
  '1727'  => array('tid' => '37', 'parent' => '32'),
  '1728'  => array('tid' => '38', 'parent' => '32'),
  '1729'  => array('tid' => '39', 'parent' => '32'),
  '1730'  => array('tid' => '40', 'parent' => '32'),
  '1731'  => array('tid' => '41', 'parent' => '32'),
  '1810'  => array('tid' => '43', 'parent' => '13'),
  '4401'  => array('tid' => '44', 'parent' => '13'),
);

```

I had to do that because we didn't use migrate for the taxonomies. I guess there's a better way if you had use migrate to import your taxonomies.

Then I've declared a callback which use that static array to retrieve the tids and their parent tid :

```
public function getHierarchicalThemeByTids($tids) {
  $mapped_tids = array();

  foreach($tids as $tid) {
    $mapped_tid = FOMigration::getMappedId(self::$hierarchicalThemesToTheme1TidsMap, $tid, NULL);
    if($mapped_tid !== NULL) {
      $mapped_tids[] = $mapped_tid['tid'];
      if (!in_array($mapped_tid['parent'], $mapped_tids)) {
        $mapped_tids[] = $mapped_tid['parent'];
      }
    }
  }
  return $mapped_tids;
}

```

Finally I just tell migrate he has to use that callback to get the values :

```
$this->addFieldMapping('field_types', 'field_theme')->callbacks(array($this, 'getHierarchicalThemeByTids'));
$this->addFieldMapping('field_types:source_type')->defaultValue('tid');

```
> 0 votes

---
Tags: migrations, importing-exporting, taxonomy-terms
---


# Question
Title: global variable/array unset when hook_field_presave() is being called
I am trying to pass a global array and work with it in hook\_field\_presave() but that global array is unset. How do I pass a global array and work with it in presave?

example

```
function find_feed_field_widget_form(&$form, &$form_state, $field, $instance, $langcode, $items, $delta, $element) {
   etc.
   etc.
global $testvar;
$testvar = $array = array(
    "foo" => "bar",
    "bar" => "foo",
    );
}

function find_feed_field_presave($entity_type, $entity, $field, $instance, $langcode, &$items) {
   global $testvar;
   dpm ($tesvar);  // result = NULL
   etc.
   etc.
}

```

# Answer
This will never work - global variables only exist in the context of a single page request. Since the form build and presave happen in different requests, you can't use globals in the way you're trying to.

Use a session var instead, that will persist
> 3 votes

# Answer
The "drupal way" would be to serialize the value you want to keep, and save it with :

```
variable_set('name_of_your_variable', serialize($your_array));

```

Then get the value with :

```
variable_get('name_of_your_variable', 'default_value');

```

But if the variable is user-related, it will obviously not work and you will have to use the sessions, as indicated above.
> 1 votes

---
Tags: entities
---


title: Sorting the terms of taxonomy

text:
# Question
Title: Sorting the terms of taxonomy
How to set sort alphabetically in this view

I badly I asked the question above. I did not write that I want to sort alphabetically by the "slownik". The first in the table. This field is a term taxonomy.

# Answer
Click here:

Then set the column to sortable, set the default sort order, and set the column to the default sort column:

Save settings and done.
> 0 votes

# Answer
I did so

Save settings and done.
> 0 votes

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


# Question
Title: Drupal Form Suffix + Suffix As a href + pop up the drupal users listing with checkboxes by click on that link
I have requirement like ..

I have to put one link in the Drupal Form, That i achieve with using suffix while creating Drupal form..

Now I want to pop up the list of all drupal users & their email ids with checkboxes by on click that Link..

now if i choose the check box in front of particular user .. the name of the users with semicolons replace that link that i made with suffix..

so how to achieve that...? Any suggestions guys..?

# Answer
What you need is pretty much a huge select box :)

i can think to a couple of different approaches, but to mention one, i would proceed like this

1. Create your form and set the default values obviously.
2. At the end of your form add a that will wrap around the list of possible choices
3. Target that with the show/hide script triggered by the click on the link.
4. Create the list, using either a table or several divs, as long as you give each row an #id, something like user-$uid".
5. since you are here you can even set a class for the rows that will highlights the row on hover.
6. Split each row into, assuming tables, cells and populate the table with the user data you need. give each cell the same #id of its row, extend with something else to obtain things like

"user-$uid-mail" "user-$uid-name"
7. I would avoid the checkboxes and go with an onClick event on each row, that calls a function passing the row #id as parameter.
8. The function will, hide the list, use the row #id to read the values of the fields, like

document.getElementById("user-$uid-name").value

and write the values inside the form elements.

profit. i may have typed some function wrong, but that's the idea
> 0 votes

---
Tags: forms
---


# Question
Title: During insertion of the field in the drupal view, there is image contained text but text is displaying not in image
During insertion of the New field in the Drupal view, there is content type field containing text and image but text is displaying not in image what to do ?

**for example**

Filed Name : text\_field

During insertion of the that text\_field in the Drupal view the new image not visible what to do? i wanted to display that new image also.

# Answer
It might be field settings issue.. Make sure your field has "full\_html" format also,

Make sure formatter is default in view field settings..

Make sure Rewriting results has not been enabled..
> 0 votes

---
Tags: views
---


# Question
Title: Backup & Migrate: Restored changes lost after clearing cache
I have a live and a development version of a Drupal 7 site. I want to keep them as close in content as possible so I am using the Backup and Migrate module to take a backup of the live site and restore it onto the development site. This works fine until I clear the cache on the development site after the restore and things like views, menu items and entity forms disappear for some reason. They work fine after the restore up until I clear the cache.

Anybody have any idea what's going on?

I'm using the features module if that makes any difference.

# Answer
> 2 votes
Sorry, but your approach is wrong.

If things gets to disappear after cache clear, you have some serious bug in your implementation.

1. You should exclude all cache tables from migration.
2. After migration, you should clear cache of recipient site.

If your procedure is different, it's buggy. Details may vary but these two points are pretty much needed for consistent workflow.

If one of your sites generates different menu than the other after cache clear, then you failed to migrate some files that provide `hook_menu` or `hook_menu_alter`, or you have a problem with migrating menu data in database. Either way, disable cache for migration, don't **ever** try to rely on migrated cache.

# Answer
> 2 votes
Caches don't go well with the **Backup and Migrate** module. You should never migrate any cached material (it bloats the size of the dump and create all sorts of stability problems).

*Before* migrating, you should clear all caches on the site you migrate just to make sure your site is stable and all features still present after its cache is cleared.

**Check the site after clearing the cache.** If there are features missing, your site is broken and your problem is with the site, not with whatever method you use for migration.

Fortunately, **Backup and Migrate** lets you create *profiles* where you can exclude certain tables from the dump. You should always exclude any tables starting with `cache*`, but there a number of other tables you'd better off excluding to avoid state mismatches when you roll your backup back in again.

Also: *Always* make sure your site is in maintenance mode when making a backup, and when you roll your backup back.

Here is a list of tables I recommed excluding from the backup, with a brief explanation about what information the table holds:

* `{batch}` – disconnect user from his/her batch, so make sure site is in maintenance mode;
* `{cache*}` – the cache just optimises page loads, always safe to exclude;
* `{sessions}` – loses user sessions, so make sure site is in maintenance mode;

In addition, excluding the following tables from only delete information that can simply be regenerated, so you may want to exclude to keep the size of the backup down:

* `{flood}` – flood log generated by built-in flood control;
* `{search*}` – loses search indices and statistics, indices is regenerated by cron;
* `{watchdog}` – loses log messages.

To exclude these tables, navigate to *Configuration → System → Backup and Migrate → Profiles*. Click on *Add profile*, and give the profile a name so you can recognise it. Then under *Default database backup options*, select the tables you don't want included in the backup from the menu as show below.

>

---
Tags: caching, backups
---


# Question
Title: Flags: get Action after a user flagged a specific number of nodes?
I would like the users of my site to choose a specific number of nodes. After this they should see, to which taxonomy term these nodes belong to.

I have already found the flag module as well as flag limiter module. I have put the limit to 12 (This is the amount of nodes the user should be able to choose).

Now I would like that the user is redirected to a new page (where he can see the belongig taxonomy terms to his flagged nodes - this I can manage to create with views), after he flagged the 12th node.

Could anyone help me, how to achieve this?

Thanks, Tabea

# Answer
> 1 votes
You can able to detect limit has reached using hook\_flag\_flag hook exposed by flag module..

Flag Limiter module uses the same logic to detect the limit as you can see the below code

```
function flag_limiter_flag_flag($flag, $entity_id, $account, $flagging) {
  // Get the flag limits.
  $flag_limit = variable_get('flag_limiter_' . $flag->name . '_value', 0);
  $peritem_limit = variable_get('flag_limiter_' . $flag->name . '_peritem_value', 0);

  if ($flag_limit) {
    $user_flags = flag_limiter_get_user_flags($account->uid, $flag->fid);
    if (count($user_flags) > $flag_limit) {
      $unflag = flag('unflag', $flag->name, $entity_id, $account, TRUE);
      if ($unflag) {
        drupal_set_message(t("You've already signed up @num times", array('@num' => $flag_limit)), 'error');
      } else {
        drupal_set_message(t('Fail limiter operation'), 'status', FALSE);
      }
    }
  }

  if ($peritem_limit) {
    $flagging_data = flag_get_counts($flag->entity_type, $entity_id, TRUE);
    if ($flagging_data[$flagging->flag_name] > $peritem_limit) {
      $unflag_item = flag('unflag', $flag->name, $entity_id, $account, TRUE);
      if ($unflag_item) {
        drupal_set_message(t("The event already signed up @num times", array('@num' => $peritem_limit)), 'error');
      } else {
        drupal_set_message(t('Fail limiter operation'), 'status', FALSE);
      }
    }
  }
}

```

You can implement same hook in your custom module to redirect user to the page you want.. You can use drupal\_goto function to redirect user..

```
function YOURMODULENAME_flag_flag($flag, $entity_id, $account, $flagging) {
  if ($flag_limit) {
    $user_flags = flag_limiter_get_user_flags($account->uid, $flag->fid);
    if (count($user_flags) >= $flag_limit) {
      drupal_goto('path');
    }
  }
}

```

writing custom module instructions ..

* Create a folder called "custom" inside sites/all/modules
* Create a folder called "myflaglimit" inside sites/all/modules/custom/
* Create a file called "myflaglimit.info" inside "myflaglimit" folder create above.
* Put in below code and save file

Below code goes into myflaglimit.info file..

```
name = My Flag Limit
description = Provides a redirect on reaching limit.
core = 7.x
package = Custom
dependencies[] = flag_limiter

```

Your logic goes into .module file

* Create a file called myflaglimit.module file inside myflaglimit folder you have create with below code
* You extend drupal function using hooks which are nothing but functions which starts with modulename\_hook

use below code inside module file

```
<?php
function myflaglimit_flag_flag($flag, $entity_id, $account, $flagging) {
  if ($flag_limit) {
    $user_flags = flag_limiter_get_user_flags($account->uid, $flag->fid);
    if (count($user_flags) >= $flag_limit) {
      drupal_goto('path');
    }
  }
}

```

---
Tags: flags, actions
---


# Question
Title: Drupal 8 Menu Tree issue in my contrib theme possibly because of "Convert menu tree building to a service."
Previously, in my Drupal 8 contrib theme, I was rendering the full menu tree as:

```
function gratis_preprocess_page(&$vars, $hook) {

// Build the main menu links tree.
  $vars['primary_nav'] = FALSE;
  if (!empty($vars['main_menu'])) {
  // Build links.
    $config = Drupal::config('menu.settings');
    $menu_enabled = Drupal::moduleHandler()->moduleExists('menu');
    // When menu module is not enabled, we need a hardcoded default values.
    $main_links_source = $menu_enabled ? $config->get('main_links') : 'main';
    $vars['main_menu'] = menu_tree($main_links_source);
    $vars['main_menu']['#theme_wrappers'] = array('menu_tree__primary');
    $vars['main_menu']['#attributes']['id'] = 'main-menu-links';
    $vars['main_menu']['#attributes']['class'] = array('links', 'clearfix');
  }
}

```

However, in testing the theme with the latest Drupal 8 dev, I am getting a WSOD with this specific error:

```
PHP Fatal error:  Call to undefined function menu_tree() in /themes/gratis/gratis.theme on line 93

```

Line 93 from the above is:

```
$vars['main_menu'] = menu_tree($main_links_source);

```

I did a little searching and discovered this core change: Convert menu tree building to a service. and its corresponding change notice.

I tried adjusting my code to:

```
$vars['main_menu']= \Drupal::service($main_links_source);

```

... but now I am getting this error:

```
Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException: You have requested a non-existent service "main". Did you mean one of these: "maintenance_mode_subscriber", "user_maintenance_mode_subscriber"? in Symfony\Component\DependencyInjection\Container->get() (line 303 of core/vendor/symfony/dependency-injection/Symfony/Component/DependencyInjection/Container.php).

```

So I am at a loss of how to fix this. You can see the repo for my `.theme` file here.

Cross referencing Render full menu tree in Drupal 8 version.

**Update: \[working code\]**

Here is the code in its fixed and working version thanks once again to **@Clive**

```
// Build the main menu links tree.
  if (!empty($vars['main_menu'])) {
  // Build links.
    $config = Drupal::config('menu.settings');
    $menu_enabled = Drupal::moduleHandler()->moduleExists('menu');
    // When menu module is not enabled, we need a hardcoded default values.
    $main_links_source = $menu_enabled ? $config->get('main_links') : 'main';
    $vars['main_menu'] = \Drupal::service('menu_link.tree')->renderMenu($main_links_source);
    $vars['main_menu']['#attributes']['id'] = 'main-menu-links';
    $vars['main_menu']['#attributes']['class'] = array('links', 'clearfix');
    $vars['main_menu']['#theme_wrappers'] = array('menu_tree__primary');
  }

```

and then we render the wrapper set above with `menu_tree__primary`

```
/**
 * Theme wrapper function for the primary menu links.
 */
function gratis_menu_tree__primary(&$vars) {
  return '<ul class="toggle-menu">' . $vars['tree'] . '</ul>';
}

```

# Answer
> 3 votes
Does https://drupal.org/node/2226481 help you?

This should be something like

```
\Drupal::service('menu_link.tree')->renderMenu($main_link_source);

```

---
Tags: routes, theming, 8
---


title: How To Change The $tid to $term_name

text:
# Question
Title: How To Change The $tid to $term_name
I've tried to change this code to show the term name instead of the term ID but now no term name or term id show at all

Orginal code for term ID

```
function MYTHEME_preprocess_node(&$vars) {   if (array_key_exists('content', $vars)) {
    $content = &$vars['content'];
      if (array_key_exists('field_photo_topic', $content)) {
        foreach ($content['field_photo_topic']['#items'] as $index => $info) {
          $tid = $info['tid'];
          $content['field_photo_topic'][$index]['#href'] = 'photos/' . $tid;
        }
      }   } }

```

What I changed it too

```
function MYTHEME_preprocess_node(&$vars) {   if (array_key_exists('content', $vars)) {
    $content = &$vars['content'];
      if (array_key_exists('field_photo_topic', $content)) {
        foreach ($content['field_photo_topic']['#items'] as $index => $info) {
          $term_name = $info['term_name'];
          $content['field_photo_topic'][$index]['#href'] = 'photos/' . $term_name;
        }
      }   } }

```

Many thanks for your help

# Answer
> 3 votes
To convert from `$tid` to term name, use `taxonomy_term_load()` to load the object, and then access `$term->name`:

```
$term = taxonomy_term_load($tid);
$term_name = $term->name;

```

Your function should look like:

```
function MYTHEME_preprocess_node(&$vars) {
  if (array_key_exists('content', $vars)) {
    $content = &$vars['content'];
      if (array_key_exists('field_photo_topic', $content)) {
      foreach ($content['field_photo_topic']['#items'] as $index => $info) {
        $tid = $info['tid'];
        $term = taxonomy_term_load($tid);
        $term_name = $term->name;
        $content['field_photo_topic'][$index]['#href'] = 'photos/' . $term_name;
      }
    }
  }
}

```

Please note that this will only work the way you intend if you use **PathAlias** or similar to alias the path to be accessible by term name instead of numeric `$tid`.

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


title: Can TableSort be used without a query?

text:
# Question
Title: Can TableSort be used without a query?
In my module, I'm using TableSort for some of my tables, but I also have some tables that are generated by code, so not directly linked to a query. These tables are also created with theme('table') and so have the $header and $rows arrays. Is it possible to use TableSort on those as well, maybe with writing my sorting function?

The documentation for tablesort.inc seems to suggest it is possible (*All tables created with a call to theme('table') have the option of having column headers that the user can click on to sort the table by that column*). However, I haven't found any instructions or example on how to do this. Everything I found so far is based on a query. I'm using Drupal 7.

# Answer
Tablesort actually consists of two different systems which work together.

The first part is the rendering, the stuff that happens directly within theme\_table() or is called from that. All it does is display the table headers with the sort indication if a default sort or override through $\_GET is present and makes them links so that you can click on them.

The second part is the TableSort query extender, that adjusts the query it is added on based on the default sort direction or the $\_GET override.

These two systems are actually pretty separated, the just work together easily because they get their data from the same $header structure and use the same helper functions and naming conventions for the $\_GET parameters. But nothing stops you from using only one of these.

To actually answer your question, if you just need the rendering part, you just need to make sure to do something similar to TableSort::orderbyHeader(). Instead of the orderBy() call, you'd use a array sort function, or pass it as an argument to a web service or anything else.

And for the opposite, you'd just need to make sure that you display a link that is basically the equivalent of tablesort\_header() so that it is recognised by the TableSort query extender.
> 10 votes

# Answer
Thanks to Berdir I got it working. This is how it works in more detail.

Tablesort is triggered "automatically" if the (column) arrays in the $headers array contains the keys 'data', 'field' and optionally 'sort'. This will create links with 'sort' and 'order' in the column headers and show the little arrow and such.

To do your own sorting, get the current sort settings with tablesort\_get\_order and tablesort\_get\_sort and use those values for your own sorting function. The key 'sql' in the array returned by tablesort\_get\_order contains the field name to be used for sorting.

A piece of (untested) example code with the array $users containing some details for each user:

```
// setup the table data that we want to show
$tableData = array();
foreach ($users as $userDetails) {
  $tableData[] = array(
      'name' => $userDetails['name'],
      'visits' => $userDetails['visits'],
      'views' => $userDetails['views'],
      'comments' => $userDetails['comments']
  );
}

// headers array, sorting by default on comments
$headers = array(
    array('data' => t('Name'), 'field' => 'name'),
    array('data' => t('Visits'), 'field' => 'visits'),
    array('data' => t('Views'), 'field' => 'views'),
    array('data' => t('Comments'), 'field' => 'comments', 'sort' => 'desc')
);

// getting the current sort and order parameters from the url
$order = tablesort_get_order($headers);
$sort = tablesort_get_sort($headers);

// sort the table data accordingly (write your own sort function)
$tableData = my_array_sort($tableData, $order['sql'], $sort);

// create the array with rows for theme table
$rows = array();
foreach ($tableData as $entry) {
  $rows[] = array(
      array('data' => $entry['name']),
      array('data' => $entry['visits']),
      array('data' => $entry['views']),
      array('data' => $entry['comments']),
  );
}

// add any attributes and sent everything to theme table
$attributes = array('class' => array('my_class'));
$table = array('header' => $headers, 'attributes' => $attributes, 'rows' => $rows);
$html = theme('table', $table);

```
> 17 votes

# Answer
Here is the code that i ended up on the answer of whiskey. It uses entity field query.

```
 $query = new EntityFieldQuery();
  $query
  ->entityCondition('entity_type', 'vehicle')
  ->entityCondition('bundle', 'car');
  $result=$query->execute();
  $ids=array_keys($result['vehicle']);
  $values=entity_load('vehicle',$ids);
  $rows=array();
  foreach($values as $val){
    $rows[]=array('data'=>array(
      'id'=>$val->id,
      'title'=>$val->title,
      'price'=>$val->field_price['und'][0]['value'],
      'model'=>$val->field_model['und'][0]['value'],
      'color'=>$val->field_color['und'][0]['value'],
      'speed'=>$val->field_speed['und'][0]['value'],

    ));
  }

  // We are going to output the results in a table with a nice header.
  $header = array(
    // The header gives the table the information it needs in order to make
    // the query calls for ordering. TableSort uses the field information
    // to know what database column to sort by.
    array('data' => t('Entity Id'),'field' => 'id'),
    array('data' => t('Title'),'field' => 'title'),
    array('data' => t('Price'),'field' => 'price'),
    array('data' => t('Model'),'field'=>'model'),
    array('data' => t('Color'),'field'=>'color'),
    array('data' => t('Speed'),'field'=>'speed'),

  );

  $order = tablesort_get_order($header);
  $sort = tablesort_get_sort($header);
  $sql=$order['sql'];
  if($sort=='desc') {

    usort($rows, function($a, $b) use($sql) {
    return $a['data'][$sql] > $b['data'][$sql]? -1 : 1;

  });

  }
  if($sort=='asc') {
      usort($rows, function($a, $b) use ($sql) {
        return $a['data'][$sql] < $b['data'][$sql]? -1 : 1;
      });
  }

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

  return $output;

```
> 4 votes

---
Tags: 7
---


# Question
Title: Howto limit access to a main menu link using drupal 7 api
in my scenario I am using Drupal 7 with the ubercart modules. I like to add a link in my main menu that is only visible if you are an authenticated user.

For testing purposes I am using the bartik theme.

It is the same function like user/login, which is only visible if you are an anonymus user.

I found some hints and even examples in the drupal api - like

https://api.drupal.org/api/drupal/modules!system!system.api.php/function/hook\_menu\_alter/7

```
The following implements hook_menu_alter to remove access to the "forum" tab for the anonymous user:

/**
* Implements hook_menu_alter.
* Check access for forum menu item.
*/
function MYMODULE_menu_alter(&$items) {
$items['forum']['access callback'] = '_accesscheck';
}

/**
* Callback to disallow access for the anonymous user.
*/
function _accesscheck(){
  global $user;
 return $user->uid;
}

```

Even after many attempts, I can't catch a value for $items, I was using main\_menu.

I like to use the function in the theme template. How can I find the variables that I need to alter one item of my menu - I called it \> cart \<.

I even tried to print\_r($items), but nothing was found.

How can I retrieve $items for the main menue

# Answer
hook\_menu\_alter only gets executed when you clear cache or rebuilding menu. I would suggest if you want to debug the $items variable, What I used to do is do `print_r($items)` and `die()` after that. Then I would try to clear the cache from the admin UI or save it into watchdog for debugging.
> 1 votes

# Answer
Please note that in *most* cases, Drupal will manage menu item visibility and access via menu items just fine by itself. If you link to "something" in the main menu, and access to "something" is limited, Drupal will hide the menu item from those that shall not have access. In other words: In *most* cases, there is no need for you to do anything. (i.e.: there is no need to use `hook_menu_alter`, etc.)

In *some* cases, it doesn't work like that. The example you've copy-pasted from is a remedy for one of these rare case.

I suggest you first try to create the menu link normally in the admin panel, set access control for whatever it is it points to only allow the authenticated user access. Clear caches, and test. If all went well, the menu item will not be visible for the anonymous user when you test it.

And if this is one of those pesky cases where the above don't work, come back here. Edit your question an give us all the details about what you're linking to and how access to that is controlled. Then we need to review other options.

The reason you're unable to "catch" a value for `$items` by placing a `print_r` statement inside `hook_menu_alter` is because this hook is not invoked on page loads. It is only invoked when the menu list is rebuilt. This happens when a module is installed/uninstalled, or when all caches are cleared. However, he output of `print_r` may be lost if it is output outside of a page load. Instead, to debug `$items`, install and enable the **Devel** module and use the following instead of `print_r`.

```
dpm($items, '$items');

```

The output of `dpm`, unlike `print_r` is not output immediately, but queued and will be shown on the next page load.

However, in this case, I don't think you will learn what you need to know in order to block access by looking at `$items`. Instead, just figure out what *paths* of the menu items you want to block access to. It is not what the menu is called that matters, it is the path it leads to.
> 0 votes

---
Tags: routes
---


# Question
Title: How do I add a class to HTML bookmarks generated by core?
I'd like to add a CSS class to HTML bookmarks generated by core. Examples of these bookmarks include:

```
<a id="new"></a>

<a id="comment-766013"></a>

```

I'd like to turn them into:

```
<a id="new" class="bookmark"></a>

<a id="comment-766013" class="bookmark"></a>

```

I'm unable to alter these in comment.tpl.php and it looks like theme\_comment\_view is unavailable in D7, so I'm kind of lost.

Background: I have a sticky header menu that's 60px tall and as such, HTML bookmarks are landing about 60px lower on the page than they should. An example of this is when you link to comment by ID, like http://site.com/article#comment-766013.

Thanks!

# Answer
> 2 votes
Those anchors are added in `comment_view()`. To override them you'll need to implement `hook_comment_view_alter()` and reproduce a bit of the logic from the original view function:

```
function MYMODULE_comment_view_alter(&$build) {
  $comment = $build['#comment'];
  $node = $build['#node'];

  if (empty($comment->in_preview)) {
    $prefix = '';
    $is_threaded = isset($comment->divs) && variable_get('comment_default_mode_' . $node->type, COMMENT_MODE_THREADED) == COMMENT_MODE_THREADED;

    // Add 'new' anchor if needed.
    if (!empty($comment->first_new)) {
      $prefix .= "<a id=\"new\" class=\"bookmark\"></a>\n";
    }

    // Add indentation div or close open divs as needed.
    if ($is_threaded) {
      $prefix .= $comment->divs <= 0 ? str_repeat('</div>', abs($comment->divs)) : "\n" . '<div class="indented">';
    }

    // Add anchor for each comment.
    $prefix .= "<a id=\"comment-$comment->cid\" class=\"bookmark\"></a>\n";
    $build['#prefix'] = $prefix;
  }
}

```

# Answer
> 1 votes
i would prefer using drupal.behaviors which allows you to add class and add css anytime. what it does is whenever you include anything in drupal.behaviors it will apply for every event that happens in your drupal page even on ajax event. using traditional js won't allow you to do it.

https://stackoverflow.com/questions/3941426/drupal-behaviors

http://www.benmarshall.me/drupal-behaviors-introduction/

```
Drupal.behaviors.makeMeSmelly = {
  attach: function (context, settings) {
    // This will only get ran once
    context.once(function() {
     $('h1', this).addClass('.the-original-smelly-bean');
    }

    // This get's ran on every request
    $('h1').addClass('.smelly-beans');
  }
}

```

# Answer
> 0 votes
add js file and write code for D7

```
(function($) {

    $(document).ready(function(){

        $('#new').addClass("bookmark");

        $('#comment-766013').addClass("bookmark");

    });

})(jQuery);

```

---
Tags: 7, theming
---


# Question
Title: Unique field value per multivalued field collection
**Field collection Config (multi value)**

```
Field1---Name -Autocomplete (single value) (Entity Reference)
Field2---Score - Computed field.

```

**Example Values for field collections**

```
Field collection [0]
------Bill (1112)- where 1112 is nid
------Score - some value will be generated depends on 1112

Field collection [1]
------Roger (1345)- where 1345 is nid
------Score - some value will be generated depends on 1345

Field collection [2]
------Roger (1467)- where 1467 is nid
------Score - some value will be generated depends on 1467
..
..
Field collection [n]
------Maddy (1652)- where 1652 is nid
------Score - some value will be generated depends on 1652

```

From above config how to make field Name's value should not hold the duplicate value for field collection ie *Bill* should not be applied again.
There is a module called https://drupal.org/project/unique\_field which forces field's value to be unique per content type or per all node, but not per field.
In above case somehow(that what is required) if we make per field then also it could only applied to *Name* field which is inside field collection rather than field collection itself. Right?

# Answer
I had to do this the other day and found it easiest with a custom validation function.

Using hook\_form\_alter add a new validation function:

```
function YOUR_MODULE_form_alter(&$form, &$form_state, $form_id) {
  //drupal_set_message("Form ID is : " . $form_id);
  switch($form_id) {
    case 'YOUR_FORM_ID':
      //dpm($form);
      $form['#validate'][] = 'validate_unique_field_collection_names';
      break;
  }
}

```

And then in your new validation function:

```
function validate_unique_field_collection_names($form, &$form_state) {
  $used_ids = array();
  foreach($form_state['values']['field_people_collection'][LANGUAGE_NONE] as $k => $item) {
    if($k === 'add_more') continue; // skip loop if key is add_more
    $user_target_id = $item['field_name'][LANGUAGE_NONE][0]['target_id'];
    if(in_array($user_target_id, $used_ids)) { // check if UID is in used array
      form_set_error('field_people_collection]['.LANGUAGE_NONE.']['.$k.'][field_name', t('Names must be unique.')); // if it is set an error
    } else {
      $used_ids[] = $user_target_id; // else add it into the used array
    }
  }
}

```
> 6 votes

# Answer
With this modification we can highlight the repeated fields.

```
        if(in_array($user_target_id, $used_ids->id)) { // check if UID is in used array

            form_set_error('field_people_collection]['.LANGUAGE_NONE.']['.$used_ids->k[$user_target_id].'][field_name');
            form_set_error('field_people_collection]['.LANGUAGE_NONE.']['.$k.'][field_name', t('Names must be unique.')); // if it is set an error

        } else {

            $used_ids->id[$user_target_id] = $user_target_id; // else add it into the used array
            $used_ids->k[$user_target_id] = $k;
        }

```
> 2 votes

---
Tags: entities
---


# Question
Title: Does storing my database as a .sql file in my site git repository cause problems?
I have been saving a series of database export files each time I do a git commit of my Drupal site. I have a nice git repository for my site files and a messy folder for my database backups. Because the database file is related to a commit, should the database file be included with the Drupal site files (in a temporary folder of some kind?) It seems helpful to bind these files together in a single commit. However, this practice does not seem commonplace, so there may be a problem with it. Have I overlooked a major issue?

If so, would it be better to create another repository for my database backups?

# Answer
It should be the right way so that both site & database are in sync.

I'd suggest you better backup the (zipped) mysql dump from backup-migrate module. If you can use lzma compression then you can save another 20% space on mysql backups using this way.
> 1 votes

---
Tags: 7, database, version-control
---


# Question
Title: Put social Icons next to body field ($content['body'])
I want to align my social icons vertically next to the body field, in my node.tpl.php file the body is included in the $content with everything else. The social icons sit a few lines above and look like this in my node.tpl.php file:

```
<div class="main-node-social-share">
  <?php print render($main_node_social_share);?>
</div>

```

How can i get $main\_node\_social\_share to render right before the $content\['body'\] field?

```
// We hide the comments and links now so that we can render them later.
hide($content['comments']);
hide($content['links']);
print render($content);

```

# Answer
Try some thing like this in custom module and see it helps.

```
function modulename_page_alter(&$page) {
  $social=array(
    '#markup'=>'<div id="social"><img src="https://cdn3.iconfinder.com/data/icons/free-social-icons/67/twitter_square-128.png"></div>',
  );
  array_unshift($page['content']['system_main']['nodes'][1],$social);

}

```
> 2 votes

---
Tags: theming
---


# Question
Title: Drupal Commerce order completes but reverts from pending to billing
We are having issues where a Commerce Order will complete checkout, but once marked Paid in Full and set as Pending, it bounces back to Billing and Shipping (Shipping checkout page, name changed.)

Edit: We are using Authorize.net, no IPN.

Our checkout settings:

* Checkout
    + Shopping cart contents
    + Coupons
    + Account Information
* Billing and Shipping (default Shipping page, name changed)
    + Billing information
    + Shipping information
    + Shipping Service
* Billing (empty, moved into previous page)
* Review and Payment
    + Review
    + Payment

# Answer
> 0 votes
This actually had to do with Commerce Order entity revisions and Commerce Shipping. During checkout AJAX shipping rate calls were not properly checking form state, causing the order revision ID to set back after checkout.

# Answer
> 0 votes
Most likely the order processing rules.

Look into whether your payment gateway is firing an IPN / notification which changes the order. If some orders process in a different order (eg some browsers varies in speed and fires checkout rules in a different order to the others) then you can see this sort of inconsistent behaviour.

Your checkout rules can permit EITHER the IPN or customer redirect to provide checkout notification - this can avoid showing some customers "we're awaiting confirmation from payment gateway". Just check order status and don't update an order which is already completed.

Your gateway may refer to IPN under another name. IPN requests can be discerned by the differing origin IP and authentication (if purchase is from a logged in user, but the above image is an anonymous purchase so not discernible there).

---
Tags: commerce
---


# Question
Title: Trying to find variable names from $user array
I need to manually pull through user images and and users first name for a comment section, but i cant find what these array items are named, if anybody knows please tell me and or tell me how to find similar information in the future.

# Answer
The best way to do this is use the devel module.

Once enabled you can use the `dpm($variable)` function to have it printed out on the screen.

Another (more complex to set up) solution would be to use xdebug and a debugger.
> 1 votes

---
Tags: users
---


# Question
Title: How to get the managed_file progress bar working in a custom theme?
I'm trying to get the managed\_file progress bar working in a custom theme. Right now, when I start an upload, the empty progress bar widget appears in the form, but it doesn't visually update while the file is being uploaded. If I switch my site from my own theme to Bartik, the bar works properly, so it's evidently a theming problem. (This also confirms that I've got all the uploadprogress stuff properly installed.)

I've found `theme_progress_bar`, and tried adding it to my theme's template.php file, renaming it to `MYTHEME_progress_bar`, but it didn't work. Any advice on how to get it to work? Thanks!

# Answer
> 0 votes
Found, I think: My theme was based on Bootstrap 2, and I was getting bit by a problem of Drupal and Bootstrap disagreeing on what sort of thing the "Upload" button should be:

https://drupal.org/node/2155419

Since I'm still on Bootstrap 2 (I think) I wasn't having the problem with the input fields being out of order, but I did need to deal with the behavior assignments. In addition to the fix outlined in the cited page, I also needed to run the assignments on page load / document ready to get things properly assigned.

---
Tags: 7, theming, forms
---


# Question
Title: Why does template.php override not work?
I'm trying to get links from the PDFPreview module to open in a new tab. As described in this issue, overriding the formatter function in template.php does not work. One can modify the function in the actual .module file, but this is obviously not good practice. Why does it not work?

Code from the module:

```
/**
 * Theming functions for our formatters
 *
 * @todo Clearify the image cache thing...
 * @todo Let user choose what preview image to show on non-PDF files
 */
function theme_pdfpreview_formatter($variables) {
  $img_tag = '';
  $item = $variables['item'];

  $image = array(
    'title' => $item['description'],
    'uri' => $item['preview'],
  'alt' => $item['description'],
  );

  $element =array();
  $element['item'] = $image;
  $element['image_style'] = $variables['settings']['image_style'];
  switch ($variables['settings']['image_link']) {
    case 'file':
      $element['path'] = array(
        'path' => file_create_url($item['uri']),
        'options' => array(),
      );
      break;
      case 'content':
      $element['path'] = array(
        'path' => $variables['entity_type'] . '/' . $variables['entity']->nid,
        'options' => array(),
      );
      break;
  }
  $img_tag = theme('image_formatter', $element);
  $wrapper_tag = $variables['settings']['tag'];
  $description = $variables['settings']['show_description'] ? '<' . $wrapper_tag . ' class="pdfpreview-description">' . $item['description'] . '</' . $wrapper_tag . '>' : '' ;
  return sprintf(
          '<div class="pdfpreview pdfpreview-%s" id="pdfpreview-%s">'
          . ' <%s class="pdfpreview-image-wrapper">%s</%s>'
          . ' %s'
          . '</div>',
          $variables['instance']['field_name'],
          $item['fid'],
          $wrapper_tag, $img_tag, $wrapper_tag,
          $description
  );
}

```

Code from template.php:

```
/**
 * Theming functions for our formatters
 *
 * @todo Clearify the image cache thing...
 * @todo Let user choose what preview image to show on non-PDF files
 */
function my_theme_pdfpreview_formatter($variables) {
  $img_tag = '';
  $item = $variables['item'];

  $image = array(
    'title' => $item['description'],
    'uri' => $item['preview'],
  'alt' => $item['description'],
  );

  $element =array();
  $element['item'] = $image;
  $element['image_style'] = $variables['settings']['image_style'];
  switch ($variables['settings']['image_link']) {
    case 'file':
      $element['path'] = array(
        'path' => file_create_url($item['uri']),
        'options' => array('attributes' => array('target' => '_blank')),
      );
      break;
      case 'content':
      $element['path'] = array(
        'path' => $variables['entity_type'] . '/' . $variables['entity']->nid,
        'options' => array(),
      );
      break;
  }
  $img_tag = theme('image_formatter', $element);
  $wrapper_tag = $variables['settings']['tag'];
  $description = $variables['settings']['show_description'] ? '<' . $wrapper_tag . ' class="pdfpreview-description">' . $item['description'] . '</' . $wrapper_tag . '>' : '' ;
  return sprintf(
          '<div class="pdfpreview pdfpreview-%s" id="pdfpreview-%s">'
          . ' <%s class="pdfpreview-image-wrapper">%s</%s>'
          . ' %s'
          . '</div>',
          $variables['instance']['field_name'],
          $item['fid'],
          $wrapper_tag, $img_tag, $wrapper_tag,
          $description
  );
}

```

# Answer
Use `my_theme_pdfpreview`, because even though there's a specific function assigned to it in `hook_theme()`, you should use the key to override.

I admit I got confused as well at first :)
> 0 votes

# Answer
To override a theme function like this one `theme_pdfpreview_formatter()`.

* Replace the word `theme` with you theme name `my_theme`. It should look like this `my_theme_pdfpreview_formatter()`.
* Avoid using underscore for theme names (it's known for causing problems). Ideally your theme would be called `mytheme`, the function would be `mytheme_pdfpreview_formatter()`
* Make sure you're editing the correct `template.php` file.
* Clear Cache after adding the new function.
> 0 votes

---
Tags: theming
---


title: Offers with reservations

text:
# Question
Title: Offers with reservations
My client wants a site where registered users can create paid offers of rooms to rent and other users can book those rooms. Users who created offers should be able to see those reservations.

I think that registered users could create offers as nodes with payment options using the Pay-per-node module. I don't know how to create the booking feature. I tried to use a few modules, but none was proper for my goal.

# Answer
There are some useful options, Please note that both Drupal Commerce and Ubercart have Marketplace modules which you could use in combination to achieve your desired functionalities:

A. Rooms helps with booking and room management, More info also available here

> Drupal Rooms is a booking and room management solution for hotels, vacation rentals and B&Bs.
>
> It allows an accommodation owner to:

* Create rooms and assign availability (or on hold states) via a calendar.
* Manage pricing for rooms using calendars that allow to set pricing for entire seasons or just change it for specific dates.
* Define optional add-ons for rooms. Charge either per-night or per-person. Handle children discounts. Create bookings and keep customer records.
* Make rooms available for booking with a availability
* search functionality and/or calendar - handling both immediate bookings and bookings following owner confirmation.
* Search by Room Type.
* Full integration with Commerce to manage payments, a range of different payment gateways, and a host of other e-commerce features.
* Accept full or partial payments (deposits) using Commerce features.

B. Hotel Booking System For Ubercart

> The uc\_hotel module is a hotel booking system for Drupal and Ubercart.
>
> It does not manage individual rooms, but rather lets you create room types, and set how many of each type are available for specific dates on the calendar. Each room type can be assigned a different rate, or be based off a single master rate and have a modifier applied to adjust that rate by a certain amount.
>
> You can vary the rate based on the number of adult and child occupants.
>
> The module also features an add-ons and upgrades sub module that allows you to bundle other date-based upgrades with the booking such as tennis lessons or spa treatments.

C. Open Hotel

> Open Hotel is a Drupal 7 Distribution that helps you create a full featured Hotel site with online booking and online availability.

**Features**

* Online Availability
* Online Booking
* Multilingual
* Photo Galleries
* Responsive Design
* Google Analytics E-Commerce Integrated
* Free and Open-Source
* Easy to integrate with any payments processor.
* Search Engines Optimized
> 0 votes

---
Tags: bookings
---


# Question
Title: drush 7 won't take a command without a site alias?
I just installed drush 7.0-dev and with it all the composer and bash-completion goodness. The installation went well and in a new shell it (drush 7) is now my default drush.

However it doesn't seem to want to take commands without aliases. Is this really the new behavior or did I setup something wrong?

Here is a screenshot of a simple "drush dd files" command executed in my sites drupal root path. I compare it to the drush 6 version which works fine without an alias.

Don't get me wrong I like aliases and all but this seems a bit draconian to force you to have to use them.

# Answer
> 0 votes
You need to specify path or create sym link based on your server os.. Check Drush Installation instructions for more details..

It's documented in Github page to under Install Manual..

> Configure your system to recognize where Drush resides. There are 3 options:
>
> Create a symbolic link to the Drush executable in a directory that is already in your PATH, e.g.:
>
> $ ln -s /path/to/drush/drush /usr/bin/drush
>
> Explicitly add the Drush executable to the PATH variable which is defined in the the shell configuration file called .profile, .bash\_profile, .bash\_aliases, or .bashrc that is located in your home folder, i.e.:
>
> export PATH="$PATH:/path/to/drush:/usr/local/bin"
>
> Your system will search path options from left to right until it finds a result.
>
> Add an alias for drush (this method can also be handy if you want to use 2 versions of Drush, for example Drush 5 or 6 (stable) for Drupal 7 development, and Drush 7 (master) for Drupal 8 development). To add an alias to your Drush 7 executable, add this to you shell configuration file (see list in previous option): $ alias drush-master=/path/to/drush/drush
>
> For options 2 and 3 above, in order to apply your changes to your current session, either log out and then log back in again, or re-load your bash configuration file, i.e.:
>
> $ source .bashrc
>
> NOTE: If you do not follow this step, you will need to inconveniently run Drush commands using the full path to the executable "/path/to/drush/drush" or by navigating to /path/to/drush and running "./drush". The -r or -l options will be required (see USAGE, below).
>
> Test that Drush is found by your system:
>
> $ which drush

---
Tags: drush
---


title: Imagecache percentage resize

text:
# Question
Title: Imagecache percentage resize
I just noticed imagecache on my Drupal-7 site is not allowing percentages for resizing images.

This is making it impossible to size images to the full width of my header region.

Does anyone know if there is a configuration I might be missing or an add-on module which will allow percentages?

# Answer
> 1 votes
You can use the module ImageCache Actions with a custom script:

```
image_gd_resize($image,$image->info['width']*0.5,$image->info['height']*0.8);
return $image;

```

and there is a sandbox project that maybe is not ready for production...

---

Update:

ImageCache Actions supports **Scale / Resize by percent** since 7.x-1.5

---
Tags: 7, media
---


# Question
Title: Why are the images missing in newsletter emails created using Simplenews?
I have created newsletter using the Simplenews module. I have inserted images using the WYSIWYG editor. The mail received is missing those images. There is no indication of images in the newsletter. How to make the images appears in the newsletter email?

mailsystem: SMTP

# Answer
> 1 votes
For Sending newsletter with image you have to send mail in HTML format not in text format. One more thing for Html mail format you have to use Mimemail or Html mail.

Mail content images have absolute src path. So that image will be accessible by email.

---
Tags: 7, emails
---


# Question
Title: Set a theme for a single content types edit page
How do you set the theme for the edit page for just one content type on your site? I am using bootstrap for non-admin pages and using the default seven for the admin pages. So basically I need to override the admin theme of seven with the bootstrap theme, but only for one content type.

Any help is much appreciated.

# Answer
Using hook\_menu\_alter you can override even the theme a path uses.

```
function hook_menu_alter( &$items)
{
    $items['path']['theme callback'] = 'variable_get';
    $items['path']['theme arguments'] = array('theme_default');
}

```

like this you set the theme for that path to whatever the user theme is, even for admins.
> 1 votes

# Answer
Use Content Theme module to assign theme for content creating, editing, and viewing pages.

This module features are :

* Assign a theme to all content. (This overrides the system default theme)
* Assign a theme to a content type. (This overrides content wide themes and system default)
* Assign a theme to a content node. (This overrides content type themes, content wide themes, and system default)
* Allow to use different themes on content creating/editing pages than on viewing pages. Fine-grained permission control.
> 1 votes

---
Tags: theming
---


# Question
Title: What is the convention for naming routes?
Lets say I have these paths:

```
/admin
/admin/settings
/admin/settings/myentities
myentity/id
/admin/settings/myentities/id/edit
/admin/settings/myentities/id/delete

```

What would be the proper route names for each one of them?

My current usage is this:

**admin**

```
/admin

```

**admin.settings**

```
/admin/settings

```

**admin.settings.myentities OR admin.myentities**

```
/admin/settings/myentities

```

**myentit OR myentity.view**

```
/myentity/id

```

**myentity.edit OR admin.myentities.edit OR admin.settings.myentities.edit**

```
/admin/settings/myentities/id/edit

```

The things I mostly not sure about is whether I should use the path structure for the route name or not(ie. /path/to/some/where =\> path.somewhere OR path.to.some.where) and when it comes to entities if I should use admin.myentities + admin.myentities.myentity OR admin.myentity.edit) etc..

# Answer
By design, the route name should NOT mirror the path. You want to be able to change the path without breaking the route name, which is why other code in the system should refer to the route name only, not the path. Having a route name that maps directly to the path is akin to a CSS class named .left-align-blue :-)

Some of these conventions are still shaking out. However, for the typical case the recommended pattern is $module\_name.$something\_meaningful. So in your mymodule module, you'd have routes like:

```
mymodule.settings
mymodule.advanced_settings
mymodule.status_page

```

And so on. Note those tell you little about the path. That's by design, as above.

For entities it's a little bit trickier since core has the advantage that most entities are the same name as the module. Contrib doesn't always have that. I would recommend either $entityname.$operation or $module\_name.$entityname\_$operation. (I don't think core has any double-period route names at present, but I could be wrong.)

So if I were writing a module with a new entity called "nerd" (it's a candy site), I'd have:

```
nerd.view (for the page that lets you view a nerd)
nerd.edit (for the edit page)
nerd.delete (for the delete confirmation page)

```

And so on. Make sense?
> 10 votes

---
Tags: 8, routes
---


# Question
Title: Why do many functions now require more code than the equivalent functions of the previous version?
Every time I read about how to convert code from D7 to D8 is seems like the D8 version is longer.

For example drupal\_goto was:

```
drupal_goto('user');

```

and the D8 equivalent is:

```
return new RedirectResponse(\Drupal::url('user.page'));

```

And an example hook\_init in D7:

```
function mymodule_init() {
  if (!empty($_GET['redirect-me'])) {
    drupal_goto('http://example.com/');
  }
}

```

And the equivalent is D8 is:

mymodule.services.yml

```
services:
  mymodule_event_subscriber:
    class: Drupal\mymodule\EventSubscriber\MymoduleSubscriber
    tags:
      - {name: event_subscriber}

```

and then also:

```
namespace Drupal\mymodule\EventSubscriber;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
class MymoduleSubscriber implements EventSubscriberInterface {
  public function checkForRedirection(GetResponseEvent $event) {
    if ($event->getRequest()->query->get('redirect-me')) {
      $event->setResponse(new RedirectResponse('http://example.com/'));
    }
  }
  /**
   * {@inheritdoc}
   */
  static function getSubscribedEvents() {
    $events[KernelEvents::REQUEST][] = array('checkForRedirection');
    return $events;
  }
}

```

This is only a couple of examples but it seems that to achieve anything is D8 is going to take far more code.

* Is this actually the case or am I misinterpreting whats happening.
* If this is the case then what is the advantage?
* Would it be possible / desirable to use lots of wrapper functions to reduce the amount of code to achieve simple tasks?

# Answer
> Is this actually the case or am I misinterpreting whats happening.

Yep, a lot of D8 stuff is more verbose than that of its predecessor. A huge chunk of the codebase has moved to OO based on PSR-0, so you're always going to be writing more code, more files, creating more folders to put those files in, etc.

> If this is the case then what is the advantage?

You can't directly apply an 'advantage' or 'disadvantage' to the concept of "D8 will use more code" (if that's indeed even true when you average it all out); it's simply an inevitability - the D8 page request has completely changed with the introduction of Symfony, so what was possible in a few lines in D7 just isn't possible with the same code now. The *overall* advantage is that Drupal gets all the power of Symfony driving it, and Symfony's framework/request lifecycle is generally considered to be stable and to use good practice. Plus, introducing a strict DI methodology to any kind of project is a big win in my opinion.

> Would it be possible / desirable to use lots of wrapper functions to reduce the amount of code to achieve simple tasks?

Possible? Of course. Desirable? Depends on your opinion, and what you're creating a wrapper for. If it's something you do 10 times a day, and you can shorten 10 lines to 1 or 2 lines, then you'd be mad *not* to do it. Obviously that attitude transcends Drupal/PHP and should apply to any language/technology.

> This is only a couple of examples but it seems that to achieve anything is D8 is going to take far more code.

The *anything* there isn't true - some things will be more verbose, some things less, it depends on exactly what you're looking to do.
> 11 votes

# Answer
Also bear in mind that most of the code samples in change notices and such are lacking in context. That means they have to call out to context (like the DIC, or the request object, or whatever) explicitly, which is something that a well-behaved module should almost never do.

The biggest architectural shift in Drupal 8 is away from "there's always a globally-accessible function and some globally-accessible state data you can leverage" to "you need to tell the system to give you the context and services you're going to need". That's a prerequisite of testability and loose coupling, which are priorities for Drupal 8.

In places where you're expected to be doing certain things there are already utility methods. For instance, if you're using the common controller base class there is a $this-\>redirect($route\_name) method ready for you; that's not appreciably more code than in Drupal 7, especially once you factor in the url() call.

That method is only available in controllers, of course... because if you're not in a controller you have no business sending a redirect. :-) You should be passing back data to the controller that has business meaning, and then the controller can interpret that as needing to send a redirect.

So it's not that it's "more code"; it's that the code needs to be better organized and separated. Once you do that, the code should actually be much more readable and far far easier to debug once you're not dealing with globals all the time.
> 4 votes

---
Tags: 8
---


title: Drupal 7 Really Slow on admin pages

text:
# Question
Title: Drupal 7 Really Slow on admin pages
I have a Drupal 7 installation and several admin pages are incredibly slow and time out after 30 seconds. I've tried several things without success:

* APC is enabled
* innodb\_buffer\_pool\_size is set to 100 M
* No unused modules are enabled. I still have 155 modules enabled, for localization, commerce, captcha, questions & answers, etc.
* Standard cache is enabled and JS/CSS compression enabled. Memcached not being used.
* Drupal 7, latest version

Even with that, the site is still really slow and there are pages that won't open (time out). For example, installing a module will always fail the first time. Accessing the settings of the Language Selection Page module will always fail, and so on. Any recommendations other than increasing the timeout?

I'm using WAMP.

**UPDATE:** The time out error shows it takes a while in this function mainly: drupal\_flush\_all\_caches( ) ..\system.admin.inc:1766

Sometimes in other functions too.

# Answer
> 1 votes
After researching a bit more, I think I was able to improve its performance a little bit.

I've changed several variables in MySQL. Some are not recommended really (the first one mainly), but as I'm in development it helps:

* Set `innodb_flush_log_at_trx_commit = 0` (Source)
* Increased `query_cache_size` and `query_cache_limit`
* Increased `innodb_buffer_pool_size`
* Changed `semaphore` table to memory by executing this script

Also,

* Disabled the `Update manager` module (not sure if it helped)
* Uninstalled the `Content Translation` (and dependent modules) as I was using `Entity translation`

# Answer
> 1 votes
If you can profile your site that's always helpful. https://drupal.stackexchange.com/questions/724/why-is-drupal-7-so-slow

https://groups.drupal.org/node/210683 \- Older post but some patches have still not been committed.
https://groups.drupal.org/node/415883 \- Speedups for the DB layer (caches mainly).

Because of windows checkout this post and this group
https://groups.drupal.org/node/242443
https://groups.drupal.org/drupal-windows

---
Tags: performance
---


# Question
Title: There is no register form but spams are sending register request in Drupal 7!
There is no register or login form in `front-page` or any other pages in my website but every day I receive emails of my website that some people asked for registration, How does such a thing is possible and how do they do this?

# Answer
By default there's a registration form at /user/register; bots will find it trivial to discover and submit that form.

If you really don't want that path to be accessible you can just use a menu alter to deny access:

```
function MYMODULE_menu_alter(&$items) {
  $items['user/register']['access callback'] = FALSE;
}

```
> 3 votes

# Answer
Go to `admin/config/people/accounts` and configure : Registration and cancellation for administration only
> 3 votes

---
Tags: advertising, users
---


# Question
Title: How do I post a node that has its created field set to the past in a test class?
I am creating a test class using the framework of the core **Testing** module for a module that is supposed to autoexpire nodes some time after they've been created.

Nodes have two timestamp fields: `changed` and `created`. I've tried to use the following code inside my test class (subclass of `DrupalWebTestCase`) to post an article that is supposed to have been created some time ago:

```
  // Post an article.
  $edit = array();
  $edit["title"] = $this->randomName(8);
  $edit["body[und][0][value]"] = $this->randomName(16);
  $edit['changed'] = 1397700000; // This is accepted.
  $edit['created'] = 1397700000; // This fails.
  $this->drupalPost('node/add/article', $edit, t('Save'));

```

The above code snippet produces the following error message when the test is run:

> Failed to set field created to 1397700000

Do anyone know how to explicitly set the `created` field to some specified Unix timestamp date for a node created inside a test class?

# Answer
When you access node create form using admin role created value is exposed using Authored Information...

So, You can able to set created date by creating user with administrator role for testing...

Please see implementation below..

```
<?php

/**
 * Tests the functionality of the Simpletest example content type.
 */
class SimpletestExampleTestCase extends DrupalWebTestCase {
  protected $privileged_user;

  public static function getInfo() {
    // Note: getInfo() strings are not translated with t().
    return array(
        'name' => 'Simpletest Example',
        'description' => 'Ensure that the simpletest_example content type provided functions properly.',
        'group' => 'Examples',
    );
  }
  public function setUp() {
    // Enable any modules required for the test. This should be an array of
    // module names.
    parent::setUp(array('simpletest_example'));
    // Create and log in our privileged user.
    $user = $this->drupalCreateAdminUser();
    $this->drupalLogin($user);
  }

  public function drupalCreateAdminUser(array $permissions = array()) {
    $roles = user_roles();
    $index = array_search('administrator', $roles);
    $user = $this->drupalCreateUser($permissions);
    $user->roles[$index] = 'administrator';
    return user_save($user);
  }

  /**
   * Tests creation of a Simpletest example node.
   */
  public function testSimpleTestExampleCreate() {
    // Create node to edit.
    $edit = array();
    $edit['title'] = $this->randomName(8);
    $edit["body[und][0][value]"] = $this->randomName(16);
    $edit["date"] = "2012-04-19 22:54:38 +0530";
    $this->drupalPost('node/add/article', $edit, t('Save'));
    $this->assertText(t('Simpletest Example Node Type @title has been created.', array('@title' => $edit['title'])));
  }
}

```

Here is the output
> 2 votes

# Answer
The value for `created` isn't exposed to the node form, it comes directly from `node_object_prepare()`. So there's no way to override it using form values unfortunately.

The only way to adjust the created timestamp when it comes through a node form submission is to implement `hook_node_presave()`. The easiest way to do this would be for your test to require a companion module, which implements that hook.

There is precedent for this: the core node tests include the node\_test module, which implements `hook_node_presave()`, so `NodeSaveTestCase::testTimestamps()` can test that `created` dates can be overridden...

```
function node_test_node_presave($node) {
  if ($node->title == 'testing_node_presave') {
    // Sun, 19 Nov 1978 05:00:00 GMT
    $node->created = 280299600;
    // Drupal 1.0 release.
    $node->changed = 979534800;
  }
  ...

```

After creating the module you just need to declare it as a dependency in the `setUp` method, e.g.

```
parent::setUp('MYMODULE_test');

```

And you should be able to test properly.
> 1 votes

---
Tags: 7, testing
---


# Question
Title: Migrate old admin's posts to his new user
I'm taking over maintenance of a Drupal site but the old admin is staying on as a user.

I need to adjust the ownership of the posts currently under uid 1.

Is this query sufficient or is uid associated with a blog post in other ways?

Is there an admin module for this process?

```
UPDATE `drupal_node_revisions` r,
`drupal_node` n
SET n.uid = 13392, r.uid = 13392
WHERE
r.uid = 1
AND n.uid = 1
AND n.type = 'blog'
AND r.nid = n.nid

```

# Answer
Node data is stored in node table also.. It's a bad practice to change node content directly using sql queries...

You can use Views Bulk Operations (VBO) module to change node authors in bulk...

> This module augments Views by allowing bulk operations to be executed on the displayed rows. It does so by showing a checkbox in front of each node, and adding a select box containing operations that can be applied. Drupal Core or Rules actions can be used.
> 3 votes

---
Tags: database, nodes, users
---


# Question
Title: Display categories in views to get chosen and to display specific tags
I wonder if there is a possibility to display categories and after clicking them, views display only specific category's items. Is it possible?

# Answer
Yes, You can able to list taxonomy terms of specific vocabulary using views.

You need to create a custom block and a view for this..

* A custom block, Which lists all vocabularies .. Views doesn't support vocabulary listing..
* Two, A view which lists specific vocabulary terms. You need to pass vocabulary id to this view in an URL and read it using contextual filters to filter the terms by category.

You can get list of vocabularies using below api function..

taxonomy\_get\_vocabularies

Link the vocabularies terms to some path like category/list-terms/{vid} .. make category/list-terms/% as your view path and read the argument using contextual filter vocabulary id to list terms..
> 0 votes

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


# Question
Title: How to change the title of submit button when someone register in mailchimp?
I want to be able to change the title of the submit button of the Mailchimp block when someone subscribes or unsubscribes to mail chimp list. I'm using mailchimp block on D7. How shall I do it?

# Answer
> 1 votes
As mentioned, you'll want to use hook\_form\_alter(). You can check if the user has subscribed with mailchimp\_is\_subscribed() and change the submit button text accordingly.

```
/**
 * Implements hook_form_alter().
 */
function my_module_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'mailchimp_lists_user_subscribe_form_test') {
    global $user;
    // First parameter is the list id, which can be found here:
    // https://polkaspots.zendesk.com/hc/en-us/articles/201070513-Where-can-I-find-my-MailChimp-API-key-and-List-ID
    $form['submit']['#value'] = mailchimp_is_subscribed('123abc', $user->mail) ? t('Unregister') : t('Register');
  }
}

```

# Answer
> 0 votes
You could use the `hook_form_alter()` hook or install the string overrides module if you don't wish to write any code.

---
Tags: forms, emails
---