# Question
Title: Will migrating content types be possible?
I have a Drupal 7 site with 40 content types. When Drupal 8 will be released than I would like to migrate these content types.

Would this be possible, or would I have to create this content types from scratch?

# Answer
I guess the best place to search for upgrade process is **UPGRADE.txt** file. Here you can find the step-by-step approach to follow in upgrading the site from Drupal 6/7 to Drupal 8.

Drupal 8 core will include a robust data migration API: https://drupal.org/node/2121299, part of the IMP initiative: https://groups.drupal.org/imp . Also you can check the recently updated list of modules that are included in Drupal 8 core: http://blog.merge.nl/2014/01/21/drupal-which-drupal-7-modules-went-into-drupal-core

Few of the links that you check:

1. Getting your site ready for Drupal 8: http://www.acquia.com/blog/getting-your-site-ready-drupal-8
2. Drupal 8 - Improved upgrade process: http://www.acquia.com/blog/d8migrate
3. Converting modules from Drupal 7 to Drupal 8:http://webchick.net/upgrade-modules-d8
4. Converting 7.x modules to 8.x: https://drupal.org/update/modules/7/8
> 18 votes

# Answer
Bas is right, but there is a lot of activity going on regarding this topic, so here is a more up-to-date (November 2015) answer:

Given the big difference in architecture between Drupal 7 and 8 there is no direct upgrade path, but Drupal 8 offers various *migrate* tools to *upgrade* sites from Drupal 6 and 7 to 8.

Using the core modules **Migrate** and **Drupal Migrate** and the contrib module **Drupal Upgrade** you can migrate all 40 content types from Drupal 7 to 8.

These modules allow you to migrate content types, content, comments, fields, vocabularies, terms and other Drupal 7 core entities and entity types (views, for example, cannot be migrated yet). Read about Drupal 7 to 8 upgrades.

With Drush and the contrib module Migrate tools you can select which content types to migrate. Read about executing a Drupal 7 to 8 upgrade.

Make sure you do not create any of the 40 content types before starting the upgrade. Read more about preparing an upgrade.
> 1 votes

# Answer
You can try to "upgrade" using the D8 core migrate module. Also install the contrib module migrate\_plus. It allows you to convert custom content types, users, comments, taxonomy, etc. Most common fields should be covered. If you got something really custom going on, like a custom module, you'll also have to do some programming. But if you only used the essentials of D7, migrate might have you covered. In any case you'll have to rebuild a new site and migrate the content there, so it's not a painless solution in any sense.

Your most up to date documentation is found here: https://www.drupal.org/upgrade/migrate
> 0 votes

---
Tags: 8, migrations, upgrading
---


title: Same user for multiple sites

text:
# Question
Title: Same user for multiple sites
I am planning to use different server for multiple purpose. like

Groups.eg.com

Privatecontent.eg.com

review.eg.com

etc... I have up to 5 different subdomains and everything runs in different server and different drupal installation.

I want to use the same user base across all these sites.

I am aware that if a single drupal installation have multiple sites we achieve this using domain module.

Is there a best solution for my use case. Because we are going to load 10k users in the site.

# Answer
> 0 votes
Sounds like Bakery module would meet the requirements for you. It will handle single sign-on between Drupal sites on different sub-domains.

As far as performance goes, Bakery is used by drupal.org when you switch between https://www.drupal.org, https://groups.drupal.org, https://assoc.drupal.org and others.

What it doesn't do is to switch between different domains like `drupal.org` and `drupal.com`. Bakery also doesn't sync user information, if you have user fields.

For more advanced features like SSO between Drupal and non-Drupal, look at CAS module, or some of the other single sign-on solutions.

---
Tags: users, domain-access, subsites, cookies
---


title: Running drush as regular user

text:
# Question
Title: Running drush as regular user
I've recently upgraded to Drush 8, from Drush 6.2 (That was installed using pear).

Drush on cPanel runs fine as root, but when I try to run it as a regular user in a valid Drupal directory I get the error:

```
Command pm-refresh needs a higher bootstrap level to run - you will need to invoke drush from a more functional Drupal environment to run[error]

```

this command

Or for just trying to clear cache using drush cc all:

```
No Drupal site found, only 'drush' cache was cleared

```

And when I add --debug to the end of a command I get a mysql error with drush:

```
Access denied for user 'username'@'localhost'

```

# Answer
I was able to get to the bottom of this problem. When I ran drush in debug mode, for example "drush status --debug" it outputted an error that it could not connect to the database.

After hours of digging for some reason on this particular cPanel server there were .my.cnf files in each user's home directory which contained mysql authentication details. Drush was taking precedence on these credentials and in turn not able to connect to the particular Drupal install's database. I simply did "rm -rf /home/username/.my.cnf to delete each of these hidden files, then running drush works!
> 1 votes

---
Tags: drush, 8
---


# Question
Title: How can I retrieve the value of a field in a flagging?
I have a global flag, `spam`, that has a textfield, `reason`, attached to it.

According to the Flag API documentation, I know I can check whether a user is flagged like this:

```
$spam && $spam->is_flagged($account->uid)

```

However, in this case, I want to retrieve the flagging, and then check the value of a field in that flagging. I didn't see any directions for doing so in the documentation, so I'm at a loss about how best to proceed.

# Answer
According to the Flag API

flagging\_load

> Loads a flagging entity. Parameters
>
> $flagging\_id: The 'flagging\_id' database serial column.
>
> $reset: Whether to reset the DrupalDefaultEntityController cache. Return value
>
> The entity object, or FALSE if it can't be found

Therefore something like this might work:

```
$flaggings = flag_get_user_flags('node', $node->nid);
if (isset($flaggings['spam'])) {
    $flagging = flagging_load($flaggings['spam']->flagging_id);
}

```

You will then find your field in:

```
$flagging->field_reason

```
> 3 votes

---
Tags: flags
---


# Question
Title: Add panelizer display when create a node programmatically
I create a node programmatically on hook\_enable of mu custom module. I have panelizer display for this content type and I want to set when create a node programmatically. Can you help me ?

# Answer
Here is some example code for creating a node and setting the panelizer variant/display automatically. Note: The EntityMetadataWrapper module is used for setting the title.

```
  $entity_type = 'node';
  $bundle = 'page';
  $variant = 'YOUR_VARIANT_NAME';
  $variant_name = $entity_type . ":" . $bundle . ":" . $variant;

  $values = array(
    'type' => $bundle,
    'uid' => 0,
    'status' => 1,
    'comment' => 0,
    'promote' => 0,
  );

  $entity = entity_create($entity_type, $values);

  ctools_include('export');

  $panelizer = ctools_export_load_object('panelizer_defaults', 'names', array($variant_name));
  $entity->panelizer['page_manager'] = $panelizer[$variant_name];

  $wrapper = entity_metadata_wrapper('node', $entity);
  $wrapper->title->set('Your Title');

  $wrapper->save();

```
> 0 votes

---
Tags: panels
---


title: Site install fails with Aegir

text:
# Question
Title: Site install fails with Aegir
I've been using Aegir to install Atrium sites without a hitch. Users self register through Aegir to spawn their own open atrium sites. Today I noticed new atrium sites failed to install. A week ago this worked fine and as far as I know nothing has been changed with core content/modules. I did some comparisons in looking at the task log between the failed install and a successful install (from a week ago). The simplexml load and "Could not download project status information" is weird. Here's what I gathered so far. Task install log looks identical until near the end. The failed install shows the following after "downloading release history…":

```
Downloading release history from http://updates.drupal.org/release-history/drupal/6.x
simplexml_load_file(): 6.x:2: parser error : Specification mandate value for attribute http-e pm.drush.inc:2103
simplexml_load_file(): s="http://www.w3.org/1999/xhtml">
simplexml_load_file(): ^ pm.drush.inc:2103
simplexml_load_file(): 6.x:2: parser error : attributes construct error pm.drush.inc:2103
simplexml_load_file(): s="http://www.w3.org/1999/xhtml">
simplexml_load_file(): ^ pm.drush.inc:2103
simplexml_load_file(): 6.x:2: parser error : Couldn't find end of Start Tag meta line 2 pm.drush.inc:2103
simplexml_load_file(): s="http://www.w3.org/1999/xhtml">
simplexml_load_file(): ^ pm.drush.inc:2103
simplexml_load_file(): 6.x:12: parser error : Opening and ending tag mismatch: p line 11 and body pm.drush.inc:2103

```

This goes on for several more lines - finally ending in the following error:

```
Could not download project status information from http://updates.drupal.org/release-history/drupal/6.x

```

This compares to This compares to the successful site task install log here:

```
Downloading project drupal to /tmp/drush_tmp_1368706259 ...
Downloading drupal-6.28.tar.gz was successful.
Md5 checksum of drupal-6.28.tar.gz verified.
Verifying signature for svn version control engine.
Verifying signature for bzr version control engine.
Project drupal (6.28) downloaded to /var/www/vhosts/site.com/platforms/atrium-1.0/drupal-6.28.
Project drupal contains: - 1 profile: default - 6 themes: pushbutton, min... (Expand)

```

The diff analysis looks similar again for many more lines, then shows the following error for the failed install log:

```
WD form: Illegal choice 5 in Roles allowed to use this profile element.
WD form: Illegal choice 6 in Roles allowed to use this profile element.

```

The rest of the task log for the failed install shows typical Aegir behavior of dropping the database and deleting directory.Searching through my general site logs, or when I run cron, I get

"Unable to fetch any information about available new releases and updates." I also get that error when I try to manually run cron Also a few other things like:

```
Warning: include() [<a href='function.include'>function.include</a>]: Unable to allocate memory for pool. in theme_render_template() (line 1079 of/var/www/vhosts/site.com/hostmaster-6.x-1.4/includes/theme.inc).

An illegal choice has been detected. Please contact the site administrator.

```

The "unable to fetch information about new releases..." error is weird and similar to the Aegir error on the failed install task log. Unfortunately I don't know where to start. I'm wondering if this is a write permissions issue with drush, or php version issue. It;s starnge that it's happened suddenly, so maybe Aegir changed something on the fly. Don't know... Any thoughts? Thanks!

# Answer
This line says it all: Could not download project status information from http://updates.drupal.org/release-history/drupal/6.x

Probably not a problem you or Aegir could do anything about. Just an Internet hickup.
> 0 votes

---
Tags: aegir
---


# Question
Title: Remove every Javascript except own theme scripts
In my current Drupal 6 installation, a lot of Javascript scripts are being loaded (core scripts, jQuery, modules, etc).

I only have one script in my theme that I need, so I want to only include that file and get rid of everything else.

What's the best way to accomplish this?

# Answer
In your `template.php` you can override the generation of `$vars['scripts']` to be just your file.

However, I suspect that this is a really bad idea and may have a lot of consequences.
> 2 votes

# Answer
You can put something like this in your template.php:

```
function phptemplate_preprocess_page(&$vars) {
  drupal_add_js($theme_path . '/js/your_js.js', 'theme');

  $js = drupal_add_js();
  unset($js['core']);
  unset($js['module']); // or
  unset($js); // but then it would also clear the drupal_add_js above
  $vars['scripts'] = $js;
}

```
> 2 votes

# Answer
Drupal ships jQuery as a default JavaScript library. It is not included to the system unless a JavaScript code is added by recommended way using:

* Adding an entry to `scripts` array in theme info (ini) file
* Calling drupal\_add\_js()

A number of other scripts are also added by core and modules.

You can manage to stop them by overriding `phptemplate_preprocess_page` function in your themes' `template.php`

If you want to include a single JS file due to performance penalty of loading a lot of script you can turn on `Optimize JavaScript files` at `example.com/admin/settings/performance`. After enabling it you will have to flush cache in order the changes to take effect.
> 1 votes

# Answer
This is a pretty old issue but I can't really see a good solution on here so I thought I'd write one.

Basically what you need to do in your template.php is use `hook_js_alter($js)` then use devel (or what ever you prefer to debug with) to see what the `$js` array has in it.

Unset what you do now want to have included. Be aware that you'll lose quite a lot of functionality if you remove drupal.settings.

I would advise keeping jQuery. If you must use another version of jQuery use the jquery update module (http://drupal.org/project/jquery\_update), or if you are importing JS from another source then just make sure that your version is loaded above where drupal.settings is loaded.
> 0 votes

# Answer
Drupal only has one sanctioned mechanism for removing specific assets, regardless of the motivation for doing so.

For CSS:

`hook_css_alter`

For JS:

`hook_js_alter`

**To remove all style and scripts except `.info` style and script use below codes:**

```
function hook_css_alter(&$css) {
    $themes=list_themes();
          foreach($css as $key=>$item) {
            if (!in_array($key, $themes['yourthemename']->stylesheets['all'])) {
                unset($css[$key]);
            }
        }
}

function hook_js_alter(&$js) {
    $themes=list_themes();
    foreach($js as $key=>$item) {
        if (!in_array($key, $themes['yourthemename']->scripts)) {
            unset($js[$key]);
        }
    }
}

```

If the theme/module is custom, then obviously you can just remove the offending code manually if that makes more sense.
> 0 votes

---
Tags: 6, javascript
---


# Question
Title: Migrating data from Drupal 6 to 7 with a twist
I am working on an update of a site from Drupal 6 to 7. The site will have a complete redesign and - since the structure is somewhat chaotic - I don't want to migrate the complete data.

On the current site, articles are stored in 6 different content types which are different only by name, but have the same fields. I want to migrate them to the standard "article" type and only add a tag which will indicate which section they belong.

On the current site, images were uploaded to the server and then just linked from the teaser. I want them stored in an image field on the new site, and I need to modify the teaser too before inserting to the new site.

Can I do this on database level with a php script or should I do this in Drupal? In that case - how do I communicate between the old and the new version?

Or is there a module for this? What I need is:

1. Move all articles (6 content types) to new site (about 500 articles), all in the article content type and set a tag based on the original 6 content types
2. Catch images in teasers, make them drupal managed files and attach them to the correspondig node
3. Delete the image tags from the teasers (they will be displayed from the image field)
4. Retain paths and tags for the nodes as we have a lot of indexed pages

Is this possible or shuld I choose another path?

**EDIT:** Ok, I can insert nodes in the new system by code and add taxonomy terms as required, but I still trying to figure out how to add images and the way of communication between the two systems.

**EDIT** Thanks everyone for the ideas. I solved the problem by writing a custom module that communicated with the D6 install and pulled the nodes I needed.

# Answer
> 2 votes
In my experience the Migrate Module works really well for this.

In your migration you could use `Preparerow()` method to modify the fields you want to change before the import.

You can find more documentation on it here: Advanced Field Mapping Drupal Migration Documentation

Hope it helps :)

# Answer
> 0 votes
To put a fine point on Vic's answer, you'll find Migrate\_D2D does most of the heavy lifting you'll need to migrate content where Drupal is both the source and target. Migrate is great for generic data migrations, such as from CSV, MySQL, and other non-Drupal native data sources. There is a migrate\_d2d\_ui submodule that may serve your purposes if you're uncomfortable with code. In my uses,however, I found coding the migration per Drupal object type well worth the time. Like Drush, the time you invest in learning migrate and migrate\_d2d has big payoff.

---
Tags: migrations
---


# Question
Title: Ajax error while uploading or removing file through managed file
I am getting following error while using managed file through my custom form.

> "An Ajax HTTP request terminated abnormally."

Also, I updated my jquery version to latest using jquery\_update module. Still no any benefit.

Any idea on how to solve it?

**EDIT:**

Code

```
  $form['path_image'] = array(
    '#title' => t('Image'),
    '#type' => 'managed_file',
    '#description' => t('The uploaded image will be displayed on the page unless it is marked as "removed".'),
    '#default_value' => $current_image,
    '#upload_location' => 'public://subpage_banner/',
  );

```

# Answer
> 0 votes
**MaxRequestLen** sometimes gets lowered as a result of server/module updates. Also, adding modules that add to the request length can also introduce this problem. This is why disabling modules can sometimes "fix" the problem.

See http://drupal.org/node/1015938#comment-7412202 for a solution that involves updating your vhost file, eg:

```
<IfModule mod_fcgid.c>
  # 50MB
  MaxRequestLen 52430000
</IfModule>

```

Or try switching from **FastCGI** to **mod\_php** or **php-fpm** (if you're using FastCGI).

# Answer
> 0 votes
Anyone having lots of AJAX issues might want to try disabling the jquery\_update module. It is because some modules and library scripts work with different versions of jQuery.

# Answer
> 0 votes
One reason for this error may be permissions. Please check that the upload AJAX menu item has the right access argument `$items['file/ajax']['access arguments']` and no module else hooks and changes its default value.

# Answer
> -1 votes
It's a jquery\_update issue. Check with lower version of jquery.

---
Tags: ajax, files
---


# Question
Title: How to make the permissions of a module more granular?
Assume a (contributed) D7 module, say module **ABC**, comes with only a few permissions (which can be set on the typical `/admin/people/permissions` page). For example:

* Administer module ABC.
* Access (view) "*all results*" produced by module ABC.

Whereas "*all results*" can be found within a site via a combination of URLs (with corresponding menu items also) like:

* ABC/SomethingX (X=1, 2, ...).
* ABC/SomethingElseY (Y=1, 2, ...).
* node/\*/ABC.

Which site building techniques can be used (without hacking the module), to grant access to such URLs as in this example:

* Access to `ABC/SomethingX` is allowed for anybody.
* `ABC/SomethingElseY` is only allowed for authenticated users.
* `node/*/ABC` is only allowed for authenticated users.
* For any URL that is only allowed for authenticated users, its corresponding menu item should be visible to anonymous also. This to show such users that such menu item is available, but with some type of Drupal message to inform them that login is required to actually use such link.

# Real world situations (use cases):

* The question about "content access + menu block =\> not shown all links in menu block": by using the Content Access module access to selected nodes is restricted (of course). But how can menu items corresponding to such selected nodes remain visible for anonymous users anyway?
* The Visitors module: replace 'ABC' by 'visitors' in the example above, and assume that you want to grant access to "some" reports (= `ABC/SomethingX`) for anybody, but not to "some other" reports (= `ABC/SomethingElseY`).

If permission `Access (view) "all results" produced by module ABC` would be set to "authenticated", then anonymous users cannot see any URL. While if that permission would be set to "anybody" (= either "anonymous" or "authenticated"), then anonymous users also have access to (eg) `ABC/SomethingElseY` (which is not what is desired).

How can menu items corresponding to `ABC/SomethingElseY` remain visible for anonymous users anyway?

# Answer
> 0 votes
Rules (the module) is your friend ... Here is the rule (in Rules export format), that does exactly what this question is about (using the Visitors module as an example, like the *ABC* in the question):

```
{ "rules_limit_access_to_some_urls_related_to_visitors_" : {
    "LABEL" : "Limit access to some URLs containing \u0027visitors\u0027",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "init" : [] },
    "IF" : [
      { "user_has_role" : {
          "account" : [ "site:current-user" ],
          "roles" : { "value" : { "1" : "1" } }
        }
      },
      { "OR" : [
          { "data_is" : {
              "data" : [ "site:current-page:path" ],
              "op" : "IN",
              "value" : { "value" : [
                  "visitors\/hosts",
                  "visitors\/hits",
                  "visitors\/referers",
                  "visitors\/user_activity",
                  "visitors\/pages"
                ]
              }
            }
          },
          { "text_matches" : {
              "text" : [ "site:current-page:url" ],
              "match" : "node\/\\d+\/visitors",
              "operation" : "regex"
            }
          }
        ]
      }
    ],
    "DO" : [
      { "redirect" : { "url" : "visitors" } },
      { "drupal_message" : {
          "message" : "Access to the content located at \u0022\u003Cstrong\u003E[site:current-page:path]\u003C\/strong\u003E\u0022 is not allowed.\r\n\u003Cbr \/\u003E\r\nAnonymous users can only see its corresponding menu item (login required).",
          "type" : "warning"
        }
      }
    ]
  }
}

```

After you enable the above rule, you can safely grant `Access (view) "all results" produced by module ABC` permission to anybody. That will make the menu items visible to anonymous users also (of course). The above rule will ensure that anonymous users will NOT be able to actually "view" the specified URLs. Instead they'll get a message starting with "*Access to the report located at ...*".

To make the above rule work in similar situations, just adapt the URLs (change 'visitors' to whatever fits), and the message to be shown for those who are not allowed to access those URLs.

Possible variations: instead of using the above rule for anonymous versus authenticated users, it can also be used for any combination of 2 roles. eg: "authenticated" versus "editors" (or whatever other role), in which case you'd grant the permission to "authenticated" (and use the role id for authenticated users).

**Remarks**:

* This won't prevent the path from being omitted from menus. But that is exactly what is desired (as mentioned in the last phrase of the question).
* What is above does not relate to any "other places" where path checks happen that aren't direct page access. But whenever one attempts to use those paths in those "other places" to actually visit such paths (URLs), the above rule will catch those situations also (provided such URL is correctly mentioned in either of the Rules Conditions in my sample above).

---
Tags: 7, rules, users
---


title: Restricting block changes

text:
# Question
Title: Restricting block changes
How can you let an editor edit the text in a block, but not make other configuration changes, as moving the block from one region to another?

# Answer
> 0 votes
After coming back to this question after a year or so, there are two methods that are very simple.

Create a block and put the following code in the block body:

```
<?php
$node = node_load(77);//77 is the nid of the node I want to put in the block.
$node_content = node_view($node,"full");
print render($node_content);
?>

```

Or you can create a view block and filter on the node id.

Now you give someone permission to edit the content type but not permission to create or delete it.

# Answer
> 6 votes
In Drupal, only the users with the permission to administer blocks can change the block settings, including which region the block is assigned.

As far as I know, there aren't modules that allow to assign to users a more granular permission. You should write your own custom module that shows only the fields that a user is allowed to edit.

For example, the following code would alter the form build from block\_admin\_configure(), the function that build the configuration form for any block, to permit to users with the "edit block titles" permission to edit the block title.

```
function mymodule_form_block_admin_configure_alter(&$form, &$form_state, $form_id) {
  if (isset($form['settings']['title'])) {
    $form['settings']['title']['#access'] = user_access('edit block titles');
  }
}

```

The function is the implementation of hook\_form\_FORM\_ID\_alter() made for a module named mymodule.module.

The fields for the region settings (the theme regions a block is output) are contained in `$form['regions']`; The field set contains a select field for each enabled them.
To show the field set only to users with the "edit block regions" permission, you can use the following code, for example.

```
function mymodule_form_block_admin_configure_alter(&$form, &$form_state, $form_id) {
  if (isset($form['regions'])) {
    $form['regions']['#access'] = user_access('edit block regions');
  }
}

```

Users with the permission to administer blocks could alter the region assigned to blocks from http://example.com/admin/structure/block. To not allow the user without the "edit block regions" permission to access that page, you should alter the access handler of that menu, and replace the default access handler with a custom one that would return `FALSE` when users don't have that permission.
For more information, see hook\_menu and hook\_menu\_alter().

# Answer
> 5 votes
See the Block Access module.

> This module adds a set of global permissions for creating, viewing, moving, enabling, disabling and configuring blocks as well as permissions at the individual block level.

# Answer
> 0 votes
One simple solution I would recommend is checking out the Boxes module. This module is going to provide a nice inline editing options (via AJAX) for blocks, which would make it super easy for editors to change the text in the blocks. The permissions would still need to be "administer blocks" for the editors, but since they will now be able to edit blocks inline there's really no need for them to ever get to the block configuration page.
Now if you still insist on removing access to that block configuration page you can just do a simple menu alter that changes the permission required for the block configuration page such as the following code.

```
function hook_menu_alter(&$items) {
  //Example Use Case, switching permission from "administer block" to "administer site configuration"
  $items['admin/structure/block']['access arguments'] = array('administer site configuration');
}

```

# Answer
> 0 votes
The Bean module is a possible alternative to answer this question. Here is a quote about its project page:

> Think of a Bean as a method to provide new types (compared to node this would be a content type) which then provides an add content interface to create as many blocks as you require (see screenshot below). The bean content can then be placed around the site just like any other block.

Combined with the options available for granting the appropriate **Bean permissions**, it should give you a lot of flexibility about how exactly you want to use this (great) module in your specific case: for each individual block created with the BEAN module, you can use the typical *Permissions* page (at `admin/people/permissions`) to grant **Add/Edit/View/Delete** access to selected roles.

This module also works great in combination with the UUID and UUID Features Integration modules. And after you become familiar with the Bean module, you might find other cases in your site where you also want to use this module (which somehow compensates the fact that you need to add another module).

The video tutorial Drupal Bean module tutorial - using Bean Admin UI provides a great introduction to really understand the power of this module, and the kind of things you can do with it (by only using site building techniques, no custom coding involved). It also shows how the Bean module transforms Drupal blocks into fieldable entities.

This module only started as of D7 (because of the "entities" of course that were only introduced in D7), and already has over 22K reported installs. Those who don't use it yet should definitely start looking at it in preparation of some day upgrading to D8. Because this is what is currently shown on its project page (I added the bold markup here):

> **This module has been included with Drupal 8 core**. Refer to this issue for more information.

---
Tags: 7, blocks
---


# Question
Title: Panels problem with changing the width of columns or regions
Some times when I try to change the width of columns or regions with `Fluid Width` the panels displays the `NAN%` and it doesn't change the width

Using Firebug I got the following error

What should I do?

---

UPDATE

It only displays this javascript error in console in `flexible-admin.js` file

```
splitter.parent.css('padding-right', (splitter.right_padding + moved) + 'px');

```

# Answer
I found it. when the current language of the site is `rtl` such error reported. it must be `ltr`
> 0 votes

---
Tags: 7, javascript, panels
---


# Question
Title: How do I move a view display from a view to another one?
I have a old view named Users with two displays (All-Users and Flagged-Users) and today I create another view named Flags and I have a display named Flagged-Books, but now I want transfer my display named Flagged-Users to my view named Flags.

I search inside the view configuration and inside the display configuration and I can't found this functionality. There is a trick or a way to achieve this?

I have installed Views 3.11.

# Answer
This is tricky, but you can export both views to code and then add the desired display manually to the View.

In your case:

1. First export User view and Flags views

The exported views should be something like this:

```
$view = new view();
$view->name = 'frontpage';
$view->description = 'Emulates the default Drupal front page; you may set the default home page path to this view to make it your front page.';
$view->tag = 'default';
$view->base_table = 'node';
$view->human_name = 'Front page';
$view->core = 0;
$view->api_version = '3.0';
$view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */

/* Display: Master */
$handler = $view->new_display('default', 'Master', 'default');
$handler->display->display_options['use_more_always'] = FALSE;
$handler->display->display_options['access']['type'] = 'perm';
$handler->display->display_options['cache']['type'] = 'none';
$handler->display->display_options['query']['type'] = 'views_query';
$handler->display->display_options['query']['options']['query_comment'] = FALSE;
$handler->display->display_options['exposed_form']['type'] = 'basic';
$handler->display->display_options['pager']['type'] = 'full';
$handler->display->display_options['style_plugin'] = 'default';
$handler->display->display_options['row_plugin'] = 'node';
/* Sort criterion: Content: Sticky */
$handler->display->display_options['sorts']['sticky']['id'] = 'sticky';
$handler->display->display_options['sorts']['sticky']['table'] = 'node';
$handler->display->display_options['sorts']['sticky']['field'] = 'sticky';
$handler->display->display_options['sorts']['sticky']['order'] = 'DESC';
/* Sort criterion: Content: Post date */
$handler->display->display_options['sorts']['created']['id'] = 'created';
$handler->display->display_options['sorts']['created']['table'] = 'node';
$handler->display->display_options['sorts']['created']['field'] = 'created';
$handler->display->display_options['sorts']['created']['order'] = 'DESC';
/* Filter criterion: Content: Promoted to front page */
$handler->display->display_options['filters']['promote']['id'] = 'promote';
$handler->display->display_options['filters']['promote']['table'] = 'node';
$handler->display->display_options['filters']['promote']['field'] = 'promote';
$handler->display->display_options['filters']['promote']['value'] = '1';
$handler->display->display_options['filters']['promote']['group'] = 0;
$handler->display->display_options['filters']['promote']['expose']['operator'] = FALSE;
/* Filter criterion: Content: Published */
$handler->display->display_options['filters']['status']['id'] = 'status';
$handler->display->display_options['filters']['status']['table'] = 'node';
$handler->display->display_options['filters']['status']['field'] = 'status';
$handler->display->display_options['filters']['status']['value'] = '1';
$handler->display->display_options['filters']['status']['group'] = 0;
$handler->display->display_options['filters']['status']['expose']['operator'] = FALSE;

/* Display: Page */
$handler = $view->new_display('page', 'Page', 'page');
$handler->display->display_options['path'] = 'frontpage';

/* Display: Feed */
$handler = $view->new_display('feed', 'Feed', 'feed');
$handler->display->display_options['defaults']['title'] = FALSE;
$handler->display->display_options['title'] = 'Front page feed';
$handler->display->display_options['pager']['type'] = 'some';
$handler->display->display_options['style_plugin'] = 'rss';
$handler->display->display_options['row_plugin'] = 'node_rss';
$handler->display->display_options['path'] = 'rss.xml';
$handler->display->display_options['displays'] = array(
  'default' => 'default',
  'page' => 'page',
);
$handler->display->display_options['sitename_title'] = '1';

```

As you can see, first you have the general View config, and then the definition and config for each view's displays.

2. Then you have to select the code regarding your display in User view and copy to the code of the Flag view, so you end with a Flag view with an added display.
3. Using the import functionality of Views import the modified view.

If everything is ok, Views will import your modified view with the added display.

The two views should be similar (they should show similar content, for example).
> 7 votes

---
Tags: 7, views
---


title: Edit Drupal Commerce Confirmation Email

text:
# Question
Title: Edit Drupal Commerce Confirmation Email
I've been searching everywhere but i do not know how to edit the confirmation email sent when the checkout process is complete.

Where can I edit this?

# Answer
Its in rules

admin \> config \> workflow \> rules
> 2 votes

# Answer
I would suggest you use this module https://drupal.org/project/commerce\_invoice\_receipt and then its very easy to modify what gets sent out.

From README:

1. Drop the 'commerce\_invoice\_receipt' folder into the modules directory '/sites/all/modules/'.
2. In your Drupal site, enable the module under Administration -\> Modules '?q=/admin/modules'.
3. Setup new Commerce Order display under Store -\> Configuration -\> Order Settings -\> Manage Display '?q=admin/commerce/config/order/display'. Click on the 'Invoice/Receipt' tab. Unhide any fields you want to use in your invoice.
4. Setup a rule under Store -\> Configuration -\> Checkout settings -\> Checkout rules '?q=admin/commerce/config/checkout/rules'. Then 'Add a checkout rule', you'll find an action called 'Send invoice receipt email' under Commerce Order that you can use.

You can customize the rule to send out any info you need.
> 2 votes

# Answer
\[Using Kickstart\] you can also find the raw text and tokens for messages here:

/admin/structure/messages
> 0 votes

# Answer
install this module https://www.drupal.org/project/commerce\_message it will proivde access many type of messages along with their rules. You can configure and add your own message types
> 0 votes

---
Tags: emails, commerce
---


# Question
Title: How to do recurring subscriptions with credit card and Drupal 7
I need to implement recurring payments properly for my site. The payment model I have in mind is that as in use by linode: you sign up, pay for a linode and it will be billed forever recurring to your credit card. If you choose to make that linode larger, or order another one, you'll still be billed only once at the first day of the month, except now with the new amount.

Is there a decent module to do this under Drupal 7? I'm looking at drupal commerce and the commerce\_moneybookers module (since i already have a moneybookers merchant account) but moneybookers only provides recurring payments if you sign up for an account with them. I'm not prepared to make my customers do that.

ideas?

# Answer
> 4 votes
Been doing a bunch of research, and it seems there are two main contenders for my scenario: http://www.fastspring.com and http://www.moneyscripts.net/drupal-membership-suite

I like the second one because it is pure drupal. But I like fastspring because it's very easy to use and pricing seems to be moderate. They also offer a great range of payment methods and they are PCI-DSS certified.

I'll do some more research and let you know my final choice

# Answer
> 0 votes
This is not a complete answer to your question, but I have heard some interesting thoughts about this in Lullabot Podcast #99. The main takeaway was that they're very happy with the services from Authorize.net.

Hope that helps.

# Answer
> 0 votes
You can do recurring billing with Ubercart and uc\_recurring.

You can use authorize.net ARB or CIM, or Paypal WPP

# Answer
> 0 votes
It looks like MoneySuite is the best option if looking for a Drupal module/suite, and not an external service. It's the successor to MoneyScripts.

From the project page:

> This project is differentiated from the existing commerce modules in that it requires no special adaptation for the sale of memberships and handles one time or recurring payments through a variety of payment gateways.

---
Tags: commerce
---


# Question
Title: Include file with functions in node.tpl.php and execute them on node content
First at all, I know that this isn't the correct way to do this in D7, but I need to do in this way.

I've included a file in node.tpl.php:

```
include DRUPAL_ROOT . '/sites/all/themes/mytheme/inc/node_functions.php';

```

In this included file I have a function which, afterwards I want to call from a node's content-body.

Currently, if I call the function from a node content, I get a WSOD. I also checked if within a node-content the function exists, with a PHP function:

```
function_exists('name_of_my_function')

```

but it returns FALSE, so the function no exists in this 'scope'.

In summary, I want a collection of helpful functions included/attached to a node, but I don't want to write the include/require statement everytime I'm creating a node. I only want to simple 'call' those functions. So, how can I do it?

Thanks in advance.

# Answer
## Implementation Issues

1. Included a file in node.tpl.php
2. I have a function which, afterwards I want to call from a node's content-body

Sorry but I think these are not following best practices. As you can see If these was possible then it would have worked because it's just including a PHP file and calling a function in it but I think Drupal doesn't do it that way and runs the PHP in the body field way before node.tpl.php w/c results to no included PHP file at that time yet.

## Suggested solution

Might I suggest, it's better for us to:

1. Create a custom module
2. Add your helper functions there with any structure of the files you can but following Drupal standards.
3. Use Drupal hooks if needed because if you place your functions in the .module file, it will be available already for use.

One example of this way is after adding your helper functions into the .module file and want to execute/run functions when viewing the node, you can use hook\_node\_view. Maybe add some scripts, remove data, alter data and etc. and you can also do conditional statements there if you want to run specific things for a specific content type.

This just doesn't align your site with best practices but makes it easier to maintain in the long run with less technical debt.

Hope this helps you to be able to call/execute your needed functions on nodes.

## UPDATE

You can remove the PHP file inside your theme and transfer the functions/codes inside it in the .module file. After that, you need to Clear All Caches then that will make your functions available or callable.

You don't need to use the include\_once or hook function.
> 0 votes

---
Tags: 7, theming
---


# Question
Title: Site map module assigns random frequencies to content
I just created an XML sitemap in Drupal 7. As I click on the '***rebuilt links***' button, all my content pages are assigned random frequencies and the module does not give me an option to edit content frequencies.

For eg: I have 15 content pages and all these pages share the same content type. I assigned priority of 0.9 to this content type. As I hit '***rebuilt links***', few pages were randomly assigned daily frequency, where as rest of the pages were given monthly frequency.

Is there a way I can assign uniform frequency to all my content pages? or edit individual page frequencies? What exactly is making the XML site map module assign two different sets of frequencies to the same content type?

# Answer
> Is there a way I can assign uniform frequency to all my content pages? or edit individual page frequencies?

Not through the UI as far as I know, but it's possible in code using `hook_xmlsitemap_link_alter()`:

```
function MYMODULE_xmlsitemap_link_alter(&$link) {
  if ($link['type'] == 'node' && $link['subtype'] == 'article') {
    $link['changefreq'] = 86400;
  }
}

```

`$link` also has a `loc` field which contains the router path for the node (e.g. "node/1"), although it's not ideal you can use that quite reliably to determine what specific node is being dealt with.

> What exactly is making the XML site map module assign two different sets of frequencies to the same content type?

It's intentional - the change frequency for each link is calculated dynamically by the module. I assume the idea is that giving Google an accurate change frequency is better than setting something static and then ultimately struggling or failing to live up to it in the mighty engine's eyes. Doesn't always work like that in practice, of course.
> 1 votes

---
Tags: 7, nodes, xml-sitemap
---


title: Render template for HtmlResponse

text:
# Question
Title: Render template for HtmlResponse
In my controller I want to return `Drupal\Core\Render\HtmlResponse`, and also I want to take HTML content from the template. The problem is that if I will try to `render()` a rendereable array before returning HtmlResponse - I'm getting `"The website encountered an unexpected error. Please try again later."` error. Array is being rendered correctly when I will just return it as it is, but with all Drupal HTML, which I don't want. What am I doing wrong?

**Added #1:** Discovery - all works well when I return `Zend\Diactoros\Response\HtmlResponse` . Now I'm even more confused. Why is that?

**Added #2:** When I use "renderPlain()" renderers method it also works, but I'm not sure of drawbacks yet.

# Answer
> 0 votes
Oh, I believe I should use "renderRoot()" method of renderer in case where I'm rendering HTML for response just to be send. Please correct me someone if I'm wrong.

---
Tags: 8, theming
---


title: how a module is installed?

text:
# Question
Title: how a module is installed?
I was successfully able to install the Nivo\_Slider. But I want to have proper understanding on how module installations work.

My question is: Why doesn't the simple module installation of Nivo\_slider do the job? Why do I manually have to copy and paste something (look at the first step from here? Isn't that the whole purpose of module installation? Some other modules just get installed by copy and pasting the tar.gz file.

# Answer
The Nivo Slider module relies on libraries that have a different license from the module itself. To work around this aspect, the Nivo libraries are distributed apart from the module. Consider this explanation from the licensing page at Drupal.org:

> **10. Can I write a "bridge module" to interface between Drupal and another system or library?**
>
> That depends on the other system.
>
> It is possible to distribute a module that communicates with a 3rd party system over HTTP, XML-RPC, SOAP, or some other wire protocol, that leaves the 3rd party system unaffected.Examples of such systems include Flickr, Mollom, or certain legacy systems.
>
> It is possible to distribute a module that integrates with a 3rd party PHP or JavaScript library, as long as the library is under either a GPL or GPL-compatible license. Examples of compatible licenses include BSD/MIT-style "permissive" licenses or the Lesser General Public License (LGPL). The Free Software Foundation maintains a list of popular GPL-compatible licenses.
>
> It is not possible to distribute a module that integrates a non-GPL compatible library with Drupal, because it would be a derivative work of both Drupal and that other library and would therefore violate either the GPL or the license of the other library. Please be aware that includes some open source licenses that are incompatible with the GPL for one reason or another, such as the PHP license used for most PEAR packages.
>
> If you wish to contribute a bridge module to a Drupal Git repository, please do not check in the 3rd party library itself. Doing so creates a fork of that 3rd party library, which makes it more difficult to maintain and only serves to waste disk space. Instead, provide detailed instructions for users to download and install that 3rd party library for use with your module. If you believe that your module is a special case where it really does need to be included in a Git repository, usually only because you need to make substantial modifications to it in order for it to work, please file an issue with in the Licensing Working Group issue queue first to discuss it.
> 5 votes

---
Tags: installation
---


# Question
Title: Additional tab in custom module's admin configuration page
Can't figure out why two admin pages of my custom module are not showing in different tabs. I've disabled and re-enabled the module, cleared cache, however while both pages are accessible and I see the "Leads" link in the menu, unfortunately they are not aligned into tabs. Can anyone help me to get my tabs?

```
/**
 * Implementation of hook_menu().
 */

function leads_menu() {
  $items = array();

  $items['admin/commerce/leads'] = array(
    'title' => 'Leads',
    'access arguments' => array('administer leads'),
    'page callback' => 'leads_active',
  );
  $items['admin/commerce/leads/subscribed'] = array(
    'title' => 'Subscribed Leads',
    'page callback' => 'leads_subscribed',
    'type' => MENU_DEFAULT_LOCAL_TASK,
    'weight' => -10,
  );

  return $items;
}

```

# Answer
> 2 votes
It seems that first main path 'admin/commerce/leads' needs to be defined, and then other two items added. The first item inherits the properties of the main menu item, and the second defines its own callbacks. Far from obvious, but it works for me now:

```
  function leads_menu() {
  $items = array();

  $items['admin/commerce/leads'] = array(
    'title' => 'Leads',
    'access arguments' => array('administer leads'),
    'page callback' => 'leads_active',
  );
  $items['admin/commerce/leads/active'] = array(
    'title' => 'Active',
    'type' => MENU_DEFAULT_LOCAL_TASK,
    'weight' => -10,
  );
  $items['admin/commerce/leads/subscribed'] = array(
    'title' => 'Subscribed',
    'page callback' => 'leads_subscribed',
    'type' => MENU_LOCAL_TASK,
    'access arguments' => array('administer leads'),
  );

  return $items;
}

```

---
Tags: routes
---


# Question
Title: extracting data from webform and parsing it
I looked into this question, but it was irrelevant.

I have data entries on my webform... obviously each field has its own key field. Let's say it has key1, key2, key 3

What I want to do is to create an email draft as such:

---

Hi "key1"

I wanted to say "key2"

**SUBMIT BUTTON**

---

After pressing the submit button it will be emailed to "key3"

---

If there isn't any module that does do this, then can anyone tell me the steps( doesn't have to be very detailed) needed to do this?

# Answer
> 0 votes
You can use token for that purpose. Webform do have a facility to add token in mail template. But this would be default mail template using dynamic value of submitted form.

There you can find all field component available in webform.

---
Tags: webforms
---


# Question
Title: Unable to export and import custom block type fields
I have created a new custom block type and added some fields to it. I am able to export and import the custom block type in another Drupal instance via configuration management, but there are no fields.

How do I import the fields too?

# Answer
The field definitions are in their own yml-files. To check this, export the full archive and search for the dependencies. For example the body of the block content type `basic` has this yml-file:

```
field.field.block_content.basic.body.yml

```

and there you find the dependencies for the block content type:

```
dependencies:
  config:
    - block_content.type.basic

```
> 2 votes

---
Tags: 8, configuration
---


# Question
Title: How do I use the #autocomplete_route_name property?
I created a custom form and I want add a "users" reference field.

I see here I must use the property autocomplete\_route\_name, but what value must I set?

```
$form['project']['users'] = array(
  '#type' => 'textfield',
  '#title' => t('choose users'),
  '#autocomplete_route_name' => 'user.autocomplete',
);

```

With the previous code, I get the following error:

> Uncaught PHP Exception Symfony\Component\Routing\Exception\RouteNotFoundException: "Route "user.autocomplete" does not exist." at /var/www/drupal8/core/lib/Drupal/Core/Routing/RouteProvider.php

What is the correct code I should use?

# Answer
> 5 votes
Users are entities so they're treated generically. The route is `system.entity_autocomplete`, with some parameters, but you don't need to get your hands that dirty. You can use the "entity autocomplete" form element type instead, which should be as simple as:

```
$form['project']['users'] = array(
  '#type' => 'entity_autocomplete',
  '#title' => t('choose users'),
  '#target_type' => 'user',
);

```

It's derived from a `TextField`, so you can use all the usual properties. Examples do seem to be a little hard to find other than in the core files (it's early days), but you can see all the available properties the entity\_complete adds in `EntityAutocomplete::getInfo()`, and how they're used within other methods of the class.

# Answer
> 2 votes
From the entity reference element

```
$element['#autocomplete_route_name'] = 'system.entity_autocomplete';
$element['#autocomplete_route_parameters'] = array(
  'target_type' => $element['#target_type'],
  'selection_handler' => $element['#selection_handler'],
  'selection_settings_key' => $selection_settings_key,
);

```

See http://cgit.drupalcode.org/drupal/tree/core/lib/Drupal/Core/Entity/Element/EntityAutocomplete.php

---
Tags: forms, 8, ajax
---


# Question
Title: How to perform views date calculations using global math?
Is it possible to calculate date in Views like to calculate two cell using global math for this case?

Example:

* Nick's birth of date was 20/10/2005
* Only 20 years old can join the club
* So before **31/10/2025** Nick cannot join the club, its mean Nick needs to wait for **10 years 10 days** (date **31/10/2025**) to join the club.

Can anyone assist me to solve this?

# Answer
> 0 votes
You can try Views PHP which allows you to add a php code field to a View.

Otherwise, for a less "dangerous" solution, you can add a field to your content type for which you are creating the View, hide the field from the node creation form with css, `hook_form_alter()` or Display Suite, and create a Rule that calculates the new date when a user save new content. This field could be a Date field, or an Interval field if you want to store the interval between two dates.

# Answer
> 0 votes
Have a look at the Computed Field module. You can use it to define a new dynamic field for any content type, which can either be stored in the database or computed on the fly. Some more details about this module (from its project page):

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

You may also want to look at its Community documentation, especially its child page about "Calculating a duration given a start and end time", here is a quote from it:

> ... create a new computed field to calculate the duration as a decimal number of hours (where 1.5 is 1 hour and 30 minutes).

PS: not 100% sure if it would apply in this case, but for a possible alternative to the Views PHP module (as suggested in another answer here), you may want to use an approach as explained in "44,497 People Are Wrong: How to NEVER Need Views PHP".

---
Tags: views, datetime
---


# Question
Title: Why implementation of node access for different content type breaks my other type access control?
System architecture:

Main entities:

* Company
* Employee (and other user types)
* Document

References:

* Every document has reference to company and employee.
* Every employee has reference to company also (at least one company)

I've implemented custom access control for documents, which suppose to working fine (my unit tests gives me all green also).

Now I'm creating View - documents list for an employee. Basic version of View is working correct. I want to add exposed filter for a company. By default this is a list of all companies. But I want to restrict this list only for companies from employee documents, related to current logged in employee.

Code:

```
/**
 * Implements hook_node_access_records().
 */
function mymod_company_node_access_records($node) {
  if ($node->type <> myCompany::CONTENT_TYPE_NAME) {
    return array();
  }

  return array(
    array(
      'realm' => MYMOD_COMPANY_LOCK_NAME,
      'gid' => $node->nid,
      'grant_view' => 1,
      'grant_update' => 0,
      'grant_delete' => 0,
      'priority' => 0,
    )
  );
}

/**
 * Implements hook_node_grants().
 */
function mymoo_company_node_grants($account, $op) {
  if ($op <> 'view') {
    return array();
  }

  if (mymod_user_is_an_employee($account)) {

    $myUser = myUser::createFromUser($account);
    $companies = $sdUser->getCompanies();
    if (empty($companies)) {
      return array();
    }

    $grants = array();

    foreach(array_keys($companies) as $nid) {
      $grants[MYMOD_COMPANY_LOCK_NAME][] = $nid;
    }

    return $grants;

  } else {
    return array();
  }
}

```

Indeed filter list is restricted to employee related companies, but in my View, I'm seeing ALL documents related to these companies. Why?

My View main content type is Document. Company is related node via entity reference field. I don't understand why company access control has some type of precedence here.

# Answer
> 0 votes
While browsing through the Drupal docs about `hook_node_access_records`, I stumbled upon this comment:

> Note that (as of 7.35) if your module and every other module in your installation implementing this hook return empty arrays, Drupal will automatically insert a record into the node\_access table for the given node with GID 0, grant\_view set to 1, and grand\_update and grant\_delete set to 0.

You can find it here (last comment).

---
Tags: 7, views, users
---


# Question
Title: How to create a view of existing blocks?
My aim is to make a Views grid of existing blocks in Drupal 7 (Might be possible without any additional code\module in Drupal 8).

I've tried to make a Content based View and filter it via Block ID's, but when I came to filter this View, I found no such option.

I've tried to check the "Relationships" option to see if I can add a relationship to Blocks but no such option was available there either.

Therefore, I wonder if a View of existing block is even an option naturally.

# Answer
This question seems like a perfect illustration of why you'd use the Bean module (to actually create such view as in this question). Here is a quote about its project page:

> Think of a Bean as a method to provide new types (compared to node this would be a content type) which then provides an add content interface to create as many blocks as you require (see screenshot below). The bean content can then be placed around the site just like any other block.

This module also works great in combination with the UUID and UUID Features Integration modules. And after you become familiar with the Bean module, you might find other cases in your site where you also want to use this module (which somehow compensates the fact that you need to add another module).

The video tutorial Drupal Bean module tutorial - using Bean Admin UI provides a great introduction to really understand the power of this module, and the kind of things you can do with it (by only using site building techniques, no custom coding involved). It also shows how the Bean module transforms Drupal blocks into fieldable entities.

In this specific case, after you enabled the BEAN module, you should be able to create a view of blocks. As an illustration, have a look at this (basic) view (in Views export format):

```
$view = new view();
$view->name = 'blocks_created_with_bean';
$view->description = '';
$view->tag = 'default';
$view->base_table = 'bean';
$view->human_name = 'View of blocks created via the BEAN module';
$view->core = 7;
$view->api_version = '3.0';
$view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */

/* Display: Master */
$handler = $view->new_display('default', 'Master', 'default');
$handler->display->display_options['title'] = 'View of blocks created via the BEAN module';
$handler->display->display_options['use_more_always'] = FALSE;
$handler->display->display_options['access']['type'] = 'none';
$handler->display->display_options['cache']['type'] = 'none';
$handler->display->display_options['query']['type'] = 'views_query';
$handler->display->display_options['exposed_form']['type'] = 'basic';
$handler->display->display_options['pager']['type'] = 'full';
$handler->display->display_options['pager']['options']['items_per_page'] = '10';
$handler->display->display_options['style_plugin'] = 'table';
$handler->display->display_options['style_options']['columns'] = array(
  'bid' => 'bid',
  'label' => 'label',
  'title' => 'title',
  'type' => 'type',
  'uid' => 'uid',
  'url' => 'url',
);
$handler->display->display_options['style_options']['default'] = '-1';
$handler->display->display_options['style_options']['info'] = array(
  'bid' => array(
    'sortable' => 0,
    'default_sort_order' => 'asc',
    'align' => '',
    'separator' => '',
    'empty_column' => 0,
  ),
  'label' => array(
    'sortable' => 0,
    'default_sort_order' => 'asc',
    'align' => '',
    'separator' => '',
    'empty_column' => 0,
  ),
  'title' => array(
    'sortable' => 0,
    'default_sort_order' => 'asc',
    'align' => '',
    'separator' => '',
    'empty_column' => 0,
  ),
  'type' => array(
    'align' => '',
    'separator' => '',
    'empty_column' => 0,
  ),
  'uid' => array(
    'sortable' => 0,
    'default_sort_order' => 'asc',
    'align' => '',
    'separator' => '',
    'empty_column' => 0,
  ),
  'url' => array(
    'align' => '',
    'separator' => '',
    'empty_column' => 0,
  ),
);
/* Field: Block: Internal, numeric block ID */
$handler->display->display_options['fields']['bid']['id'] = 'bid';
$handler->display->display_options['fields']['bid']['table'] = 'bean';
$handler->display->display_options['fields']['bid']['field'] = 'bid';
/* Field: Block: Label */
$handler->display->display_options['fields']['label']['id'] = 'label';
$handler->display->display_options['fields']['label']['table'] = 'bean';
$handler->display->display_options['fields']['label']['field'] = 'label';
/* Field: Block: Title */
$handler->display->display_options['fields']['title']['id'] = 'title';
$handler->display->display_options['fields']['title']['table'] = 'bean';
$handler->display->display_options['fields']['title']['field'] = 'title';
/* Field: Block: Type */
$handler->display->display_options['fields']['type']['id'] = 'type';
$handler->display->display_options['fields']['type']['table'] = 'bean';
$handler->display->display_options['fields']['type']['field'] = 'type';
/* Field: Block: Uid */
$handler->display->display_options['fields']['uid']['id'] = 'uid';
$handler->display->display_options['fields']['uid']['table'] = 'bean';
$handler->display->display_options['fields']['uid']['field'] = 'uid';
/* Field: Block: URL */
$handler->display->display_options['fields']['url']['id'] = 'url';
$handler->display->display_options['fields']['url']['table'] = 'views_entity_bean';
$handler->display->display_options['fields']['url']['field'] = 'url';
$handler->display->display_options['fields']['url']['link_to_entity'] = 0;

/* Display: Page */
$handler = $view->new_display('page', 'Page', 'page');
$handler->display->display_options['path'] = 'view-of-blocks-created-via-the-bean-module';

```
> 2 votes

---
Tags: 7, views, blocks
---


# Question
Title: View of taxonomies connected to view of each taxonomy
I'm creating a store using Drupal commerce and I'm trying to show a catalog of products.

1. First I create taxonomy of product types
2. Then I use taxonomy to create a view of product types(product type view) and I'm showing taxonomies image
3. Then I add a taxonomy reference field to product contents

I want to show all products of a type every time I click on a taxonomy in product type catalog view.

Can anyone help me?

# Answer
With this solution yo can get the result with some struggle, but I have a better solution for you.
Create a list that show all product in categories. (If you do not need this, skip this step.)

* Create a view of product type
* Add a relation to category (taxonomy you used in product display)
* Add a taxonomy field (also images)
* Group the result by category

Create a view with path something like `product/*` and pass the category ID to it.

then add contextual filter on your category field,and get default value from the URL.

for getting better involve with views contextual filter read this article.
if you need more details tell me to provide it.
> 1 votes

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


# Question
Title: How to hide the content of nodes/ completely, and still maintain use within Drupal?
So, to start off, I've seen:

All the answers to those questions make the proposal to make the node unpublished, which was the solution that looked cleanest to me, given that I was making some content types to be viewed exclusively with slideshows, i.e., having `www.mysite.com/node/40` showing a list of all the raw images that make up my slideshow in a block elsewhere was not something I wanted. I only want the images viewable within the context of a slideshow.

However, when I followed these answers and made the content of the node unpublished, the content was inaccessible to the slideshow View: It was now blank to anonymous viewers. Is there something I missed in how to make a node unpublished, but still allow its contents to be accessed through Views, as a block?

I'm looking to do this without using the htaccess, hooks, or javascript options I've seen mentioned in the links above.

I can't imagine that having a list of content accessible nakedly under `nodes/123` is actually an intentional feature.

One other qualification that makes this a tricky problem---there are ways of preventing access to `node/123`, but they can also hinder your own ability to create or edit nodes!

# Answer
***EDIT: NEVERMIND, THIS DID NOT WORK!***

***I discovered that any access rules I could add to enable the administrator to create and edit content, because editing content is under "/node/add/..." also undid the anonymous user access restriction and enabled all users to see the content. Sort of back where I started, but leaving this up in case it helps anyone else see the way. Original answer follows:***

OK, here's the recipe to achieve this in a non-programmatic way, as simply as I could (explanation of why follows):

1. Enable the Page Manager module (part of ctools), install and enable the Page Manager Redirect module: http://drupal.org/project/page\_manager\_redirect.
2. In the admin menu, go to Structure \>\> Pages
3. In the table below, identify the custom page "System node\_view Node template /node/%node " and click "edit" on the right.
4. For me, I had by default "Basic Page" and "Storyauthors." I hit disable on both of these (but you may want to preserve them, if you use these features---I do not).
5. Click "Add Variant"
6. Title: "redirect to main." Variant type: "HTTP Response Code." And Check "Selection Rules." Click "Create Variant."
7. Now, add selection rules.
7.a. In the drop-down box, go to "user: Role," click "Add." \>\> NOT (Logged in user has role "administrator")
7.b. Add another selection rule \>\> node:type. Click every content type for which you do not want a user to be able to see naked nodes. Then click NOT. For me, since I never want naked nodes to be visible, I clicked every content type I have.
8. Set HTTP response code to 301, and leave the redirect blank (= to main).

The rationale:

* I went this route instead of htaccess or creating modules because this seems like the sort of problem that should be accessibly fixable within the interface. Again, I don't believe there would be a group clamoring for all content to be visible under nodes/, numbered, if it weren't the default behavior.
* Regarding selection rules: The first one, for administrator (or any editor-level group you have), ensures that you can still create and edit content! If you leave this off, when you try to add new content, you will be redirected to main. The second one, about content types, was necessary to allow viewing pages under their URL alias. Without this checked, when I clicked on say, blog posts, I was unable to view them at full page, only their teasers. Not sure why this was the case, or why I needed to do negative permissions here, rather than positive permissions. But this is what I had to change to allow editors to edit, and anonymous viewers to view formatted content types and not node/.

Potential pitfalls:

If you create a new content type, you'll need to remember to come back to page manager and update (ie, check its box in the second selection rule).

Future improvement:

If someone is really cool, they'd make a single module that does this process automatically, and call it "Hide nodes." =) Again, I wish hiding "nodes/" were default Drupal behavior, and I'm sure I'm not the only one. I really view these as a staging and collection area---it seems very strange to allow them to be visible to the public. It's like seeing the magician shove the pigeons in his sleeves!

Thanks to Chance G's pointing me there, and Johan Falk's tutorial for getting me going!

***EDIT: UPDATE***

From the above, I'm going to say the answer to this question is there's no way to do this. You're stuck with nodes!
> 0 votes

# Answer
There are two Drupal modules that offer this functionality:
> 5 votes

# Answer
Johan Falk of nodeone.se just reciently did an excellent video series on Page Manager (part of cTools, a very common module) and he covered a use case like you are describing very well. link.

Basically you set up a variant in Page Manager and have the response be a http request code (probably a 301 in your case) to redirect to your intended destination. In his example (I think it was the 2nd or 3rd video in the series, they are all pretty quick though) he was using node references and he didn't want anyone to get to a 'sub node' but redirect you to the parent node if you tried to access it. Your use case sounds like it could be even simpler, just have anyone trying to access one of your slideshow nodes redirected to page that shows the correct full slideshow.

You don't even need panels to get all of this magic to work. And you can get pretty complex in your redirect rules if you have stuff like node references installed to load related nodes.
> 2 votes

# Answer
If it's just a matter of search engine accessibility you can should use the robot.txt file, which prevent search engines from accessing certain page of your site.

Though using this Technic users of your site can still access URLs like in your example www.mysite.com/node/40
> 1 votes

# Answer
As no one has given a code answer here is another option:

```
/**
 * Implements hook_init().
 */
function HOOK_init() {
  $object = menu_get_object();
  $action = arg(2);
  if(isset($object->type) && $object->type == 'TYPE_OF_NODE' && (empty($action) || $action == 'view')) {
    drupal_goto();
  }
}

```

Replace `HOOK` with the name of your module and replace `TYPE_OF_NODE` with the name of the type of node that you want to hide.

This will only redirect when the path is `node/123` or `node/123/view`. `node/123/edit` or `node/123/whatever` is allowed. Note this is the path, not the URL I'm talking about. The path alias of the node is irrelevant here.
> 0 votes

# Answer
Using the Rules module you can implement a rule that looks similar to this:

```
{ "rules_check_url" : {
    "LABEL" : "Disallow node/* access",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "init" : [] },
    "IF" : [
      { "text_matches" : {
          "text" : [ "site:current-page:url" ],
          "match" : "node\/\\d+$",
          "operation" : "regex"
        }
      }
    ],
    "DO" : [
      { "drupal_message" : {
          "message" : "Sorry, URLs like [site:current-page:url] are not allowed around here ...",
          "type" : "error"
        }
      },
      { "redirect" : { "url" : "no_access" } }
    ]
  }
}

```

Anybody using an URL like `node/...` will be redirected to a page with path `no_access` (adapt that path to fit your needs).

The above rule does not (yet) take into account to only apply the "action" for selected roles (such as anonymous users) only. But for anybody a bit familiar with the Rules module, that is a straight forward "Condition" to add ... Should you only want to prevent such access to a limited list (a few) of nodes, then there is no need to use the "regex" operation in the "text\_matches" condition (just replace it with an exact match of the relevant node(s)).

To experiment with this rule in your own site, just copy the entire Rules code above, and paste it in a new Rule in your own site, created via the "Import" function. Then further edit/refine to make it fit in your own environment (e.g the "Sorry, ..." message to be shown).

**Attention**: this rule takes the "completely"-part from the question title seriously ... With this rule enabled (with no extra Rules condition added to only apply it for selected rules), even an administrator (or user/1 ...) will not be able to get access to any (repeat: any) URL like `node/...`. The only way to get around that, is to (temporary) disable this rule, add relevant Rules conditions (to allow selected roles anyway), and enable the rule again.
> 0 votes

---
Tags: views, nodes, users
---


# Question
Title: How can I modify the result of the core Path listing filter?
The core Path module defines the page `admin/config/search/path` which gives a listing of all path aliases.

The menu hook in the module calls the `path_admin_overview` function in `path.admin.inc` which makes the query to retrieve a list of URL aliases:

```
$query->condition('alias', '%' . preg_replace('!\*+!', '%', $keys) . '%', 'LIKE');

```

What I would like to do is somehow intercept this query and modify the condition in a custom module (to avoid hacking core, of course). **To be more precise, I want to make it possible to extend the condition to search the `source` column as well as the `alias` column as indicated above.**

My first thought was to intercept the Path admin listing form: `path_admin_filter_form` which I have done using `hook_form_alter`. I was then hoping that somehow I could override the existing submit handler or attach an second one which would call `path_admin_overview`, but of course I cannot directly modify that core function.

So it seems like I would have to make my own custom copy of `path_admin_overview` and modify the code inside, then have that called instead. Of course this doesn't feel right either - since if the Path module changes, the module will fall behind.

Is there some kind of hook or pattern I can employ here to modify the query in `path_admin_overview` or otherwise achieve the goal indicated in bold in a standalone module?

EDIT: It looks like it could be possible if the query in `path_admin_overview` was tagged (it isn't currently), see here: https://www.drupal.org/node/310077#hook\_query\_alter

# Answer
> 2 votes
You can override `admin/config/search/path` path using hook\_menu\_alter and use a custom function as menu callback.

```
function oyurmodule_menu_alter(&$items) {
  $items['admin/config/search/path']['page callback'] = 'mymodule_custom_path_admin_overview';
}

```

Then your `mymodule_custom_path_admin_overview` shoud be a copy of `path_admin_overview` with your needed alterations.

This is not optimal as you should keep your function code in sync with original code, so any patches applied to `path_admin_overview`function should applied to your altered function, but is the only way you can alter the functionality without hacking core.

---
Tags: 7, path-aliases
---


# Question
Title: How exactly does a View Preview differ from what is rendered on a page/block?
There are a number of questions relating to this issue. I'm interested in a general explanation so I can troubleshoot why my complex (contextual filters, relationships, etc) view preview would be working as expected while the view block shows different results.

What exactly is being run for the preview compared to the normal display of the view? What happens 'after' the preview, or are these different paths/processes/methods/hooks altogether?

# Answer
If aggregation is enabled and query settings distinct and/or pure distinct as well with flags relationships, I experienced differences in what the preview was showing and what showed in the actual block/page version. The solution for me was disabling the distinct option.
> 1 votes

# Answer
Your issue is likely related to the contextual filter. If the data you are supplying to the preview doesn't match the data provided from the url, etc. then the results will differ.
> 0 votes

---
Tags: 7, views
---


# Question
Title: drupal_http_request give 400 response code for working url
I have major problem while getting response. I am using drupal\_http\_request to get the response but I get 400 as response though url given is working... I tried Curl Http Request module to overrride drupal\_http\_request. If i do that, then I get response code as 47 and error is maximum redirect followed. If I dont use CHR module, then error is 400 but through fiddler, or by POSTMAN, response is 200Ok.. Any help on this?

Below is my code

```
$url = "https://lastpass.com/misc_download2.php";
$options = array(
  'max_redirects' => 20,
  'headers' => array(
  'Content-Type' => 'application/x-www-form-urlencoded',
  'User-Agent' => 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36   (KHTML, like Gecko) Chrome/46.0.2490.86 Safari/537.36',
  )
);
$check_url = drupal_http_request($url, $options);

```

print\_r($check\_url) is giving code=400

# Answer
> 0 votes
drupal\_http\_request() has GET as a default method, you are requesting a resource with application/x-www-form-urlencoded which is only available on POST requests as far as I know. a fix can be as simple as:

```
$check_url = drupal_http_request($url, $options, 'POST');

```

Source: https://api.drupal.org/api/drupal/includes%21common.inc/function/drupal\_http\_request/4.6

---
Tags: http-request
---


# Question
Title: How to print Json data from Facebook in a block?
I would like to print the amount of Facebook likes for a url into a block. The Facebook API returns JSON like so: https://api.facebook.com/method/fql.query?query=select%20like\_count%20from%20link\_stat%20where%20url=%27https://drupal.stackexchange.com/%27&format=json

What is the Drupal 8 way to print this data in an block?

# Answer
Normally I would look for a contributed module that might already be written, but at this time none of Drupal for FaceBook, FaceBook Like Button, Views FaceBook Like, FaceBook Social, or Social Media Links have Drupal 8 releases. It would be a good idea to look at contributing to the above projects.

In order to accomplish this, you will need to create a Block plugin in a custom module. There are a few of options. Code examples are sort of pseudo-codeish.

1. Contribute and port one of the modules above to Drupal 8.
2. In PHP, you may use Guzzle in the build method in the block plugin. The advantage here is that the block will be cached and save performance on subsequent loads.

\`\`\`

```
$client = \Drupal::service('http_client');
$options = [
  'query' => [
    'query' => "select like_count from link_state where url = 'http://drupal.stackexchange.com/'",
    'format' => 'json'
];
$response = $client->request('https://api.facebook.com/method/fql.query', $options);
// the "serializer" service could also be used if deserializing into a known Drupal typed data type.
$data = json_decode($response->getBody());

```

\`\`\`

3. You may also add a JavaScript asset to the render array of the block, and then code some JavaScript that makes a request. The advantage here is that this is that this is done after Drupal render, but it will make an additional http request on each page load.

\`\`\`

```
(function($, Drupal) {
  Drupal.behaviors.myModule = {
    attach: function(context, settings) {
      $.ajax('https://api.facebook.com/method/fql.query?query=select%20like_count%20from%20link_stat%20where%20url=%27http://drupal.stackexchange.com/%27&format=json', {
        dataType: 'json'
      }).done(function(data) {

      });
    }
  };
})(jQuery, Drupal);

```

\`\`\`
> 2 votes

---
Tags: blocks, 8
---


title: How do I use the jQuery Multi module?

text:
# Question
Title: How do I use the jQuery Multi module?
I have a site theme that needs to use Jquery 2.1.3. The theme uses on() and affects the `node/add` form. So I also need Drupal's default Jquery 1.4 to be running, otherwise the default Drupal scripts on the `node/add` form will not work.

The Jquery Multi module is supposed to be the best way of doing this. But how do you use the module? I have installed it and verified that the Jquery 2.1 library is running.

The Read Me file says:

> For instance, if you're loading jQuery 1.7.1, the alias will be jq171, and you can use it in your scripts by wrapping your code as follows:
>
> ```
> (function($) {
>   // The using jQuery 1.7.1
> })(jq171)
>
> ```
>
> NOTE: All jQuery targeted to use jQuery Multi (using methods A, B, or C above) must properly use a closure around the jQuery code, as is best practice for all Drupal jQuery code, i.e.:
>
> ```
> (function($) {
>   // The code using jQuery 1.7.1
> })(jQuery)
>
> ```

Do I wrap my code in both jq213 and Jquery?

```
(function($) {
    (function($) {
        "use strict";
        $(document).ready(function() {

            /* *********************** */
            /* Mobile only Hamburger menu       */
            /* *********************** */
            $(".masthead .menu").on("click", function() {
                $(this).toggleClass('menu-close');
                $("body").toggleClass('menu-open');
                $(".masthead ul").toggleClass("animated bounceInDown");
                $(".masthead .tap-back").toggle();
           });
                  });
    })(jq213)
})(jQuery);

```

I have tried this, but it doesn't work. When I check the HTML source I can see that Jquery 2.1.3 doesn't load, so presumably I am wrapping my scripts wrongly.

In admin/config/system/jqmulti, I can see that Jquery 2.1.3 has been loaded.

# Answer
Why you did double code wrap? Try to use:

```
(function($) {
    "use strict";
    $(document).ready(function() {

        /* *********************** */
        /* Mobile only Hamburger menu       */
        /* *********************** */
        $(".masthead .menu").on("click", function() {
            $(this).toggleClass('menu-close');
            $("body").toggleClass('menu-open');
            $(".masthead ul").toggleClass("animated bounceInDown");
            $(".masthead .tap-back").toggle();
       });
              });
})(jq213);

```
> 2 votes

---
Tags: javascript
---


# Question
Title: Commerce product variation with different variations
I'm still pretty new to Drupal Commerce so I don't know if it's possible to group different variations under a product variation. This may sound weird, so here is an example of a grouped product variation.

As you can see the different product types have common values. The networking one has all values. So this is what I would like to achieve:

* Create one product variation called `transmission`
* Have the option to select the product type

+ The selection you made in the product type column will change the values you need to fill in.

Is this possible? Or would there be an other recommended solution to group like this. I would like to prevent that I have to create variations for each product type.

# Answer
> 1 votes
For something like this, you can create a **Type** field on the product and then have allowed values for Fiber, UTP or other. If you create these as a Taxonomy field, then they can be used to categorize other products or services with that same term.

You can create all of the fields and then use custom code to alter the form states to require/hide/show/etc. various fields on the form. All of the fields will exist, but only some of them might be shown. When you create your template for the product, you'll just need to ensure that you theme it properly.

---
Tags: 7, commerce
---


title: How to calculate datetime in hours?

text:
# Question
Title: How to calculate datetime in hours?
I have a date time field to input working hours and then I need calculate total work hours. I was try using Global math expression in views, but the results is 0, although I was try to change views formmater from date and time, ago and plain.

This is the condition, lets say the rule in office is:

```
Employee In 1: 08.00
Employee Out 1: 12.00
Employee In 2 : 13.00
Employee Out 2 : 17.00

```

It's mean that employees **must have 8 hours** a day.

The question is, how can I calculate that employee **is late in 2 hours** if the field value like this:

```
filed Employee In 1: 09.00 <- late
field Employee Out 1: 12.00
field Employee In 2 : 13.00
field Employee Out 2 : 16.00 <- earlier out

```

Is there any module date related or some one chould assist me ho to solve my problem?

# Answer
> 2 votes
Have a look at the Computed Field module. Some details about it (from its project page):

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

You may also want to look at its Community documentation, especially its child page about "Calculating a duration given a start and end time", here is a quote from it:

> ... create a new computed field to calculate the duration as a decimal number of hours (where 1.5 is 1 hour and 30 minutes).

# Answer
> 2 votes
You can override views template file and add below code. The below code will find difference between two in-timings and two out timings and calculates total worked hours. This is assuming there won't be exactly 2 in and 2 out.

```
$start = strtotime($row->field_field_time_in[0]['raw']['value']);
$end = strtotime($row->field_field_time_out[0]['raw']['value']);
$diff = $end - $start;
$secondstart = strtotime($row->field_field_second_time_in[0]['raw']['value']);
$secondend = strtotime($row->field_field_second_time_out[0]['raw']['value']);
$seconddiff = $secondend - $secondstart;
$diff = $diff+$seconddiff;
$hours = floor($diff /3600);
$minutes1 = intval(($diff/60) % 60);
print $hours.'.'.$minutes1;

```

You can add any required calculations you require based on this.

---
Tags: views, datetime
---


# Question
Title: Separate Display for Start date and End date using Date module
I have a date field which collects both start date and end date. I would like to display start date and end date as seprate in the display.

I don't see any options in the display page. I am sure I am missing some basic setting. Any ideas?

**Note :** I am not using views and I would like to do it using the field display options only.

# Answer
> 0 votes
There a few options. If you're comfortable with code you could add a preprocess hook to duplicate the date field and manipulate its configurations. That is a little heavy-handed and hard to maintain.

With the Panels suite of modules (particularly panelizer module) you get the ability to do things like take over entity view modes. Then you can place fields as "panes" as many times as you want with different configurations.

---
Tags: theming, datetime
---


title: What does drupal_clone($node) do

text:
# Question
Title: What does drupal_clone($node) do
What does `drupal_clone($node)` do in Drupal? Will it clone a node? I know the node will be saved only if `node_save($clone)` is rendered. So what will happen when `drupal_clone($node)` is rendered ?

```
/**
 * Generate a node preview.
 */
function node_preview($node) {
    if (node_access('create', $node) || node_access('update', $node)) {
        // Load the user's name when needed.
        if (isset($node->name)) {
            // The use of isset() is mandatory in the context of user IDs, because
            // user ID 0 denotes the anonymous user.
            if ($user = user_load(array('name' => $node->name))) {
                $node->uid = $user->uid;
                $node->picture = $user->picture;
            } else {
                $node->uid = 0; // anonymous user
            }
        } else if ($node->uid) {
            $user = user_load(array('uid' => $node->uid));
            $node->name = $user->name;
            $node->picture = $user->picture;
        }

        $node->changed = time();

        // Extract a teaser, if it hasn't been set (e.g. by a module-provided
        // 'teaser' form item).
        if (!isset($node->teaser)) {
            $node->teaser = empty($node->body) ? '' : node_teaser($node->body, $node->format);
            // Chop off the teaser from the body if needed.
            if (!$node->teaser_include && $node->teaser == substr($node->body, 0, strlen($node->teaser))) {
                $node->body = substr($node->body, strlen($node->teaser));
            }
        }

        // Display a preview of the node.
        // Previewing alters $node so it needs to be cloned.
        if (!form_get_errors()) {
            $cloned_node = drupal_clone($node);
            $cloned_node->build_mode = NODE_BUILD_PREVIEW;
            $output = theme('node_preview', $cloned_node);
        }
        drupal_set_title(t('Preview'));

        return $output;
    }
}

```

# **Real Issue**

I am getting the node cloned when clicking the preview button. Is it related to any code changes?

# Answer
allows users to make a copy of an existing item of site content (a node) and then edit that copy. The authorship is set to the current user, the menu and url aliases are reset, and the words "Clone of" are inserted into the title to remind you that you are not editing the original content.

https://www.drupal.org/project/node\_clone
> 1 votes

# Answer
`drupal_clone` exists because Drupal 6 originally supported PHP 4.x, which didn't have a clone keyword (the min now is 5.x; I don't totally recall when this happened, but there was a big purge a few years ago to rid the planet of PHP 4.x).

To clone an object in PHP 4, you just used the = operator. In PHP 5, the = operator with an object will create a new reference.

This just clones the new object in memory. It should behave the same as if you loaded it from the database, but nothing DB related will happen to it unless you explicitly cause something to happen.
> 0 votes

---
Tags: nodes, 6
---


# Question
Title: Is --overrides an accepted option in drush 8.x?
I'm creating a build script and would like to include the `--overrides` flag as describe in the documentation. I'm using Drupal 8.0.0 and Drush 8.0.1 and I get the following:

> `drush make build.make.yml ~/Sites/built --prepare-install --overrides=dev.make --no-cache -y -vvv`
>
> Unknown option: --overrides. See 'drush help make' for available options. To suppress this error, add the option --strict=0.

Am I missing something? Is this functionality not built yet?

# Answer
It appears to be in the master branch, but not yet in 8.0.x.
> 2 votes

---
Tags: 8, drush
---


title: .htaccess problem for Drupal

text:
# Question
Title: .htaccess problem for Drupal
I decided to ask about this issue, because I found this problem is a common problem for many Drupal designers.

It seems to be a common problem for many drupal designers to face with the Server Error 500 after moving their site to the production server.

There are mainly two lines in the default .htaccess, which are:

```
# Don't show directory listings for URLs which map to a directory.
Options -Indexes

# Follow symbolic links in this directory.
Options +FollowSymLinks

```

So, for some hosts these lines should be removed.

What is your solution, after removing these lines from the .htaccess file? How should the directory listing be prevented?

# Answer
This is a known issue, see: https://www.drupal.org/node/1269780 regarding a longterm resolution.

In general it looks like going forward `+FollowSymLinks` should be replaced with `+SymLinksIfOwnerMatch`, but refer to the issue queue item above for a definitive answer.

Typically per host, and definitely with Shared Hosting plans it's up to your webhosts documentation as to what Apache Overrides are allowed by your (system) user account. There is a certain amount of trial and error is seeing if `-Indexes` for example is allowed on your webserver.

This is why when you upgrade Drupal they recommend backups of your projects `.htaccess` and `robots.txt` file as per webhost and project these files are highly likely to be modified.
> 5 votes

---
Tags: 7, .htaccess
---


# Question
Title: Why the cron is launched when I visit the website and why is it taking so much to complete?
I have a site in development. It has Feeds module installed, with mandatoty Job Scheduler also installed. When I come back to the office to keep working on the site, it takes almost a minute for the webpage to complete. I have checked the log messages, and says that it is the Cron doing its tasks. The Feeds imports are switched off, and configured to launch only on submission (admin), and the cron is scheduled every 3 hours, in times different to those in which the problem appears, apparently it is the visit to the webpage what launches the Cron tasks.

How can I check what is causing the problem?

# Answer
The cron can make different tasks such as check for updates to Drupal core and modules, removing temporary files, index content and cleaning up log files.

When you enter to your site the cron is executed and performs his tasks every X hours. You need enter to your site to activate the cron execution, if you want a different behavior you need read this: https://www.drupal.org/cron

There is no way for Drupal to run a cron job without bootstrapping. And the bootstrapping occurs when a visitor hits the site (Nothing happens on a server without someone or something running it). If you want really scheduled cron jobs, you have to set it up server side and this is certainly the best option, for this read: https://www.drupal.org/node/23714

Edit: I found now this article Why Drupal cron is not running as often as you think and how to fix it
> 2 votes

# Answer
For Drupal to work properly, it has to run certain background tasks from time to time. These are all categorised under the heading "cron" because that's the name of the \*nix service that's used for scheduling background tasks.

As @Adrian Cid Almaguer says you should read https://www.drupal.org/cron for more about this. You can schedule cron from control panel in most hosting environments.

If you DON'T schedule cron automatically, there's a feature called "poormanscron" that gets run when someone visits your site. As you've noticed this means prolonged response times for the unlucky person. So the lesson is to set up cron to run automatically. You need to configure it so the automated cron runs *more* frequently than the time configured under Adminstration \> Configuration \> System \> Cron Settings, otherwise poormanscron will still run sometimes.
> 2 votes

# Answer
with elysia cron module you have full control in your admin UI, but need to add some executions to your cron tab.
> 1 votes

---
Tags: datetime, cron
---


# Question
Title: How to get an editable cart at checkout with Drupal Commerce?
I always used `Commerce Kickstart` as a starting point for making e-commerce stores, but this time I opted to go with pure `drupal + commerce` modules.

One problem I have is that the cart view I get when I enter the checkout process is non-editable: it's just the list of items. The view used by the checkout is "Shopping cart form (Commerce Order)", and the cart uses `Shopping cart summary (Commerce Order)`. The latter has "remove" button in rows and an "update cart " link. Actually, I was able to replicate the elements of the formerin tha latter, save for the `update" cart` link.

I can get the one I am used to by going to `view cart`, but I do not get this one on chceckout. I tried to change settings at `admin/commerce/config/checkout/form/pane/cart_content`, but I can't get the desired result.

Any Ideas?

# Answer
> -1 votes
The module Commerce cart form checkout pane does this very well.

---
Tags: commerce
---


# Question
Title: How to check if field is empty and hide a css class in render array?
I am new to drupal core development any help will be much appreciated. I have a tab group from content type hidden from anonymous users (by default) when the field content within the tab is empty, how do I hide this tab when login in editors are viewing the same content.

This is what I have done so far in my node.inc using `template_preprocess_node`

```
function template_preprocess_node__event(&$variables, $hook)
{
//  kpr($variables);
$node = $variables['node'];
//  kpr($node);
$custom_tab = field_get_items('node', $variables['node'], 'field_route_text');
$custom_tab = (!empty($custom_tab)) ? kpr ('not empty from node') :  kpr('empty from node');

// jQuery UI accordion lib
drupal_add_library('system', 'ui.accordion');
}

```

# Answer
> 1 votes
I achieved this by the code below;

```
    function template_preprocess_node__event(&$variables, $hook) {
    $node = $variables['node'];
    $custom_tab = field_get_items('node', $variables['node'],    'field_override_group_label')
    if (! isset($custom_tab[0]['safe_value'])){
        drupal_add_css(drupal_get_path('theme', 'template some ') . "/css/customtab.css");
    }
    // jQuery UI accordion lib
    drupal_add_library('system', 'ui.accordion');
}

```

In customtab.css file, I add a css to hide the class. I think this might have impact on the general site performance.

---
Tags: 7, theming
---