# Question
Title: How i can change page with "next" previous" buttons in the same node
i want create something like that :

and after clicking next page , the node doesn't change :

# Answer
> 0 votes
The node from your screenshots is using the Webform module to create a multi-step form. The URL doesn't change because it's still the same node, the form's current step is just changing when you submit the form.

Without more information, I'm unsure if this is the same kind of functionality you're looking for, but when setting up a webform, I believe there is a "page break" component that you can add, which is what determines which components belong to which page. You could also use something like the Webform Steps module to create a clickable progress bar for your form.

# Answer
> 0 votes
Have you considered smart\_paging module

---
Tags: views, 7, nodes, forms, webforms
---


# Question
Title: Organic Groups Create Content Link does not appear
When I log in with my administrator account I am able to see the Create Content Link in my Organic Group. But when I am logged in with another account - permission to create content for content types is set - the create content link does not appear. I also activated entityreference prepopulate. Does anyone know what the problem could be?

# Answer
> 1 votes
Not sure which permission you mean with the "Permission to create content for content type is set" (consider adding the URL within admin to clarify that, is it `/admin/people/permissions`?).

However, it could well be that your issue is because you've not yet completed the "OG Permissions" located with something like `/admin/config/group/permissions/` (and then select the 'edit' link for the group type your issue is about).

---
Tags: organic-groups
---


# Question
Title: Commerce line item fields - getting value
I have a custom line item type that has a List(Text) field. When I do this:

```
$line_item = commerce_line_item_load($lid);

```

I get an object that contains the value, but not the label of the selected option.

```
$line_item->field_ring_size[LANGUAGE_NONE][0]['value'] // returns 2 instead of, say, Large

```

How can I get the value's label instead?

I've tried using field\_info\_instance to get all values, as follows:

```
$info = field_info_instance('commerce_line_item', 'field_ring_size', 'ring_setting');

```

...but this does not return the values as far as I can see. Similarly, I've tried field\_get\_items, but this gives me the key back again.

How can I get the value (or a list of all values) instead of the key?

# Answer
You can do it using list\_allowed\_values function

```
  $field = field_info_field('field_name');
  $allowed_values = list_allowed_values($field);

```
> 1 votes

---
Tags: commerce
---


# Question
Title: Numbering the content list in drupal (as simple as it sound) - possible via the UI?
Went through the conf and the Drupalsite \> Content page but couldn't find any where to number the list (or at least to get a nubmer of all contents of all entities and types - including Views, Panels, Webforms, ETC).

Would thank you for showing a simple way for numbering this list \ get a content-total number.

Here is the picture of my natural display of the content page... Thanks, Ben.

# Answer
> 2 votes
Looks like you might be looking for number of nodes by content type (among other things). If that's the case then you may want to consider the Charts module. It comes with a sample view that gives you both a tabular overview and a chart of these numbers.

The (accepted) answer to the question Views and node count for taxonomy terms contains another (views) based example.

The question Count of nodes by type contains some code snippets that may help to write your custom module to calculate these counts.

If you don't want to install/enable the Charts module permanently, you may want to temporarely enable it to (eg) look at the view for the tabular format display, and then create a clone of that view to perfectly fit your needs (and then uninstall the Charts module again). Of course the "Views" module is yet another module. But it's rare to find a site that does not use the views module, so that's maybe an acceptable compromise to consider (you might have Views available already)?

---
Tags: nodes
---


# Question
Title: How to delete or autodelete unused images in a Drupal site?
Every time I remove or replace an image in my Drupal 7 site (via image-field or CKeditor) it remains stored in the site's folder (x3 times at least for every style). Almost always it takes me about 3 MB of storage and creates a mess in the "styles" folder.

Is there a way (or module) to issue a command to remove all image files which are not being used (anymore) at my site?

# Answer
> 2 votes
The following drush command:

```
drush image-flush

```

may be used to remove all the image style copies generated as image styles via image-field or CKeditor. This is completely safe, as it will not touch the originals.

Those still in use will be regenerated when needed. Those no longer used will not not be regenerated.

As noted in a comment by *cptstarling*:

> If you don't have access to drush, you may consider the Image style flush module.

# Answer
> 1 votes
Normally, in a recent Drupal installation files are being deleted automatically when they're not related to node content. Update to the latest Drupal core and run cron (make sure that any occurance in nodes has been removed), also clear Drupal's cache to make sure.

AFAIK CKeditor works independently from the Drupal core, so I guess you'll have to delete files manually there, in its CKfinder.

---
Tags: media
---


# Question
Title: Blank page after save amazon s3 configuration
I open configuration http://www.mysite.gr/admin/config/media/amazons3 and I put Amazon S3 API Key * Amazon S3 API Secret * and Default Bucket Name * When I push the save button I get blank page

# Answer
> -2 votes
I've installed composer and it's working

# Answer
> 0 votes
1. Make sure your environment enable php "curl" extension.
2. Check your s3-php5-curl library is right place folder
3. check user have Amazon S3 Full Access Permission。

---
Tags: 7
---


# Question
Title: Content access based on the content author's role
I have a content type named "Files". I have given access for users with roles `editor 1`, `editor 2` and `editor 3` to `update` and `delete` their own content.

Now If a user with *editor 1 creates a files content*. I need to allow other users with same role (editor 1) to update and delete the content.

I tried Content Access Module but it doesn't helps.

Can anyone give me a working example for this scenario.

# Answer
The permission on "own content" is connected to the node's author's uid and only relates to role in that a user with the role holding that permission can edit a node they created.

How I would solve your use case is with a hook\_node\_access in a custom module. https://api.drupal.org/api/drupal/modules!node!node.api.php/function/hook\_node\_access/7 WARNING: I just threw this together as an example, I did not test, and you need to put in the right role values.

```
hook_node_access($node, $op, $account) {
  if( $op !== 'update'){
    // not my use-case
    return NODE_ACCESS_IGNORE;
  }

  $author = user_load($node->uid);
  if( in_array( 'role1', $author->roles) && in_array( 'role1', $account->roles) ) {
    // the user editing has the same role as the author
    return NODE_ACCESS_ALLOW;
  }
  // repeat ... etc.

  // we did not find what we were looking for, continue with normal access check
  return NODE_ACCESS_IGNORE;
}

```
> 1 votes

# Answer
It seems to me that with the Rules module (together with the Content Access module you already have) you can get this to work ... The rule to create in this case woud be a variation of what's described in Tutorial: editorial workflow with rules (within the paragraph "Create rules to publish the content").

In this case, the "action" would be to "Grant access by role".
> 0 votes

---
Tags: 7, users
---


title: Using entity form display modes

text:
# Question
Title: Using entity form display modes
I have created a custom form display mode `my_mode` for nodes and wish to display node form using this mode instead of default one at a custom page. How can I do it?

`$this->entityFormBuilder()->getForm()` accepts an operation as a parameter, but not form mode.

# Answer
Form modes and form operations are a bit strange. You also need to define a form operation through `hook_entity_type_alter()` to be able to use a custom form mode.

Which makes the UI to create form modes pretty useless, but ssshh, don't tell anyone :)

For an example, see `views_ui_entity_type_build()`: `$entity_type->setFormClass($operation, $class_name)`
> 4 votes

# Answer
Indeed it is quite strange I find to have both operation and form display, but you do not especially need to have a form operation to use your display. You have to use `hook_entity_type_alter` though...

Here is the way for example to load the "super" form mode (if exists and is activated) :

```
/**
 * Implements hook_entity_form_display_alter().
 */
function my_module_entity_form_display_alter(&$form_display, $context) {

  // Load the right entity form display.
  $id = $context['entity_type'] . '.' . $context['bundle'] . '.super';
  $storage = \Drupal::entityManager()->getStorage('entity_form_display');
  $change_display = $storage->load($id);

  // If form mode is activated, replace the given one with ours.
  if ($change_display) {
    $form_display = $change_display;
  }
}

```
> 3 votes

---
Tags: 8, entities
---


title: How is comment widget controlled

text:
# Question
Title: How is comment widget controlled
In the core within the comment module a widget is provided by CommentWidget.php file (namespace`Drupal\comment\Plugin\Field\FieldWidget;`). In this widget comment settings like open, close, hidden is provided. I am able to understand its working but not able to find from where it is being further controlled. By controlling I mean where in module (node or comment) status of comment is being processed, how the node decides whether it should show comments or not. Please tell me the file in the core where I should be looking for the code which does this processing. Thanks.

# Answer
> 1 votes
It's not being controlled, it controls.

The widget allows you to edit the comment status of a given node/entity. That is stored in the comment field, and the comment formatter, that displays the comments/comment form is then using it to decide what to show.

---
Tags: nodes, entities, 8, comments
---


title: Adding custom block problems

text:
# Question
Title: Adding custom block problems
I've created my own module in drupal 8. I also created block in my module. I tryied to add my custom block (which is type of custom form) to view. But when I am trying to add custom block in view, its not appearing in the list. Block is only appearing in block layout. What is wrong or is there other way of adding custom block from module to your view in drupal 8?

```
<?php
/**
 * @file
 * Contains \Drupal\reviewhelper\Plugin\Block\ReviewHelperBlock.
 */
namespace Drupal\reviewhelper\Plugin\Block;

use Drupal\reviewhelper\Form;
use Drupal\Core\Block\BlockBase;
use Drupal\Core\Form\FormStateInterface;

/**
 * Provides a 'ReviewHelper' Block
 *
 * @Block(
 *   id = "ReviewHelper",
 *   admin_label = @Translation("Review helper block"),
 *   category = @Translation("Custom Blocks"),
 * )
 */
class ReviewHelperBlock extends BlockBase {
  /**
   * {@inheritdoc}
   */
  public function build() {
    $form = \Drupal::formBuilder()->getForm('Drupal\reviewhelper\Form\ReviewHelperPush');
    return $form;
  }
}

```

# Answer
There are two different "block things". Actually, three.

1. First, there are block plugins. That's code, that's what you have. It's the thing you select on the block layout page. It's *not* something that you can list with views (Well, theoretically, it would be possible, but you would have to write a views query plugin that queries plugins.)
2. Then, there block config entities. That's a plugin + configuration, a block placement.
3. Last, there are custom blocks or content blocks. Those are content entities, similar to nodes with different types, fields and so on. Those are the user-created data. Each of them is exposed on the block layout page as a plugin derivate. There's one plugin class for them and then there are derivates for each content entity. Those are the things you can list with views. Only those.

Everything is connected, you can create custom/content blocks, which are exposes as a block plugin, which is then placed and becomes a block config entity. But they're all different things.
> 3 votes

---
Tags: blocks, 8
---


title: Render a custom menu in a custom block

text:
# Question
Title: Render a custom menu in a custom block
I want to create a block that contains somes links of a menu, without using the interface. So I created a custom module. Inside, there are somes files.

a mymodule/test.links.menu.yml :

```
test.menu.listown:
  title: list
  route_name: test.listown

test.menu.addnew:
  title: Add new
  route_name: test.addnew
  weight: 0
  parent: test.menu.listown

```

and a mymodule/src/Plugin/Block/test\_block\_main.php

```
class test_block_main extends BlockBase {
  public function build(){

    $mp = \Drupal::menuTree()->getCurrentRouteMenuTreeParameters("test.menu.listown");
    $test = \Drupal::menuTree()->load("test.menu.listown", $mp);
    $render = \Drupal::menuTree()->build($test);

    return array('#markup' => \Drupal::service('renderer')->render($render));
  }

}

```

I cleared caches (`drush cache-rebuild`). When I go to my homepage, the "test\_block\_main" is displayed, but it is empty. Why is my custom block empty? Is the `"test.menu.listown"` parameter passed to the methods not correct?

# Answer
> 1 votes
You also need to provide the actual menu config entity as default configuration in `config/install`. Note that test.menu.listown is *not* a valid menu name, they can't contain dots only alphanumeric characters and dashes.

I'd recommend to prefix all default configuration with your module name, so that they're unique. Something like `mymodule-something`.

And, try to follow coding standards and conventions. For example, always use camelCase for class names, like TestBlockMain in TestBlockMain.php.

And last, avoid calling render() yourself whenever possible. You can just return a render array from a block.

---
Tags: routes, blocks, 8
---


# Question
Title: Disabled AJAX paging with embedded views when used in Views template files
I am using a View in two different pages: **page--front.tpl.php** and **views-view-grid--inside--page-1.tpl.php** which is a custom display of a view.

This is the code that is used in both of these

```
print views_embed_view("loadcover","block",$nid);

```

and I also set **Use AJAX:Yes** in the Views settings. The problem is the View's Ajax paging works in the **page--front.tpl.php** but it's Ajax paging doesn't work in **views-view-grid--inside--page-1.tpl.php**, In this page the pager is appeared as a link not ajax. What is the problem?

---

UPDATE:

I tried

```
print views_embed_view("loadcover","block",$nid);

```

in **page.tpl.php** and it worked with Ajax, Is there any problem with Views template files?

I found Disabled AJAX paging with embedded views when used in page.tpl.php it gave me some clues but still I'm unable to solve the problem.

---

UPDATE:

This is the complete code, This code is exactly the code that is works in **page--front.tpl.php**. I moved the *print views\_embed\_view("loadcover","block",$nid);* in different places of this code but it didn't work again. I guess the problem might be because of js codes that are not loaded in this page.

```
<?php
global $base_url;
global $language;
$menu  = new stdClass();
$menu = buildMenuObject($menu);
$bookCounter = 0;
while ($bookCounter < sizeof($view->result)){
    $nid = $view->result[$bookCounter++]->nid;
    if($bookCounter <= 6)
    {
        $top = 222 + (188 * floor($bookCounter/7));
    }
    else
        $top = 252 + (188 * floor($bookCounter/7));
    $node = node_load($nid);
    $wrapper = entity_metadata_wrapper('node',$node);
    $title = $wrapper->title->value();
    $detail = $wrapper->field_detail->value();
    $writer = $wrapper->field_writer->value();
    $edition = $wrapper->field_edition->value();
    $translators = $wrapper->field_translators->value();
    $publisher = $wrapper->field_publisher->value();
    $year = $wrapper->field_year->value();
    $nop = $wrapper->field_nop->value();
    $jelds = $wrapper->field_jeld->value();
    print "<div style='top:".$top."px' class='lib-td-detail lib-td-detail-counter-$bookCounter library-td-detail-nid-".$nid."'>";
        print "<img class='lib-detail-close' src='".$base_url."/sites/all/themes/lib/images/cross.png' />";
        print "<div class='library-fields-container lib-inside-fields-$nid'>";
            print "<div class='library-fields-right library-fields'>";
                print "<div class='library-title'>";
                    print $title;
                print "</div>";
                print "<div class='library-field library-writer'>";
                    print $menu->writer." : ". $writer;
                print "</div>";
                print "<div class='library-field library-edition'>";
                    print $menu->edition." : ". $edition;
                print "</div>";
                print "<div class='library-field library-translators'>";
                    print $menu->translators." : ". $translators;
                print "</div>";
                print "<div class='library-field library-publisher'>";
                    print $menu->publisher." : ". $publisher;
                print "</div>";
                print "<div class='library-f-detail'>";
                    print $detail;
                print "</div>";
            print "</div>";
            print "<div class='library-fields-left library-fields'>";
                print "<div class='library-fields-left-top library-fields-top'>";
                    print views_embed_view("loadcover","block",$nid);
                print "</div>";
                print "<div class='library-fields-left-bottom library-fields-bottom'>";print "</div>";
            print "</div>";
        print "</div>";
    print "</div>";
}

?>

```

# Answer
> 1 votes
It looks like you are adding some chunks of code logic to your theme templates? This is not usually recommended in a drupal instance. Have you tried adding a context to include your loadcover view block on the view generating your grid, so that you do not need to print embed in the tpl? https://www.drupal.org/project/context

Enable the module and go to /admin/structure/context/add Set the name of this context, something like Book Grid Display. We use a "Layout" tag group for things like this, but you could use "custom" or just about anything you want, it is optional. Under the Conditions dropdown select Views, and on the list that appears to the right check the box in front of your Inside grid view. Under Reactions select Block. The theme regions will appear as well as the different groupings of blocks available on your system. The last grouping is Views, select your Loadcover view and click the +Add on the theme region you are wanting (I assume Content since you were printing this in the content template).

The page content will have a weight of 0, and the drag-and-drop reorder likes to start at weight -10 so use the Show Row Weights to get it under the view grid if desired. Or at least that is a quirk I have seen when using this method.

Another note, the views\_field\_view that was mentioned in a comment would allow you to add your Loadcover view as a field in your book grid view, so that you did not have to inject it with custom code from the theme logic layer. If you were wanting to invoke LoadCover for each cell in your grid and I missed that part, then yes views\_field\_view would solve the problem for you instead of this context solution which will get you one instance of Loadcover.

# Answer
> 0 votes
you can try adding the javascript code with views\_add\_js

```
views_add_js('ajax');

```

---
Tags: views, theming, ajax, paging
---


# Question
Title: Is there a way to search for instances of hook_views_query_alter() in my database?
I am running a D7 site that someone else built and I'm having trouble seeing how an SQL command in a particular view has been altered. In particular, the attributes in the `SELECT` statement appear to have been altered.

Is there a way to search my database to see if the person building the site added an errant `hook_views_query_alter` command that is the reason the SQL filter looks different than one would expect just looking at the fields in the View?

Or is there another, better way to debug this issue? Thanks for any help!

# Answer
Views field output can also be rewritten under the view's fields setting in the views interface using "rewrite the output of this field" using tokens from previous rows or arbitrary HTML. That's the likeliest place.

If not there, the next candidate for views output modification is in the theme template files. People will stick any kind of logic in views theme template files. To see if custom template files are in use, see "Theme: Information" in the views and the template file in use will be in bold.

Generally, hook\_views\_query\_alter is not the normal way of modifying a view. But a hook\_views\_query\_alter would be added in the code rather than the database. Drupal does cache a list of implemented hook functions in a the theme registry table, but that's not very readable nor informative. Not where you should be looking. Your best bet is to search your code for "\_views\_query\_alter" and see what you turn up. There will be a lot of results, but likely you'll recognize any custom modules.

I might also turn on Show SQL Queries in under Views-\>Settings to see the output of the views query as views reports it as it's being run in the Views preview interface below the view builder interface. Then you can see the query being run to see if it matches your expectations.

There is also a setting in views under Advanced -\> Query to turn off SQL rewriting for a view. This will disable access checks as well as some query rewriting (but not all) so use sparing.
> 1 votes

---
Tags: 7, views
---


title: Dynamic query returns multiple data

text:
# Question
Title: Dynamic query returns multiple data
I have a quite simple query : (find all nodes, fetch 3 fields from the node table and join the results with some tax.terms)

```
$query = db_select ( 'node', 'n' );
  $query->fields ( 'n', array(
      'nid',
      'title',
      'type' ));
  $query->fields('b',array('body_value'));
  $query->fields('ttd',array('name'));

  $query->leftJoin ( 'field_data_body', 'b', 'b.entity_id = n.nid');
  $query->leftjoin ( 'taxonomy_index', 'ti', 'ti.nid = n.nid');
  $query->leftjoin ( 'taxonomy_term_data', 'ttd', 'ttd.tid = ti.tid AND ttd.vid = "5"');

  /* $query->condition('ttd',5); */

  $result = $query->execute ()->fetchAll ();

```

Now the problem is that i want a single object returned form the query for each node. Like this :

```
stdClass Object
(
    [nid] => 557
    [title] => Lorem ipsum
    [type] => content_type
    [body_value] => lorem ispum
    [name] => taxonomy_term_value
)

```

But what i get is multiple objects because of the taxonomy index table (where a node can have anywhere **from 12 term id's to none at all**) but i only need 1 that corresponds to the condition stated above in the query (vid = 5, from the tax.term data table) **if** that node has a link to the tax.term, if the node does not have link it should return nothing,null,empty string...

So my results are as follows :

```
stdClass Object
(
    [nid] => 155
    [title] => lorem ipsum
    [type] => content_type
    [body_value] => lorem ispum
    [name] =>
)
stdClass Object
(
    [nid] => 3411
    [title] => lorem ipsum
    [type] => content_type
    [body_value] => lorem ispum
    [name] => value1
)
stdClass Object
(
    [nid] => 161
    [title] => lorem ipsum
    [type] => content_type
    [body_value] => lorem ispum
    [name] => value4
)
stdClass Object
(
    [nid] => 561
    [title] => lorem ipsum
    [type] => content_type
    [body_value] => lorem ispum
    [name] => value16
)

```

# Answer
> 0 votes
What you get currently is what you asked for: `leftJoin`.

To get only the single object you're looking for, you must use `join` instead (which is default and equivalent to `innerJoin`).

BTW you may simplify your code using the short notation, like this:

```
$query = db_select('node', 'n')
  ->fields('n', array('nid', 'title', 'type' ))
  ->fields('b', array('body_value'))
  ->fields('ttd',array('name'))
  ->join('field_data_body', 'b', 'b.entity_id = n.nid')
  ->join('taxonomy_index', 'ti', 'ti.nid = n.nid')
  ->join('taxonomy_term_data', 'ttd', 'ttd.tid = ti.tid AND ttd.vid = "5"');

```

---
Tags: database
---


# Question
Title: Centered layout with div borders on left and right (with bg images)
I have begun a new theme on drupal using the Boilerplate theme. I am trying to achieve a centered(responsive width) layout with borders on both left and right sides. I have attached a diagram. DIAGRAM HERE

I have the left side borders working fine, they are within the #PAGE div which is the one and only WRAPPER of all content. (there is no other div above it)

As i have shown in the diagram, i am having trouble with the RIGHT side borders. With the same CSS syntax as the left borders, you can see they are positioned all the way to the right, even though they are inside the #PAGE div. Why is this? why is the #PAGE div not pulling it together?

Thanks for the help!

EDIT `code`jsFiddle demo/mockup

PS- these 'borders' need to hold images as backgrounds so i can not simply use the 'border' property. And the 'border-image' is not well supported. DIV's is what i need.

# Answer
> 0 votes
The main problem in your example is that your "border" `<div>'s` have `position: fixed;` so they refer to the viewport rather than to the parent `<div id="page">`.

It's why you observe the right ones behaviour, which is pretty normal.
The left ones *seem* to refer to `#page`, only because they have not any `left` or `right` property set, so it defaults to `auto`.

Hence here is the first point: **you must set `position: absolute;` for these "borders".**

Additionaly you must remember that, for the `absolute` positioned element to refer to its nearest parent, this one must not have `position: static`, or another parent will be looked for as reference... till `<body>` if none is found, so it will be the same as for a `fixed` positioned element.

So here is the second point: **you must set `position: relative;` for the parent `#page`.**

From there you have to manage with `left`and `right` properties to get what you want.
You can look at this fiddle, where I added the needed properties to strictly conform to your DIAGRAM exposed wills.

---
Tags: theming
---


# Question
Title: How can I let users create their own playlists of a particular content type?
How can I let users create their own playlists of a particular content type?

I have used the Flag module but it allows only a single list. I want the user to be able to create multiple lists.

I have tried the Flag Lists module but cannot seem to get it working.

Any help would be appreciated.

# Answer
> 1 votes
I used the **Flag Lists** module. Here is a quote about it (from its project page):

> Flag lists allows regular users to create unlimited private flags called lists. Flag lists extends Flag. In Flag, a site administrator creates the flags that any authorized users may use. In Flag lists, users create their own lists, and they may only add to their own lists.
>
> An example use case would be a shopping site where users make private wishlists that they name and manage: "Books I need for my Drupal library" or "Guitar strings I've tried on my Yamaha acoustic". The site builder can then work with the lists, most likely using Views, to provide useful content display, perhaps integrating with a shopping cart or an email broadcast.

# Answer
> 4 votes
# Flag module

Use the Flag module to create 1 flag for each of the lists you want to use it for (do NOT make it a 'global' flag though). The flags are to be created by an admin, but each user (authorized to use a flag) will then be able to build their own "lists" using such flag.

Then create a view (with the views module) for each such playlist you want, whereas you create a "views relationship" with one of those flags.

This approach requires the types of flags to be pre-defined (via admin), such as playlist-flags named like Bookmarked, Revisit Later, Add to my queue, Played, etc. Though it is ony like a 5 min admin update to add any other relevant flag later on (eg if a user requests another variation).

If you're not familiar with the Flag module, checkout the set of 8 video tutorials about the flag module.

You might also want to look at some of the Flag related modules, such as (partial list):

* Views, to create lists of flagged content, users, etc, such as in the video about Creating global flags and listing flagged content in Views.
* Rules, to trigger rules for anything that is flagged, such as in the video about Triggering rules with Flag, or to set flags with the Rules module, such as in the video about Setting flags with Rules.
* Flag Lists, to allow users to create custom lists.
* Flag Weights, to add weights to Flags (to be used for sorting).
* DraggableViews, to make Views draggable (so that they can be rearranged by Drag'n'Drop.).
* Flag Friend, a pre-built flag for marking other users as friends (using the Flag module).
* Flag Abuse, a pre-built flag for marking offensive content, with some extra administrative features.
* Flag, Hide & Mute, for users to hide individual nodes, such as site-wide announcements or advertisements, and/or to suppress all posts by users they do not want to see.
* Flag Files, to flag media files.
* Flag Service, to allow Flag to be accessed via a web services interface through the Services module.
* DLike, provides a Facebook like "Like" functionality using the Flag and Lightbox2 module.
* Conditional Flags, provides an extra API to Flag module, for custom conditions between flags.
* Organic Groups Flag Integration, extends the flag module with organic groups support allowing the administrators of each group to override the global flag settings for their group.
* Context Flag, allows the use of Flags as conditional triggers for use with the Context module.

Refer to its community documentation for way more details.

# Entity Reference module

Create a content type like "Playlist" for which each user should be able to create/edit "their" nodes for (with 1 node for each Playlist they want). And add a field in it using the Entity reference module for it (with multiple values allowed). Combine this with the Node Access module to ensure that each user can only "edit" their own Playlist nodes.

## Other usecases

Refer to my answer to How to motivate visitors to comment (technically)? for other usages of the Flag module as illustrations of other great things you can do with the Flag module, and some other great modules that play well with it (i.e. the Rules module).

---
Tags: users, flags
---


title: How to store form in order

text:
# Question
Title: How to store form in order
I have customers filling out an entry form before sending them to checkout. Is it possible to store, or serialize, the $form\_state array in the order? There is a 'data' field in the order. Is it simple as me calling:

```
$order->data = serialize($form_state);
commerce_order_save($order);

```

EDIT:

The data field in the order is an array that gets serialized. So, it looks like I can do:

```
$order->data['myform'] = $form_state;

```

# Answer
There is the `data` attribute on entities, which you cannot access through Entity Metadata Wrappers (per previous answer.)

Do you need the full form state or just values? Also, you do not need to serialize the data, as the entity controller will do this for you.

I would do something like:

```
form_state_values_clean($form_state);
$order->data['myform_values'] = $form_state['values'];

```

form\_state\_values\_clean() will remove build IDs and such.
> 4 votes

# Answer
You would need to add a field to commerce\_order called field\_data and then save it, yes.

The pattern might be more like:

```
$order_wrapper = entity_metadata_wrapper('commerce_wrapper', $order_id);
$order_wrapper->field_data = serialize($form_state);
$order_wrapper->save();

```
> 0 votes

---
Tags: 7, commerce
---


# Question
Title: Panopoly WYSIWYG exclude buttons configurations
Can anyone tell me if it's possible to configure the Panopoly wysiwyg to we can have different buttons available to different roles?

At the moment, without have to create a module, I can't find a configuration area which will allow the exclusion of certain buttons for some roles.

# Answer
> 0 votes
Since Panopoly WYSIWYG module does not provide this kind of configuration out of the box, you will need to add additional text formats and WYSIWYG profiles. When configured, export them to your own Features project. If you customize the WYSIWYG profile provided by Panopoly WYSIWYG, be sure to export those using Features Override module (provided in full distro and if using Panopoly Core I believe.)

WYSIWYG profiles merely build on top of existing text formats which have restrictions by roles.

The alternative, however, is to use hook\_wysiwyg\_editor\_settings\_alter() and possibly remove buttons based on role, that way.

---
Tags: security, wysiwyg, distributions
---


# Question
Title: Path aliases not updating or setting automatically
I have an Open Atrium site where the path aliases are not generated automatically and not updated if I change them manually.

How can I fix this?

# Answer
The aliases are generated when you create an object in your site and are based upon the pathauto patterns (placeholders) you specify at:

For 6.x: `Administer > Site Building > URL aliases`, in the "Automated alias settings" tab.

For 7.x: `Administer > Configuration > Search and Metadata > URL aliases`, in the "Patterns" tab.

Pattern tab provides several default patterns that automatically alias the different content types.

Settings tab allows to refine length and case, as well as defining if an alias is to be replaced or added to the list.
> 0 votes

---
Tags: path-aliases, distributions
---


title: #ajax form_set_error

text:
# Question
Title: #ajax form_set_error
I'm using the below code to query a webform field's value against database, and if the value exists, I want to use form\_set\_error, however I can't, since it requires rewriting the page. I have found this post but it doesn't have an answer, hence my question.

```
function tubitekuz_form_alter(&$form, &$form_state, $form_id) {
  switch($form_id) {
    case 'webform_client_form_97':
      global $user;
      if ($user->uid > 0) {
        $form['submitted']['kullanici_adi']['#access'] = FALSE;
      }
      $form['submitted']['kullanici_adi']['#ajax'] = array(
        'event' => 'blur',
        'callback' => '_tubitekuz_check_username',
      );
      break;
    case 'contact_site_form':
      $form['#submit'] = array('_tubitekuz_show_message');
      break;
    default:
      break;
  }
}

function _tubitekuz_check_username($form, &$form_state) {
  $username= $form_state['values']['submitted']['kullanici_adi'];
  $exists = db_query('SELECT name FROM {users} WHERE name = :entered', array(':entered' => $username))->fetchField();
  if ($exists) {
    $commands = array();
    $commands[] = drupal_set_message('Kullanıcı adı kayıtlı, lütfen başka bir kullanıcı adı seçin');
    return array('#type' => 'ajax', '#commands' => $commands);
  }
}

```

How do I go about that?

PS: drupal\_set\_message does its thing only when I refresh the page, whereas form\_set\_error doesn't do at all.

EDIT: I tried to replace the above with the below code:

```
function _tubitekuz_check_username($form, &$form_state) {
  $username= $form_state['values']['submitted']['kullanici_adi'];
  $exists = db_query('SELECT name FROM {users} WHERE name = :entered', array(':entered' => $username))->fetchField();
  if ($exists) {
    drupal_add_js(drupal_get_path('module', 'tubitekuz') . '/js/tubitekuz.js');
    drupal_add_css(drupal_get_path('module', 'tubitekuz') . '/css/tubitekuz.css');
  }
}

```

and in tubitekuz.js I am doing

```
$(document).ready(function() {
    var username=jQuery('#edit-submitted-kullanici-adi');
    username.addClass('err');
    setTimeout(function() {
      username.removeClass('err');
      }, 3000);
});

```

and in tubitekuz.css I have the below:

```
.err {
  border-color:red;
  border-width:2px;
}

```

however, CSS rules are not applied even though class is added. What is the cause of this? All I'm trying to do is use `form_set_error` with `#ajax`

# Answer
> 0 votes
You can try this one:

```
//playground.module

function playground_form_alter(&$form, &$form_state, $form_id) {
  switch($form_id) {
    case 'webform_client_form_1':
      global $user;
      if ($user->uid < 0) {
        $form['submitted']['username']['#access'] = FALSE;
      }
      $form['submitted']['username']['#ajax'] = array(
        'wrapper' => 'webform-client-form',
        'method' => 'replace',
        'effect' => 'fade',
        'event' => 'blur',
        'callback' => '_playground_check_username',
      );
      break;
  }
}

function _playground_check_username($form, &$form_state) {
  $exists = FALSE;
  $commands = array();
  $username= $form_state['values']['submitted']['username'];

  $parents = $form_state['triggering_element']['#array_parents'];
  array_pop($parents);
  $element = &drupal_array_get_nested_value($form, $parents);

  if (!empty($username)) {
    $exists = db_query('SELECT name FROM {users} WHERE name = :entered', array(':entered' => $username))->fetchField();
  }

  if ($exists) {
  form_error($element, 'Kullanıcı adı kayıtlı, lütfen başka bir kullanıcı adı seçin');
  $error_selector = '.form-item.webform-component--username';
  $commands[] = ajax_command_replace($error_selector, theme('status_messages'). drupal_render($element) );
  // Use below commands if you want to display in message region.
  // $commands[] = ajax_command_replace($error_selector, drupal_render($element) );
  // $commands[] = ajax_command_remove('#messages');
  // $commands[] = ajax_command_before('#main-wrapper', '<div id="messages"><div class="section clearfix">' . theme('status_messages') . '<div></div>');

  return array('#type' => 'ajax', '#commands' => $commands);
  }
}

```

# Answer
> 0 votes
Your code needs to be adjusted to something like:

```
function tubitekuz_form_alter(&$form, &$form_state, $form_id) {
  switch($form_id) {
    case 'webform_client_form_97':
      global $user;
      if ($user->uid > 0) {
        $form['submitted']['kullanici_adi']['#access'] = FALSE;
      }
      $form['submitted']['kullanici_adi'] += array(
        '#prefix' => '<div id="kullanici-adi-container">',
        '#ajax' => array(
          'callback' => 'kullanici_adi_form_login',
          'wrapper' => 'kullanici-adi-container',
        ),
        '#suffix' => '</div>',
      );

      // Check the form state to see if an e-mail address has been specified.
      if (!empty($form_state['values']['kullanici_adi'])) {
        $mail = trim($form_state['values']['kullanici_adi']);

        if ($account = user_load_by_mail($mail)) {
          form_set_error('submitted][kullanici_adi', 'Kullanıcı adı kayıtlı, lütfen başka bir kullanıcı adı seçin');
        }
      }
      break;
  }
}

function kullanici_adi_form_login($form, $form_state) {
  return $form['submitted']['kullanici_adi'];
}

```

You will probably have to play around with some of the arrays, etc. to get the correct values, etc.

# Answer
> 0 votes
it would be something like this:

```
$form['submitted']['kullanici_adi']['#ajax'] = array(
        'callback' => '_tubitekuz_check_username',
        'wrapper' => 'the_form_id'
      );

```

and this one in your ajax callback \_tubitekuz\_check\_username, you can put your form\_set\_error before. be carefull you might need

```
form_set_error('kullanici_adi', t('your error'));

```

or this one if the first doesn't work (I don't remember for this case)

```
form_set_error('submitted']['kullanici_adi', t('your error'));

```

then this code to rebuild a part/entire of the form

```
$commands[] = ajax_command_replace('#the_form_id', drupal_render($form));

```

This should do it.

That's pretty much what I told you 2 days ago.

EDIT:

```
function tubitekuz_form_alter(&$form, &$form_state, $form_id) {
  switch($form_id) {
    case 'webform_client_form_97':
      global $user;
      if ($user->uid > 0) {
        $form['submitted']['kullanici_adi']['#access'] = FALSE;
      }
      $form['#validate'][] = 'webform_client_form_97_form_validate';
      break;
    case 'contact_site_form':
      $form['#submit'] = array('_tubitekuz_show_message');
      break;
    default:
      break;
  }
}
function webform_client_form_97_form_validate($form, &$form_state){
  $username = $form_state['values']['submitted']['kullanici_adi'];
  $exists = db_query('SELECT name FROM {users} WHERE name = :entered', array(':entered' => $username))->fetchField();
  if ($exists) {
    form_set_error('submitted][kullanici_adi', 'Kullanıcı adı kayıtlı, lütfen başka bir kullanıcı adı seçin');
  }
}

```

---
Tags: webforms, forms
---


# Question
Title: How to add JavaScript code to a webform?
I want to add JavaScript code to a webform. For example, to add things like onclick, onchange, mouseover function to webform's textbox, textarea, select, email, etc.

How do I do so?

# Answer
The recommended way to add a JS to any form in Drupal is using #attached to the `$form` element.

In order to add the JS to a webform, you would have to implement `hook_form_alter` or `hook_form_FORM_ID_alter`, and add the `#attached`

```
function MODULE_form_webform_client_form_3_alter(&$form, &$form_state) {
  $form['#attached']['js'] = array(
    drupal_get_path('module', 'MODULE') . '/MODULE.js',
  );
}

```

Then create the MODULE.js file inside the module directory, and write your JS there.

Refer to The Drupal JavaScript API, to see how to work with JS in Drupal way.
> 6 votes

# Answer
To load a script on a specific form , follow the following steps:

1. Copy webform-form.tpl.php to your sub-theme's root directory.
2. Rename it webform-form-NID.tpl.php, where NID is the node ID of your webform.
3. Add the following code in above created theme file:

> drupal\_add\_js(path\_to\_theme() .'/scripts/SCRIPT\_NAME.js');
> -1 votes

---
Tags: 7, webforms, javascript
---


title: Prevent "Fit to Window" setting

text:
# Question
Title: Prevent "Fit to Window" setting
I have the following image and when I click on it. it will pop out into a **colorbox** modal, but it currently re-sizes it to fit to the window. How would I just resize it up to only the width of the window and have the user scroll down to see the rest of the image?

I'm using the colorbox module. I know I have to unset the innerHeight to auto or something. But how would you override a javascript snippet without affecting other pages on the site?

# Answer
You can try with below Jquery snippet.

```
(function ($) {
var cboxOptions = {
     width: '95%',
     height: '95%',
     maxWidth: '768px',
     maxHeight: '768px',
}

$('#colorbox').colorbox(cboxOptions);

$(window).resize(function(){
   $.colorbox.resize({
     width: window.innerWidth > parseInt(cboxOptions.maxWidth) ? cboxOptions.maxWidth : cboxOptions.width,
         height: window.innerHeight > parseInt(cboxOptions.maxHeight) ? cboxOptions.maxHeight : cboxOptions.height
   });
});

```
> 1 votes

---
Tags: javascript
---


# Question
Title: How to edit image field output from template
My goal is to edit the output of a specific field in a view.

There is an image field, and I would like to specify how it is output. So that instead of

```
<img typeof="foaf:Image" src="https://url.com/sites/default/files/styles/com_home_news/public/field/image/myimage.jpg?itok=8e4_c1xI" width="290" height="140" alt="">

```

I can output something like

```
<img src="imagepath/image.jpg">

```

I'd like to be able to edit the output freely and just have access to the image path for this specific view.

I am currently editing

```
views-view-field--com-retheme-home-news--field-image.tpl.php

```

However I'm not sure how to actually access the path to the image. Using

```
<?php print $output; ?>

```

Only prints out what it would have before.

I understand that I could change the field itself to only present the path, however that isn't an option since there is already a lot of content taking advantage of how the field is already setup.

# Answer
> 0 votes
It's a bit of a work around but I found a solution. What I ended up doing was use a regular expression on $output to grab the path and then used it to spit out what I wanted like so:

```
$pattern = '/src\s*=\s*"(.+?)"/';
$img = preg_match($pattern,$output,$results);
print "<img ".$results[0].">";

```

# Answer
> 2 votes
You need to install the Image URL Formatter module

Then in your view, click on your image field and select url as the formatter, so it prints the url rather than the image.

**Option A)** In the rewrite results field, use the token for your image field.

Example: `<img src="[field_image]" class="yay-we-did-it">`

**Option B)** if you want to use the .tpl.php file, put this inside it.

`<img src='<?php print $fields["field_image"]->content; ?>' class='yay-we-did-it'>`

---
Tags: entities, theming
---


# Question
Title: Using Views to filter the content based on the current month
I am building a site, using Views, that needs to filter the content for each month. I have created a date field on the custom content type, and I made a publish start and end date fields.

I need the view to change the content at the start of the new month. Can anyone please explain how to make a view only display content based on the current month?

# Answer
> 3 votes
In the latest versions of Views, you can use a date argument to do this. For example, you could select the node post date as a date to use with the argument, and then if you passed 2011-12 as the argument, it would limit the display to only nodes posted in December 2011. You can use any ISO date for this, too, so P1M, which means a period of 1 month, would create an argument for the current month. Check out http://en.wikipedia.org/wiki/ISO\_8601 for an indepth explanation of a lot of different ISO date formats. All should work here, the only one you have to be careful of is the interval format; with drupal you need to use -- instead of / to separate them for hopefully obvious reasons.

If, however, you are wanting to group or aggregate your content by month, check out http://drupal.org/node/388140.

# Answer
> 0 votes
For those who still looking for a way to figure out this one.

1. Open your views UI
2. Look to Page Settings -\> Path
3. Set the Path like this: "news/%". You can use any word you like, obviously.
4. Go to "Advanced Tab" -\> Contextual Filter -\> Created Year. Use Defaults

Now you can filter your nodes by passing additional argument to your URL like this:

news/2015

news/2014

Thats all

---
Tags: views
---


# Question
Title: What causes very long initial visit load times intermittently?
I'm working on what is basically a one page site externally:

There's very little to it. But I'm getting reports that it's sometimes loading so slow to the point that a couple refreshes are required to get it to load on first visit. Now as this is such a small site, virtually every significant module is turned off.

I mean Update is off, Views is off, Date is off and on and on. In addition to that the few graphics are optimized. There's no external content integrated that could be causing it to hang that I can think of. CSS and JS are being aggregated. Caching is off, but it is a one page site, so on initial visit I wouldn't think caching would provide any advantage.

What are some of the potential causes of an issue like this?

# Answer
> 0 votes
If users experience very long response time for initial visit, but then next visits are fast - then it definitely could be related to the cron (as suggested by Geoff).

Here is a quote from official cron documentation:

> It \[internal cron\] works by checking at the end of each Drupal request to see when cron last ran and, if it has been too long, processing the cron tasks as part of that request. The two down-sides are (1) cron tasks will only run when Drupal is processing requests; and (2) the 'weight' (processing and memory) of running the cron tasks will be added to some arbitrary unknown page request, which may slow down those requests, and has the potential to exceed memory limits on a complex site.

To prevent this, configure external cron job that will trigger Drupal cron jobs more often that 3 hours (my suggestion is to run external cron every hour).

In addition you can configure internal cron to run less often by configuring it here /admin/config/system/cron.

---
Tags: caching, performance
---


# Question
Title: How to override function system_send_email_action_validate
The following is in the core system.module

```
/**
 * Validate system_send_email_action form submissions.
 */
function system_send_email_action_validate($form, $form_state) {
  $form_values = $form_state['values'];
  // Validate the configuration form.
  if (!valid_email_address($form_values['recipient']) && strpos($form_values['recipient'], ':mail') === FALSE) {
    // We want the literal %author placeholder to be emphasized in the error message.
    form_set_error('recipient', t('Enter a valid email address or use a token e-mail address such as %author.', array('%author' => '[node:author:mail]')));
  }
}

```

This is stopping VBO send email from sending email to a CCK email field. How can I override this function? I want to change it to the following...

```
/**
 * Validate system_send_email_action form submissions.
 */
function system_send_email_action_validate($form, $form_state) {
  $form_values = $form_state['values'];
$has_tokens = count(token_scan($form_values['recipient'])) > 0 ? TRUE : FALSE;
  // Validate the configuration form.
  if (!valid_email_address($form_values['recipient']) && !$has_tokens) {
    // We want the literal %author placeholder to be emphasized in the error message.
    form_set_error('recipient', t('Enter a valid email address or use a token e-mail address such as %author.', array('%author' => '[node:author:mail]')));
  }
}

```

But without hacking core. Is there a way to do this in my custom module? Im having a bit of trouble understanding how overriding a module function works, in theme functions, I can just replace the function in mt template.php using the name of my theme, however `MYMODULE_system_send_email_action` doesnt work.

# Answer
> 0 votes
You can use "hook\_preprocess\_HOOK"

---
Tags: 7
---


# Question
Title: Entity reference field on select show some data about entity
consider i have a customer content type with fields (name, phone, address) and i have a feed back content type with an entity referenced field to customer.

When the user select the customer i want to show the phone and address somewhere near the field.

Is there a module for this? Or how do i do this?

# Answer
There is an option to use views for populating the dropdown in the entity reference fields. Since you are building the options using views, you can pretty much customize it as you want.

Check out this video http://codekarate.com/daily-dose-of-drupal/using-views-entity-reference-module-drupal-7 for more details.

----------------THIS PART ADD BY QUESTIONER-----------------

Thanks to Gokul N K.

This tutorial made what i want in the view mode. What to do in the edit mode?

1. Create a custom module
2. Hook form\_alter
3. Add a HTML div just below the autocomplete field
4. Inject some JavaScript and bind the auctomcompleteSelect trigger on your specified field.
5. In the bind function add an ajax callback to acquire your desired information and display it inside the div.
> 2 votes

---
Tags: entities
---


title: Ubercart- Assign new role on expiry

text:
# Question
Title: Ubercart- Assign new role on expiry
I am granting users specific a role on purchase of some product( using ubercart). In doing so I have added a rule to take away their initial role(so that they do not have 2 roles and confuse the content access permissions). When the role expires, I want to grant the use back his original role. I am trying to use rules to do this. However, I am unsure on what action to call this rule. Any suggestions? Thanks!

# Answer
It seems that "*I am unsure on what **action** to call this rule*" is your remaining issue, and that by using the rules module you are already close.

However, when talking about Rules and its Event-Condition-Action concept, your issue is about what **Event** to use. With that in mind, I would try to use the Rules Scheduler submodule of Rules, to schedule the rule to be executed at the moment of the purchase already.

Makes sense?
> 1 votes

# Answer
You can do this with using Ubercart Roles.

In Ubercart Role there is an option to send the notification to that user whose role is expired. You can trigger a rule on that event or you can define a role expiration event if you wish to tie it to a discrete event rather than the sending of an email.

I have found a patch for Role Expire which creates a Rules event upon role expiration that you might use as a model.

First you need to create a rule, then a simple action to assign a role (Add user role action) to the `expiration:user`.
> 0 votes

# Answer
This problem is you can handled by drupal rules.
> 0 votes

---
Tags: rules, ubercart, users
---


title: Color code field in View?

text:
# Question
Title: Color code field in View?
Use case: When the Status is *Overdue*, the word overdue should display in red, and if it's *Accepted*, it should display as green.

I was hoping to use Rules to set this up, but don't see options to get this logic in.

# Answer
> 0 votes
You can use Style Settings in the field setting and and use replacement tokens as a css class.

# Answer
> 0 votes
You can do that with Format Table Settings.

Click on Format Table Settings And then enter the class with token in the row class option.

For example you can use something like 'status-\[status\]' and then write css for the class. Please make sure that status field is in the list of fields.

---
Tags: views, rules
---


# Question
Title: A relationship to the latest referencing entity in views
I am not quite sure how to do this. I have content type A and another content type B which references content type A using an entity reference field. So A can have multiple nodes of type B referencing it. Not B has a date field.

Now what I want to do is create a view that lists content of type A but sorted based on the date field of the latest node of type B that references it.

I am not really sure what is the best way to achieve that. Any help is highly appreciated.

# Answer
> 0 votes
1. Make a view that lists nodes of Type B.
2. Sort this view based on date.
3. Add relationship based on the reference field which reference content type A.
4. Now list the fields you want from Content type A.
5. If you don't need fields from Content type B, hide them.

---
Tags: views, entities
---


# Question
Title: How to add extra tab in common browsing widget in drupal commons
Here i working in Drupal Commons.7.x and i need to add extra tab in that common browsing widget **(Common Browsing Widget)** section in common drupal.How to achieve to add extra tab in common browsing widget in common drupal.Here my need to in that image Here i tried to change using

> **structure =\> View =\> Common browsing Widget (Poll,Q&A,Event and etc.,)**

. Need to add extra tab with content.how to achieve it.Kindly guide me.!

# Answer
> 0 votes
It uses Quick Tabs.

You can either goto `admin/structure/quicktabs` and edit the quicktab.

Or you can visit `admin/structure/quicktabs/manage/commons_bw/edit` which is the default quicktab for `browsing widget` directly add any block that you want.

---
Tags: 7
---


# Question
Title: Drupal services forbbiden error on put but not on post
I'm using Drupal Services Module to upload data to my site. It works good on local host, and I can do PUT and POST without problems. But after upload my site to a shared hosting, I can do POST, but PUT always get "Forbidden" errors. For exmple, when I try to update a taxonomy term, it returns "Forbbiden. You don't have permission to access taxonomy\_term/2601", where 2601 is a taxonomy term previously created with POST and the same web service's user. And this user has permission to edit this term. Any suggestion? Thanks.

# Answer
> 1 votes
Assuming it is an apache web server you could try this in your .htaccess file.

```
<Limit GET POST PUT DELETE>
  Allow from all
</Limit>

```

Otherwise you may need to contact the hosting support to see if they have restricted PUT requests

---
Tags: services
---


title: How to create simple confirmation page?

text:
# Question
Title: How to create simple confirmation page?
I want to create simple confirmation page. It means that after user change his email then he gets confirmation email with link to page. This link contains token. This link should open page for user with appropriate message (success or fail if token expired). I want to create simple module, But I don't know which hook I should use to create this simple page. I must check this token by sending POST request to REST API before rendering page.

Any advice?

# Answer
I suggest you use `hook_user_update`. Then you compare `$account->mail` and `$account->original->mail`. If the two email addresses are different, the user's email address changed. Next you generate the token and send an email to the user with a link to your page.

For the page, create a new menu entry via `hook_menu` and do the logic for the REST call there. You can get URL query parameters (especially the token) by using `drupal_get_query_parameters`. Maybe you should ensure that the token is unique and store it with the email address and the creation time (to check if it has expired) in the database.

The documentation for hook\_menu (or 99% of all other modules available) should give you an example on how to use it.
> 0 votes

# Answer
```
function custom_menu() {
  $items = array();
  $items['admin/sendmail/%'] = array(
    'title' => t('Delete Entry'),
    'page callback' => 'drupal_get_form',
    'page arguments' => array('custom_confirm_form'),
    'access arguments' => array('send mail'),
    'type' => MENU_CALLBACK,
  );
  return $items;
}

  function custom_confirm_form($form_state){
    return confirm_form($form, t('Are you sure you want to Send Mail?'), //message title
    'admin/send-mail', //redirect if cancelled
    t('Only say yes if you are really sure. Otherwise please click on cancel button.'), //message description
    t('Yes'), //confirm button text
    t('Cancel') //cancel button text
  );
}

function custom_confirm_form_submit($form, &$form_state){
   //verify that the form was confirmed
  if ($form_state['values']['confirm']) {
     custom_send_mail();
  }
}

```
> 0 votes

# Answer
I wrote a blog post that you may find helpful. Good luck!
> 0 votes

---
Tags: 7
---


title: VBO Send email to CCK E-mail field

text:
# Question
Title: VBO Send email to CCK E-mail field
I have a content type called "*Business*", and a user can have multiple "*Businesses*".

Each business has a "*business e-mail*" field. This is different from the users email address, and is different for every business.

I want to be able to use VBO to send an email to all selected businesses. I have the view set up ok, and in the recipients field on the send email page I add the token....

```
[node:field-business-e-mail]

```

and I also tried...

```
[node:field_business_e_mail]

```

But I still get the error :

> Enter a valid email address or use a token e-mail address such as `[node:author:mail]`.

Is there a way to get around this?

# Answer
> 0 votes
You can do this by updating code on `system.module` file. Below are the code :

```
   function system_send_email_action_validate($form, $form_state) {
       $form_values = $form_state['values'];
       $has_tokens = count(token_scan($form_values['recipient'])) > 0 ? TRUE : FALSE;
       if (!valid_email_address($form_values['recipient']) && !$has_tokens) {
          form_set_error('recipient', t('Enter a valid email address or use a token e-mail address such as %author.', array('%author' => '[node:author:mail]')));
       }
}

```

For any help, I have refer you to this PATCH.

This is not working directly try to do it manually.

---
Tags: emails, views
---


# Question
Title: Drupal Commerce Need Function To Retrieve Customer Profile Fields From Commerce Order
I want to display some info from the Customer Profile (Customer Number, Contact Number) whenever the shopping cart view displays. I can see these fields in 'People' but obviously they are -extended- fields... when I run this:

```
$my_user = user_load( $user->uid );

```

...I get the field names for the data I want, but not the values.

I -thought- I could do this...

```
$order = commerce_cart_order_load($user->uid);

```

...and then somehow get to the customer\_profile like so:

```
commerce_customer_profile_load ($profile_id);

```

...but I have no idea how to connect the $order or the global $user-\>uid with the $profile\_id

How does one do this?

Again, I just need to retrieve the string values of Customer Number and Contact Number.

TIA,

---JC

# Answer
> 6 votes
There are probably a few different ways to bridge that gap but here are the first 2 that spring to mind:

1. Use `commerce_customer_profile_load_multiple` instead, and make use of the `$conditions` parameter, e.g.

```
$profiles = commerce_customer_profile_load_multiple(array(), array('uid' => $order->uid));

foreach ($profiles as $profile) {
  // Make sure this is the correct profile (users can have multiple profiles)
  // and extract the field values as you would with any entity (field_get_items())
}

```

But the `$conditions` array is deprecated for core entities so probably will be for commerce entities too at some point.
2. Use an `EntityFieldQuery` to get the profiles, e.g.

```
$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'commerce_customer_profile')
  ->propertyCondition('uid', $order->uid);

$results = $query->execute();

if (!empty($results['commerce_customer_profile'])) {
  $profiles = commerce_customer_profile_load_multiple(array_keys($results['commerce_customer_profile']));

  foreach ($profiles as $profile) {
    // ...
  }
}

```

# Answer
> 4 votes
You can also use entity\_metadata\_wrappers:

```
$order = commerce_cart_order_load($user->uid);
$order_wrapper = entity_metadata_wrapper('commerce_order', $order);
$billing_profile_wrapper = $order_wrapper->commerce_customer_billing;

```

So now you have your profile wrapped in an entity\_metadata\_wrapper in the var `$billing_profile_wrapper`. Since it's a entity\_metadata\_wrapper, we can access it's field really easy:

```
$billing_profile_wrapper->field_name_you_need->value();

```

More info on entity\_metadata\_wrapper's:

Feel free to add more links, these are just the ones I like the most

# Answer
> 1 votes
If you have the $order object, then...

$profile\_id = $order-\>commerce\_customer\_billing\[LANGUAGE\_NONE\]\[0\]\['profile\_id'\];

# Answer
> 0 votes
You may need this information outside the context of a commerce order. I worked this out to get the profile ID associated to a User. You will need to loop through results if you get more than one:

NOTE: **field\_profile** is the name of the Customer reference profile field on my User accounts.

```
<?php

  global $user;
  $uid = $user->uid;
  $query = db_select("field_data_field_profile","p");
  $query->fields("p",array("field_profile_profile_id"));
  $query->condition("entity_id",$uid);
  $output = $query->execute()->fetchObject();

  $profile_id = $output->field_profile_profile_id;
  if(!empty($profile_id)){
    $profile_info = commerce_customer_profile_load ($profile_id);
  }

```

---
Tags: commerce, users
---


# Question
Title: Organic Groups D7 : How to get custom group list of login user?
How to get logged in user group list in select box.

Need to help Please suggest me any one ?

# Answer
> 0 votes
You can use og\_get\_groups\_by\_user function.

```
$current_user_groups = og_get_groups_by_user();

```

---
Tags: organic-groups
---


title: Display node add form in popup

text:
# Question
Title: Display node add form in popup
I want to display **node add form** of a particular content type in a pop-up for anonymous users too. There are posts related to displaying a node content in pop-up but not about node add form.

I have a .tpl for a calendar display view. Now when anyone click on a particular div of the table I need to open a pop-up of node add form. So I need to add the `<a> anchor tag` in the tpl file.

How to achieve this? Is there a way to call the node add form as a pop-up in jquery?

# Answer
> 0 votes
First, I would say dont put this logic in a .tpl if you can put it somewhere else, for maintainability.

Second, as with many drupal solutions, there is more than one way and they differ in some aspects. Let me try a few for you:

**Solution A**: https://www.drupal.org/project/colorbox This adds a checkbox to the views field controls that says "Open link in Colorbox", and you use the Output as a Link controls to make this link point to /node/add. Verify necessary permissions are set.

**Solution B**: Ctools modal link conversion. In your calendar view add a nid field and use the 'Rewrite Field' options to replace it's value with your Create anchor tag. Make sure this tag has the class "ctools-use-modal". The reason for doing this so early is that links tagged with that class, when passed through the render process, get converted into a modal link. Since this is on a calendar display, I am guessing that you are wanting people to make events for the calendar, and it would be really cool to have the event creation form pre-populate with the day they clicked? Look at https://www.drupal.org/project/prepopulate and alter your anchor path to include the token from the date field that is already in your view. Now the hard part, you will need to write a hook, so you will need a custom module. I havent tried https://www.drupal.org/node/1312770 but it looks like it can make a skeleton for you.

You will need to implement this:

```
function hook_views_pre_build(&$view) {
  if ($view->name == [your_view_here]) {
    $current = $view->current_display;
    // Include the CTools tools that we need.
    ctools_include('ajax');
    ctools_include('modal');
    // Add CTools' javascript to the page.
    ctools_modal_add_js();
  }
}

```

That will make sure the view is processed by ctools looking for modal pop-ups. I just used this the other month in a slightly more complicated use case, where path in the view is a custom registered callback and anonymous user gets a sign-up form in modal, and logged in user gets the requested resource. Using what I have explained above, you should have a site where everybody gets the modal. Make sure you have the appropriate Node Create permissions checked.

**Solution C**: There is an Overlay module that ships with Drupal 7, has been in there from the begining. This is less popular than colorbox and ctools, and bit more limited. Enable the module, give anon user permission to use it, and add "#overlay=" to the beginning of your link path in the view. I dont recall at the moment if they solved some security issue involved with anonymous access to this module, so I caution against using it. I am really only including it here as an example of how many solutions are available in drupal.

Good luck, and please do say how this worked for you.

# Answer
> 0 votes
Install lightbox module then add

```
rel='lightbox'

```

To the `a` tag as a property. I mean

```
<a rel='lightbox' href='node add form link'>some text </a>

```

Anything can be displayed as a nice smooth popup by lighbox. Forms,slideshow,gallery and ... can be displayed by lightbox.

---
Tags: 7, javascript
---


# Question
Title: How to create a fieldset in a node form, that expands with ajax
I have a (view of a ) tasks list on a page, and also a form block where users can add a new tasks. I want to increase page load time by hiding some fields in the tasks form block, which can expand using ajax by clicking on "task details" link (the fieldset label)

Is this is possible without programming?

# Answer
You might need to add this module. https://www.drupal.org/project/field\_group Add those fields on the form to a field group, and set the group to start out "Collapsed".
> 0 votes

---
Tags: views, ajax
---


title: show/hide fieldgroup with ajax drupal 7

text:
# Question
Title: show/hide fieldgroup with ajax drupal 7
I have a field group that contain sub field group with almost 30 fields also I have a `checkbox` field that I want ajaxly show hide field group accoridng checking event of it.

I have no problem with ajaxly show hide a field according to checking.but I have no idea how I can perform with fieldgroup.
Any idea?

# Answer
> 4 votes
Have you take a look at conditionals fields, works great for node-form and can help you to build your own code.

Oskar

# Answer
> 1 votes
If you want a programatic replacement for conditional fields, then you are looking for the #states attribute in the form api. https://api.drupal.org/api/drupal/developer!topics!forms\_api\_reference.html/7#states Add that in a form\_alter and it does the ajax for you.

---
Tags: forms, ajax
---


# Question
Title: Proxying a subdirectory to a remote site
**The goal**

Make all requests to a previously static page at https://www.example.com/sub/folder on server 1 (Proxy) ACTUALLY go to a Drupal site at https://other.example.com on server 2 (Origin)

This is also getting setup as a multisite, because there are sub/folder2, sub/folder3, etc. that will need to be converted to Drupal sites. I don't *think* this has anything to do with the problem, but for the sake of completeness, I'm adding the sites.php changes too below.

**What I've done so far**

Changes on Server 1 (Proxy): Apache config

```
RewriteCond %{HTTPS} off
RewriteCond %{REQUEST_URI} ^/sub/folder
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}
SSLProxyEngine On
<Location /sub/folder>
  ProxyPass https://other.example.com/
  ProxyPassReverse https://other.example.com/
  ProxyPassReverseCookiePath / /sub/folder
</Location>

```

Changes on Server 2 (Origin): settings.php and sites.php

sites.php (because of multisite; and sites/sitename/settings.php is the file I'll be referencing below)

```
$sites['other.example.com'] = 'sitename';
$sites['www.example.com.sub.folder'] = 'sitename'; // I don't think this one is necessary, but just in case?

```

Aside from the standard DB setup in settings.php, the following has been added:

```
// $base_url allows for links/URIs to be generated properly
// Changing the REQUEST_URI seems to have fixed form issues, like the search block/form
// Not sure if the cookie_domain is doing anything/working properly
if (isset($_SERVER['HTTP_X_FORWARDED_HOST']) && $_SERVER['HTTP_X_FORWARDED_HOST'] == 'www.example.com') {
  $base_url = 'https://www.example.com/sub/folder'; // NO trailing slash!
  $_SERVER['REQUEST_URI'] = '/sub/folder' . $_SERVER['REQUEST_URI'];
  // (Edit) note don't put 'http' in front of this
  $cookie_domain = '.other.example.com';
}
...
$conf['reverse_proxy'] = TRUE;
...
$conf['reverse_proxy_addresses'] = array('ip.of.origin.server');

```

**The problems**

1. Trying to login through www.example.com/sub/folder/user validates (according to Drupal log)... but then it treats the page re-load as an anonymous user and fails access. Presumably, the cookie gets broke/lost/invalidated somehow in between. So, authenticated access to the server has to be done through other.example.com Not a huge problem (since the average Joe won't be logging in), but...
2. There's just a lot of annoying things occuring having to deal with fixing user/content created links and URIs. Currently, links that are first viewed after a cache clear are cached as whatever domain they're being viewed from. (This happened from using Pathologic module to force absolute URLs.) I realize this might not have been the BEST solution--using Pathologic--but if I fix problem 1., this should become a moot point.

So, I think I've got some kind of SSL/Proxy cookie issue at this point... any suggestions?

# Answer
Drupal should be able to install into a sub-directory and "just work" without fiddling around with it. This question already answers this particular sub-directory issue:

How to get Drupal 7 installed in a sub-folder / sub-directory properly?

Try re-installing a fresh installation into the sub-directory. Can you login? The .htaccess of 2.site.com should have nothing to do with the issue at hand regarding 1.site.com.

The reason for your problem is likely something along the lines of a clean-url issue fighting against your configurations. A fresh install will be the easiest way to resolve this particular issue.

Regarding this line:

> and I'd like only that subdirectory to go to an arbitrarily named server with a drupal install at, say "https://2.site.com"

The domain merely points to a directory. The domain ISN'T an actual file location. As such, this particular line doesn't seem to make any sense. If the issue is not resolved by simply clearing out and reinstalling Drupal in the sub-directory at hand, please re-state your question by providing more information, describe where these sub-directories are in the system root relative to each other and then describe which directory each domain points to. Don't describe domains AS directories because they aren't directories - they're pointers.
> 0 votes

---
Tags: 7, multi-sites, proxies, ssl
---


# Question
Title: Drupal 7 Organic Groups, Drupal Commerce and Paypal
I have a Drupal 7 site, with OG and commerce installed. I have an og content type populated with content. Everything is working as expected. I found this link on Drupalcommerce: https://drupalcommerce.org/blog/10809/selling-organic-groups-using-drupal-commerce and it is very close to what I'm after. However, I don't want to charge the users for access to the group. I want to charge per group. Just like meetup.com does.

In short, I would like for a user to:

1. Enter a group name Username and email
2. They are taken to Paypal to complete transaction
3. Paypal signals the transaction is complete
4. The group and user are created.

Any tutorial or guidance is appreciated. Many thanks Chris

# Answer
Please check out Commerce Node Checkout Module It gives you a basic **Pay to Pubish** workflow, which is exactly what you are try achieve.

As the project page says the module helps you

> Integrate with Commerce in order to allow you to charge users to create nodes.
> 2 votes

---
Tags: commerce, organic-groups, payment-gateways
---


# Question
Title: How can I allow/facilitate users to upload images and create a slideshow?
I want the users of my page (who will not be especially technical) to be able to upload multiple images which other users can comment on etc.

I'm thinking of using the Drupal core module 'book' to create the parent page, which would display the images stored in its children.

Is it possible to do this dynamically so that the users do not have to create a new content type for each of the slideshows?

# Answer
Sure you "could" use the 'Book' module with the child pages as you described. However that is not really going to help your users a lot. Except maybe from easily navigating from the images posted by 1 user to another user (if that is what you also want to consider)? And it does not really help I think for reducing the number of nodes to be created.

What I think is more important to consider are these items:

* Add an image field to the content type you are considering using, in which you allow "multiple images". That way a single user may add all their images to "their" node. And with "permissions" it's straight forward to ensure that they can only edit their "own" node (e.g. to add more images later on). And at the same time avoid they (accidently?) add "their" images to a node of another user.
* Use the Field Slideshow module to actually create a slideshow from these images.
* To further simplify (for your users) the upload process of images, you may also want to consider using the IMCE module, which is an image/file uploader and browser that supports personal directories and quota.

With only these 3 items you should get pretty close to what you're looking for I think, no?
> 0 votes

---
Tags: views, javascript
---


# Question
Title: How to create something like a textual "add other term" for taxonomy terms?
How can I setup taxonomy terms so that you can have an extra field called "others", where you can add your own terms if the term you want to use is not defined yet as a term of that taxonomy?

I have researched and came across a module called Select(or other). It does what I want, but it is in text.

My problem now is that I've added so much taxonomies for my student record content type (like countries, or faculties). So I've gone too far and cannot cancel (undo) the taxonomies and replace them with the module I found.

Any suggestion of how to add something like such extra field to the existing taxonomy module?

I imagine that when users insert data, they might not find appropriate terms to choose from. So I want to give them an option that "if current term don't apply to you, then please insert your term manually".

I'm still newbie in Drupal7 and PHP programming.

# Answer
> 1 votes
Consider something that looks like this "Type of Fruit" taxonomy (with 'Banana' and 'Pear' as the only existing terms):

Obviously, the Select (or other) module that you mentioned is for select lists, you cannot use it for taxonomies. However, to somehow address your requirement like "... insert term here ...", you might want to consider using "Widget type" = "Autocomplete term widget (tagging)" when you actually define the Term reference field.

To further enhance the experience of your users, you may want to also consider the Autocomplete Deluxe module or the Chosen module (for better UI and functionality).

# Answer
> 1 votes
When you go to your Taxonomy Vocabulary (`[your_domain]/admin/structure/taxonomy/your_vocabulary`) you can click on `Manage Fields` tab and add any field you want. Or go to `[your_domain]/admin/structure/taxonomy/your_vocabulary/fields`.

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


# Question
Title: How to add <meta http-equiv="X-UA-Compatible" content="IE=edge"> to the header
I'm attempting to figure out a way to add

```
<meta http-equiv="X-UA-Compatible" content="IE=edge">

```

to the header of my pages. I've heard that you could add it in your theme settings but I could not find where that would be located. I also heard you can resolve the issue using template.php in your theme. I've added

```
<?php
function retheme_alpha_0_2_preprocess_html(&$head_elements) {
    $element = array(
        '#type' => 'html_tag',
        '#tag' => 'meta',
        '#attributes' => array('http-equiv' => 'X-UA-Compatible', 'content' => 'IE=edge,chrome=1'),
        );
    drupal_add_html_head($element, 'chrome_frame');
}

```

to mytheme/templates/template.php

However it seems to have no effect.

# Answer
Try this, it works for me, I just tested. I don't think you need #type and http-equiv needs to match in the html head call.

```
/**
 * Implements template_preprocess_html().
 *
 */
function mytheme_preprocess_html(&$vars) {

    $element = array(
        '#tag' => 'meta',
        '#attributes' => array(
          'http-equiv' => 'X-UA-Compatible',
          'content' => 'IE=edge,chrome=1'
        ),
      );
      drupal_add_html_head($element, 'http_equiv');

}

```

Beyond that, if it does not work, then you have some other issue. Be sure to clear all caches.
> 3 votes

---
Tags: theming
---


# Question
Title: Placing header element inside list element
I am using the Group: Combine fields filter (grouped) in Views and I want to separate my first few list items from the last two with a header before the last two. Is it possible without theme functions, like with some field in Views I do not know about?

Found these similar, but they use theme functions.

Add additional element to exposed view form? https://www.drupal.org/node/893392

# Answer
Not that I know of without a theme function or a view display template. However one option without any code would be to create two separate blocks views.

The first view, limit the displayed items to whatever your want, three for example. Clone the first view, but set the offset to three, and also limit it. Add the header to this view. Then plunk them down as you normally would with view blocks.

EDIT: What it would like like to add a new template file.

As an example, if you are using the unformatted list output, you would need to find the theme suggestion for that particular view. Example below.

Then as you can see it is currently using views-view-unformatted.tpl.php

So use that file as a base, it is located in:`sites/<all|default|siteurl>/modules/views/theme/views-view-unformatted.tpl.php`

It currently contains this code below

```
<?php

/**
 * @file
 * Default simple view template to display a list of rows.
 *
 * @ingroup views_templates
 */
?>
<?php if (!empty($title)): ?>
  <h3><?php print $title; ?></h3>
<?php endif; ?>
<?php foreach ($rows as $id => $row): ?>
  <div<?php if ($classes_array[$id]) { print ' class="' . $classes_array[$id] .'"';  } ?>>
    <?php print $row; ?>
  </div>
<?php endforeach; ?>

```

So you need to copy this file into your theme templates folder, rename it, and edit it.

You're going to want to create a count variable, and then when the count reaches the right number, print the title you want like so

```
<?php

/**
 * @file
 * Default simple view template to display a list of rows.
 *
 * @ingroup views_templates
 */
?>
<?php if (!empty($title)): ?>
  <h3><?php print $title; ?></h3>
<?php endif; ?>
<?php $count = 1; ?>
<?php foreach ($rows as $id => $row): ?>
  <?php if ($count == 3) print "<h1>" . t('Header') . "</h1>"; ?>
  <div<?php if ($classes_array[$id]) { print ' class="' . $classes_array[$id] .'"';  } ?>>
    <?php print $row; ?>
  </div>
  <?php $count++; ?>
<?php endforeach; ?>

```

That will print a H1 header after the third row.
> 0 votes

---
Tags: views
---


# Question
Title: drupal_html_id() alternative for non-Ajax content?
I am looking for a `drupal_html_id()` function alternative which returns incremented ID's of non-Ajax contents only.

1. Is this "ajax/non-ajax" distinction feasible in this context or any other way?
2. If yes, can anyone provide a solution or recommendation?

# Answer
Here's a simpler version I came up with by altering drupal\_html\_id() that doesn't pay attention to the $ajax\_html\_ids. Also note that it produces dashes instead of hyphens:

```
function foo_html_id($id) {
  $id = strtr(drupal_strtolower($id), array(' ' => '_', '_' => '_', '[' => '_', ']' => ''));
  $id = preg_replace('/[^A-Za-z0-9\-_]/', '', $id);
  $id = preg_replace('/\-+/', '_', $id);

  $seen_ids = &drupal_static(__FUNCTION__);

  if (isset($seen_ids[$id])) {
    $id = $id . '_' . ++$seen_ids[$id];
  }
  else {
    $seen_ids[$id] = 1;
  }

  return $id;
}

```
> 1 votes

# Answer
You could manually prevent any handling of AJAX within drupal\_html\_id():

```
unset($_POST['ajax_html_ids']);
drupal_html_id($some_id);

```

Be careful with this, because any other AJAX-dependent forms rendered after your code will also be affected.
> 0 votes

---
Tags: 7, ajax
---


# Question
Title: Undesired toggle effect with #states and checkboxes
I'm working on a patch for the Login Disable module, and on the settings page, I want to have two mutually exclusive options so that when one is checked, the other is unchecked. Using the FAPI #states value, I have the following code:

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

  $form['all_users'] = array(
    '#type' => 'fieldset',
    '#title' => t('All Users'),
    '#collapsible' => TRUE,
    '#collapsed' => FALSE,
  );

  $form['all_users']['login_disable_is_active'] = array(
    '#type' => 'checkbox',
    '#title' => 'Prevent user log in',
    '#description' => t('When active the user login form will be disabled for everyone. For roles granted bypass rights they must use the access key defined below.'),
    '#default_value' => (bool)variable_get('login_disable_is_active', FALSE),
    '#states' => array(
      'unchecked' => array(
        ':input[name="login_disable_individual"]' => array('checked' => TRUE),
      ),
    ),
  );

  $form['all_users']['login_disable_key'] = array(
    '#title' => t('Access key (optional)'),
    '#description' => t('For added security, a word can be required to be added to the URL.'),
    '#type' => 'textfield',
    '#size' => 10,
    '#default_value' => variable_get('login_disable_key', 'admin'),
  );
  if (!empty($form['login_disable_key']['#default_value'])) {
    $form['login_disable_key']['#description'] .= '<br />' . t('The URL to use to log in is: @url', array('@url' => url('user/login') . '?' . $form['login_disable_key']['#default_value']));
  }

  $form['all_users']['login_disable_message'] = array(
    '#title' => t('End-user message when login is disabled'),
    '#description' => t('The message to display to users when login has been disabled.'),
    '#type' => 'textfield',
    '#size' => 80,
    '#default_value' => variable_get('login_disable_message', t('Member access has been temporarily disabled. Please try again later.')),
  );

  $form['individual'] = array(
    '#type' => 'fieldset',
    '#title' => t('Indivdual'),
    '#collapsible' => TRUE,
    '#collapsed' => FALSE,
  );

  $form['individual']['login_disable_individual'] = array(
    '#type' => 'checkbox',
    '#title' => t('Disable on user profile'),
    '#description' => t('Checking this box allows disabling individual logins on user profile pages.'),
    '#states' => array(
      'unchecked' => array(
        ':input[name="login_disable_is_active"]' => array('checked' => TRUE),
      ),
    ),
  );

  $form = system_settings_form($form);

  return $form;
}

```

So as I see it, my code should just uncheck a checkbox when the other checkbox is checked. I also want the option that neither is checked. However, what's happening is that they are working as a toggle, in that if I uncheck one, the other one is being checked, which is prohibiting the third option of neither of them being checked. Can anyone tell me why I'm getting this effect?

Thanks.

# Answer
Form API states act in both directions. Suppose you set an element to be unchecked if a condition X is true. Then it gets unchecked when X becomes true, and gets non unchecked (i.e. checked) when X becomes false. See the example code on drupal.org.

You need some custom jQuery in the case.
> 1 votes

# Answer
Alex is right of course, in that the way the mechanism behaves is that it **always** toggles. Either it toggles between a TRUE/FALSE of some active state ("enabled", "checked", etc) or it toggles between a TRUE/FALSE of some inactive state ("disabled", "unchecked", etc).

This doesn't mean it's impossible to achieve what you're trying to do though; in order to do that you'll want to use the logical **AND** modifier by specifying the condition like this:

```
STATE_WE_WANT_TO_SWITCH_TO => array(
  REMOTE_ELEMENT => array(THE_STATE_THAT_TRIGGERS_THIS => true),
  LOCAL_ELEMENT => array(THE_STATE_WE_WANT_TO_GET_OUT_OF => true),
)

```

or alternately I think this would work too ... but I haven't tested to see if it goes in a loop.

```
STATE_WE_WANT_TO_SWITCH_OUT_OF => array(
  REMOTE_ELEMENT => array(THE_STATE_THAT_TRIGGERS_THIS => false),
  LOCAL_ELEMENT => array(THE_STATE_WE_WANT_TO_GET_OUT_OF => true),
)

```

where

```
STATE_WE_WANT_TO_SWITCH_TO = the state you want to switch your form element into,
and NOT automatically toggle back out of again when the triggering thing gets switched back.
REMOTE_ELEMENT = the other form element whose state change triggers this action
THE_STATE_THAT_TRIGGERS_THIS = the state that element needs to be in, to trigger this
LOCAL_ELEMENT = this form element itself
THE_STATE_WE_WANT_TO_GET_OUT_OF = the state it needs to be in, in order for this action
to be triggered. Setting this makes the statement evaluate to FALSE once
it's happened once, making this a one-way action.

```

So in your case this becomes:

```
'#states' => array(
  'unchecked' => array(
    ':input[name="login_disable_is_active"]' => array('checked' => TRUE),
    ':input[name="login_disable_individual"]' => array('checked' => TRUE),
  ),
),

```

https://api.drupal.org/api/drupal/includes%21common.inc/function/drupal\_process\_states/7
> 0 votes

---
Tags: forms, javascript
---


# Question
Title: When I try to browse to a site I get the localhost default page (WampServer)
I use WampServer, and just installed a theme drupal (Jollyany) on localhost, but when I click to explore the site, this sends me to localhost default page:

I try to see what happens when i get on the hosting. ... get me the following error:

Please help

# Answer
Do you have properly configured /sites/defaults/settings.php? Looks like somthing in your connection is wrong, it can be database name, username or/and password.
> 1 votes

---
Tags: theming, installation
---


# Question
Title: How do I access an Entity Reference's field values?
I have 2 content types.

```
BaseContent:
Field1: Title
Field2: ID#

RelatedContent:
Field1: [Entity reference to a BaseContent]
Field2: **[Automatically insert the value of the referenced BaseContent here]**

```

But I can't work out how to do the part in the \**s.

I feel like it should be easy, but nothing I have tried has worked.

Can I do it with any of the following:

-Tokens?

-Entity References using a Views Selection Type and relationships?

-Programatically with PHP (using the Computed Field module?)

If so, how?

any help much appreciated!

# Answer
> 0 votes
The rules module can do this for you. Set up a rule to fire when (new?) content is saved, set a condition that the content be of type RelatedContent and has a value in Field1. Then set the action to be saving a value in Field2 using the available tokens of the referenced node from Field1. It should be something like \[Field1:entity:target\_field\]

You can do the same thing in php code with hook\_node\_presave.

Entity reference with a view to limit the selection options would be better used if you just wanted Field1 and wanted to pick the entity to reference based on the value that you would be storing in Field2 if you had a Field2. This is because the view can be used to show you the label using the value of that other field, but leave the key as the entity id needed to be stored in Field1. Since entity reference can be used for a data connection by views, rules, code, etc this is a common practice to reduce your database size and not store the same data in more than one place. However, it is a little more complicated to configure than just using rules.

# Answer
> 0 votes
Programmatically is easy to do this.

There are minimum two ways to do it.

First: using field\_get\_items() where you get referenced ID's. You can use then entity\_load() or node\_load() depends on your referenced entity.

Second: use Entity Metadata Wrapper \- but this depends on Entity module.

---
Tags: entities, nodes
---


# Question
Title: How do you theme a pager in a specific View?
I have a few views, but each view would have a pager that would be themed differently. How do I go about targetting the pagers of each View for theming?

# Answer
> 0 votes
each view has own class like .view-id-name so this class or id you can use to CSS your pager for each view

---
Tags: 7, views
---


# Question
Title: Is there an easy way to include a Facebook remarketing tag in my D7 site?
Adding Google Remarketing Script tags to Drupal 7 website shows how to add a Google remarketing tag using a module. Is there a similar solution for adding a Facebook remarketing tag easily?

I would use the `drupal_add_js` hook if that were so easy, but the issue is that the remarketing tag also includes an `<img/>` element (the pixel) in a `<noscript>` tag, so I can't include that easily in the same hook.

# Answer
Turned out to be very simple. All I had to do was paste the code into the `<head>` part of html.tpl.php from within the /templates/ folder.
> 1 votes

---
Tags: 7, social-network, javascript
---


# Question
Title: display results from a form in theme-settings.php
I've been working on a way to upload a background image for months and I finally got it to work. How do I display the URL to the image on page.tpl.php? It's a form called `background_file`. Here's my code that I'm using:

```
<?php
function tsaudio_form_system_theme_settings_alter(&$form, $form_state) {
$form['background_file'] = array(
'#type'     => 'managed_file',
'#title'    => t('Background'),
'#upload_location' => file_default_scheme() . '://theme/backgrounds/',
'#default_value' => theme_get_setting('background_file'),
'#upload_validators' => array(
'file_validate_extensions' => array('gif png jpg jpeg'),
),);
form_load_include($form_state, 'inc', 'system', 'system.admin');}?>

```

# Answer
> 0 votes
When you upload a file it creates an file ID (fid) that we need to call back, then generate the URL and then insert it. Place this in your template file.

```
$fid = theme_get_setting('background_file');
$image_url = file_create_url(file_load($fid)->uri);
print '<img src="' . $image_url . '">';

```

To print it out with an image style such as thumbnail:

```
$fid = theme_get_setting('background_file');
print '<img src="' . image_style_url('thumbnail', file_load($fid)->uri) . '">';

```

Not tested.

---
Tags: media
---


title: Custom 404 - menu disappears

text:
# Question
Title: Custom 404 - menu disappears
I have created a custom 404 page using `hook_preprocess_page()`:

```
function THEME_preprocess_page(&$variables) {
  $header = drupal_get_http_header('status');
  if($header == '404 Not Found') {
    $variables['theme_hook_suggestions'][] = 'page__404';
  }
}

```

The contents of `page--404.tpl.php` is identical to the contents of `page.tpl.php` except that use a static text block instead of calling `print render($page['content']);`. When this page is displayed one of the menus disappears from the header. Everything else look just as it does when I'm on a ordinary page except for the menu.

Since I only wan't to change the actual message that is displayed when receiving a `404` page and still use the rest of the markup contained in `page.tpl.php` perhaps it would be a better idea to only alter the `$page['content']` inside a hook or similar?

Would appreciate if anyone could help me figure out why the menu is vanishing or could give me a solution that only alters the `$page['content']` in `page.tpl.php` in case of a 404.

# Answer
> 1 votes
If you can accept using a module for this, rather than a theme override, you should be able to use **CustomError**:

> This module allows the site admin to create custom error pages for HTTP status codes 403 (access denied) and 404 (not found), without the need to create nodes for each of them.

Just to make sure I've understood the use case: You write:

> Since I only wan't to change the actual message that is displayed when receiving a 404 page

This message is by default "Page not found The requested page "..." could not be found. ". I think **CustomError**' will reproduce the standard message unless you override this - but it may something about your use case that I have not understood.

# Answer
> 0 votes
One option would be to update your `THEME_preprocess_page` function to initialise a custom boolean variable based on whether the page returns a 404.

```
function THEME_preprocess_page(&$variables) {
  $header = drupal_get_http_header('status');
  $variables['page']['page_not_found'] = false;
  if($header == '404 Not Found') {
    $variables['page']['page_not_found'] = true;
  }
}

```

You could then use this custom variable in your `page.tpl.php` (similar to how you check for `$logo` or `$site_title`) to display either the custom 404 text or `$page['content']`.

```
<?php if($page['page_not_found']): ?>
    <p>CUSTOM 404 TEXT</p>
<?php else: ?>
    <?php print render($page['content']); ?>
<?php endif; ?>

```

I would only recommend doing this if the 404 page contains *only* minor changes to a standard page. Otherwise, a different template file woild be the way to go.

Regarding the menu issue, I believe by default the primary links are hidden on 404 pages. This topic is discussed on drupal.org here, 'setvik' states the following solution:

To work-around the problem, do the following:

1) Create a custom node to handle "Page not found"'s.

2) go to Admin -\> Site Configuration -\> Error Reporting and set the "Default 404 (not found) page:" to the node you just created.

I can vouch for this as I've had to do it myself numerous times in the past.

---
Tags: 7, theming, routes, debugging
---