# Question
Title: Which Views template file to override to display fields in formatted table?
I have some hierarchical content and I am trying to customize the output. I am trying to output a table something along lines of

```
Lesson Title    Description

 Exercises in Lesson    Exercise1
                        Exercise1 Description
                        Exercise2
                        Exercise2 Description

```

I looked at the existing display output template, expecting it to generate the view output. But that is not the case. I need to find the right file to edit, to add the PHP code to build my customized table.

Any ideas?

Thanks

# Answer
> 2 votes
There are quite a few ways to find this information, most of them are pretty easy to accomplish. I'm going to list a few different ways that I usually include in my process. (See update below for the choice to use template suggestion or template.php override function)

**Theme Debug**

Read here: https://www.drupal.org/node/223440#theme-debug

When turning on theme debug you can inspect the HTML of the page and you will see the templates that are actually used and template suggestions for the markup of the page. The Drupal gods blessed us with this one as of D7.33, so it won't work on anything before that.

**Views Theme Information**

There are quite a lot of little tricks built into views to help developers. One of them is the ability to see what template file is being used for a particular view.

This is where the magic is for the template files being used.

This is what that modal shows.

Read here for more in depth documentation of each particular template file and what it does exactly.

**Notes:**

From your question and your layout of what your view is doing or trying to do (only speculation, so take this with a grain of salt, the more information given the easier it is to answer these types of issues) you are using views grouping of some sort to achieve that layout or hierarchical display of information. Views grouping is a little bit different than the regular template files as it uses a registered theme function for that, which is better for performance but you can still override with a template file as well. You can find that template file here if you think that may help in your current situation. I know that there are a lot of ways to skin a cat and a Drupal page so I could be off on that assumption. If I can add anything more to help just let me know.

I haven't watched the video mentioned in the comments yet but if I see exactly what that is referring to I will add some more information about that. You can also search for custom view handlers and other cool custom view options to achieve basically anything a BA can imagine.

**Update:**

I watched the video from the comments. I'm guessing that is fairly important to you since you mentioned it specifically in the comments on your question. Just to be clear for future readers incase the video is ever lost or deleted, OP is asking if he should use the template override (as in getting the template suggestion and copying the file to your theme/sub-theme and changing it from there) or overriding the template file in a function in your themes template.php. I have seen either way used before but there is a rule of thumb to use for this, if you are doing a major logic change of some sort use the override function in template.php. If you are only making basic markup changes and small data display changes you are safe to just use the actual template file. I will go ahead and say that on larger projects the amount of template files can get pretty large and unruly so unloading some of that in your template.php (even better broken out into inc files, see Bootstrap/Zurb themes for examples of breaking pieces out) helps out in some cases, but besides the rule of thumb mentioned that is up to you as the developer. (I haven't ever been told any different or read anything in Drupal standards as to say which way to go on this one besides the basic rule of thumb I mentioned and I consider myself pretty high up there with wanting/needing to follow Drupal standards, if anyone has any more information on that please chime in)

---
Tags: views
---


# Question
Title: All content types displaying in "Show only items where" search
When I log in as a user who doesn't have access to certain content types, I can still see a list of those content types in admin/content under the "Show only items where" search. Also, some of the content types don't have any nodes using those content types, yet they are still listed in the dropdown menu under "type".

Rather than confusing certain users, I would prefer only for the content types they have access to, to be listed here. Is this possible?

# Answer
Yes. You can alter the form's select box with a `hook_form_alter()` invocation. All that's needed is to remove the options that aren't relevant to the user.

For example, if you wanted to remove content types where the user didn't have the *Edit any TYPE content* or *Edit all TYPE content* permissions, you could do the following:

```
function token_form_node_admin_content_alter(&$form, $form_state, $form_id) {
  global $user;
  $types = &$form['filter']['filters']['status']['filters']['type']['#options'];
  foreach($types as $type => $type_name) {
    if($type != '[any]' &&
       (!user_access("edit any $type content", $user) &&
        !user_access("edit own $type content", $user))) {
      unset($types[$type]);
    }
  }
}

```
> 0 votes

---
Tags: nodes
---


# Question
Title: Move label to RIGHT of checkbox in Webforms
When setting the label to "inline", Webforms will place the label to the left of my checkbox. Is there any way I can move it to the right?

Here's what it looks like right now, I want the label to be to the RIGHT of the box.

thanks

# Answer
> 1 votes
Drupal is spitting out the markup as `[title][field]` and what you want is `[field][title]` so to accomplish this you need to override Drupal's default theme implementation of your field. To do this copy example.com/modules/field/theme/field.tpl.php to your theme template folder(if one does not already exist in there ...sites/all/themes/my\_theme/templates) and modify the template file to your desired markup. When naming your template file you can restrict it to the webform fields, Drupal will use the most specific template it finds in the following order:

* field--field-name--content-type.tpl.php
* field--content-type.tpl.php
* field--field-name.tpl.php
* field--field-type.tpl.php
* field.tpl.php (in your theme)
* field.tpl.php (in drupal's field module)

Take a look at this link, Drupal documentation on field.tpl.php

Hope this helps.

# Answer
> 0 votes
Another option, which I found useful, is to check the css of the form label. My checkboxes were indeed on the left, but looking at the label.option, i saw that the float was to the left.

I changed this to float:none, and it seems to have fixed my input box.

label.option { display: inline; font-weight: normal; float: none; }

---
Tags: webforms
---


title: Doing a simple checkbox in field API

text:
# Question
Title: Doing a simple checkbox in field API
I'm trying to add a simple checkbox in a Drupal 8 Entity Form that displays like the old Form API:

```
$form['approved'] = [
  '#type' => 'checkbox',
  '#title' => t('Approved'),
  '#description' => t('Check this to indicate this person is approved for membership'),
];

```

Using D8 style field definitions, this should be something like

```
$fields['approved'] = BaseFieldDefinition::create('boolean')
  ->setLabel(t('Approved'))
  ->setDescription(t('Volunteer is approved for trusted work.'))
  ->setSettings(array(
    'display_label' => TRUE,
  ))
  ->setDisplayOptions('view', array(
    'type' => 'unicode-yes-no',
    'weight' => -3,
  ))
  ->setDisplayOptions('form', array(
    'type' => 'boolean_checkbox',
    'weight' => -3,
  ))
  ->setDisplayConfigurable('form', TRUE)
  ->setDisplayConfigurable('view', TRUE);

```

This doesn't quite work; I'm getting a checkbox with the label "On".

How do I fix this? Also has anybody gathered the various parameters used for setDisplayOptions() in one place and documented how these map to the Form API and the Render API? I've been looking at the sources in core/lib/Drupal/Core, and I'm not finding much. And there isn't even a test for the boolean\_checkbox widget, so no code to look at there either.

# Answer
> 1 votes
You can always just create a field in the UI and extract the settings from there. Or look at the defaultSettings() method in the plugin class, where you can find this:

```
/**
 * {@inheritdoc}
 */
public static function defaultSettings() {
  return array(
    'display_label' => FALSE,
  ) + parent::defaultSettings();
}

```

So, add `'settings' => ['display_label' => TRUE]` to your form display definition and you have what you want.

# Answer
> 1 votes
@Bendir has the right idea, but for my field, the configuration was spread over four different config files. These were, for adding a field "approved\_example" to the "Article" node type:

* field.field.node.article.field\_approval\_example.yml
* field.storage.node.field\_approval\_example.yml
* core.entity\_form\_display.node.article.default.yml
* core.entity\_view\_display.node.article.default.yml

```

    $fields['approved'] = BaseFieldDefinition::create('boolean')
     ->setLabel(t('Approved'))
     ->setDescription(t('Volunteer is approved for trusted work.'))
     ->setDisplayOptions('view', array(
       'settings' => [
         'format' => 'unicode-yes-no',
       ],
       'weight' => -3,
     ))
     ->setDisplayOptions('form', array(
       'settings' => [
         'display_label' => TRUE,
       ],
       'type' => 'boolean_checkbox',
       'weight' => -3,
     ))
     ->setDisplayConfigurable('form', TRUE)
     ->setDisplayConfigurable('view', TRUE);

```

The documentation problem is that *settings* can appear at several levels, and that the distinction between "options" and "settings" is not clear in the documentation.

I also think that making On/Off buttons the default UI for fields was the wrong thing for Core to do -- even getting a simple checkbox done in the UI is not very discoverable -- but the code in this answer seems to do the trick.

---
Tags: entities, 8
---


# Question
Title: Entity Translation - create a translation for all existing nodes
Using Entity Translation, is there a way to create a translation for all existing nodes, instead of translating each one manually? For other languages there is lots of missing content, and would like to create temporary English versions for all languages before they are edited.

# Answer
A possible solution could be to use a custom module that uses **hook\_node\_view**, as in this example:

```
function yourmodule_node_view($node, $view_mode, $langcode){
   global $language;
   if (!empty($node->language) && $node->language != $language->language) {
      drupal_goto('path/to/some/temporary/version');
   }
}

```

What the content of such `path/to/some/temporary/version` node should be is up to you. E.g. you could point to some custom 404 page.
> 0 votes

---
Tags: i18n-l10n
---


# Question
Title: How to select Views as a Context reaction block?
I would like to create a new Context (Drupal 7.39) and choose Blocks as reaction. In blocks, I would like to choose a specific View and add it to a region. However, 'Views' is not in the list on the right (where it says nodes, search, system, users, etc). In other sites I manage, Views is part of that reaction\>blocks list.

Does anyone have any idea why it might not be listed here?

# Answer
> 1 votes
To achieve you requirement please follow the steps below.

1. In view configuration, under advance settings select **Exposed form in block** as a *Yes*.
2. Now you can see your **view** listed at right side.

> Please remember, only blocks can be place into region, thats why you have to first expose your view as block.

---
Tags: views, 7
---


# Question
Title: How to make users with administrator role member of all organic groups?
Is there a way to make all administrator users a member of all the Organic Groups?

For the moment, if an administrator creates an organic group, the only one who will be member of the newly created group will be this particular Admin user.

Maybe I should just find a way to do it throught a Rule ?

**UPDATE** I FOUND HOW:

# Answer
> 0 votes
I found How,

go to your content type and change the widget for your field "og\_group\_ref" from OG\_Reference to Select List

---
Tags: users, organic-groups
---


title: Show publication date in search results

text:
# Question
Title: Show publication date in search results
I've got a website with lots of content that has been migrated. For each node I've added the original date as the *Authored on* date. However, search snippets show the date a node was last updated.

I've read the *search-result.tpl.php* file and can't figure out how to change the `$info_split['date']` variable so that it shows the publication date instead.

How can I display the *Authored on* date instead of the updated date in the search results?

# Answer
Use a the preprocess function, `template_preprocess_search_result()` to add a custom *authored on* date variable to your **search-result.tpl.php** template.

```
function MYTHEME_preprocess_search_result(&$variables) {
  //$variables['result']['node'] is the node object returned in the search results
  //the $variables['result']['node']->created property contains the authored on date
  if(isset($variables['result']['node'])) {
    $variables['created_date'] = format_date($variables['result']['node']->created, 'short');
  }
  //$created_date will be available in your search-result.tpl.php for printing
}

```

It's probably worth mentioning that the base template is printing out the `$info` variable which is the concatenation of a few vars in `$info_split`. Changing `$info_split` won't change the printed date without changing **search-result.tpl.php**.
> 3 votes

---
Tags: 7, search
---


title: How install Drupal on SSD on Linux

text:
# Question
Title: How install Drupal on SSD on Linux
I have an installed SSD on my Ubuntu Linux machine. It's blank, partitioned, and formatted. I'd like to install my Drupal sites on it so I can work on them locally there. However, the only way I've found to install Drupal so far on Ubuntu is in the /var/www/html folder (and only 1 site there at a time at that).

Anyone have a suggestion (or a tutorial! - dare to dream) for installing multiple Drupal 7 sites on a SSD on Ubuntu Linux for local development?

# Answer
You can do many things to fix this.

1. Delete the /var/www/html directory. Create a symlink from your SSD to the location.

$ rm -rf /var/www/html && ln -s /media/ssd/document\_root /var/www/html
2. Modify your web servers configuration to use the SSD as the document root.
3. Create a virtual host for your webserver and point it at the SSD. Edit. I just saw youur previous question. Copy your 000-default.conf to 25-example.com.conf and alter the document root and directory durectives. Don't forget to restart apache.

Are you using stock Apache? What version of Ubuntu?
> 1 votes

---
Tags: installation
---


title: Views Filter by View Field

text:
# Question
Title: Views Filter by View Field
I've created View with list of entity registrations. This list display users registered for events with info, like conference name (node title), user name etc.

Is it possible to add filter, which contains list of all existing conference names by default? Because right now I have to add values manually.

# Answer
> 1 votes
You can use the Views Reference Filter. You can create an entity reference view which will contain the all existing conference names, and then use this view as a filter for the main view.

> This module provides the views filter for entity ID or entity reference fields such as node ID, user ID, taxonomy term ID, term reference field (Drupal core) and entity reference field (Entity reference module).

---
Tags: views
---


# Question
Title: Why does the Multifield module not show an "Add" option?
After downloading the Multifield module, I enabled it from the module section.

After that I went to `Structure -> Multifields`, to create a new Multifield. But there is no "Add" button, as shown in this image:

Any suggestions about what I'm missing?

# Answer
First you must add a Multifield field to a Content Type. For this go to:

```
admin/structure/types/manage/YOUR_CONTENT_TYPE/fields

```

And if you go to:

```
admin/structure/multifield

```

You will see your Multifield field and you will be able to "Add" (Manage subfields) the subfields
> 3 votes

---
Tags: entities
---


# Question
Title: Error Finding Home page for Drupal 7 Site on Ubuntu Linux
I installed Drupal more or less successfully in /var/www/html on Ubuntu Linux. However when I go to 'localhost' it still just shows the Apache home page. However, if I go anywhere WITHIN my drupal site it works fine. So the home page is the problem. In fact if I click 'home' in the admin toolbar it takes me (again) to the apache home page.

Here's what I set in my 000-default.conf file on Ubuntu:

```
<VirtualHost *:80>
    . . .
    ServerName  mysite.dev
    ServerAdmin webmaster@example.com
    DocumentRoot /var/www/html

    <Directory /var/www/html>
        AllowOverride All
    </Directory>
    . . .
</VirtualHost>

```

I tried following the directions here but didn't see any reference to index.htm or .html in my apache2.conf file:

https://www.drupal.org/node/1484514

Not sure what else to try.

Suggestions?

# Answer
> 1 votes
Where did you install drupal? in the `/html` folder? If so, perhaps you need to delete index.html (inside /html folder) which is the page you are seeing. Or did you do `/var/www/html/drupal`?

I installed my drupal in `/var/www/drupal` (I created the drupal folder inside `/www` and left the `/html` folder alone, untouched).

then in 000-default.conf I have:

```
ServerAdmin webmaster@localhost
        ServerName mysite.com
        ServerAlias www.mysite.com
        DocumentRoot /var/www/drupal

<Directory /var/www/drupal/>
        Options +FollowSymLinks
        AllowOverride All
        order allow,deny
        allow from all
</Directory>

```

# Answer
> 1 votes
You need to enable php in your apache conf. You can try

```
$ sudo a2enmod php5

```

---
Tags: installation
---


# Question
Title: Forms alter submit button callback not working
I have managed to override a profile2 form using hook form alter. After adding a second submit button to the form successful an issue arose. I can not get the call back function to work. Below is the hook and the call function. Can anyone see a issue with the code?

```
function multi_step_form_form_profile2_form_alter(&$form, &$form_state){
          $form['profile_x']['field_personal_info']['submit']['und'][0] = array(
            '#name' => 'personal_info_alt',
            '#type' => 'submit',
            '#value' => t('Info Save'),
            '#attributes' => array('alt' => t('get data')),
            '#submit' => array('testing_to_see'),
          );
}

function testing_to_see() {
  print'I am in call back ';
  exit;

}

```

Thanks for the responses. The reason I am trying to add another submit button is that the current profile page is using JQuery to hide and display some field collections that have been added to the profile page.

Currently when the user fills out the inputs in a fieldset and clicks next it only hides that fieldset and then displays the next fieldset.

Now each fieldset needs to save the data on the server each time you press next. So I found a way to add a submit button using the above code and to display the next fieldset by unsetting the array.

What I can't get the submit button to do when pressed is go to a call back function so I can manipulate the process to achieve this goal.

To answer the current questions below.

* field\_personal\_info is adding the submit button inside the fieldset
* multi\_step\_form is the name of the module

# Answer
> 1 votes
Expanding on my comment, be sure you have the correct form ID in the hook\_form\_FORM\_ID\_alter. This is an example of how I made this work. You'll need to modify the name of the hook and the FORM\_ID

```
function tempo_form_profile2_edit_pet_ownder_form_alter(&$form, &$form_state){

    $form['actions']['new_button'] =  array(
            '#type' => 'submit',
            '#name' => 'personal_info_alt',
            '#value' => t('Info Save'),
            '#attributes' => array('alt' => t('get data')),
            '#submit' => array('testing_to_see'),
        );
}

function testing_to_see(&$form, &$form_state) {
  drupal_set_message('I am in call back');
}

```

---
Tags: forms
---


# Question
Title: Is FIELD COLLECTION VIEWS module only for showing data in table format?
I am using field collection module and in search of formatting it I came across field collection views module. But whatever tutorial I came across, in all it is display data in Table form only. Is there possibility that we can use field collection views module as Views module so we can have lots of option for formatting? Or Field collection views module is limited to show data to Table format only?

# Answer
> 1 votes
At admin/structure/types/manage/\[node-type\]/display/full changed the view mode for my field\_collection where format = "Table of field collection items". The view mode setting is ignored, as viewing the original node still shows all fields as configured in the "Full content" display mode.

field\_collection\_table.patch

---
Tags: entities
---


title: key value field for content types

text:
# Question
Title: key value field for content types
I've got a content type which consists of many (arbitrary number) key/value pairs.

What I'm looking for is a module like Options Element, which I can add to my custom content type. Are there any modules like this?

# Answer
> 4 votes
Double field may be used as key/value field.

# Answer
> 1 votes
I found multifield to work better than Double field.

---
Tags: 7, entities
---


# Question
Title: Why are my translated Select List values not shown after switching language?
I have a content type for **Job Openings**, which has many fields and some of them are drop-downs (select lists).

The issue is that when I switch the language (German) everything switches to the currently selected language but the data coming from select field stays in English.

I have been going over the internet and have not found anything. Any suggestions?

**Notes**:

* All the fields are translated in the backend but they just doesn't show up (in German).
* I have simple text\_fields too and they are shown translated, but not the select list fields.

# Answer
Go To **Home » Administration » Structure » Content types » your content type » Manage fields » your select list » Translate**

Click Translate and Select **Field Settings**. In Field settings update all your options with corresponding translated strings.

Another option is Check for any untranslated string here .. **Home » Administration » Configuration » Regional and language » Translate interface**
> 2 votes

# Answer
After you translated the select list options of your field(s), make sure that you ALSO change the **Format** of that selection list from ***Default*** to ***Default Tanslated***

You can do so via "Manage Display", located at `/admin/structure/types/manage/yourtype/display` (whereas `yourtype` corresponds to your Job Openings content type). Similar to what is explained in this comment also ...
> 3 votes

---
Tags: i18n-l10n
---


# Question
Title: Add condition to specific content type in apache solr
I've installed apachesolr,search api solr and views. I have only indexed article and basic page content type.

Then i've added new field "internal use only" as checkbox for article content type. I want to add filter "internal use only" only in article content type. I want to show except those articles.

How to alter apache query?

# Answer
> 0 votes
Check apachesolr.api \>\> hook\_apachesolr\_query\_alter

```
function hook_apachesolr_query_alter(DrupalSolrQueryInterface $query) {
  // I only want to see articles by the admin.
  //
  // NOTE: this "is_uid" filter does NOT refer to the English word "is"
  // It is a combination of flags representing Integer-Single, which is
  // abbreviated with the letters i and s.
  //
  // @see the <dynamicField> definitions in schema.xml or schema-solr3.xml
  $query->addFilter("is_uid", 1);

  // Only search titles.
  $query->replaceParam('qf', 'label');
}

```

More details about solr query DrupalSolrQueryInterface

---
Tags: views, search
---


# Question
Title: Show all values of a multi File field sorted by upload time
I have a content type with a File field that allows multiple values. What's the best way to display these files as a list ordered by upload time rather than delta but still using the file descriptions?

The Manage Display options don't really give any options for sorting the list on the node display.

I tried creating a File View using the content id in the url as a contextual filter, while this does let me sort by date I can't seem to use the file description in the output.

Is there a way to get file descriptions in File views or should I look at writing a custom formatter for the node display?

# Answer
I found the module Extended File Field does exactly what I want.

https://www.drupal.org/project/extended\_file\_field
> 0 votes

---
Tags: views, files, entities
---


# Question
Title: Create a form programmatically and display result on template
I'm trying to create a simple page with a form. With the different filled fields I want to execute different `EntityFieldQuery` in the `HOOK_form_submit. To finish I want to display the result of my`EntityFieldQuery`under the form like a`View\`.

For the moment I created a module with `HOOK_menu` :

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

    $items['statistiques'] = array(
        'title' => t('Statistics Page'),
        'description' => t('Homepage for statistics'),
        'page callback' => '_homepage_for_statistics',
        //'page arguments' => array('form_example_form'),
        'access arguments' => array('access content'),
    );

    return $items;
}

```

A simple form here :

```
function statistiques_form($form, &$form_state) {
    $form['age'] = array(
        '#title' => t('Age'),
        '#type' => 'textfield',
        '#required' => TRUE,
        '#maxlength' => 3,
        '#size' => 3,
        '#weight' => 0,
    );

    $form['submit'] = array(
        '#type' => 'submit',
        '#validate' => array('statistiques_form_validate'),
        '#submit' => array('statistiques_form_submit'),
        '#weight' => 10,
        '#value' => t('Click Here!'),
    );

    return $form;
}

```

I have two functions `statistiques_form_validate` and `statistiques_form_submit` under hook\_form

Then i send my form and others vars to my template like this :

```
function statistiques_theme() {
    return array(
        'statistiques_template' => array(
            'template' => 'statistiques',
            'variables' => array(),
        ),
    );
}

function _homepage_for_statistics(){
    global $user;

    $output = '';
    $vartest = 'my var test to template';

    $output .= theme('statistiques_template', array(
        'vartest' => $vartest,
        'form' => drupal_get_form('statistiques_form'),
    ));

    return $output;
}

```

My template look like this :

```
<?php print render($form['age']); ?>
<?php print render($form['submit']); ?>

```

I tried **Example** module, but this case isn't on this module. There is some cases which are close to my problem, after submit the form data are sent to flash message.

With my code the form doesn't work, I can't submit the form but I think it's a small problem... my real problem will come when I will need to display the result of my form validation to my template under the form or on another template. How can do that ?

Thanks

# Answer
I recommend adding the results of the query to the form markup-like:

```
$form['something'] = array(
  '#theme' => 'statistiques_template',
  '#vartest' => $vartest,
);

```

is equivalent to `theme('statistiques_template', array('vartest' => $vartest))` -- the theme system will remove the `#` from the variable names if `#theme` is set.

But, of course, you can add the form to the page build as well, see how `comment_reply` does it:

```
  $build['comment_node'] = node_view($node);
  $build['comment_form'] = drupal_get_form("comment_node_{$node->type}_form", (object) $edit);

```

If coding in Drupal 7, forget direct `theme` calls, strings and the `.` operator. Work with render arrays instead. It's also a good preparation for Drupal 8 where concatenating strings leads to double escape bugs.
> 0 votes

---
Tags: theming, forms
---


# Question
Title: How to add a list of stock and node reference to create the perfect stock of beers?
I'm creating a Drupal site that is able to follow the stock of your beers.

For beers, I have a Beer Content type wth all info on the beer, it's OK.

Now, for each user, I want to give the possibility to create a list of beer and the number of beer user has in fridge. How can I do that?

I was thinking of making these Content Types:

* **InStock** (fields : int + node reference to beer).
* **MyBeers** (fields : node reference to InStock).

But with that, user has to create one InStock for each beer and then after that create one MyBeers and reference to all it's beers, so it isn't the good approach.

I don't want to make custom module if it's possible.

Ideally in fact, in my perfect works, I can add directly a List of (node reference to beer + int items in stock) into the InStock but I don't know how to do so.

# Answer
Only use the Flag module, so that your users can just "flag" the nodes related to your Beer Content type. With such approach, there is no need for the extra content types *InStock* and *MyBeers* that you are considering (a commonly known best practise in Drupal is to try to keep the number of content types to a minimum).

Some details about the Flag module (from its project page):

> Flag is a flexible flagging system that is completely customizable by the administrator. Using this module, the site administrator can provide any number of flags for nodes, comments, users, and any other type of entity. Some possibilities include bookmarks, marking important, friends, or flag as offensive. With extensive views integration, you can create custom lists of popular content or keep tabs on important content.
>
> Flags may be per-user, meaning that each user can mark an item individually, or global, meaning that the item is either marked or it is not marked, and any user who changes that changes it for everyone.
>
> In this way, additional flags (similar to published and sticky) can be put on nodes, or other items, and dealt with by the system however the administration likes.

Create a flag that can be used by each user individually (not a "global" flag), so that each user can flag the Beer Content types, and which would be the equivalent of your "MyBeers" type you had in mind. And by using the technique of Attaching fields to flags, you could create a field corresponding to that "int" field of your "InStock" content type you had in mind.

Super easy and straight forward. And by using the Flag module, as a bonus you get all those amazing features about integrations with other modules such as Rules, Views, Views Bulk Operations (VBO), etc. Some samples:

* Build a view to see what is in "your" fridge, and or apply mass updates using the VBO module.
* Use the Rules module to send eMail reminders when your stock "is running low".

If you're not familiar with the Flag module, checkout the set of 8 video tutorials about this module. Especially the Video about Creating non-global flags: between about 6:00 and 8:30 it explains how to add a Flag-related relationship in your view, so that you can then also use flag related data in your view (for fields, etc). The same video (near the end) also shows how to combine this with VBO.

Some more suggestions related to some additional (non-global) flags I recommend you to create, which would probably enhance the beer-experience of your users even further:

* *My favourites*: a flag to indicate the favourite beer(s) of a user (... like "Leffe Blond" ...)
* *Looking for it*: a flag to indicate the beer(s) a user is looking/searching for, like where to buy such beer (like "Celis White" ...).
* *Tasted it*: a flag to indicate the beer(s) a user ever tasted, e.g. to create a contest about nr of different beers somebody every tried (like "400" ...), or an inventory of beers that are still on your whish list to ever try (like "empty" ...).
> 2 votes

---
Tags: nodes
---


# Question
Title: How to create a Views custom exposed filter with predefined range of date values (today, next 15 days, next month)
I have a content type "event" with start\_date and end\_date (fields by date module).

A View lists this events and I need a custom exposed filter with a SELECT with 3 options:

* -All-
* Today
* In the next 15 day
* Next month

With the following comparison:

**Today** (start\_date \<= NOW && end\_date \>= NOW)

**In the next 15 days** (start\_date \<= NOW+15day && end\_date \>= NOW)

**Next month** (start\_date \<= $next\_month\_last\_day && end\_date \>= $next\_month\_first\_day)

What is the best way to go to create the above custom filter?

I have to create a Views custom filter handler that does everything, in this case I can generate html select directly in the handler and expose it by default without pass trough views interface to check "expose this.."? Or is best to FIRST create the above separate filters trough Views interface and then ALTER the form to combine all filters in a unique SELECT and then ALTER the query?

I've already take a look to Easy date selector for Views Exposed Date Filter but grouped filters are not a solution for me because I have to manage 2 dates, and not a single one (post date) as in that example.

I also look at How to customize exposed filter for date field? but I'm not sure if using templates like suggested is a good solution for me or there is a more elegant way to reach the goal.

Also found this module: https://www.drupal.org/project/views\_between\_dates\_filter but doesn't provide the select I need.

Thank you very much for any help.

# Answer
I've written a custom module exactly for this purpose but haven't released it as it ended up being a little less abstracted than I'd like.

The way you do it is by writing a Views filter handler (which is surprisingly easy). Without giving the whole game away and leaving a little homework for you: please read on. Let me know how you go.

You'll need a line in your .info file.

```
files[] = inc/views_relative_date_filters.inc

```

Register it with the Views API in the .module file.

```
/**
 * Implements hook_veiws_api().
 */
function views_relative_date_filters_views_api() {
  return array(
    'api' => 2,
    'path' => drupal_get_path('module', 'views_relative_date_filters') . '/inc'
  );
}

```

Register the Views handlers `inc/views_relative_date_filters.views.inc`

```
function views_relative_date_filters_views_handlers() {
  return array(
  // ...
  );
}

function views_relative_date_filters_views_data() {
  $data = array();
  // ...
  return $data;
}

```

And finally write the filter itself in `inc/views_relative_date_filters.inc`

```
class views_relative_date_filters extends views_handler_filter {
  // You'll need an options form (just use the parent)
  function options_form(&$form, &$form_state) {
    parent::options_form($form, $form_state);
  }

  // You can use a views_form or an
  function exposed_form(&$form, &$form_state) {
    // Return a Form API select element
    // ... all, this-day, this-fornight, this-month
  }

  // The query to get your results based on your time period
  function query() {
    $this->ensure_my_table();

    // Get the value of the submitted filter
    if (isset($this->value[0])) {
      $value = $this->value[0];
    } else {
      $value = 'all';
    }

    // A switch on the $value
    switch( $value ) {
      case 'all';
        return;
      case 'this-month':
        // Modify your query with where conditions, groups, joins, whatever
        // ...
        break;
      case 'this-fortnight':
        // Modify your query with where conditions, groups, joins, whatever
        // ...
        break;
      case 'this-day':
        // ...
        break;
      case default;
        break;
    }
  }
}

```
> 3 votes

# Answer
I finally found the module Composite Views Filter that allows to easily reach the goal.

(Ref topic: https://www.drupal.org/node/2576837)
> 0 votes

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


title: Reset password in Drupal 6?

text:
# Question
Title: Reset password in Drupal 6?
My site is on localhost and I have access to database too. This is the structure of "users" table:

The password field is of type "varchar(32)" having collection "utf8\_general\_ci". I tried to decrypt the password online but it displays that password can't decrypted.

I manually updated the table and changed the password using md5 but whenever I try to login to the site as admin, it displays "Access Denied".

How to change the password for site?

# Answer
# Option 1 - Ask for a password reset link

If eMail is working in your site, ask for a password reset link. Use that link to then reset the password.

# Option 2 - Use Drush

If you have Drush available, then you can use eiher of these Drush commands:

* `drush upwd --password="NewPsw" "username"`, to reset the password for `username` to `NewPsw`.
* `drush uli username`, to generate a 1 time login link for `username`.

# Option 3 - Copy an encrypted password that you know

Just copy the encrypted password from the same user table from any other user for which you know the password. Then paste that encrypted password in the record for your admin user. You should then be able to use that password for login with your admin user.

If you don't have another user yet (or don't know any of their passwords), then use standard Drupal facilities to create a new user first (and remember the new user's password).

If you don't have any user that is allowed to create new users (or you can't login with such new user), then (temporarily) create a new Drupal site and use the user/1 password of that new site.

# Option 4 - Create a new admin user

Insert a new user in the "user" table (with an encrypted password for which you know the password). And make that new user an administrator also by inserting an appropriate row in the "user\_roles" table (cloned from the row related to the user/1).

Then use the newly created user to perform a reset of the password for the admin user.
> 1 votes

# Answer
Install Drush and use `drush uli` from within the site directory; you'll get a login URL you can use to log in and change your password.

The URL will start with `http://default` unless you set `$base_url` in `settings.php` or use the `-l` option to Drush to correct it.

Just replace *default* with your local IP etc.
> 1 votes

---
Tags: 6
---


# Question
Title: How do I add JS and CSS to the HTML code created in the body field?
I am using CKEditor; there is an option to add HTML using Full HTML filter format. My HTML code is working fine, but how shall I add JS and CSS in the HTML code?

# Answer
> 2 votes
First and most important: Probably you shouldn't. Both can break your site, so having them in database, where they are hard to find, is bad idea. Better would be to use classes to "trigger" predefined behaviors or styles. If you still want to do it per node, then you have two options:

1. In Full HTML, you can use inline CSS and JS all right. If you can't, go to the format settings and make sure these are not stripped.
2. Code per Node gives you superior editing capabilities and is more manageable. And you can just disable it if you happen to know there is malicious code, but you can't find node it's on.

# Answer
> 0 votes
go to `/sites/all/themes/yourthemename/style.css` and add the css there.

For adding JavaScript there are various ways to do it. Read This Article

---
Tags: javascript, theming, wysiwyg
---


title: List of users who visited node

text:
# Question
Title: List of users who visited node
Is there any module available, with a functionality to show list of users who have visited certain nodes?

I've searched for module like this but haven't found anything like this.

# Answer
Consider using the Node view count module for this. Here is a quote about it (from its project page, bold markup added here):

> ... allows to count node views. Unlike statistics module, this module **records each view of node with user uid and timestamp**. So now you can know **how many times a user viewed node by day, week, month and etc**.
>
> This module is **integrated with Views module**. You can use it to create different statistics pages, output new not viewed nodes for user and many more.

By using this module, and to the extend it should be needed, you can then further refine / extend what you get (out-of-the-box) from this module via a custom module(s) and/or view(s).
> 0 votes

# Answer
I think this Node view count contrib module helps you.

Node view count

> Node View Count module allows to count node views. Unlike statistics module, this module records each view of node with user uid and timestamp. So now you can know how many times a user viewed node by day, week, month and etc.
> 1 votes

# Answer
Recently read

> **Recently read** allows site administrators to enable blocks displaying a history of recently read content (nodes) both to anonymous and authenticated users. For logged in users, each user has its own history. For anonymous users, the history is based on sessions. This module may be useful i.e. for displaying recently viewed products on the e-commerce site.
>
> Note about performance: page caching is disabled for pages containing Recently read block and viewed by anonymous users.

OR

list-recently-viewed-nodes-drupal
> 0 votes

---
Tags: nodes
---


# Question
Title: Why does the EN version of the Main menu not appear on the EN version of my site?
I can't see any menu in the EN version of my drupal site with the following settings in my menu :

* EN and FR languages installed.
* 2 Menu's : main menu en (fixed language : en) and main menu fr (fixed language : fr)
* I add some menu items in those menu's indeed

When I'm navigating trough FR, all is ok, but when I select EN, nothing appears.

I see in HTML that no menu is shown too (0 div for the menu)...

( I cleared the cache 10 times haha )

Site is available here : http://drupatest.clementhallet.be/en

I'm going crazy about this, any suggestions?

# Answer
I've been struggling with a similar issue in the past too. Below is how I resolved this for a multilingual site with menus in multiple languages. In this case for the "main menu", but you can do this for any menu.

# Step 1

Use a single "main menu" that contains all menu items for all languages, so not 1 main menu for only EN menu items and another main menu for only FR menu items.

# Step 2

Configure the multilingual options of the menu via the Menus administration page and follow the "edit menu" link to the menu in question. For the Main menu that would be `admin/structure/menu/manage/main-menu/edit`.

For "Translation Mode", use the option "Translate and Localize". So that menu items with language will allow translations, and menu items without language will be localized.

# Step 3

Add the links for any of your languages to the single menu, but make sure to specify for each of these links for which specific language you want the link to be shown. Or as an alternative, if you have menu items that should be shown for al languages, make sure such link is marked as "Language Neutral".

# Summary

For any language the very only (single) "Main menu" is shown. However based on the selected language, only those menu items in it will be shown that match the selected language. Not sure if it is the best/most elegant way to make this work, but IMHO it works like a charm ...
> 0 votes

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


# Question
Title: How to provide theme override for stylesheet conditionally included by a module
I have a module that conditionally includes a stylesheets using `#attached` on a render array it outputs. (By *conditionally* I'm meaning that sometimes the module adds the attached css, sometimes not; I'm not referring to conditional stylesheets as in "is it IE9".)

The render array the module outputs includes the following:

```
$output['#attached'] = array(
  'css' => array(
    'tiles-styles.css' => array(
      'data' => drupal_get_path('module', 'mymodule') . '/css/tiles-styles.css',
      'type' => 'file',
    ),
  ),
);

```

In my theme, I have css under a `css/` directory. I want to override both these, but only when they are required.

It seems that by adding

```
css[tiles-styles.css][data] = 'tiles-styles.css'

```

to my `theme.info` file I can get my file included, and it overrides the module-provided one. However, doing this *also* includes this stylesheet on every page load, which is unnecessary.

Is there a way to override the stylesheet but only if the stylesheet was included in the first place?

# Answer
You can do this by implementing `hook_css_alter` as follows:

```
/**
 * Implements hook_css_alter().
 */
function mytheme_css_alter(&$css) {
  if (isset($css['tiles-styles.css'])) {
    $css['tiles-styles.css']['data'] = drupal_get_path('theme', 'mytheme')
                                       . '/css/tiles-styles.css';
  }
}

```
> 0 votes

---
Tags: 7, theming
---


# Question
Title: On/Off Checkbox to toggle filter value in views exposed filter
I am using Better Exposed Filters Module and **Has Boyfriend** field is `Boolean Yes/No` field type of the content.

The Current View I have is:

When I click the **Yes** Checkbox I get:

My quest is when the **checkbox** is not-checked it'd only display girls without boyfriend like: (please ignore the filters here, I just showed it to explain my question, the filter should not have **No**, it should be default filter)

I can acheive this with such multiple-checkbox as above but I have the requirements to display only **Girls without Boyfriend** as default display list. When the checkbox **Yes** is clicked it'd hide all the Girls without boyfriends and display only Girls who has boyfriend.

There were few similar questions like this when I was searching like This and This but the answers doesn't satisfy my requirements.

# Answer
> 2 votes
I fixed this with Simple jQuery functions.

At first I set the views filter to default as **No**. Like:

Then I hid the div that contains **No** checkbox with `CSS` Class `element-invisible` like:

```
$('div.containsNoCheckbox').addClass('element-invisible');

```

Then I toggled between checkbox On/Off with:

```
$('#YesId').change(function () {
                 if($('#NoId').is(':checked')) {
                     $('#NoId').prop('checked', false );
                 }
            });

```

When I *check* the **Yes Checkbox**, this will *Uncheck* the **No Checkbox**.

When I *Uncheck* the **Yes Checkbox**, default value defined in the filter will be used. This how it toggles now.

# Answer
> 6 votes
Not totally sure if this is the same as your requirements, but I managed to have one checkbox that only shows relevant content when checked. Basically, I chose these options in filter options:

1. Expose this filter to visitors, to allow them to change it
2. Filter type to expose: Single filter
3. Is one of: (select the 'on' value)
4. Allow multiple selections (checked)
5. Limit list to selected items (checked)

Then in BEF: 6. Display exposed filter as: Checkboxes/radio buttons.

So, pretty much the only difference is the selection of "Limit list to selected items" in the filter options. See pic below. (And it doesn't use jquery, so should be more performant) Hope that helps.

.

# Answer
> 3 votes
Whenever I run into issues like these, I tend to use the grouped option with exposed filters. You shouldnt need better exposed filters at all for this.

1. Choose 'Grouped Filter' options
2. Choose 'radios'
3. uncheck 'optional' to make the filter required (and not display the -any- option)
4. Choose 'allow multiple selections' so one can choose either/and and so that checkboxes appear.
5. Configure the grouped filters similarly (I used the panopoly 'featured' boolean field since it was readily available).

# Answer
> 1 votes
I wanted to implement a similar approach and I finally found a solution, perhaps it will help some others.

I took these steps

1. Implement `hook_form_alter()`

* Add a new form element checkbox
    * `hide()` the original form element
    * Add a new validation callback
2. Created the validation function

* calculate the desired filter input
    * use `form_set_value()` on original filter element

```
    function hook_form_alter($form, $form_state, $form_id) {
        if (checkIfItIsTheDesiredForm()) {
            hide($form['originalFilter']);
            $form['newCheckbox'] = array(
                '#type'         => 'checkbox',
                '#title'        => 'Boyfriend',
                '#return_value' => 1,
                '#default_value' => 0,
            );
            $form['#validate'] = array_merge(array('manipulateFilterLogic'),$form['#validate']);
        }
    }
    function manipulateFilterLogic ($form, $form_state) {
        if (checkIfItIsTheDesiredForm()) {
            $filterValue =  ($form_state['input']['newCheckbox']) ? 1 : 'All';
            form_set_value($form['originalFilter'],$filterValue, $form_state);
        }
    }
```

---
Tags: views
---


title: Webform / add hidden field with token

text:
# Question
Title: Webform / add hidden field with token
When adding a hidden secure field to a webform it does not show up in markup. Both for default value and tokens.

> Secure value (allows use of all tokens)

If I choose a hidden element it is present in DOM.

> Hidden element (less secure, changeable via JavaScript)

I have cleared cache several times, rearranged elements with both text fields and normal hidden fields. Those show up, but not the hidden secure ones.

What am I not doing right?

Here's what I'm referring to:

# Answer
Fields with **Secure value (allows use of all tokens)** won't appear in your markup (that's why they are secured). They are 'created' on server side and are not available on Client Side. So nobody can't change their value (f.x. via XSS)

Hope it helps.
> 2 votes

---
Tags: webforms, tokens
---


# Question
Title: What's the best option for responsive drupal theme using sass, Zen sub-theme or twitter Bootstrap
I am going to start a new project using sass but not sure whether I should use twitter bootstrap and start fro scratch or use Zen. Any suggestion on which one to use and why?

# Answer
In my opinion bootstrap, with bower you can download bootstrap-sass in your theme folder really handy.
> 1 votes

# Answer
I think you should go with Zen and create your own sub-theme from it. Because it is a powerful, yet simple, HTML5 Starter Theme with a responsive, mobile-first grid design.

If you are building your own standards-compliant theme, you will find it much easier to start with Zen than to start with Garland or Stark. This theme has fantastic online documentation and tons of helpful code comments in its PHP, HTML, CSS and Sass.
> 0 votes

---
Tags: theming
---


# Question
Title: How to specify granularity for the Access log Timestamp field to display access log entries using Views?
Normally when you select a date field in Views there is the option to specify the 'granularity'. Ie: Day, Hour, Minute etc... ie: When you add the 'Post date' field from a node.

Does this functionality not exist at all for the 'Access log: Timestamp' field, when displaying access log entries using Views?

This would be really helpful for displaying simple custom statistics, but it doesn't seem to exist and I'm not sure where to even look to add the functionality to the relevant module!

# Answer
> 0 votes
Maybe the Views Date Format SQL module is what you're looking for. Here are some details (from its project page):

> The Views Date Format SQL module allows to format date fields using SQL. This enables group aggregation for date fields using the choosen granularity.
>
> The core functionality is to remove the date formatting from render() and put it in query(). I.e. format date values using SQL's DATE\_FORMAT rather than PHP's format\_date. This is achieved by assigning a new default handler to node 'created' and 'changed' date fields. This handler extends and overrides views's build in views\_handler\_field\_date.
>
> The UI is completely unobtrusive, only a single checkbox "Use SQL to format dates" is added to the handler configuration popup.

As an illustration, and/or to better understand the challenge here, you may want to look at Graph node input over time (support date formatting on a continuous axis) also. Comment #3 of that issue states: 'The trouble here is that neither Views nor Date modules provide aggregation options for date-based fields.'.

---
Tags: views, datetime, nodes
---


# Question
Title: Can I restrict which user can use a given term of taxonomy?
I am using Taxonomy as Category.

For example taxonomy "Categories" have "Internal Coms" as term.

Then I have a view that shows all Internal Coms.

But this term must be used only by some users (or role), because those are institutional communications.

I see that any user that can publish an article can select Internal Coms. as term and then his post will be shown as something that it is not.

How can I handle this situation?

# Answer
Taxonomy Term Permissions seems to be created just for this purpose:

> This module allows taxonomy administrators the ability to restrict setting individual terms on nodes by user or role.

Alternatively, you could implement `mymodule_form_alter()`. In it, test something like `user_access('use_internals')`, and if it returns `false`, remove forbidden terms from `[#options]`.

Source: https://stackoverflow.com/a/21289211/2389310
> 1 votes

---
Tags: users, taxonomy-terms
---


# Question
Title: Is it possible to use mixed LDAP and local Drupal authenticated users on the same site
I have a site in which site editors and administrator need to login using LDAP authentication. However, the site also will have regular authenticated users, who can register for an account directly through the standard new user registration form. I was wondering if it is possible to configure a Drupal site so that regular users can use the standard Drupal authentication process, but site editors and administrators can LDAP authentication?

I see that the LDAP module has a mixed mode setting in which it will use LDAP authentication if local authentication fails. I would assume in such a situation, any users that registered for an account through the standard create new account form would have a local account and thus would be authenticated locally. But how would it work with creating a new editor or administrator account? Is it the case that I just need to add them to the LDAP server, after which they be automatically added to the Drupal system?

# Answer
> 0 votes
Any accounts created through LDAP will have access to the site. Alternatively you can create local Drupal users that also have access when using mixed mode.

For instance I work with sites where I have LDAP credentials that allow me access to all the sites. I also had a local Drupal user for one or two that have different credentials and I can log in with either (same email).

Depending on what modules you are using to facilitate this process they may even create a local user for each LDAP user (not sure if they all do this or not). This comes in handy when experiencing LDAP issues as you still have access to your site/s.

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


# Question
Title: Cannot load ctools automodal associated menu call from another module
I have several modules that make extensive use of the Ctools Automodal modal to activate custom-driven modals. These Link references live in their own module, `example_item_modals`:

```
/**
 * Implements hook_menu()
 */
function example_item_modals_menu() {
  $items['product/product1'] = array(
    'page callback' => 'product_order_modal_1',
    "access arguments" => array('interact with orders'),
    'type' => MENU_LOCAL_TASK,
    'modal' => TRUE
  );

  $items['product/product2'] = array(
    'page callback' => 'product_order_modal_2',
    "access arguments" => array('interact with orders'),
    'type' => MENU_LOCAL_TASK,
    'modal' => TRUE
  );

  return $items;
}

```

We have another module that loads in a User Profile (developed by another third party) and the requirements call for loading some of the products here, and interacting with the modal. Actually displaying the links are done using a tpl.php call to those menu calls with an `l()`.

```
<ul>
  <li>
    <?php echo l("View Product", "product/product1"); ?>
  </li>
</ul>

```

So when we eventually load the template call in this custom user profile module, this link should load and have the necessary logic to fire the modals. Except, its not. Here, it treats it like a backpage link. Is there something I am missing for this link to function as a modal? Do I need to explicitly include the parent module the links are defined with, and if so, what API call accomplishes that? (I looked at `module_load_include()` but i'm importing settings thrown in the .module, not a .inc file).

# Answer
I think you need specific class for your link to be preprocessed as a modal link (but i don't know the 'automodal' feature so maybe im wrong)
> 1 votes

# Answer
```
<ul>
  <li>
    <?php echo l("View Product", "product/product1", array('attributes' => array('class' => array('ctools-use-modal')))); ?>
  </li>
</ul>

```
> -1 votes

---
Tags: 7, chaos-tool-suite
---


title: Simple markup field module

text:
# Question
Title: Simple markup field module
I'm looking simple markup field (similar to Field Hidden which would provide dummy field which can place hold some html code (such as field title and its description without showing any field).

So basically something equivalent to this Form API element:

```
$form['markup'] = array('#markup' => '<span>foo bar</span>');

```

but as a proper field (so no custom coding or styling involved) which can be attached to Entityform.

# Answer
> 0 votes
As suggested by Clive, there is a Static field which provides a static text that can be configured on a per instance basis via Field API.

Just enable the module and use Field UI to add and configure the field.

There is also another module, called: Pseudo field which allows you to render an extra field as a real field (with field label).

---
Tags: entities
---


# Question
Title: Date module: detect if an end date was set
I have a content type with a date field. It is setup to collect an end date (optional). The field type is Date (UNIX timestamp).

The field is to store "experience" as (from) January 2011 - (to) March 2012.

If I don't check the "show end date" when creating content, the end date is the same than the start date. But in my case, I sometimes need to collect an end date that would be the same than the start date (January 2011 - January 2011).

**So how do I know if that "show end date" checkbox was checked?**

Right now here is what I get when the end date is the same than the start date:

```
value (String, 10 characters ) 1443650400
value2 (String, 10 characters ) 1443650400

```

And this is what I get when the "show end date" was not checked:

```
value (String, 10 characters ) 1443650400
value2 (String, 10 characters ) 1443650400

```

# Answer
I'm going to take a guess and assume you have the end-date defaulting to the start-date in the Date field, field-settings?

That way if they click the checkbox for **Show End Date**, they have to provide a value for it. otherwise it will be empty; essentially letting you know if the checkbox was checked or not.
> 2 votes

---
Tags: 7, datetime
---


title: Create an article entry without image

text:
# Question
Title: Create an article entry without image
All I want is to post a video embed, but the drupal form is forcing me to use an image for each, otherwise I can't upload my post.

Is there a way to override that field in particular?

# Answer
You can un-require the field. Navigate to:

> /admin/structure/types/manage/\[content\_type\]/fields

and un-require there.
> 2 votes

---
Tags: media
---


# Question
Title: How to programmatically handle files (CSV import)
I'm trying to make a simple form to upload a txt/csv file, in order to parse it and update some values in database. Here's my code. Unfortunately, at the moment using the form nothing happens (no folder creation, no file upload...) Here's the code. What can be wrong here? Thank you

```
function vts_departs_conf_form() {
  $form = array();

  $form['browser'] = array(
    '#type' => 'fieldset',
    '#title' => t('Send file'),
    '#collapsible' => TRUE,
    '#description' => t("Send foo file."),
  );

  $file_size = t('Maximum file size: !size MB.', array('!size' => file_upload_max_size()));

  $form['browser']['file_upload'] = array(
    '#type' => 'file',
    '#title' => t('CSV File'),
    '#size' => 40,
    '#description' => t('Select the CSV file to be imported. ') . $file_size,
  );

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

  $form['#attributes']['enctype'] = "multipart/form-data";

  return $form;
}

function vts_departs_conf_form_validate($form, &$form_state) {
  // attempt to save the uploaded file
  $filepath = 'public://depconfs';
  file_prepare_directory($filepath, FILE_CREATE_DIRECTORY);
  $file = file_save_upload('file_upload', array('file_validate_extensions' => array('CSV TXT')), $filepath, FILE_EXISTS_REPLACE);

  // check file uploaded OK
  if (!$file) {
    form_set_error('file_upload', t('A file must be uploaded or selected from FTP updates.'));
  }
  else {
    // set files to form_state, to process when form is submitted
    $form_state['values']['file_upload'] = $file;
  }
}

function vts_departs_conf_form_submit($form, &$form_state) {
  //Prepare file parsing
  $line_max = variable_get('user_import_line_max', 1000);
  ini_set('auto_detect_line_endings', true);
  $filepath = $form_state['values']['file_upload']->filepath;
  $handle = @fopen($filepath, "r");

  while ($row = fgetcsv($handle, $line_max, ',')) {
    // do stuff
  }
}

```

## EDIT :

As a first step, @bdurbin corrected my naming mistakes.

Reading `file_save_upload()` API description, I realised that my basic validation checks are already performed, so I removed them.

So final is quite lighter :

```
function vts_departs_conf_form_validate($form, &$form_state) {

  $filepath = 'public://depconf/';
  $validators = array('file_validate_extensions' => array('csv txt'));
  $file = file_save_upload('file_upload', $validators , $filepath, FILE_EXISTS_REPLACE);
  //push file object to submit step
  $form_state['values']['file_upload'] = $file;

}

```

# Answer
Drupal's naming convention for the automagic association of validation and submit handlers for a given form is:

* name\_of\_form() (builder)
* name\_of\_form\_validate() (validation handler)
* name\_of\_form\_submit() (submit handler)

In your case, if you wanted to name your form vts\_departs\_conf\_form(), you'd want to either rename your validation handler to vts\_departs\_conf\_form\_validate() and your submit handler to vts\_departs\_conf\_form\_submit(), or use the #validate and #submit form attributes to associate functions that don't follow the naming conventions.

In your example, changing the builder name to vts\_departs\_conf() made the form work as expected.
> 1 votes

---
Tags: forms, files
---


# Question
Title: How detect format of date field in form alter?
How can I find if a form has date/time field or not and if it has, how can I detect what is **date format** for it?

# Answer
> 1 votes
For the Date popup selector, the `#date_format` element in the form element. For example:

```
    //The date field has the format of "d-m-Y"
    $form['date_field'] = array(
      '#type' => 'date_select',
      '#title' => t('My Date'),
      '#date_format' => 'd-m-Y',
      '#date_label_position' => 'within',
      '#date_year_range' => '0:+1',
      '#description' => t('This is a test date picker'),
      '#default_value' => date('Y-m-d H:i:s'),
    );

```

There's an D6 documentation page on d.o, but it's still valid for D7 last I looked.

---
Tags: datetime
---


# Question
Title: How to display multiple nodes of a content type on a page displaying a parent node?
I have a content type called **PRODUCT**. Each of these product's has an entity relationship to one or more other **PRODUCT** items that are similar. When a user views a **PRODUCT**, using the themed output for that **PRODUCT**, I would like to display the other similar **PRODUCT**'s below it.

Initially I used the entity full item display option in the content output and that worked fine, but I really need each node in a tag of its own and not have the one product group the related product items under it in the output which is what the entity display filter does.

Entity Display Output....

```
<div class="main-node">
  ...
  <div class="entity-node1">
     ...
  </div>
  <div class="entity-node2">
     ...
  </div>
</div>

```

But what I would like is the following.

```
<div class="main-node">
  ...
</div>
<div class="entity-node1">
  ...
</div>
<div class="entity-node2">
  ...
</div>

```

Where is the best option to create this type of output?

# Answer
Just use a `Views Attachment` to attach another view `After` your first view.

Another similar option is the Entity Views Attachment module:

> "Eva" is short for "Entity Views Attachment;" it provides a Views display plugin that allows the output of a View to be attached to the content of any Drupal entity. The body of a node or comment, the profile of a user account, or the listing page for a Taxonomy term are all examples of entity content.
>
> The placement of the view in the entity's content can be reordered on the "Field Display" administration page for that entity, like other fields added using the Field UI module.

So the nice thing about the EVA module is that it allows you to easily place and manage the View from the Field UI of your content type. Thus, making the administration of this *tacked on view* a little bit easier for site administrators.
> 0 votes

---
Tags: nodes, theming
---


# Question
Title: "public://" is not resolved correctly to the full path
In my script, `public://` resolves to http://./sites/default/files/test.txt

This is the code I used to get the actual value for `public://`:

```
$path = file_create_url('public://test.txt');

```

`$GLOBALS['base_url']` is also resolving to http://.

Any idea why the domain is missing from the `public://`?

Thanks

# Answer
> 3 votes
The reason there's no `$base_url` is because the script you're running isn't in a HTTP context; when Drupal bootstraps, unless you've specified a `$base_url` in **settings.php**, it retrieves this value from `$_SERVER['HTTP_HOST']` which doesn't exist in the command line context.

To remedy this, you can set the `$base_url` in your **settings.php** or, if you're running Drush, use the `--uri` argument.

```
drush scr --uri="http://www.example.com" my_script.php

```

---
Tags: files
---


# Question
Title: How to customize drupal_mail() error messages
How can I customize `drupal_mail()` error messages? I 've switched off the display of error messages, but this config does not seem to affect to the management of email messages, which insists on displaying the status of the delivery in the navigator screen.

# Answer
`drupal_mail()` uses `drupal_set_message()` to push error messages on mail failure. The only way to suppress those messages is by altering `drupal_set_message()` output. Depending on the how/why, there's a couple of tacts to take.

One way to do this is a blanket suppression via the Disable Messages module that lets suppress messages based on a few different criteria.

> Gives a site owner options to disable specific messages shown to end users. The core drupal message system as offered by drupal\_set\_message is an excellent way for modules to send out messages to the end users. However not all drupal site owners are keen to show all the messages sent out by drupal core and all modules to their users. This module gives site administrators a reasonably powerful way to filter out messages shown to the end users.

Another, more surgical way, is to manipulate the `$_SESSION['messages']` variable which contains the array of pending messages to render, following the execution of `drupal_mail()`.
> 2 votes

---
Tags: 7, emails
---


# Question
Title: Migrate Module: How to construct a map on a UNION query
I am trying to create a hierarchical taxonomy from two different tables in the source database, one containing the parent entries, and the other containing the children. Here is my query:

```
    $query1 = $this->getConnection()
      ->select('envirolib_area', 'a')
      ->fields('a', array('areaname', 'areaname_japanese', 'sort_order', 'acronym', 'areaid'));
    $query1->addExpression(':empty','parentid',array(':empty'=>0));
    $query2 = $this->getConnection()
      ->select('envirolib_task', 't')
      ->fields('t', array('taskname','taskname_japanese','sort_order','acronym','taskid'));
      $query2->addField('t','areaid');
    $query1->union($query2, 'UNION ALL');

    $queryx = $this->getConnection()
      ->select($query1,'x')->fields('x', array('areaname','areaname_japanese', 'sort_order', 'acronym', 'areaid', 'parentid'));

```

The `envirolib_area` table has a primary key of `areaid`, and the `envirolib_task` table has a primary key of `taskid`. The `envirolib_area` table doesn't have a `taskid` column, and in my union I am actually calling `a.areaid` and `t.taskid` `areaid`, with `t.areaid` called `parentid` and 0 inserted in that column for rows from the `envirolib_area` table.

the addition of `$queryx` was necessary to stave of errors about unven numbers of queries in a union, which seems to be caused by the mapping method joining onto the query (thought the explanation I read, claimed that shouldn't happen if `'map_joinable' => FALSE` as it is in my case.

So here is my attempt at `MigrateSQLMap`:

```
$this->map = new MigrateSQLMap($this->machineName,
  array(
    'areaid' => array('type' => 'int',
                       'length' => 3,
                       'not null' => TRUE,
                       'description' => 'Area ID',
                       'alias' => 'a'
                      ),
    'taskid' => array('type' => 'int',
                        'length' => 3,
                        'not null' => TRUE,
                        'description' => 'Parent ID',
                        'alias' => 't')
    ),
  MigrateDestinationNode::getKeySchema()
);

```

When I try to run the migration I get a wall of errors like this:

```
Undefined property: stdClass::$taskid File /Users/bob/ultrabob.prv/www/sites/all/modules/migrate/includes/migration.inc, line 943(file: /Users/bob/ultrabob.prv/www/sites/all/modules/migrate/includes/migration.inc, line 943)
Could not save to map table due to NULL value for key field taskid

```

How should I set up the MigrateSQLMap in a case like this? Would it make more sense to migrate this taxonomy in two migrations, one for each table?

# Answer
Either do 2 migrations. Or create a derivative table of your term data to easily set the `$query` for the migration before running the migration task.

You can do this by writing a custom php script to be called by `drush php-script` or by using the `preImport` migrate hook to build/rebuild the derivative table.
> 1 votes

---
Tags: migrations
---


# Question
Title: Duplicate entry/Contraint violation 1062 in file_managed on browser crash
I'm using Drupal 7.28. Today when I tried to upload some 100 image files in Image field type, it aborted in the middle saying that "20 MB" limit reached. Now it wouldn't even show me way to delete the files.

Since then I'm getting the following error (below). when I try to upload the same files.

I've run cron and also cleaned all caches but this error does not go.

I can see that these orphaned files are still stored in the file\_managed table.

**How can I resolve this problem?**

Related post: https://stackoverflow.com/questions/8809010/pdoexception-on-duplicate-filename-in-drupal-7

Another solution comment here on Drupal.org which says that such files should be cleaned by 6 hours by Cron run.

## Error on repeat uploads

> PDOException: SQLSTATE\[23000\]: Integrity constraint violation: 1062 Duplicate entry 'public://wsgallery/DSC00441.jpg' for key 'uri': INSERT INTO {file\_managed} (uid, filename, uri, filemime, filesize, status, timestamp, type) VALUES (:db\_insert\_placeholder\_0, :db\_insert\_placeholder\_1, :db\_insert\_placeholder\_2, :db\_insert\_placeholder\_3, :db\_insert\_placeholder\_4, :db\_insert\_placeholder\_5, :db\_insert\_placeholder\_6, :db\_insert\_placeholder\_7); Array ( \[:db\_insert\_placeholder\_0\] =\> 1 \[:db\_insert\_placeholder\_1\] =\> DSC00441.jpg \[:db\_insert\_placeholder\_2\] =\> public://wsgallery/DSC00441.jpg \[:db\_insert\_placeholder\_3\] =\> image/jpeg \[:db\_insert\_placeholder\_4\] =\> 305012 \[:db\_insert\_placeholder\_5\] =\> 0 \[:db\_insert\_placeholder\_6\] =\> 1413799461 \[:db\_insert\_placeholder\_7\] =\> image )

# Answer
Check whether the file is being used by another part of the system with the file\_usage\_list()

```
$file = file_load($fid);
$usage = file_usage_list($file);

```
> 0 votes

---
Tags: 7, media
---


# Question
Title: Is it safe to send the unencoded JSON output?
The mobile app developers wants an api to get a list of articles from our Drupal site. It should have these fields in the output:

1. nid
2. title
3. field\_teaser\_body

The api resonse has to be in JSON format.

The field type of `field_teaser_body` field is `Long text` and text processing is `Plain text`.

I created a custom code to get this working. Here's a simplified version of it.

```
$query = db_select('node', 'n');

$query
  ->fields('n', array('nid', 'title'))
  ->condition('n.status', 1)
  ->orderBy('n.created', 'DESC')

$result = $query->execute();

$nodes = array();
foreach ($result as $value) {
  $node = node_load($value->nid);

  $data = array(
    'nid' => $node->nid,
    'title' => $node->title,
    'field_teaser_body' => !empty($node->field_teaser_body['und'][0]['value']) ? check_plain($node->field_teaser_body['und'][0]['value']) : '',
  );

  $data = (object) $data;
  array_push($nodes, $data);
}

$content = new stdClass();
$content->nodes = $nodes;

print json_encode($content);

```

Just for the security purpose, I'm using `check_plain()` function to sanitize the teaser body text. But, when using this function, it encodes all special characters.

For e.g., `Bob's height is > than Alice.` converts to `Bob's height is > than Alice.`

The mobile app developers said that they don't want any encoded text in the JSON output.

**Is it a safe practice to send the unencoded (unsanitized) text in the JSON output ?**

# Answer
There is no need to encode or escape anything yourself. json\_encode() will take care of properly escaping any special purpose characters.
> 0 votes

# Answer
From a Drupal standpoint, it's ok to send markup in JSON fields.

After all, you're delivering the content which may need markup to work (e.g. `<p>` & `<h1>` tags for formatting). The onus should be on the app developer consuming the JSON to do sanitary checks (e.g. `<script>` injection, broken markup, malicious `<iframe>`, etc.). If you have any custom input forms that's where you should be doing your sanitary checks.

With all that said, if security is a concern, I'd suggest looking at a ready made solution for delivering content in a JSON format (e.g. Services). Any community-provided module solution is likely to have more security vetting than your own solution.
> 0 votes

---
Tags: security, 8
---


# Question
Title: How to force users to logout after X minutes of inactivity using Rules, Views?
How to force users to logout after X minutes of inactivity using Rules, Views or any other popular module ?

---

*update 2012-01-27*

Where can I find an example how to do the forced session expire using Rules module ?

# Answer
> 2 votes
Drupalmodules.com shows two potential modules:

Session Expire \- "Expires rows from the session table older than a certain time."

Automated Logout \- "This module provides a site administrator the ability to log users out after a specified time of inactivity."

Either module would probably be able to give you the functionality you want. The automated logout module looks like it could give you a timer to show how much longer a user has before being logged out.

# Answer
> 0 votes
Add some PHP-Code to the rule, if interested I could also provide a rules export.

```
global $user;

// Session longer than 3 hours
if ((REQUEST_TIME - 10800) > $user->timestamp) {
  module_load_include('pages.inc', 'user');
  user_logout();
}

```

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


# Question
Title: How to do menu rebuild when having PHP Fatal error?
I have been trying to get the command `menu_rebuild();` to work on `drush`. However, I keep getting this error:

I, of course, think I installed Drush correctly. However, I can't be 100% certain since I've never used Drush before.

The reason why I am trying to run this command is because my admin menu is giving me problems. Whenever I install new modules, the settings pages corresponding to those modules are missing. Yet, they are installed and working according to Drupal.

# Answer
Turns out that the Backup and Migrate module we had installed was causing the issue. Why? I'm not entirely sure but the problem is gone now that we removed it.
> 0 votes

# Answer
Make sure you're running `drush` in your web root and `drush status` is showing `Drupal bootstrap: Successful`.

Then try the following steps:

* `drush cc all` to clear the caches or clear cache tables manually, e.g.:

```
echo "SHOW TABLES LIKE 'cache%'" | $(drush sql-connect) | tail -n +2 | xargs -L1 -I% echo "DELETE FROM %;" | $(drush sql-connect) -v

```
* try rebuild menu again: `drush eval 'menu_rebuild();'`
* try rebuild your Drupal registry via:

```
drush -y dl registry_rebuild
drush rr

```
* consider disabling caches

---

In case your `drush status` doesn't show `Drupal bootstrap` as `Successful`, you either running it outside of your Drupal webroot or your db credentials are not configured properly in `settings.php`, or you've some missing/corrupted files which prevents from bootstrapping your Drupal core.

If you're using multisite, then don't forget to specify your profile by either running inside sites/X dir or make sure you're specifying the right `--uri` parameter, e.g.: `drush -l http://myprofile status` (see: `drush topic core-global-options` for proper syntax).

If you still having the issue, try: `drush -vd status` to troubleshoot the source of your problem.
> 3 votes

---
Tags: drush
---


# Question
Title: Flag, flag link, and flagging: create an advanced relationship
On my site I have two content types:

* event – with node flag “Attend” and Entity Reference field
* band

And flags:

* “Attend” – node flag - with Entity Reference field
* “Accept” – flagging flag – connected to “Attend” flag

Each user can create unlimited number of Bands (he is manager of each Band) and create unlimited number of Events.
On Event creation form I add Entity Reference field with list of user Bands. This way band which he choose will become an Event organizer.
And now: other Users can click on flag “Attend” in Event node. On next step they need to choose witch of their bands will participate in this event (entity reference field)

Quick example:
“User 1” create “Band A”, “Band B” and “Band C”
“User 2” – “Band D”
Events and attendance:
“Band D” is the organizer of the “Event A”. “Band A”, “Band B”, “Band C” want to attend.
“Band A” create “Event B”. Attend: “Band D”,
“Band D” create “Event C”. Attend: “Band B”, “Band C”

In views I create a private page with table of events of each user. I add all necessary relationships to show Events of each user with list of bands which use “Attend”. Please imagine it as a table:

Band A – 1 event:

* Event B
    + Band D – “Accept flag”(flag link)

Band D – 2 events:

* Event A:
    + Band A - “Accept flag”
    + Band B - “Accept flag”
    + Band C - “Accept flag”
* Event C:
    + Band B - “Accept flag”
    + Band C - “Accept flag”

User (author) creator of the event using flagging flag can decide which band he Accept for event.

**Problem:**
**When Band D click “Accept” for Band B under Event A the status also change in Event C.**
Do you think it is possible to separate this?
I hope I have described all process clear enough.
Thank you!

# Answer
> 0 votes
Using Drupal rules module you can set up the right triggering conditions. It is possible to use rules to alter the data in fields arbitrarily, however your question is a little confusing because bands are also described as users, so you would need to make use of user related fields in the rules configuration. Take a look at the large rules documentation section and this intro to the rules module to get an idea. Flag module is compatible with rules.

---
Tags: views, flags
---


# Question
Title: How do I render the 'user_picture' of a user account?
I load a user object, and I would like to be able to show the user's picture somewhere. I tried the following code.

```
$row_user = \Drupal\user\Entity\User::load($uid)->user_picture->first()->view('large');

```

What I get is this (using `kint()`).

This user has a picture and it is shown correctly in the user page.

How do I exactly show the picture associated with a user account?

# Answer
> 1 votes
Just like every other render array, render it.

If you print it out in twig, that just works, in PHP, use `\Drupal::service('renderer')->render()`.

---
Tags: 8, users
---


# Question
Title: Setting current node url as default value for "Link" field
I have a content type with a field type Link. I would like to set default text and url for the field. Under:

> Structure » Content types » MY CONTENT TYPE » Manage fields

I tried entering `#` and `[current-page:url:absolute]`. Both of them were not accepted and the below are the respective error messages:

* The value `[current-page:url:absolute]` provided for MY FIELD NAME is not a valid URL.
* The value `#` provided for MY FIELD NAME is not a valid URL.

What is the right way to enter the current node URL as a default value into a Link type field?

# Answer
> 2 votes
You need to use module field default token to work global as well local token in field value. You can use your previous token i.e. `[current-page:url:absolute]`.

---
Tags: navigation
---


# Question
Title: Access By Term(abt) is not work in SOLR search Drupal 7
I'm using Access By Term contrib module which is used for show the node when the node term reference and the user term reference is equal. I can get this, Also in solr search, **Filter** tab setting I have enabled the **Node access** checkbox. However when I'm searching the particular node title with other user credentials, actuallay the other user cannot be able to search those nodes. Still solr search resulting a node. I want to restrict this??? Is there any way??

# Answer
I have found a solution. If the Solr server want to obey node access means, we must index the **Status** and **Author** field to the server. I have done this, now the node access is perfectly worked even with the search also.
> 1 votes

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


title: Profile2 with Display Suite

text:
# Question
Title: Profile2 with Display Suite
I am using profile2. In main profile type I have created some fields. Now according to my project need I want to use display suit for manage display. I followed instruction according to link, but no effect. If I do some changes in manage field it is showing but if I do any changes in manage display it is not effecting.For example in my first screen shot designation is above full name that i have set by manage display but in front end full name is above  Please help me if some one sort out this issue. Thanks in advance

# Answer
> 1 votes
A nice way to deal with that is to temporarily get out of profile2 rendering way. What I explain here works also for the input form.

1 - Enable the field\_collection module.

2 - Create your fields collections.

3 - Then you can arrange the field collection display, including for the form.

4 - You replace your fields in profile 2 with the field collections.

5 - Enable the overlay module (not mandatory), at the bottom of each field collection you can now see add and edit buttons.

Now your fields collections are rendered as you wanted, including for profile2 form.

This is a "good to go" workaround as can be seen on the screenshot.

OR

profile2-display-suite-forms

---
Tags: users, display-suite, entities
---


# Question
Title: Get data and uploaded files from android (mobile) version of website
I built a website and it works well in browser. We need to create android version of this website, and in this version users must be able to log in to the site and upload images in their profile.

I really have no idea how Drupal does this and how can I let that android software to connect to my website, upload images and data. I would be appreciated for any help.

thanks.

# Answer
YOu need to provide services using RESTful API to mobile app developer. Required modules are services, services definition and rest server through it you can connect to mobile application because it returns json or xml. Thorugh our site endpoint. Further you can go to its tutorial here.
> 1 votes

---
Tags: 7
---


# Question
Title: what is the difference between commerce order table and commerce line item table?
which table should i consider for created date for an order in commerce\_order table and commerce\_line\_item table.

I can see created dates in both the tables.

# Answer
The `commerce_order` table stores data *about an order*. The `commerce_line_item` table stores line items (e.g. products, fees, misc charges) *in that order*.

If you need to track when the order was created, reference `commerce_order.created`. If you need to track when the line item was originally added to an order, reference `commerce_line_item.created`.
> 0 votes

---
Tags: datetime, commerce
---


# Question
Title: How to set body field display programmatically on node type install?
When hook\_installing a new custom node type filled with custom fields I call `field_create_instance($instance)` where I also set the custom fields' display like so:

```
'display' => array(
  'default' => array( // view mode
    'label' => 'hidden',
    'type' => 'text_default'
  ),
  'teaser' => array( // view mode
    'label' => 'hidden',
    'type' => 'hidden'
  )
)

```

I also added a body field via `node_add_body_field($type)` but where can I set that body's display properties programmatically? Per default it's set to be displayed in the teaser view. I want to hide it.

# Answer
You can access and alter the view mode configuration via field\_bundle\_settings(), (which is basically a shortcut to `variable_get` and `variable_set`):

```
$bundle = 'my_node_type';
$bundle_settings = field_bundle_settings('node', $bundle);
$bundle_settings['view_modes']['teaser']['custom_settings'] = true;
field_bundle_settings('node', $bundle, $bundle_settings);

```
> 0 votes

---
Tags: 7, entities, installation
---


title: Webform can't display the form

text:
# Question
Title: Webform can't display the form
Webform can't show the form.

The form is showing correctly until today I just found out the form can't display.

It shows me the message "**You may not submit another entry at this time.**"

How do I solve it?

Drupal 6

I made the changes for **Total submissions limit: Unlimited**, but still same problem.

After made the changes, error message below shown:

> user warning: Unknown column 'total\_submit\_limit' in 'field list' query: UPDATE webform SET nid = 110, confirmation = '', confirmation\_format = 3, redirect\_url = '', status = 1, block = 0, teaser = 0, allow\_draft = 0, auto\_save = 0, submit\_notice = 1, submit\_text = '', submit\_limit = -1, submit\_interval = -1, total\_submit\_limit = 10, total\_submit\_interval = 3600 WHERE nid = 110 in /home/domains/site.com/public\_html/includes/common.inc on line 3538.

# Answer
Try to update your database with update.php (http://www.YOUR-DOMAIN.com/update.php) or with drush : `drush updb` The error says that your are missing one column in DB...
> 1 votes

---
Tags: webforms
---


# Question
Title: How to hide the left tool bar of content type for non admin people?
I want to hide the left tool bar of content type also revision message box, as shown in attachement, for non admin people.

I have gone through following https://www.drupal.org/node/1276698 but it's only for particular content.

Please suggest me how to hide from all content.

# Answer
> 2 votes
in `yourwebsite.com/admin/people/permissions` check that the following permission are unchecked **under Node** (click image to enlarge)

**Edit:** I did testing, and it's the Administer Content, make sure you uncheck it! Also administer content types as you don't want them to have that either.

# Answer
> 1 votes
**Answer according updated question:**

Use this function in `template.php`.

```
/**
 * Implements hook_form_alter().
 */
function THEMENAME_form_alter(&$form, &$form_state, $form_id) {

  global $user;
  $is_administrator = in_array('administrator', array_values($user->roles));

  if($form_id == 'my_form_id'){
    // if $user does NOT have the administrator role.
    if (!$is_administrator) {
      // disable vertical tabs for this form
      form_disable_vertical_tabs($form);
    }
  }
}

```

**Answer before updating question:**

You may use this snippet in `page.tpl` of your currently active theme.

```
global $user;
$roleid = paste_role_id_of_admin; //
if(user_has_role($roleid, $user)) {
  <?php print $sidebar_first; ?>
}

```

OR

```
if($is_admin){
  <?php print $sidebar_first; ?>
}

```

# Answer
> 0 votes
Maybe you want to look at the Simplify module for this. Here is a quote from its project page:

> Simplify allows particular fields to be hidden from the user interface. This helps to de-clutter forms and present a more user-friendly experience to content editors.

---
Tags: toolbar
---


title: Edit access by checking the field?

text:
# Question
Title: Edit access by checking the field?
Is it possible to check the privileges for a particular field? For example, I have a field in the material `field_access` associated with the user who accepts an ID of the user. How to check access to edit the material through it? Currently editing is possible only if the user specified in the authors. (Google translate. Sorry for that)

# Answer
> 0 votes
Maybe you're looking for this module : Field Permissions

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

# Answer
> 0 votes
Maybe Node access user reference is the module you are looking for.

> This is great if you want your content authors to be able to choose additional authors, or choose who can view their content, as well as being able to display the list of authors or viewers within your content, or in views displays.

---
Tags: users
---


# Question
Title: Conditionally Hiding / Stopping a view from display
I have two views, for taxonomy pages, one displays the products of the current term (using contextual filter "Content:has taxonomy term"), and other display the sub-categories of the term (using contextual filter "Taxonomy term: Parent term").

My problem is that I want to display product view only when I does not get any result in sub-category view.

# Answer
I would use a block, then create a tpl.php file for the block and inside it put

```
<?php

$view = views_get_view('view_name_of_subcategory');
$view->set_display('block_1');
$view->execute();
        // results are now stored as an array in $view->result
$count = count( $view->result );

if ($count = 0) { print views_embed_view('view_name_of_products','block_2' }
else { print $view->render(); }

?>

```

Replace block\_1 & block\_2 with your actual machine name, you can find it here (see picture)

**PS** if `($count = 0)` does not work try if `($count = null)`
> 0 votes

# Answer
You can use the "NO RESULTS BEHAVIOR" from views (on the right side) and choose "Global: View area" to select your view you want to display if there aren't any results.
> 0 votes

---
Tags: views
---


# Question
Title: How to disable/hide /unset a block programatically?
I have a page whose content is visible only in certain provinces. When people visit this page from a different province other than the one it is set for,it should be giving a message saying "the content is not available in the region" by overwriting the node's body in the same page, by using `hook_node_view`. But I have blocks enabled in the content area on this page. is there a way to disable the contents of the block? i tried `hook__block_view` and `hook__block_view_alter` but it did not work. Can someone help me?

# Answer
You could try `hook_block_list_alter` to hide a specific block.

> Act on blocks prior to rendering.
>
> This hook allows you to add, remove or modify blocks in the block list. The block list contains the block definitions, not the rendered blocks. The blocks are rendered after the modules have had a chance to manipulate the block list.
> 5 votes

# Answer
This question is quite old, but unanswered, so I'd respond for the record.

When you install Drupal with the standard install profile, some blocks (Search, Login, Navigation, ...) are enabled automatically.

So if you take a look in profiles/standard/standard.install, you will see that blocks are enabled with a db query and are relative to a theme.

So disabling a block is just an update query:

```
db_update('block')
  ->fields([
    'status' => 0,
  ])
  ->condition('theme', 'your_theme')
  ->condition('module', 'the_module_providing_the_block')
  ->condition('delta', 'the_block_delta')
  ->execute()
;

```

You may need to clear caches after that.
> 4 votes

# Answer
The ninja solution for this case would be a hook\_page\_alter. Also, hook\_block\_view\_alter is a valid hook so I don't know why you can't get it to work.

If your block is from Views, you can set some tricky arguments to hide the block with no extra settings or coding.

Also, you can set per-block visibility settings as a php code.
> 2 votes

# Answer
If you can't get any of the block alter hooks to work, and/or you don't want to use PHP from the Blocks UI/Admin Page, you could dull ax it by creating your own block and then calling the view, eg, something along the lines of this in your own block:

```
 if ( "content is available" ) {

   $block['subject']='Subject....';
   $block['content']=views_embed_view('NAME_OF_VIEW','BLOCK_DISPLAY');

   return $block;

 }

```

and then include that block in your content region instead of the Views block.
> -1 votes

# Answer
most simple way to implement is create a block-YOURBLOCKID tpl in your theme , and in that tpl write the condition

```
if(AVAILABLE){
 //display block//
} else {
 echo 'Not available in your region';
}

```
> -1 votes

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


# Question
Title: Why call javascript behaviour within its own function?
Looking at the JavaScript below, what does calling the behaviourName do?

```
  Drupal.behaviors.behaviourName = {
    attach: function (context) {
      $('.someClass', context).once('some-handler').behaviourName(); // what does this do?
    }
  };

```

I though that the behaviourName was generally used for name spacing. I can see in the site that im working on that the behaviour name is normally called within itself like in this example. What is this for?

# Answer
> 3 votes
You're reading that wrong - the return from `once()` isn't `Drupal.behaviors` (it's a collection of jQuery elements), and `Drupal.behaviors.behaviourName` isn't a function that will do anything by invoking it, anyway. You would need

```
Drupal.behaviors.behaviourName.attach();

```

To get anything meaningful, but that's not synonymous with the code you're referencing.

So that code is **not** calling a *javascript behaviour within its own function*. It's calling a jQuery extension function on the elements returned from `once()`. Most commonly when code needs to do what you're describing in Drupal, you'll see `Drupal.attachBehaviors();` instead.

What you have is a convention used by the developer who wrote the script, nothing more; you'll need to ask them for their motivation for doing so, and how/where they're attaching the `$.fn` functions of the same names as the behaviours.

---
Tags: javascript
---


# Question
Title: Does Drupal keep timestamps of every time node is updated
I'm wondering whether Drupal keep tracks (keep timestamps) of every time a node is updated (not just the last updated). If it does, how could I access this in the front end?

# Answer
> 2 votes
Yes, Drupal stores the updated date, but for that you need to enable revisions on the content types you need it. From your revision table, you can get when a node has been modfied. You can also get how many times you have created a revision and other revision details.

Check the node\_revision table; you will get the details.

---
Tags: 7, nodes
---


title: How to get grouping values in views

text:
# Question
Title: How to get grouping values in views
I created a views to show all my products, in each product have a field named "Color", so now I want to group all product has same color. So now how can I get all grouping values,

```
For exam we have 6 results but just only has 2 colors : Red and Blue without Black one.

```

My question is how can I get grouping values in this views (Red, Blue)

```
$view->some_thing->some_how ?

```

I want to put those values in View footer for my personal purpose

My View should displayed like this

```
--- View Content ----
[RED]
Product 1
Produc 2
[Blue]
Product 3
Product 4

--- View footer
[RED] - [BLUE]

```

Thanks

# Answer
> 0 votes
1. add field in your views
2. select display format
3. like if you are select table format select your value like red in grouping field

# Answer
> 1 votes
1. Add **Color** field into view.
2. Now click on formate setting.
3. Select the **Color** field as a **Grouping field**.

---
Tags: views, entities
---