title: Form styled as a table not submitting

text:
# Question
Title: Form styled as a table not submitting
I am working on a form that will allow users to edit a number of nodes at the same time. The fields I'm displaying are for a single field in all the nodes of a specific type. I want to display the form in a table, so far I've been able to get this to work, but for whatever reason, the form's submit function is not getting hit, and I can't figure out why. Here is a snippet of my form

```
Array
(
  [submit1] => Array
    (
        [#type] => submit
        [#value] => Save
    )

[8 & Under] => Array
    (
        [#prefix] => <div><h1>8 & Under</h1>
        [#suffix] => </div>
        [#tree] => 1
        [#theme] => standards_sc_table
        [8 & Under-402-409] => Array
            (
                [#tree] => 1
                [Girls-36-A-9329] => Array
                    (
                        [#type] => racetime
                        [#default_value] => 18.09
                        [#number_decimals] => 2
                        [#size] => 8
                    )

                [Girls-36-B-9330] => Array
                    (
                        [#type] => racetime
                        [#default_value] => 19.89
                        [#number_decimals] => 2
                        [#size] => 8
                    )

```

The subsequent form looks like this:

The field is a custom field that I created which works great in other places. This form has about 200 or so fields. When I click submit, the page just reloads and none of the code in the submit function is hit. When I remove the theming and/or several tree levels, the form submits.

Here is the theming code:

```
function theme_standards_sc_table($vars) {
  $element = $vars['element'];
  $rows = array();
  foreach(element_children($element) as $key) {
    $rows[] = array();
    $row_count = count($rows) - 1;

    foreach(element_children($element[$key]) as $field_key) {
      $rows[$row_count][] = array('data' => render($element[$key][$field_key]));
    }
  }
  $header = array('SCY A','SCY B','SCM A','SCM B','EVENT','SCY A','SCY B','SCM A','SCM B');
  return theme('table', array('header' => $header, 'rows' => $rows));
}

```

The code to generate the form is pretty complex, but I'll go ahead and add it in case someone can see something I'm missing.

```
function standards_create_sc_edit_form() {
  /********************************************************************************
   * Each row in $standards_data is structured like this
   * $standards[$ag][$stroke][$distance][$course][$timestandard][$gender]
   * and the value is a stdClass with time and nid properties
   ********************************************************************************/
  drupal_add_css(drupal_get_path('module','standards') . '/admin.css');
  $taxonomies = _standards_get_taxonomies();
  $form = array(
  );
  $form['submit1'] = array(
    '#type' => 'submit',
    '#value' => 'Save'
  );
  $form['tax'] = array(
    '#markup' => '<pre>' . print_r($taxonomies,true) . '</pre>'
  );

  $courses = array("Short Course Yards","Short Course Meters");
  $standards = array("A","B");
  $sexes = array("Girls","Boys");
  $standards_data = _standards_get_data($courses,$standards);
  foreach($standards_data as $ag => $ag_result) {

    $form[$ag] = array(
        '#prefix' => '<div class="standards_edit_table"><h1>' . $ag . '(' . $ag_key . ')</h1>',
        '#suffix' => '</div>',
        '#tree' => TRUE,
        '#theme' => 'standards_sc_table',
    );
    foreach($ag_result as $stroke => $stroke_result) {
      foreach($stroke_result as $distance => $distance_result) {
        $fieldset_title = "{$ag}-{$stroke}-{$distance}";
        $form[$ag][$fieldset_title] = array(
          '#tree' => true,

        );
        //create fields for the A and B time standards
        $columns = array();
        $column_count = 0;
        foreach($sexes as $sex) {
          foreach($courses as $course) {
            foreach($standards as $standard) {
              $course_tid = $taxonomies['course']['names'][$course];
              $sex_tid = $taxonomies['gender']['names'][$sex];

              if(isset($distance_result[$course_tid][$standard])) {

                $time = $distance_result[$course_tid][$standard][$sex_tid];
                $field_title = "{$sex}-{$course_tid}-{$standard}-" . $time->nid;
                $form[$ag][$fieldset_title][$field_title] = array(
                  '#type' => 'racetime',
                  '#default_value' => _racetime_integer_to_formatted($time->time,2),
                  '#number_decimals' => 2,
                  '#size' => 8,
                );

              }

            }

          }
          $column_count++;
          $form[$ag_key][$fieldset_title]['event'] = array(
            '#markup' => $taxonomies['distance']['tids'][$distance] . " " . $taxonomies['stroke']['tids'][$stroke],
          );
        }

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

  return $form;
}

function standards_create_sc_edit_form_submit($form,&$form_state) {
  drupal_set_message("This worked");
  drupal_goto('admin/standards');

}

```

# Answer
It appears the issue is related to the number of fields. There are over 800 fields in this form. When I pared the form down to a smaller size, the form submitted fine. I haven't seen any documentation that says there's a limit on the number of elements in a form, but apparently, I hit it.
> 0 votes

# Answer
Try using the Tableform API to build your form.
> 1 votes

# Answer
Set: max\_input\_vars in php.ini to a higher value than 1000
> 0 votes

---
Tags: forms
---


# Question
Title: Node theme template override isn't working
I'm using the paid theme md-alpine and I added a content type called webinars, and a node template for webinars node--webinars.tpl.php

The only thing I put in the page is and I only get an HTML page with no CSS. Am I supposed to add a call to the node--webinars.tpl.php page somewhere?

EDIT: I changed dpm to print\_r and the rest of the theme printed. Put it back to dpm and it doesn't load.

This is the raw output of the page:

```
    <div id="navigation" class="navbar navbar-default navbar-fixed-top" role="navigation">
    <div class="navbar-inner">
        <div class="navbar-header">
            <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
                <span class="sr-only">Toggle navigation</span>
                <i class="icon fontello icon-menu icon-2x"></i>
            </button>
            <a id="brand" class="navbar-brand" href="http://lcl.alpine.test"> <img src="http://lcl.alpine.test/sites/all/themes/md_alpine/img/logo.png" alt=""> </a>
        </div>
        <div class="navbar-collapse collapse">
            <ul class="menu nav navbar-nav navbar-right"><li><a class="int-collapse-menu" href="http://lcl.alpine.test/#home">Home</a></li><li><a class="int-collapse-menu" href="http://lcl.alpine.test/#about">About</a></li><li><a class="int-collapse-menu" href="http://lcl.alpine.test/#portfolio">Gallery</a></li><li><a class="int-collapse-menu" href="http://lcl.alpine.test/#team">Staff</a></li><li><a class="int-collapse-menu" href="http://lcl.alpine.test/#client">Testimonials</a></li><li><a class="int-collapse-menu" href="http://lcl.alpine.test/#pricing">Donations</a></li><li><a class="int-collapse-menu" href="http://lcl.alpine.test/#blog">Blog</a></li><li><a class="int-collapse-menu" href="http://lcl.alpine.test/#contact">Contact</a></li><li class="last leaf"><a href="/members" title="Member's Area">Members</a></li>
</ul>        </div>
    </div>
</div><section class="section-content blog-content">
    <div class="container">
        <!-- Section title -->
                <div class="section-title text-center">
            <div>

                <span class="line big"></span>
                <span>Posted by <a href="http://lcl.alpine.test/user/1">admin</a></span>
                <span class="line big"></span>

            </div>
            <h1>Test</h1>
            <div>
                <span class="line"></span>
                <span><i class="fontello icon-calendar"></i>21 June 2014</span>
                <span class="line"></span>
            </div>
            <p class="lead">
                            </p>
        </div>
                <!-- Section title -->
        <div class="row">

                    <div class="col-md-9">
                                                <div class="tabs"><h2 class="element-invisible">Primary tabs</h2><ul class="tabs primary"><li class="active"><a href="/webinars/test" class="active">View<span class="element-invisible">(active tab)</span></a></li>
<li><a href="/node/39/edit">Edit</a></li>
</ul></div>

```

# Answer
Devel got disabled somehow breaking the page when calling dpm. Re-enabling fixed all.
> 0 votes

---
Tags: theming
---


# Question
Title: Entity Reference auto complete term creation on the fly?
There is a reason why I'm using an (autocomplete) Entity Reference field on my Content Type, instead of the Drupal's default term reference. It is linked to a taxonomy vocabulary and it's working just fine for my purposes.

What I can't achieve is for a term to be created on-the-fly (auto-creation), if it doesn't already exists in the tax vocabulary, while authoring a new node of that Content Type. Just like drupal's default term reference can do.

Thanks alot for your time.

# Answer
Instead you can give a try to this Autocomplete Deluxe module to achieve your goal. It have the option to create new term in auto-complete field.

> Features
>
> ```
> Combo/Select box like selecting.
> Select without entering something.
> Widget for taxaonomy
> Chosen like multiple selecting.
>
> ```

> If you want to deny adding new terms, then checkout Chosen. It converts select boxes to autocomplete fields.
> 1 votes

# Answer
Entityreference Autocreate provides this feature (create entity on the fly using Entity Reference autocomplete field).

Also you may look at this issue: https://www.drupal.org/node/1472596
> 0 votes

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


# Question
Title: CAPTCHA session reuse attack detected error message when form is submitted
I am experiencing problems with the captcha module 7.x-1.0-beta1 version. I have enabled captcha in webforms for anonymous users. After submitting the form it repeatedly gives me the error message,

> CAPTCHA session reuse attack detected

.. This happens for only one of the webform in which captcha is placed. I am using Drupal 7.2 version.

Any solution for this issue will be really helpful.

# Answer
I had the same problem because I have an ajax file upload on the form. The solution is to patch the captcha module with the patch found here http://drupal.org/node/918856#comment-6353912 . You just need to download the patch and put it in the same folder and run in command line:

```
patch < captcha-patch-10022012.patch

```

if using git, you can just use :

```
git apply --directory=your/module/derectory captcha-patch-10022012.patch

```
> 2 votes

# Answer
there is a Patch available for Drupal 7, please check this out: https://www.drupal.org/node/1395184
> 0 votes

---
Tags: webforms, captcha
---


# Question
Title: Grouping Exposed Filters (using Better Exposed Filters)
We have a view using Better Exposed Filters called Programs with an exposed filter on a taxonomy term "Level of Study". I'd like to group this so that the only values in the exposed filters are **Graduate** and **Undergraduate**.

I first tried to "group" the terms as follows

but then got errors as follows:

```
Warning: Illegal offset type in views_many_to_one_helper->ensure_my_table() (line 954 of /var/www/html/sites/all/modules/views/includes/handlers.inc).

```

I then tried to rearrange the taxonomy so that Graduate and Undergradute terms are parent to the others as follows:

```
Graduate
- MFA Degrees
- Professional Degrees
- Doctoral Degrees

Undergraduate
- Majors and Minors
- Modules
- Interdisciplinary Programs

```

And this still does not yield the desired result.

So I'm at a loss and opening up a bounty.

# Answer
> 4 votes
First I'd recommend adding a taxonomy term 'Graduate Interdisciplinary Program' to match the 'Undergraduate Interdisciplinary Program'

Assuming you have these taxonomy terms 'weighted' to their respective parent terms 'Graduate' and 'Undergraduate' you can proceed to configure your view.

Configure the filter criteria as follows:

> **Settings**
>
> Content:Has Taxonomy Terms
>
> Vocabulary: Graduate/Undergraduate Programs
>
> Selection Type: Dropdown
>
> Depth: 1

> **Configure Filter Criteria**
>
> Tick - Expose this filter to Visitors, to allow them to change it.
>
> Tick - Grouped Filters
>
> Widget Type - Select List
>
> Label - 'Area of Study'

Finally configure the table as you have it in your screen-shot ... ideally without the overlap of the term 'Multidisciplinary Program' ...

---
Tags: views
---


# Question
Title: How to set the tabs on node pages to always display in the site's default language?
I don't want $tabs to be translated. How can I set the tabs on node pages to always display in default site language?

I've tried admin language module however the setting that works in that prevents menu items from been translated.

Is there a way to manually set the rendered language in the tpl?

# Answer
> 1 votes
You can use this function (inspired from this solution wich was for Drupal 6)

```
/**
 * Reverse translation: find source string for a given translated string.
 */
function rt($string) {
  global $language;
  $langcode = $language->language;
  $query = db_select('locales_source', 'ls');
  $query->leftJoin('locales_target', 'lt', 'ls.lid = lt.lid');
  $query->fields('ls', array('source'));
  $query->condition('lt.language', $langcode);
  $query->condition('lt.translation', $string);
  $result = $query->execute();
  $records = $result->fetchAssoc();

  return $records ? $records['source'] : $string;
}

```

Then via hook\_menu\_local\_tasks\_alter

```
/**
 * Implements hook_menu_local_tasks_alter().
 */
function mymodule_menu_local_tasks_alter(&$data, $router_item, $root_path) {
  foreach ($router_item['page_arguments'] as $key => $argument) {
    if (is_object($argument) && isset($argument->type)) {
      foreach ($data['tabs'][0]['output'] as $key => $value) {
        $data['tabs'][0]['output'][$key]['#link']['title'] = rt($value['#link']['title']);
      }
    }
  }
}

```

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


title: D7. Facebook Stream: show user's feed

text:
# Question
Title: D7. Facebook Stream: show user's feed
I try to display authorised user's news feed: I installed Facebook Stream module in Drupal 7. After facebook login module displays an error:

> FacebookApiException: User must specify a valid extended permission or data permission in BaseFacebook-\>throwAPIException() (line 1325 of Z:\home\devfb.kz\www\sites\all\modules\facebook\_stream\facebook-php-sdk\src\base\_facebook.php).

I can't understand why permissions which I specified in the module are invalid? Permissions:

```
return '<fb:login-button '. drupal_attributes($attr) .' onclick="FB_Connect.login_onclick()" scope="read_stream,publish_stream,offline_access">'. $text .'</fb:login-button>';

```

Maybe I can do this with another module?

# Answer
I understud: I'm use "read\_stream" scope without additional submit in my FB App settings. To access user's news feed I must submit my App to review and only after approval I'll have ability to get access to this API feature.
> 0 votes

# Answer
If I understand what you want correctly, you don't need a specific module at all to do this. You can just have embed code generated and add that to the source code for the block/page you want to add it to. You can have embed code generated here. Be sure to select "Show Posts" if that's what you want.

**Edit**: I just re-read your question and see that you mean to do this for the authorized user... in this case my answer may not be helpful.
> 0 votes

---
Tags: social-network
---


# Question
Title: How to get rid of a style attribute so my nivo slider will show up?
I am using the Nivo Slider and for some reason it has a style attribute in its div tag that says

```
style="width: 0px";

```

I am trying to get rid of this so my slider will appear. I am not sure where this is coming from. I have CSS injector installed, but none of it makes a width: 0px and a grep search throughout the directories doesn't come up with one that will effect the outcome.

Thanks for your help.

# Answer
> 0 votes
https://www.drupal.org/node/229348 Gives a lot of good information on the subject.

---
Tags: theming, javascript
---


# Question
Title: How do I import products using commerce_feeds and commerce_autosku?
how do I import a CSV of products into a Kickstart site using commerce\_feeds, with commerce\_autosku enabled to generate the SKUs on import?

This sounds like it should be possible because an obvious use case is the one where you don't care about SKU and you have a CSV with Title, Price and Description of each product. But I keep getting an error similar to:

SQLSTATE\[23000\]: Integrity constraint violation: 1062 Duplicate entry 'commerce\_product-52' for key 'PRIMARY'

# Answer
Seeing this issue, seems that is not currently 100% possible: https://www.drupal.org/node/1662620

Answer from the mainainer in that issue:

> Have you tried unchecking the "Always regenerate SKU's" checkbox for this product type? That should allow your SKU's to be accepted without being overwritten.
> 0 votes

---
Tags: feeds, commerce
---


# Question
Title: Explanation of Content Types, Modules, and Views
Attempting to structure a page within Drupal has led me down a convoluted path and I wanted to clarify the relationship between Drupal content types, modules and the views element before I ventured any further. My current understanding is that you can add content types via modules and with these various content types create a page that you can then format with views? What I am trying to do is create a basic page from various elements (pictures, tables, text, etc.) and format it through views. I realize this may be too generic to comment upon, but I would greatly appreciate any feedback!

# Answer
> 1 votes
Reading the Drupal documentation might be your best bet to get an in-depth explanation, but let me try to summarize each in my own words so you can hopefully get a basic foundation so you can understand better.

**Content types** \- Content types are how you add any of your content to a website. For most of your general pages that have just regular text on them, nothing special, you would use the Basic Page content type to just create a basic web page, or node. However, say you were going to have an events feed on your website - you would want different fields for information that you would want to display. In this case, you would make a content type called Events (or whatever you would like), and then add fields to it (e.g., Event Title, Date, Time, Location, etc.). Now, Events would be listed as a content type you can use to add content. When you add content and choose Event to add, your fields will show up and you can add the information for an event, save that event, and repeat. Saving an event will bring you to the page for that event with all of that event's information (the formatting of which can be changed in the content type settings for that content type. Every event entry now has its own page displaying its information.

**Views** \- Now, you have pages for events, but say you wanted to have a feed or list of events on a specific page. You would do this using a View. A view aggregates content (from one or more content types) into a display. So you would create a view, specify which fields from earlier you want to display (like maybe just event name and date) and then filter the content to just show content of type events. This view can be created as its own page, or you can create a block which you can then place in a region on another page. There is a lot of customization that Views allow you to do that isn't obvious in the beginning, but this is the gist of what views do.

**Modules** \- Modules are jus "extras" for Drupal. Really, most of what you would need to create a basic site is already included. However, say you wanted to add some sort of fancy menu that Drupal can't already do. People have made modules to give you that capability. Say you wanted to create forms for people to fill out. There are modules for that.

If you want me to explain anything in more detail or if anything is not clear to you, feel free to ask and I can clarify or elaborate.

# Answer
> -1 votes
Take a look at the documentation here about Drupal

According to the documentation:

> A single web site could contain many types of content, such as informational pages, news items, polls, blog posts, real estate listings, etc. In Drupal, each item of content is called a node, and each node belongs to a single content type, which defines various default settings for nodes of that type, such as whether the node is published automatically and whether comments are permitted.

**Views**

> Although not all sites have Views, most sites include the Views module because of the excellent tools it provides. Views allows people to choose a list of nodes or other entities and present them as pages, blocks, RSS feeds, or other formats. The main use case for views is to create dynamically updating lists to content (for example, a listing of latest news), based on properties of that content (in the case of the news listing, that the content type is “News” and sorted by publication date).

---
Tags: views, 7, nodes
---


# Question
Title: Send user a reminder email after x-number of days if Profile2 field is empty and user has specific role
I have a multi-step user signup process. When the user creates their account, they are assigned role "A" and are redirected to a Profile2 form with various fields. If they complete and save their Profile2 form, they are assigned role "B" and role "A" is removed from their account.

I need to send an automated reminder email to the new user 5 days after their account was created, if they are still assigned user role "A". The email's purpose would be to remind them to log in and complete their Profile2 form. How can I accomplish that kind of time delay using Rules? If not rules, are there any other modules that would accomplish this?

Thanks!

# Answer
Here is my solution, based on tenken's advice:

1. I created a Rule COMPONENT with the condition "User has role: Role A" and the action "Send email".
2. I then created a Rule...

> Events: After saving a new user account
>
> Conditions: None
>
> Actions: Schedule component evaluation

In that Action, I chose these options:

```
Component: the component from step 1
Scheduled evaluation date: account:created
Add offset: 5 days
User > Data Selector: account

```
> 2 votes

# Answer
You can do this with Rules Scheduler, which is apart of Rules. For an in-depth tutorial on how to set this up please see this blog post I didnt write on how to use Rules Scheduler to send emails (lol).

You also need to likely have your drupal cron job properly configured as well.
> 1 votes

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


# Question
Title: Let the user add a PDF to a content type, but not as an attachment, content type is the pdf
I hope the title is a bit clear but this waht I need/want: At the moment users that have the right to make content can add a PDF for certain content types, this is added as an attachment so users have to go to the content first and then have to click on the PDF to see it. Is it possible to let my users add only a PDf to a content type and that the content type IS a pdf only? So when someone goes to that page and clicks the link the PDF is immediately shown instead of a page in between with an attachment. So this makes it 1 click to see the PDF and not 2.

# Answer
This doesn't exactly answer your question (since *maybe* there is a module for that, but not that I'm aware), but here is what I do.

I have a content type for documents with two fields: summary/abstract and then a file upload field that accepts PDFs. If a PDF has a summary or abstract, I put the summary/abstract in that field and just link to the content's page figuring that the user can read that and then click on the document if they want. Otherwise, I still use this document content type to upload the file, leave the summary blank, and then link directly to the uploaded file itself. It would still have its own page created by the content type, but a site user isn't going to see that.
> 0 votes

---
Tags: 7, nodes, files
---


# Question
Title: How to enable comments on drupal default user profile page?
I am pulling my hair out trying to find an answer to my question. I am creating a community site and one of its main feature is to comment and rate other users. For some reason it seems this is not possible on Drupal 7 since I haven´t found a clear answer to this question. Could you please please please guide me on this?

Thank you very much.

# Answer
> 1 votes
To stay in Drupal language: The problem is that *User account pages* are not *"nodes"* (**no normal content type** like you may expect) nor full *"entities"* (bundles of fields grouped as type in Drupal 7 world). This missing is a big left over from earlier days of Drupal and not really wanted as-is in the Drupal community since it is against the field-able framework idea behind Drupal. Plus that comments are sadly sticky to nodes (not usable elsewhere).

There are many efforts to change this and (from what I know) solved in D8. And the user accounts are fieldable now in D7 already, but still not really "known" everywhere in the system and that's why the system provided *"comments"* bundle can't be activated here. User pages are not nodes. The concept of "Entities" is another one of the efforts to have fieldable bundles everywhere, one of these steps away from the inconsistency and to get a more general reusable logic of field-able "groups of elements" everywhere, not only on nodes or user pages. Comments are already *entities* but not known by user pages. And so on and so forth.

Some work arounds for Drupal 7 could be now to use modules like **profile2** (a little bit limited, but fully field-able entity), or "**Reply**" (will be awesome, but new and needs some more help!), or to build own *"entities"* or *content types* (my suggestion) which can be made relative to users (like blog already is) using modules like **entityreference** or **relation** (awesome but for this usecase allone maybe too powerful). This gives you more than comments as an option, plus the complete freedom about how to field your custom *"user pages"*. And you can even show them apart from the user account page, like on facebook profiles or in tabs. (advanced views and menus knowledge needed here)

Another way could be to use the manage fields settings dialog of Drupal core and "bow" them as fields with multiple values to a kind-of-comment behaviour. I already did this very successful on project, where the clime was limited and to choose this way was less effort to achieve. But for more complex needs I would rather suggest my earlier solutions.

Aaand ... an outsourcing comment solution would be: the **Disqus** module. Surprise: it also works on profiles. (sorry, but I am limited to less than 3 links ATM, it's a new DA account.)

But as you can see: as always in Drupal, there are more than 2-3 ways to achieve a wanted behavior in Drupal projects.

Hope it helps a 'lil bit. Best regards...

---
Tags: views, users, rating
---


# Question
Title: Drupal users getting blocked automatically
I am experiencing a strange problem with my drupal website. On it, there are a good number of registered users. Sometime the users login, but not very frequently. Suddenly I figured out that some of the users (who are relatively old) are getting blocked. I check with blocked users, they said they did nothing. I do not have any idea how they got blocked.

Ok, then I unblock them manually and now they are active. Next day, I find them blocked again. So, now I need to unblock a bunch of users manually which is not the optimal way to deal with the users.

Anyidea? Anybody?

Thanks,

# Answer
> 2 votes
Do you happen to have the Inactive User module installed? This module can be used to block users who are inactive for some time. Otherwise, are you sure that the users are not trying to log in with the wrong password (5 times), which would also block them. It could be possible that someone else is trying to log in with these user accounts and is getting them blocked (I suppose it would be up to you to decide how likely this is based on whether or not your website is fairly high or low profile).

---
Tags: users, 7
---


# Question
Title: How to go about creating and formatting a custom HTML/PHP table to display SQL data
I am new to drupal and basically I made a database within drupal and filled it with some dummy data. I want create/format/populate a table that looks like on one of my drupal pages:

```
+-----------+-------------------------+---------------------------+---------------+
| Resource  |          Week1          |          Week1+7          |    TOTALS     |
+-----------+-------------------------+---------------------------+---------------+
| resource1 | Hours(Week1, resource1) | Hours(Week1+7, resource1) | totals across |
| resource2 | Hours(Week1, resource1) | Hours(Week1+7, resource2) |               |
| TOTALS    | totals above            | totals above              |               |
+-----------+-------------------------+---------------------------+---------------+

```

I understand that you do it through views and I was trying to do it by creating my own module using the views\_data() hook to try to create it (using http://mydons.com/how-to-expose-custom-module-table-to-views-in-drupal/ as a base/resource). I am kind of stuck though and I have no idea what the best approach would be to start to create a table that looks like the above. I am not sure this is the correct way/best way to do it and any direction/tips you guys can help me out with would be great.

Thanks!

# Answer
You can create a custom table to display whatever data you want in a custom module by building the information output in a function, first you have to implement HOOK\_menu for defining you path for the page containing the table and afterwards implementing the callback function for that page. I'll give you a real example here:

```
/**
* Implement hook_menu().
*/
function HOOK_menu() {
  $items = array();

$items['admin/config/my_table'] = array(
      'title' => 'My Table Page',
      'description' => '',
      'page callback' => 'my_table',
      'access arguments' => ....,
    );

 return $items;
}

```

As you can see i have my path and the callback is defined to the function `my_table`. Let's create that as well

```
function my_table {

    // Create table header
    $header = array(
        array('data' => t('COLUMN 1')),
        array('data' => t('ANOTHER ONE')),
        array('data' => t('COLUMN EXAMPLE')),
        array('data' => t('BLA BLA'))
    );

   .... // create table rows

    $output = '<div class="description">';
    $output .= '<p>' . t('Say whatever you want to appear'). '</p>';
    $output .= '</div>';

    // here we render the actual table
    $output .= theme('table', array('header' => $header, 'rows'=> $rows, 'attributes' => array('id' => 'something') ));

    // and return the html output to our page
    return $output;

}

```

Hope this helps! Cheers!
> 1 votes

# Answer
Well, exposing the data of your table to views and then fetching and displaying it as table using views formatter is a good option, but if this is all you need ( I mean no complex use cases like filtering sorting and stuffs like that) it will be overkill in my opinion.

I think you can use the awesome database API of Drupal to fetch the content and probably render it using theme\_table() which will give you the output as table. Please check the doc and examples to make sure you are passinf the data to theme\_table() in proper format. there are lots of example codes available. just google it.
> 0 votes

# Answer
If you want to take advantage of render caching return a render array. Unfortunately I have not found a good blog post of this subject. Documentation on drupal\_render(); read up on the #cache section, easiest way to speedup your site is by caching. I use they keys in my own code as the table code we use uses dates so I have an array of dates that I pass into the "keys" key of the "#cache" key. Example below just uses a simple 1 hour global cache. The trick with the cache is using the #pre\_render function, we use it to fill in the $rows; the actual render function (in this case theme\_table()) will build the table given the header and rows. Also note that I'm adding in CSS by using the #attached key; this is the standard way to do it in Drupal 8 so it's future proof. If the cached data exits, then pre\_render function does not get called. drupal\_render will take care of caching for us.

```
function my_code_table_render_array() {
  // Define table header.
  $header = array(
    'resource' => 'Resource',
    'week1' => 'Week1',
    'week1_7' => 'Week1+7',
    'totals' => 'TOTALS',
  );

  // Build table render array.
  $table = array(
    '#theme' => 'table',
    '#pre_render' => array('my_code_pre_render_function'),
    '#header' => $header,
    '#attributes' => array('class' => array('table', 'table-striped')),
    '#attached' => array('css' => array(drupal_get_path('module', 'my_code') . '/my_code.css' => array('type' => 'file'))),
  );

  // Cache this for 1 hour.
  $table['#cache'] = array(
    'expire' => REQUEST_TIME + 3600,
  );

  return $table;
}

function my_code_pre_render_function($elements) {
  $rows = array();

  // Put the rows from the database in the rows array.
  // This will change depending on your data structure.
  foreach ($query_result AS $key => $values) {
    $rows[$key][] = array(
      'data' => 'Data from the database',
      'title' => 'Extra data shown on mouse hover',
      'class' => $array_of_classes,
    );
  }

  $elements['#rows'] = $rows;
  return $elements;
}

```

If using multiple render arrays you can return an array of the render arrays like so. The order of the arrays determines the order of the output.

```
function my_code_form_table_render_array() {
  $input_form = drupal_get_form('my_code_input_form');
  $table = my_code_table_render_array();
  $page_array = array($input_form, $table);
  return $page_array;
}

```

In both examples we would set "page callback" to "my\_code\_table\_render\_array" OR "my\_code\_form\_table\_render\_array" in your own hook\_menu() hook.
> 0 votes

---
Tags: hooks, database, views, theming
---


title: D7 - List entries on config form

text:
# Question
Title: D7 - List entries on config form
I have what should be a simple question. I am coding a module that allows the user to add meta and link tags to the of your HTML page..think of something similar to CSS injector. (I'm sure something like this already exists, but I'm using this as a learning project). I am able to create the config forms and everything that the admin would need to create a new entry, and I'm able to input new entries and save them to the database.

What I want is below the "new entry" part of the form, I want to list all current entries with "edit" and "delete" links next to each one (every module under the sun has this functionality). Can someone point me in the right direction on how to do this?

# Answer
To expand on mojzis's comment:

```
// Load your data.
$entries = db_query('SELECT * FROM {my_table}')->fetchAll();

// Prepare a header for your table. The array keys will match up to the key used to input rows in a minute. The values are the column headers.
$header = array(
  'title' => 'Entry title',
  'foo' => 'Bar',
  'op' => 'Operations',
);

// Loop through your data and prepare table rows.
$rows = array();
foreach ($entries as $entry) {
  // Prepare your operation links.
  $op_links = array(
    l('view', 'path/to/entry/' . $entry->id),
    l('edit', 'path/to/entry/' . $entry->id . '/edit', array('query' => drupal_get_destination())),
    l('delete', 'path/to/entry/' . $entry->id . '/delete', array('query' => drupal_get_destination())),
  );

  $rows[] = array(
    'title' => $entry->title,
    'foo' => $entry->bar,
    'op' => implode(' ', $op_links),
  );
}

// Prepare the build
$form['existing_entries'] = array(
  '#theme' => 'table',
  '#header' => $header,
  '#rows' => $rows,
  '#empty' => t('No entries have been created.'),
);

```
> 2 votes

---
Tags: 7, forms, hooks
---


# Question
Title: How to use multiple styles for Nice Menus?
I'm having two Nice Menus, both are displayed in my website's top bar. I created a default CSS layout for them and everything looks quite nice. However, I'd now like to change the layout of the second menu's parent a bit.

How can I set up this alternative style?

# Answer
Each Nice Menu can be addressed in CSS using its name. For example I have a Nice Menu called "Product Menu" and by looking at the html of my page I can see that my menu has the following classes

```
nice-menu
nice-menu-right
nice-menu-menu-product-menu
etc..

```

You can use the `nice-menu` class for all Nice Menus, the `nice-menu-right` class is the type of menu it is set as (Right, Left, etc.). You can also customize each menu individually by addressing it in CSS using the `nice-menu-menu-MENU-NAME`
> 0 votes

---
Tags: 7, theming, navigation
---


# Question
Title: How to import a CSV with list field labels using Feeds?
I have a content type "Car". The fields are "Title", "Body" and "Gearbox". The "field type" of the field "Gearbox" is "List (integer)", and the "Allowed values list" for this field (in the "key|label" format) are:

```
1|manual
2|automatic
3|semiautomatic

```

I want to import content from a CSV file using a standard node import with Feeds. My CSV is as follows

```
GUID,Title,Body,Gearbox
1,Lexus NX,blabla,automatic
2,Porsche Cayenne,bloblo,manual

```

On importing this CSV file, the value for "Gearbox" is not copied over. Instead, it appears as empty in the content. If I replace the values for "Gearbox" by their keys, as in this modified CSV file

```
GUID,Title,Body,Gearbox
1,Lexus NX,blabla,2
2,Porsche Cayenne,bloblo,1

```

then it works correctly.

Nevertheless, I'm not the end user and I need to leave the CSV file in its more human-friendly form that uses the "labels" instead of the "keys" (as in the original CSV above).

How can I do this? I.e. how can I have the import recognize the labels "manual", "automatic", etc instead of their corresponding keys?

# Answer
> 1 votes
It seems that this is a known issue. There is a patch at https://www.drupal.org/node/2006810

# Answer
> 0 votes
Not sure what you mean with **labels** vs. **keys**. I assume you mean the database "names" of Drupal fields, the "machine\_name"?

Otherwise, are you trying to import recursively? Or do you want to place all csv data into one content entry's list field to provide selection from it? It seems like there is a misunderstanding of the use of the list field. The value of the list field can (should) contain multiple selectable key|value pairs in "one" field data set. That's what the list field is meant for. But if you want to import each set recursively into another content dataset, you have to rearrange your csv file, since one line CSV means, one dataset, means one imported "node" of data.

But despite of this, Feeds importer provides the option to "map" fields in the import settings, so the import should work perfectly by mapping the fields (you should know by their label) to the corresponding field you have set up before and which are provided to map to in the settings fields select dialog.

It works similar to CSV import in excel or calc.

That's all I can say regarding the infos you gave. If you sue a specific Drupal version and a specific Feeds version missing any of the given advice, you should update your question.

Hope it helps at least a little bit.

Best regards from Berlin

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


# Question
Title: How to limit the number of comment a user can post?
I have a content type where users can post reviews or comments. I want to achieve this with the comment module and not by creating another content type and using node reference.

**So I want to limit the number of comment a user can post per node for a specific type of content type.**

Again I also have other content types where I have given the users the option of commenting on article, and that can have multiple comments and replies.

Can anyone suggest me how to achieve this?

Can I do it through rules(I haven't tried yet)?

# Answer
You could add a validate handler to the comment form

e.g, something like:

```
/**
 * hook_form_FORM_ID_alter
 */
function MODULE_form_comment_form_alter(&$form, &$form_state, &$form_id) {
  $form['#validate'][] = 'MODULE_comment_form_validate';
}

/**
 * Validate comment form submission
 */
function MODULE_comment_form_validate($form, &$form_state){
  $node = node_load($form_state['values']['nid']);
  if(isset($node->type) && $node->type = 'targetted_type'){
    $account = user_load_by_name($form_state['values']['name']);
    if(!empty($account->uid)){
      // Get comment count for this node type
      $query = db_select('comment', 'c');
      $query->join('node', 'n', 'n.nid = c.nid');
      $query->condition('c.uid', $account->uid);
      $query->condition('n.type', 'targetted_type');
      $query->countQuery();
      $comments = $query->execute()->fetchField();
      if($comments > variable_get('max_comments_targetted_type', 3)){
        form_set_error('name',
          t('You are only allowed to post %max comments on this type of content.', array('%max' => variable_get('max_comments_targetted_type', 3))));
      }
    }
  }
}

```
> 2 votes

# Answer
If you want to allow the user to comment only once then you can look into Onecomment module.

But if you want to use more complex logic then you can implement `hook_node_view()` and put your logic there and then unset the comment form from the `$node->content`. You can refer the code of `Onecomment` module.
> 1 votes

---
Tags: 7, comments
---


# Question
Title: how do i link a field to another field in views
I have a `Views` on which I display an event calendar. Events get created through a separeate content type which contains a checkmark "Link to page" which will (if checked) display a "view" link in the table which links to the created content. Now i have added another field in the content type of type text "External link {will link to current page if left empty)" which should override the linkage to the current page and render the "view" link to link to the url entered in "External link" field. How would I do this? Please advise! Thanks!

**edit 1**

No, I currently hacve a checkbox that creates a link whichj links to the current content but nothing that woul consider the newly added field "External link (will link to current page if left empty)"... How do I can I do this?

# Answer
> 1 votes
In theory, you should be able to use the link module to create a link field within your content, and use a default value pointing to the newly created content - this may require some customization of the code - it accepts tokens, but I don't know if the node id has been assigned at that point or not.

Assuming it works, one way or another, you would then simply include that field in the view, which should display as a link - if it is used, it would link to the external link, otherwise to the content (as default value).

If that isn't reasonable, you could try to use the same field (without modifications or default value) in the view, and create a NO RESULTS BEHAVIOUR that rewrites it to the content - meaning if there is no value in the field, it would link to the content, or use the value of the field (external link) if present.

# Answer
> 1 votes
You can try using the Computed Field Module

This way you can perform your checks and store the value in the second field. Then you can just display that field in the views.

> module that lets you add a custom "computed fields" to your content types. These computed fields are populated with values that you define via PHP code. You may draw on anything available to Drupal

# Answer
> 0 votes
just needed to REWRITE RESULTS and enter something like `<a href="[field_external_link]">view</a>` to get it rendered correctly. Beauty! :)

---
Tags: views, entities
---


# Question
Title: Menu token. Problem with [current-user: name]
I saw this question, but how to make that anonymous user does not see this menu link "anonymous"?

# Answer
check permissions and make sure anonymous users don't have access to that page (or set of pages, content type)
> 0 votes

---
Tags: navigation, 7
---


title: AJAX Calculator

text:
# Question
Title: AJAX Calculator
I'd like to have three separate but interconnected calculators that generate their output with AJAX (i.e., no page refresh).

Would this process work or is there perhaps a simpler/more trodden pathway to do it:

A webform (with webform ajax) with conditional fields, having the other two calculators (still part of the same actual form) be dependent on a given value set in the first calculator.

Alternatively, three separate webforms, with some sort of multi-form submission process?

I'm trying to figure out a good way to have three forms, with a response returned in via AJAX without page refresh. What is the most efficient way to do this in Drupal? Should I use a webform or just custom code this myself?

# Answer
Try the Webform Calculator module

> 1. Provides a formula webform component for computed values, where you can enter a mathematical calculation based on the other fields. E.g., create a formula field with value formkey1 * 0.1 * formkey2.
> 2. Replaces tokens in the webform body (using webform\_tokens) with jEditable, so that users can enter calculation inputs inline & get the results via AJAX.

There is another module called Real Estate Mortgage Calculator. but not sure whether it meets your requirement or not. :)
> 1 votes

---
Tags: forms, ajax, webforms
---


# Question
Title: Execute a rule after a countdown finishes
I checked Countdown Timer Field module and some others but it seems they can't help in this issue.

I have a content type (organic group content type) I want this content type have a field for example "open until" and let the users indicate the date, once the countdown ends I want that organic group to be closed.

I want to have an event in rules like for example "countdown ends"

How to do this? thank you

# Answer
You need to use Rules Scheduler. You can create a date field on you content type, and then on some event such as creating or updating the content type you :

1. check for an old scheduled event on that content instance and delete it
2. read in the date field.
3. schedule a new event.

The event that you schedule will be a rules component that you create that will take in the nid of the content type, and then in its action section closes it.

If you need help on this check out Johan Falk from Node One's series on Rules.
> 2 votes

# Answer
In Drupal 7 you can use **Scheduler** module

> This module allows nodes to be published and unpublished on specified dates.
>
> Dates can be entered either as plain text or with calendar popups. To use calendar popups you need to install the Date Popup module, which is part of the Date module.

In create a new date field and make this filed as required in your content type. While creating the new content save this filed so that the content will be unpublished on specified dates.

* Check Using Scheduler for Drupal 7 video for configuration of Scheduler
* Steps to install the **Countdown Timer Field** Module

+ Place the entire field\_countdown directory into your Drupal sites modules directory (eg sites/all/modules).
    + Enable the module by navigating to: Administration \> Modules.
    + This module have dependency on **date\_popup**(Date module) and **libraries** module, download **libraries module** and enable both modules.
    + Download **jQuery Countdown Timer Library** from http://tutorialzine.com/2011/12/countdown-jquery/ .

    - Unzip the downloaded file and rename the directory from **countdown** to **jquery-countdown** and copy the folder and paste it inside libraries folder(if libraries folder is not exist then create new).
        - Path to the library should be : sites/all/libraries/jquery-countdown/assets/countdown/jquery.countdown.js. Check this path before proceeding.
    + Go to your content type using admin/structure/types/manage/YOUR\_CONTENT\_TYPE and click on **manage fields** of your content type.
    + Add new field and select "Countdown Timer Field" From Field type.
    + Now your timer field is ready to use.
    + Click on Manage Display link to select how do you want to display this field.
    + There are 4 display formats available:-
        - jQuery Countdown Timer without text timer.
        - jQuery Countdown Timer with text timer.
        - Date and time as string.
        - Unix time stamp.
> 1 votes

---
Tags: nodes, organic-groups, rules
---


title: Show image on solr search result page

text:
# Question
Title: Show image on solr search result page
I want to show image in my solr search result page. For that, I have created one field in my content type called media.

In db, Images are saving in field\_data\_field\_media table in the form of field\_media\_value

Any help very much appreciated.

Best, Latika

# Answer
Have you considered helping yourself with this similar question?

showing an image field from solr index on custom solr search page

To display image in your search-result.tpl.php you can follow below link also.

https://www.drupal.org/node/953096
> 0 votes

---
Tags: media, search
---


# Question
Title: Event registration for events with multiple dates/places
I'm making a event content type (representing academic conferences) for a Drupal 7 site, and I'm thinking of give visitors the posibility of registering in these events. But in some cases, these conferences can occur several times, in different dates and places. When registering, the registrant must choose in which date/place he wants to go.

For now, the date/place pairs are being stored in the event via a Field Collection. I've also checked two common modules for registrations in D7: Node Registration and Entity Registration.

Right now I'm thinking in 2 alternatives to implement this:

1. **Several registrations forms per event, one for each date/place:**

Pros:

* I could (in theory) manage each presentation separately, with different capacity/end of registration date.

Cons:

* As now, I don't find a module that permits multiple registrations in a node. (custom code?)
2. **One registration form per event, with a list field that permits to choose the date/place**

Pros:

* Implementable right now through Node Registration module + private fields per node

Cons:

* I can't manage capacity/end of registration date separately, and when the end date of one presentation comes, I must update the list field manually (custom code?)
    * The list options are defined per field (not by field instance) so I have to create a new field on each event that has multiple dates/places (each one with different machine name. Consider this is going to be done not by site admins, but event organizators with its own user role)

Is there another way to implement this feature? An module I haven't found? A hidden feature or creative use of Node/Event Registrations? Custom code/module?

# Answer
I would suggest that you create two different content types. `Event Display and Event Entity`

1. `Event Display` : Will be just used as a placeholder or display item. It will contain all jazzy text fields and images. It will also contain Node References to the Actual Event Eneities.
2. `Event Entity` : This will just contain Location, Date and Capacity.

Now Enable `Entity Registration` for the content type `Event Entity`.

Suggestion : Use Inline Entity Form so that you can edit the Event Entities directly from the Event Display Content.
> 1 votes

---
Tags: 7, users
---


title: A custom image style is not working

text:
# Question
Title: A custom image style is not working
I have created a block view with title and image using fields. When I use the default image styles, they work as they should.
The custom image style I created is a thumbnail (120 x 70) with canvas. When I try using this style in Views, I get the original image size.

# Answer
> 1 votes
Have you checked the image preset is created fine after applying the resize/crop function on admin\>config\>media\>image-styles

Just check the thumbnail(right one) is created fine by clicking on it.

Now when we add any image field in any view, make sure to use this style for display of this field

Please check with these points. And it works with Global text fields also.

# Answer
> 0 votes
If you are using it in a Global Text Area field and using the token to display it, it will not use the image style

---
Tags: 7, views, media
---


# Question
Title: How to make Language Switcher Block work with unpublished nodes?
On a multilingual Drupal 7 site, the Language Switcher Block used to work for both published and unpublished nodes.

Example: node/1: English, alias=map, published node/2: German, alias=karte, published node/3: English, alias=table, unpublished node/4: German, alias=tabelle, unpublished

On /node/1 or /map, the Language Switcher shows the link to German and it correctly links to /de/karte. This works also the other way around. However, on /node/3 or /table, the block does show a link to German version, but it links to /de/node/3 instead of /de/tabelle. On the German version at /de/tabelle (or /de/node/4) the block links to /node/4 instead of /table.

As far as I know, this change was introduced between Drupal 7.24 and 7.28 and might even not be a Core issue. However, I couldn't find the source of this behaviour.

Does anyone know, if it is related to some Security Issue with unpublished nodes or where I could start looking further? I tried to find it inside core modules locale/translation and language.inc and also in i18n to no avail.

# Answer
I was finally able to track this change down. The source lies within a security announcement which led to the i18n-7.x-1.11 update. In /sites/all/modules/i18n/i18n\_node/i18n\_node.module, l. 124 there's a new line reading

```
'access' => !$matches[2] ? $node_translation->status : NULL,

```

This line shall prevent unauthorized users from even seeing the path alias of nodes they do not have access to. However, there's no real check of permissions, this line just allows the access based on the node's status. So, even for User 1 (Superadmin) the link to the translated node is inactive if the translation is unpublished.

Whether this is only a temporary fix because of the SA or even supposed to be a permanent solution, I don't know. But that's the way it is right now and if you need to switch between unpublished translations often, you might want to comment that line.

There is already an issue at d.o for that.
> 0 votes

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


# Question
Title: Adding multiple nodes using a single form
I want a user to be able to create n nodes of type "Photo Gallery Photo" using a single form.

The node would have the following fields:

* name (For the entire upload; only shown once)
* phone number (For the entire upload; only shown once)
* town (For the entire upload; only shown once)
* email (For the entire upload; only shown once)
* title (per photo)
* description (per photo)
* photo (Image, per photo)
* galleries (node reference checkboxes, per photo)

Is this possible?

# Answer
Your question is so specific to your implementation; what you want to do is create a node with some single value fields and multiple images, each image with a title, description and nodereference.

It is the last part of the above that is actually the question: How do you add fields to an image?

* The file entity module allows you to add fields to a file, but those fields are not available on the node edit form, you have to go to admin/content/file to add these values.
* The Field Collection Module allows you to define a set of fields, so on your node you would define a field collection field which has an image, a caption, nodereferences or whatever. (not too clear...try it out)
> 2 votes

# Answer
You should write a module that saves a node for each set of values. That's doable.

Anyway that's a strange approach. I think i could be of more help knowing more details about your final purpose
> 0 votes

# Answer
I think it will work for you

Multi Node Add

> This module provides a new interface for creating nodes where the users are able to select the fields what they want to use for creating the nodes.
>
> It is designed to create multiple nodes in one round, it's possible to add more node input rows on-the-fly

In your Navigation menu (the menu with your username as title) you should see a link called Create multiple nodes, -- links to the URL `http://<yoursite>/multi_node_add`
> 0 votes

# Answer
Use the file entity module!

You can create a new content type called Album. Add the fields you want (name, phone number, town, email, images). Then using the file entity module, create a new file type or edit the already created one (Image) and add the fields (title, description). Every time you add a new photo to the Album, the image fields will show under the uploaded photo.
> 0 votes

---
Tags: 7, nodes, media
---


# Question
Title: How to deal with duplicate table name with db_select left join
Basically I have a db\_select that has two left joins. And will be calling up two table fields with the same name. The fields have different data though, so I need to be able to have access to both in my results. In a normal query I’d set this in the SELECT - how can i do the same in db\_select

```
SELECT table1.column AS column1, table2.column AS column2
FROM table1
LEFT JOIN table2
ON table1.column = table2.column

```

here's my code that i need to change

```
$query->leftjoin('migrate_map_emp', 'm', 'm.sourceid1 = i.ID');
$query->leftjoin('migrate_map_emplogo', 'ml', 'ml.sourceid1 = i.ID');

$query->fields('i', array('ID','Name'))
      ->fields('m', array('destid1'))
      ->fields('ml', array('destid1'));

```

\[solved\]

the above code works. I did a 'drush\_print\_r' on the rows returned at the second item is labelled ml\_

\[destid1\] =\> 5 \[ml\_destid1\] =\> 2

Many thanks

# Answer
> 0 votes
You can fetch data with `drupal db_select` as below code:-

```
$query= db_select('table1', 'column1');
$query->join('table2', 'column2', 'column1.column=column2.column');

$query=$query->fields('column1',array('column'))
       ->fields('column2',array('column'))
       ->execute()->fetchAll();

```

For more information on db\_select join queries click on this link

---
Tags: migrations, database
---


# Question
Title: How to display the selected value from the drop-down box?
The following code is displaying the states, but when I click the submission button, I want to display the selected state and city. I am not able to display it. How can I achieve this?

```
$form['state1'] = array(
  '#type' => 'select',
  '#title' => t('State'),
  '#options' => $options_state,
  '#required' => TRUE,
  '#ajax' => array(
    'callback' => '_ajaxfunction',
    'wrapper' => 'divaroundseconddropdown'
  ),
);

$form['city_element_wrapper'] = array(
    '#prefix' => '<div id="divaroundseconddropdown">',
    '#suffix' => '</div>',
);

function _ajaxfunction($form, $form_state) {
  $key = !empty($form_state['values']['state1']) ? $form_state['values']['state1'] : 1;
  $query_city=db_select('city', 'c');
  query_city->fields('c',array('District_Code','District_Name','State_Code'));
  $query_city->condition('State_Code', $key, '=');

  $query_city->orderBy('District_Name','ASC');
  $city_results = $query_city->execute();
  $options_city = array();

  foreach ($city_results as $city_record) {
    // This is correct.
    $options_city[$city_record->District_Code]=t($city_record->District_Name);
  }

  // Render city setting.
  $form['city_element_wrapper']['city'] = array(
    '#type' => 'select',
    '#title' => t('District'),
    '#options' => $options_city,
    '#required' => TRUE,);

  return $form['city_element_wrapper'];
}

```

The following code is not working properly:

```
function form_test_form_submit($form, $form_state) {
  echo $prog_state = $form_state['values']['state1'];
  echo $data1 = $form_state['values']['city_element_wrapper'];
}

```

# Answer
> 1 votes
`form_test_form_submit` is called in php that's not displayed to user. Form is processed, it's values saved, and user is taken to desired page. Now you have 2 options:

* In submit handler set`$form_state['redirect']` to a page you like. Save values to a database. On target page read them and display.
* In **validation** handler add `markup` elements with selected values, if you want to emphasize selection but leave user on a form.

# Answer
> 0 votes
Form:

```
$form['field_abt_aff_mainact'] = array(
  '#type' => 'select',
  '#multiple' => TRUE,
  '#size' => 5,
  '#title' => t('Main Activity:'),
  '#options' => array(
    '0' => 'select',
    '1' => 'India',
    '2' => 'U.S',
    '3' => 'UK'
  ),
  '#default_value' =>$rels,
);

```

Insertion to database:

```
$field_abt_aff_mainact = array();

foreach ($form_state['values']['field_abt_aff_mainact'] as $value) {
  $field_abt_aff_mainact[] =$value;
}

$insertion = db_insert('incident_occupation_disease')
  ->fields(array('occupation_work_main_act' => implode(',', $field_abt_aff_mainact)))
  ->condition('main_incident_id', $inst_id, '=')
  ->execute();

```

Display Default values:

To show default value of multiple select:

```
// Fetch values from databse
$fetching = db_select('incident_occupation_disease', 'ifb')
  ->fields('ifb')
  ->condition('main_incident_id', $inst_id, '=')
  ->execute()
  ->fetchAll();

foreach ($defautvalues as $default) {
  $occupation_work_main_act[] = $default->occupation_work_main_act;
}

$occupation_work_main_act = array();
$resultsed = explode(",", $occupation_work_main_act[0]);
$rels = array();
foreach ($resultsed as $rel) {
  $rels[]=$rel;
}

```

Here, `$rels` array will be use in Form API as default/selected value.

---
Tags: forms
---


# Question
Title: I can't figure out the difference/relationship between menus and menus
One of those fundamentals I skipped over because it gave me a headache to think about thinking about it:

Can someone explain, (or point me to documentation that can explain, and won't make me want to punch myself), the difference, the logic, relationships and/or whatever for "menus" (seemingly misnamed collection of page markers **the things you make with HOOK\_menu**) versus "menus" (thingees that you click on to make events happen **the things you make with menu\_save()**)?

...bonus points if you can tell me why in the name of all things holy are log-in, log-out, register, my account, and hell, even "switch back" not built into a single core menu block so that I could continue to live in blissful ignorance...

# Answer
> 2 votes
The main confusion rests in the fact that menu system does two things.

One, it is the subsystem that maps incoming URL requests to functions in Drupal to render output. This is typically called the router. In Drupal 7, routes are defined with `hook_menu()` and the information gets stored in the `{menu_router}` table. There are also a group of API functions that deal with the routes and router items, eg

* `menu_set_active_item()`
* `menu_get_item()`
* `menu_get_object()`

Most of these are defined in menu.inc, and many (but not all) have the words "item" or "router" in them.

The other subsystem is what I refer to as the menu hierarchy interface. This creates groups of links into a hierarchy which typically get rendered out to HTML as what we commonly call a menu. The menus themselves are stored in `{menu_custom}` and the menu entries are stored in `{menu_links}`. The core functionality is found in menu.inc, but the code related to rendering out a menu is in menu.module. Most (but not all) of the API functions for this have "tree" in the name, eg

* `menu_tree_all_data()`
* `theme_menu_tree()`

For better or for worse, the two of these are fairly tightly coupled, which adds to the confusion. Fortunately, this is one place where most developers don't need to work directly, other than programming against `hook_menu()`.

# Answer
> 2 votes
`hook_menu` : Is used to define a path in Drupal. It also says what should be present in that path, who should have access to it and so.

Documentation of hook\_menu

`Menus` : Is a list of links that fall under a category. For example Admin Menu(Admin Links), User Menu(Account, Logout) and Primary Menu(Home, Contact and so on)

Documentation of Menus

# Answer
> 1 votes
`menu_save()` is used to create a menu. You can use this to add to the existing system menu (Navigation, Management, User Menu, Main Menu).

`hook_menu()` Define menu items and page callbacks. You can use this to create a simple callback or a menu item. If you create a menu item by setting `$type` to `MENU_NORMAL_ITEM` then you can place this item under any of the menu created using `menu_save()`.

In simple terms

`menu_save()` \- **Menu**

`hook_menu()` \- **Menu Item** / **Simple Callback**

---
Tags: 7, routes
---


title: Form API #states with #default_value?

text:
# Question
Title: Form API #states with #default_value?
I have a form which has a select with a `#default_value` which get's set when the user has errors/has filled out the form. Then I have two fields with a `#states` that show them when the select has a value.

So basically

```
$checkout_form['wrap'] = array(
  '#type' => 'select',
  '#title' => t('How many item(s) do you wish to have wrapped?'),
  '#default_value' => $default_giftwrap_amount,
);

```

Then I have a fieldset and a textarea with

```
  '#states' => array(
    'visible' => array(
      ':input[name="wrapping[wrap]"]' => array('!value' => ''),
    ),
  ),

```

which make those two fields show when ever something is selected.

But my problem is when the `#default_value` is say 400 (ie something is selected) it doesn't show the fieldset and textarea, only when you select something.

Is there anyway for it to check on page load as well as onchange?

# Answer
Your default value in the select element must be the array **key** of your values not the value it self.So i set an empty "value" and check for that.

That said i got this working like:

```
$form['wrap'] = array(
  '#type' => 'select',
  '#title' => t('How many item(s) do you wish to have wrapped?'),
  '#options' => array('--', '1', '2', '300', '400'),
  '#default_value' => 2,
);
$form['textarea'] = array(
  '#type' => 'textarea',
  '#title' => t('How many item(s) do you wish to have wrapped?'),
  '#states' => array(
    'visible' => array(
      ':input[name="wrap"]' => array('!value' => 0 ),
      ),
    ),
  );

```

In the example above my default value is 300. The state visibility will work onload and onchange and will show the textarea only when the value is the empty value (0 =\> '--')
> 2 votes

---
Tags: 7, javascript
---


title: Add/Remove User Role on Node View

text:
# Question
Title: Add/Remove User Role on Node View
I want to be able to add and remove a role to a user via a simple click of a button on almost any node. (Specifically the plan is to allow a user to give themselves a role that would give them extra editing powers, but so that they can remove it when generally browsing the site so all the editing options don't clog up the UI).

The best method I could think of for this is to have two nodes, and set up a rule so visiting these nodes added or removed the user role. I could then create simple menu links that linked to these nodes.

Essentially what I have set up is one rule which goes:

```
Event: Content is Viewed
Condition: Node is of alias - node url
Action: Add user role - Edit Powers

```

This rule works fine. When the node is visited the role is added to the user. However the reverse rule doesn't work despite being nearly identical to the other. It reads:

```
Event: Content is viewed
Conidtion: Node is of alias - node url
Action: Remove user role - Edit Powers

```

However visiting this URL doesn't remove the user role. The question here is two-fold.

a) Why would the rule not be working, and why can't it remove a role from the user?

b) Is this a really complex way of achieving something that might be quite simple? At the moment I assume this rule is effectively being checked when any user visits any page, which I'm sure isn't great from a resource point of view - but I couldn't think of an easier way to do it with flags etc. So please do advise if there is an easier way.

Thanks in advance for any help.

# Answer
> 0 votes
Try creating a condition that the user have the role, before trying to remove it. Also, you could look into Rules Link \- you may be able to add it to a custom Profile Page, allowing the user to access and change their settings via My Account - at least from a UI standpoint it might make more sense.

# Answer
> 0 votes
There are two ways I can think of doing this.

1. Install and Enable Roles Assign Module. Once this module is enabled the user can go to his account and then assign roles(A subset selected by the admin) or remove them from his account.
2. Install Flag module. Create one flag for each of the roles. This will give you Add/remove flag options and your can integrate it with Flag actions to assign or remove the Roles.

# Answer
> 0 votes
In the condition "Node is of alias", what have you entered? It might be wrong. Post it here to help you if you want.

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


title: Permissions for new role do not work

text:
# Question
Title: Permissions for new role do not work
i have a certain problem regarding a content type and a "supervisor" role for it.

For the content type (which unfortunately did not create it myself but found it on an ongoing project), i have created a certain role (lets say "Supervisor" ) which shall give access to each user to "editing own content". Since all the content in this content type are created by the admin, for test purposes, i changed the author of a node from "Admin" to "user\_1", and then later loged-in as "user\_1" to edit the node, but no luck.

I tried several other alternatives, such as "content access" module, "create new content" permission, flexi-acces module, but nothing worked.

Whenever i try ../node/xxx/edit, it displays the node and not the edit screen.

Any ideas why this happens?

\** i gave the "edit all content" permissions to the role, and the user could edit all the profiles (obviously) - i just wanted to check if everything works ok with the roles \**

# Answer
> 0 votes
I found where the problem was and i think it is a little bit tricky.

I use different theme as user and different theme as admin. Therefore the "edit" procedure takes place under the "admin theme" (i do not know if i expressed that correctly, i hope you get what i mean). So, if the desired role does not have the property "View the administration theme", no matter how correctly are the permissions set, you do not have access to the "edit" page. Weird in my opinion. Anyway, i hope this will help someone in the future!

# Answer
> 2 votes
Make sure the "user\_1" has a role as "Supervisor".And also check "content type: Edit own content" permission in people-\>permissions has assigned to "Supervisor" Role.Finally clear the performance.

# Answer
> 1 votes
Step by step how you can solve this :-

Lets say i have content type 'demo'.

=\> Now Admin creates an node of type demo and changed the author name to (lets say 'supervisor' that have role 'supervisor')

=\> Now give permissions to 'supervisor' role to 'View published content' and 'demo: Edit own content' as shown in below screenshots

and then save permissions

=\> login as user 'supervisor' with role 'supervisor'.now 'supervisor' can edit node that have content type 'demo'.

---
Tags: 7, nodes, users
---


# Question
Title: Redirecting and removing user role after user account submit
I like to redirect my users after they submit their user/edit page. On their user/edit submit i like to remove a certain role from them as well. The redirect hasn't been a problem however removing the role is.

In a custom module i have the following code:

```
  function regform_user_profile_form_submit($form, &$form_state) {
  global $user;
 drupal_goto('user/' . $user->uid);

```

I am quit a beginner with php and couldn't find any could that fitted in this function properly. Using rules is not an option as it conflicts with the Oauth module.

Help appreciated, thanks.

# Answer
> 0 votes
I would try implementing hook\_user\_presave().

```
function custom_module_user_presave($edit, $account, $category) {
  $role_position = array_search('undesired_role', $account->roles);
  // Use !== or === here since $role_position may be zero or FALSE
  if ($role_position !== FALSE) {
    unset($account->roles[$role_position]);
  }
}

```

# Answer
> 0 votes
```
   <?php
function regform_form_user_profile_form_alter(&$form, $form_state,  $form_id) {
  global $user;
 // Making password required when role=In between role.
  if( ($form_id == 'user_profile_form') and (isset($form['account']['pass'])) and (in_array('In between role', array_values($user->roles))) ){
    $form['account']['pass']['#type'] = 'password';
    $form['account']['pass']['#required'] = TRUE;
    $form['account']['pass']['#type'] = 'password_confirm';
    $form['account']['pass']['#required'] = TRUE;
  }

// Using regform_user_profile_form_submit to redirect users with Oauh role
    elseif(($form_id === 'user_profile_form')and (isset($form['account']['pass'])) and (in_array('Oauth role', array_values($user->roles))) ) {
    $form['#submit'][] = 'regform_redirect_callback';

    }
}
function regform_redirect_callback($form, &$form_state) {
  $form_state['redirect'] = 'user/';

  }

function regform_user_presave($edit, $account, $category) {
  $role_position = array_search('Oauth_role', $account->roles);
  // Use !== or === here since $role_position may be zero or FALSE
  if ($role_position !== FALSE) {
    unset($account->roles[$role_position]);

  }
}

?>

```

# Answer
> 0 votes
You can achieve what you want without writing any custom code. Use Rules and Rules Form Support to do it.

**How to:**

1. Enable the above modules.
2. Go to *Configuration -\> Workflow -\> Rules -\> Form events* and check "*Enable event activation messages on forms*".
3. Activate the user/edit page by visiting it and pressing "*Activate events for user\_profile\_form*" which appears in the status messages area.
4. You will be redirected to a confirmation page. Give a name to your custom form label (I named it "User profile form") and check "*Enable button level validate/submit events*". Then activate the form.
5. Create a new rule, reacting on event "User profile form is submitted".
6. Add any conditions you may want. For example, as a condition you could add "User has role(s)" and select the role you want to remove.
7. Rules Forms supports many actions like "Require an element in the form" (in your case the password fields) and "Set the redirect target of the form" to change the redirect path.
8. Last one is to add one more action to remove the user role you want ("Remove user role" action).

I hope I helped you. If you have any questions feel free to ask!

---
Tags: users
---


# Question
Title: User created by REST API cannot login: wrong password
I am creating new users using Rest API provided by Services module.

The user creation goes well, but when I try to login with the user I've just created it says wrong password.

The website where I'm testing is not really Drupal, it's Open Atrium, that is based on Drupal but I don't know if that has something to do with my problem but just wanted to mention it.

In the CHANGES file it says Drupal 7.28, 2014-05-08

If I then go to Admin panel and manually change the password for that user, then I can login, but that's the problem, if I create the user from the api I cannot login it says wrong password.

So I think it must be something wrong with how the password gets encrypted inside Drupal when using the api call. I am passing it as plain text.

Any help is appreciated I've spent already lots of time on this.

The code I use to create the user is this:

```
/*
    * Server REST - user.login
    */
    // REST Server URL
    $request_url = $host.'/rest/user/login';

    // User data
    $user_data = array(
      'username' => /*admin login*/$adminLogin,
      'password' => /*admin password*/$adminPassword,
    );
    $user_data = json_encode($user_data);

    // cURL
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL, $request_url);
    curl_setopt($curl, CURLOPT_HTTPHEADER, array('Accept: application/json', "Content-type: application/json"));
    curl_setopt($curl, CURLOPT_POST, 1); // Do a regular HTTP POST
    curl_setopt($curl, CURLOPT_POSTFIELDS, $user_data); // Set POST data
    curl_setopt($curl, CURLOPT_HEADER, FALSE);  // Ask to not return Header
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
    curl_setopt($curl, CURLOPT_FAILONERROR, TRUE);
    $response = curl_exec($curl);
    $http_code = curl_getinfo($curl, CURLINFO_HTTP_CODE);
    // Check if login was successful
    if ($http_code == 200) {
      // Convert json response as array
      $logged_user = json_decode($response);
    }
    else {
      // Get error msg
      $http_message = curl_error($curl);
      //die($http_message);
      $oa_errors[]="Could not login to OpenAtrium. ($http_message)";
      return false;
    }
    // Define cookie session
    $cookie_session = $logged_user->session_name . '=' . $logged_user->sessid;
    //GET CSRF TOKEN
    $csrf_token = $logged_user->token;
    /*
    * Server REST - user.create
    */
    // REST Server URL
    $request_url = $host.'/rest/user/register';
    // User data
    $user_data = array(
      'name' => /*user name*/ $userName,
      'pass' => /*password*/ $userPassword,
      //'pass1' => /*password*/ $userPassword,
      'mail' => /*email*/ $userEmail,
      'status' => 1,
      //'roles'=>array(
      //  2,
      //  4,
      //),
      'field_user_display_name' => array(
        'und' => array (
            0 => array (
                'value' => /*screen name*/ $userScreenName,
                'format' => NULL,
                'safe_value' => /*screen name*/ $userScreenName,
            ),
        ),
      ),
    );

    $request_url = $host.'/rest/user';
    $user_data = array('account'=>array(
      'name'=>'test_user',
      'pass'=>'test_pass',
      'mail'=>'test_mail@heavydots.com',
      'field_user_display_name' => array(
        'und' => array (
            0 => array (
                'value' => /*screen name*/ $userScreenName,
                'format' => NULL,
                'safe_value' => /*screen name*/ $userScreenName,
            ),
        ),
      ),
    ));

    print_r($user_data);

    $user_data = json_encode($user_data);

    // cURL
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL, $request_url);
    curl_setopt($curl, CURLOPT_POST, TRUE); // Do a regular HTTP POST
    curl_setopt($curl, CURLOPT_HTTPHEADER, array('Accept: application/json', "Content-type: application/json", 'X-CSRF-Token: '.$csrf_token));
    curl_setopt($curl, CURLOPT_POSTFIELDS, $user_data); // Set POST data
    curl_setopt($curl, CURLOPT_HEADER, false);  // Ask to not return Header
    curl_setopt($curl, CURLOPT_COOKIE, "$cookie_session"); // use the previously saved session
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
    curl_setopt($curl, CURLOPT_FAILONERROR, FALSE); //True in prod, false for debugging
    $response = curl_exec($curl);
    $http_code = curl_getinfo($curl, CURLINFO_HTTP_CODE);

```

# Answer
I think I've managed to solve this on my own but with a really strange solution.

I have looked inside the Services module from Drupal to see if I can find what function is getting called when I make the api call to create a new user and I've found this:

/openatrium/modules/services/resources/user\_resource.inc

In this file there is this function that is getting called:

```
/**
 * Create a new user.
 *
 * This function uses drupal_form_submit() and as such expects all input to match
 * the submitting form in question.
 *
 * @param $account
 *   A object containing account information. The $account object should
 *   contain, at minimum, the following properties:
 *     - name (user name)
 *     - mail (email address)
 *     - pass (plain text unencrypted password)
 *
 *   These properties can be passed but are optional
 *     - status (0 for blocked, otherwise will be active by default)
 *     - notify (1 to notify user of new account, will not notify by default)
 *
 *  Roles can be passed in a roles property which is an associative
 *  array formatted with '<role id>' => '<role id>', not including
 *  the authenticated user role, which is given by default.
 *
 * @return
 *   The user object of the newly created user.
 */
function _user_resource_create($account) {

  // Adds backwards compatability with regression fixed in #1083242
  $account = _services_arg_value($account, 'account');

  // Load the required includes for saving profile information
  // with drupal_form_submit().
  module_load_include('inc', 'user', 'user.pages');

  // register a new user
  $form_state['values'] = $account;
  // Password may be not available as this callback is used for register as well.
  $form_state['values']['pass'] = array(
    'pass1' => isset($account['pass']) ?: '',
    'pass2' => isset($account['pass']) ?: '',
  );
  $form_state['values']['op'] = variable_get('services_user_create_button_resource_create', t('Create new account'));

  // execute the register form
  $form_state['programmed_bypass_access_check'] = FALSE;
  drupal_form_submit('user_register_form', $form_state);
  // find and store the new user into the form_state
  if(isset($form_state['values']['uid'])) {
    $form_state['user'] = user_load($form_state['values']['uid']);
  }

  // Error if needed.
  if ($errors = form_get_errors()) {
    return services_error(implode(" ", $errors), 406, array('form_errors' => $errors));
  }
  else {
    $user = array('uid' => $form_state['user']->uid);
    if ($uri = services_resource_uri(array('user', $user['uid']))) {
      $user['uri'] = $uri;
    }
    return $user;
  }
}

```

You can see this block here is doing something with the password, and what it actually does is setting both pass1 and pass2 fields to value "1", yeah, strange:

```
  // Password may be not available as this callback is used for register as well.
  $form_state['values']['pass'] = array(
    'pass1' => isset($account['pass']) ?: '',
    'pass2' => isset($account['pass']) ?: '',
  );

```

I have modified those lines to this:

```
// Password may be not available as this callback is used for register as well.
  $form_state['values']['pass'] = array(
    'pass1' => isset($account['pass']) ?$account['pass']: '',
    'pass2' => isset($account['pass']) ?$account['pass']: '',
  );

```

And what this will do is, if you pass a password when making the call it will populate both pass1 and pass2 with it, and if not, it will leave it to blank ''.

This way the user got created and I've managed to login correctly.

As I said this behaviour is strange and I don't understand howcome nobody else had this problem.

I'm also thinking maybe another solution would work, to make a 3rd api call after creating the user, to modify it and set the password again and see if that way it gets updated correctly.
> 2 votes

---
Tags: users, 8
---


title: How many times is a view used

text:
# Question
Title: How many times is a view used
Recently i'been assigned to a drupal project already in development. I need to change a view but the site is quite complex. Is there a way to know how many times is a view being used?

Thank you all

# Answer
## Views Usage Audit

From project page:

> This module can help you refactor a Drupal codebase by locating redundant views and displays or simply improving your understanding of what views are used where.
> It achieves this by logging where views get executed. You can then run reports from drush or through the UI
> 1 votes

# Answer
when you say "how many times" you probably mean "in how many 'places' in the site" the view is being used to display data...Right?

Well, an easy way to do this is to check how many and what kind of **displays** this view has. You can see this in the edit page of the view, it is the bar above the main view "frame", with each tab denote a different display. These displays can be of different type, such as "page", "block", "context" etc.

In case of pages, you just check the corresponding view "frame window". There you can find the node number (url) or the alias.

In case of blocks, go to the block page, find the corresponding (produced) block (it's name can be found on the **views** edit page) , go to it's edit page, and there you can see various information about the "places" (regions, zones etc) where the block is being displayed. Also you can find in which nodes, for which roles etc.
> 0 votes

---
Tags: views
---


# Question
Title: Proper approach to two different address data sets on the system
I have a certain design problem here. The web site I'm working on will need to have 2 sets of address details

* under user account, as an indication of user's business address
* at the commerce checkout, as billing address

For commerce checkout I've been using built-in customer billing profile and it works ok. But I'd like to maintain a similar format for user address. The plan is to populate the billing address form during checkout with user's business address by deafult but also allow to modify billing address without changing business one

At the moment I'm concerned that I'm mixing different structures too much. I have billing profile for commerce, profile2 for users but also couple of custom fields created under Account Settings. What approach would you suggest to setup the user account fields so it's clean, easily referrable to each other and not confusing?

# Answer
I'd just use Commerce Addressbook, it would allow you to have a set of addresses in your user account, from project page:

> Commerce Addressbook is a module that allows authenticated customers to reuse previously entered addresses during checkout. They can manage all entered addresses in their user panel (user/%user/addressbook).

Seems exactly what you're looking for and is way less complicated that dealing with the addresses and defaults yourself.
> 0 votes

---
Tags: commerce, users
---


# Question
Title: Feeds XPath parser - setting the created date of a node
I'm importing a date field in the format:

dd/mm/yyyy

I want to set this as the created date for the node I'm creating/updating.

I've tried the Feeds tamper module but the date function seem to convert between a string and a Unix timestamp, which doesn't seem to work anyway.

What's the best way to do this?

# Answer
You can try to use the hook\_feeds\_presave in a custom module :

```
function mymodule_feeds_presave(FeedsSource $source, $entity, $item, $entity_id) {
  $your_import_date = explode('/', $item['your_import_date']);
  $your_import_date_formated = $your_import_date[2] . '-' . $your_import_date[1] . '-' . $your_import_date[0] . ' 00:00:00';
  $item['your_import_date'] = strtotime($your_import_date_formated);
  $entity->created = $item['your_import_date'];
}

```
> 1 votes

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


# Question
Title: How can I link back to Term's page using Node Auto Term [NAT]?
I'm using NAT on a content type called Profile configured as follows in the picture below. I've been able to use this in great ways in some views.

I see that when I do a `dpm($var['node'])` from `theme_preprocess_node($vars)` that I see a NAT entry in the debug output.

My question is how do I properly grab this `tid` and automatically create a link to the taxonomy term's page (`/taxnonmy/term/503`)?

Cross reference: https://www.drupal.org/node/2291797

# Answer
> 0 votes
This is the closest I've come but it's still sort of hack-ish.

```
 function MYTHEME_preprocess_field(&$vars) {

        $termid = "none";
    if (
        isset($vars['element']['#object']->nat) &&
        $vars['element']['#field_name'] == 'body' &&
        $vars['element']['#object']->type == 'instructor_profile'
        )
    {

    list($termid, $value) = each($vars['element']['#object']->nat);
    $vars['term_id'] = $termid;

    /* Use EFQ to determine how many nodes may have this taxonomy attached
    to it. I'm only interested in the count()*/
    $query = new EntityFieldQuery();
    $query->entityCondition('entity_type', 'node')
    ->propertyCondition('status', 1)
    ->fieldCondition('field_related_instructor_mention', 'tid', $termid)
    ->addMetaData('account', user_load(1));
    $count = $query->count()->execute();

    /* If there is information ($count>0), then show. If no links
    don't worry about it */
    if($count > 0) {

        $vars['items'][0]['#markup'] =
        "<div class='only-small'>" .
        "<p><a href='/taxonomy/term/$termid'>More News</a></p>" . "</div>" .
        $vars['items'][0]['#markup'] ;
    }

}

    }

```

---
Tags: taxonomy-terms
---


# Question
Title: Field Collection Major Error! Help Needed!
After trying to add new field collection item, I get this message in Chrome when going back to the previous page in browser:

> Notice: Undefined offset: 92 in field\_collection\_field\_widget\_embed\_validate() (line 1675 of /sites/all/modules/field\_collection/field\_collection.module).

and when I tried to save I got this:

> EntityMalformedException: Missing bundle property on entity of type field\_collection\_item. in entity\_extract\_ids() (line 7734 of /includes/common.inc).

I should add that I'm having 92 items in my field collection. When I work in Firefox the browser just freeze. Can't find any other solution to my site at the moment then to use field collections this way. Any thoughts? I wonder if a field collection inside a field collection would decrease the heavy JavaScript load?

# Answer
> 1 votes
Check your maximum\_input\_vars setting in php.ini

I recently had a similar issues with a repeating field collection once we added a certain amount. We bumped from 1000 to 10000, but I feel that was excessive.

---
Tags: javascript, entities
---


# Question
Title: How to debug / log comments when developing a custom module to fire when cron is run
I am about to develop a custom module that will hook into a hook that is triggered when cron runs. Since the module will be activated during a cron run, i am not sure how to go about giving myself feedback as I develop. If I was working with javascript I could use `console.log(myvar)` to log information about variables etc.

If I was developing a module that ran on a page I could use the devel module and use dpm() in my module code.

However since this module will run with cron, dpm() doesn't seem like the best way of doing this.

From searching around I see that `watchdog('error title', 'error message');` could have been a good way of doing this in Drupal 6.

What is the Drupal 7 way of logging messages during custom module development?

# Answer
> 4 votes
The function watchdog is also available in Drupal 7

Here is an exemple of how you can use it in your case :

```
watchdog('MyModule', 'My message, this is my node title : %node_title', array('%node_title' => $node->title), WATCHDOG_INFO, NULL);

```

If you want to use a translated string you can do something like this :

```
watchdog('MyModule', t('My message, this is my node title : @node_title', array('@node_title' => $node->title)), array(), WATCHDOG_INFO, NULL);

```

If you need to print an array, you can try something like this :

```
watchdog('MyModule', '<pre>'. print_r($node, TRUE) .'</pre>', array(), WATCHDOG_INFO, NULL);

```

You can watch the log in Reports -\> Recent log messages (admin/reports/dblog) if the core module "Database logging" is activated.

Once your module is stable, you can remove the watchdog line.

---
Tags: 7, debugging
---


# Question
Title: Cannot read nodes containing an email address
```
    $email = "example@addresss.com";

    if (valid_email_address($email)) {
      $query = new EntityFieldQuery();
      $query->entityCondition('entity_type', 'node')
        ->entityCondition('bundle', 'my_content_type')
        //->fieldCondition('field_user_email_address', "email", $email)
        ->propertyCondition('status', 1);

      $result = $query->execute();
      dpm($result,"result");
      if (!empty($result['node'])) {
        $nids = array_keys($result['node']);
        $nodes = node_load_multiple($nids);

        foreach ($nodes as $node) {
          dpm($node,$node->title);
        }
      }
    }

```

The problem I have is with the fieldCondition (commented out above). When it's commented out, the $result returns all of the matching nodes, as expected. Looking at the second dpm output I can see results for "example@addresss.com" in $var-\>field\_user\_email\_address\[LANGUAGE\_NONE\]\[0\]\['email'\] = "example@addresss.com".

However, when the fieldCondition is included in the search, it always returns zero results. i.e. $result is an empty array

# Answer
> 2 votes
I'm not sure why you're having trouble with the bundle condition, but as an alternative you could use a `propertyCondition` and query on the node type instead:

```
$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'node')
  ->propertyCondition('type', 'my_content_type')
  ->fieldCondition('field_user_email_address', "email", $email)
  ->propertyCondition('status', 1);

```

---
Tags: database
---


title: Site offline notification

text:
# Question
Title: Site offline notification
How to turn off the notification about the site being offline, when in maintenance mode?

> Operating in maintenance mode. Go online.

# Answer
> 8 votes
Before I give you the answer, I would suggest that you do NOT implement this.

This message is an obvious but friendly reminder that your site is in maintenance mode. Turning off this reminder may leave you scratching your head later, wondering why anonymous visitor John Smith can't access your site. The reason may be obvious to you now but it may not be so obvious as time goes by.

This code snippet removes the 'Operating in Maintenance Mode' message, but preserves other messages. Place this code in template.php and then clear the cache:

```
function mytheme_preprocess_page(&$vars) {
  if (variable_get('maintenance_mode', 0)) {
    $message_count = count($_SESSION['messages']['status']);
    if($message_count > 1) {
      array_shift($_SESSION['messages']['status']);
    }
    else {
      unset($_SESSION['messages']['status']);
    }
  }
}

```

Edit: Updated the code, this should do the trick. Added a condition that unsets the 'status' element if empty.

One last thing: The maintenance message also appears on the administration pages. You can remove this message too, but as stated earlier, this is dangerous.

The default theme for the admin pages is 'Seven', which has its own template file. You could copy the above code into Seven's template.php. Or even better, copy the code into a new function in your custom module, `mymodule_hide_maintenance_message()` for example, and simply call that function within `mytheme_preprocess_page`.

# Answer
> 0 votes
Note : If you use the them omega 4.x, that function is already declared in your sub-theme (if you don't work with a sub-theme, you should) in the *preprocess* folder in file *page.preprocess.inc*

Thus you cannot add that in *template.php* file or you'll get WSOD. You need to edit the function in *page.preprocess.inc*

---
Tags: 7, notifications, maintenance-mode
---