# Question
Title: How to set up webhooks with the Mailchimp module
I just installed the newest version of the MC module into my D7 instance and was wondering how I can enable webhooks for the lists that I have within the lists tab.

I have already set up a test list on the MC side and created an API key and I see the list populating on the Drupal side so I have that working just fine.

When I go to enable the webhooks feature on my list on the D7 side I get this msg:

**You can change this setting back from the mailchimp administrative UI.** I then click on enable hooks. Its working to do something but then get hit with: **Unable to perform webhook action "enable" for list my-test-list**.

I also see that I need to enter a callback URL on the MC side but I'm confused as to what link I need to use there.

# Answer
I had the same problem with my site, which is fixed now. It seems like the error message pops only if you are on HTTPS secure protocol. If you are on HTTPS try disabling it and try enabling your mailchimp lists. After you enable the mailchimp list now you can re-enable the HTTPS.

There is a bug on 7.x.3.1 version Make sure you are using the latest version 7.x.3.2

On secure pages settings you can ignore these pages loading from HTTPS.

**example.com/admin/config/system/securepages**

`admin/config/services/mailchimp
admin/config/services/mailchimp/*`
> 1 votes

---
Tags: hooks, emails
---


# Question
Title: Access Denied After ERPal Platform Install
I've successfully installed ERPal Plaform with a LAMP stack on a fresh install of Ubuntu 12.04 on a VPS, and it goes to the administrative console after install. It's fully functional until I log out. When I log out, I get an Access Denied message whenever I trying to go to the domain it is installed on. I tried to chmod 777 the document root, but that didn't have any effect. Any ideas how I can deal with this issue and get access to the home page?

# Answer
> 0 votes
Currently ERPAL platform is in active development status, and you can use ERPAL platform in full power, like admin user only. As ERPAL platform is based on Drupal, you can configure permissions by yourself on admin pages.

# Answer
> 0 votes
This issue has been fixed in subsequent releases.

---
Tags: distributions
---


title: Desaturated images colored on hover?

text:
# Question
Title: Desaturated images colored on hover?
Is there a clean, "hands-free" way to have a ticker full of logotypes desaturated in normal view, but colored on hover? Or should I prepare CSS sprites by myself and go the "dirty" way?

# Answer
It's an old question but by now this seems to be the module that you needed: Image desaturate formatter
> 3 votes

# Answer
You can easily achieve this with Imagecache (included in D7 core) and maybe a few of its fellow modules depending on what you want to achieve exactly.

You setup your image presets and then CSS your hovers to your heart's content.

I've done this many times and it works perfectly, including with dynamic pictures provided in content.
> 1 votes

---
Tags: media
---


# Question
Title: Invoke a camera to start in Drupal 7 Forms API
I am currently developing a module which must be capable of taking a picture. I dont know how will I make it? How will I invoke a camera to open just by clicking a button? Any idea?

# Answer
> 1 votes
Have you tried the webcams module ? Even if it's dev I'd say it's worth trying.

Do a search on webcam on Drupal and try out some of the modules listed.

Else if you want to develop your own module then the best way is probably doing the integration of an existing webcam jquery module. (See some jquery plugin examples here)

---
Tags: 7, forms
---


# Question
Title: Real-time preview of node/form in Drupal 7
I'm trying to achieve this in Drupal 7. This is what I need URL for working example (But its not in **Drupal**).

**Requirement - Live Preview with alignment features**

From Drupal.Stackexchange I've came across this post 29325 where the user is trying to achieve the similar thing there its mentioned about the Drupal's Live Module but as the description page of the module shows yet its not made up for Drupal 7 and I'm sure this will not fulfill my requirement.

# **Question:**

1. Rather than Drupal's Live module, is there any other module available?
2. Can any of the JS/jQuery plugin or library or framework can fulfill my above mentioned requirement?

**Note**

* I've created the left/side panel form using the custom content type hence now, if I can achieve this live preview using some JS plugin/library also then I'm fine with it as I can see that no Drupal module is available for this!

# Answer
I have started development of a module - Live preview which might be more along the lines of what you're after.

> This module provides a more comprehensive, genuine and interactive version of the built-in node preview feature.
>
> The live preview feature requires JavaScript; if JavaScript is disabled it will not apply its triggers, effectively retaining the built-in preview.

It hasn't yet reached a stable release, but it's worth checking out (-dev version should work just fine).
> 1 votes

---
Tags: 7, theming, javascript, entities
---


title: Drupal 7 live preview module

text:
# Question
Title: Drupal 7 live preview module
I have recently been looking for module that will allow you to preview the page you are creating, in real time as you are creating it (just like SE questions). I came across the live module, but I realized that it was only for drupal 5 and 6. Is there a similar module that allows you to preview your page live, for Drupal 7?

# Answer
I've given this problem some thought (actually began writing code for a D7 live preview), and as it happens I simply don't think live preview is that simple in Drupal.

Live preview on SE.sites is efficient because there are no AJAX requests going on for rendering the preview. In a nutshell SE.sites merely clone the text from the editor textarea into the preview div, where CSS classes are applied to it. In reality there is more processing happening in the background as the text that you enter must be converted into real markup (ie, when using lists).

In Drupal however there can be a lot of pre-processing of text, depending on what modules you have enabled. For instance, take the `<!--break-->` control sequence (which is part of core behavior, btw). Does that really mean something in HTML? No, it must be preprocessed by Drupal into teaser and full body text snippets; take the CKEditor and the IMCE modules for example, they also depend on preprocessing text to translate special markup for images into actual `<img>` tags.

What that means is that in order to have a live preview that is faithful to it's final state, you must run whatever text you enter through a number of hooks, preprocessors, renderers and what have you. Else your live preview will not represent the final product. Therefore, having a faithful Live Preview in Drupal would mean sending an AJAX request to the back-end every time the editor in the front-end is updated. And then, you can ask yourself the question? Is this scalable? That would probably depend on your use case. If you want Live Preview for a site with a big editorial team (think www.nowpublic.com, a Drupal site), the answer would probably be no. But maybe if it is for a small site, with a few visitors or editors, then the answer would be maybe, but it still raises performance concerns.

So taking those points into consideration, what *kind* of preview would you be looking for? *Slow & Faithful* or *Fast and Unfaithful*?
> 3 votes

# Answer
Didn't test it, but ajax\_markup seems to fit your needs, and it's stable.
> 0 votes

# Answer
I have started development of a module - Live preview which might be more along the lines of what you're after:

> This module provides a more comprehensive, genuine and interactive version of the built-in node preview feature.
>
> The live preview feature requires JavaScript; if JavaScript is disabled it will not apply its triggers, effectively retaining the built-in preview.

It hasn't yet reached a stable release, but it's worth checking out (-dev version should work just fine).
> 0 votes

---
Tags: 7
---


title: Fetching text field from the node

text:
# Question
Title: Fetching text field from the node
I am working on **flex slider module** and I want to add **one button** in caption so for that I have added **one field** in content type with `Machine name: field_image_url` and `Field Type: text`.

Now I am changing in **core file** of the module to fetch that `URL` into the **front end**.For that code is below:

```
    <?php
    /**
     * @file
     * Default output for a Flex Slider node.
    */
    ?>
    <div class="flex-nav-container">
      <div class="flexslider-content flexslider clearfix" id="flexslider-<?php print $id; ?>">
        <ul class="slides">
        <?php foreach($items as $item) : ?>
          <li><?php print render($item); ?>
            <?php if(!empty($item['#item']['title']) || !empty($item['#item']['alt'])) : ?>
             <div class="flex-caption">
             <h3><?php print $item['#item']['alt'];?></h3>
             <p><?php print $item['#item']['title']; ?></p>
             <?php if(isset($node->field_image_url)): ?>
                <a href="<?php print render ($node->$field_image_url); ?>" class="btn btn-theme">Learn More</a>
             <?php endif; ?>
             </div>
            <?php endif; ?>
          </li>
        <?php endforeach; ?>
        </ul>
      </div>
    </div>

```

I know I am making **some mistake** as I am very **new to drupal development**.

```
     <?php if(isset($node->field_image_url)): ?>
        <a href="<?php print render ($node->$field_image_url); ?>" class="btn btn-theme">Learn More</a>
     <?php endif; ?>

```

Above code is for fetching URL.It is **not** giving me **any error**, but it is also not showing me the button.I have already entered URL for one slide.

Where am I lacking ?

**Edited** :

I want to also mention that `Slider` is on **front page** and there is an **article content** just below to the slider.

I have given **node path** to the front page from the Configuration to show it on **front page**.

So now, If I do

```
     <?php
        if (arg(0) == 'node' && is_numeric(arg(1))) {
          // Get the nid
          $nid = arg(1);
          // Load the node if you need to
          $node = node_load($nid); print_r($node);
        }
     ?>

```

It is giving me the `node ID` of the **article**.I want the `node ID` of the **slider Image** so that I can pull out the `image URL field` that I have added to the **Slider Image Content type**.

**EDITED**:

```
    <?php
        //this code will load all nodes from your content type and then print them
        $node_type = "slider_image";
        $result = db_query("SELECT nid FROM node WHERE type = '%s' ", $node_type);
        $nodes = array();
        while ($obj = db_fetch_object ($result)) {
          $node = node_load($obj->nid);
          echo $node->field_image_url['und'][0]['value'];
          echo '<br>';
          $nodes[] = node_load($obj->nid);
        }
    ?>

```

I have tried above code but it is giving me an error : `Recoverable fatal error: Argument 2 passed to db_query() must be of the type array, string given, called in path to modules\modules\flexslider\theme\flexslider-container.tpl.php on line 19 and defined in db_query() (line 2345 of path to site\includes\database\database.inc).`

So to resolve above error, I tried following code with help of `this`:

`$result = db_query("SELECT nid FROM node WHERE type = ':type' ", array(':type' => $node_type));`

But above code also gives me error : `Fatal error: Call to undefined function db_fetch_object() in path to module\modules\flexslider\theme\flexslider-container.tpl.php on line 21`

# Answer
> 1 votes
In general to get the value of field if the entity type is a node

```
$node = node_load($nid);
echo $node->field_image_url['und'][0]['value'];

```

or try to print the $node to figure out how to get it

```
echo '<pre>'; var_dump($node); var_dump($node->field_image_url); die;

```

in your situation try the next to figure out what is happen there

```
<?php
$node_type = "slider_image";
$sql = db_query("SELECT nid FROM node WHERE type = $node_type");
$results = db_query($sql);
foreach($results as $row){
   $node = node_load($row->nid);
   echo $node->field_image_url['und'][0]['value'];
   echo '<br>';
}
?>

```

# Answer
> 1 votes
I would suggest using field\_get\_items or if you are using wonderful entity api module you can use entity\_metadata\_wrapper. Using \['und'\]\[0\]\['value'\] is not a best way to get field values in drupal.

Thank you.

# Answer
> -1 votes
You can use KPR function that comes with devel module. Once you enable the module you could add kpr($fields) function and it show you the structure of data returned by drupal. In general it should be something like $fields-\>field\_image\_url\['und'\]\[0\]\['value'\];

---
Tags: 7, javascript
---


# Question
Title: Can panelizer automatically switch layouts based on a condition?
For a new project I'm starting, Panels+Panelizer seems a very good fit, but I'm still figuring out how to do some advanced things with it.

I like the fact that you can define the default layout and content panes for a certain node type, and allow the editor to override the default panes per node.

In some cases I want the layout and content panes to be dependent on certain conditions. For instance, if the date field on a node is not empty, I want a calendar pane in the right column; otherwise I want a 'related news' pane.

I have read about visibility rules, but the options seem rather limited (eg. there is no "not empty" condition for fields) and it does not allow you to change the layout completely. Which other methods exist make the default layout and content panes depend on certain conditions (other than the node type)?

# Answer
> 0 votes
Although the answers given by Letharion and Sumit Madan did help me understand how panels and panelizer work, I did not manage to solve my problems using access/visibility rules.

Once you enable multiple panelizer displays for a certain node type, you get to choose which display you want to use on the node edit form. It seems that the access rules have no effect after this, because the choice made on the node edit form takes precedence.

I ended up solving this with a `hook_node_validate()` implementation which analyzes the form values to decide which panelizer display must be used to display the node. The correct display is then set on the form like this:

```
form_set_value($form['panelizer']['page_manager']['name'], 'node:news:pressrelease', $form_state);

```

An additional form alter makes sure that editors can no longer edit this setting:

```
/**
 * Implements hook_form_FORM_ID_alter().
 */
function mymodule_form_news_node_form_alter(&$form, &$form_state, $form_id) {
  $form['panelizer']['page_manager']['name']['#disabled'] = TRUE;
  $form['panelizer']['#weight'] = 200;
  $form['panelizer']['page_manager']['name']['#description'] = t('The panelizer display will be chosen automatically, based on the selected News Type.');
}

```

# Answer
> 2 votes
Visibility rules are the way to go.

Granted the built in ones are not always as sophisticated as one might like at times, but on the other hand, `access plugins` are among the easiest to do on your own, allowing you arbitrary conditions.

See What are Ctools plugin (content type, access, etc), and how does one create them? for a example of how to implement one.

It can also be worthwhile checking the Ctools issue queue for a plugin that matches your requirements. Development of Ctools has almost gone away with all the active contributors working on D8 instead, but I have found useful patches in the queue.

# Answer
> 1 votes
To change the layout, you need to add multiple layout under :

```
Admin > Structure > Types > Manage > Content Type > Panelizer > page_manager

```

It will look like :

And you need to create custom access callback plugin as per Letharion's answer.

---
Tags: theming, panels
---


# Question
Title: Custom preprocess_function does not fetch translated value of the content type
* Drupal 7.34 core
* Using custom theme from Themebrain TB Sirate
* Multilingual setup works properly
* Content type has both English and Russian values

**English Language mode:** When open/viewing a node, page-title display content type that is "Article" (English)

**Russian Language mode:** When open/viewing a node, page-title display content type that is "Article" (still English, must be Russian)

Question how to display Russian value of content type.

Here code from preprocess\_funcion.inc of the custom theme

```
/**
 * @file
 * Override of theme_preprocess_...
 */

function tb_sirate_preprocess_html(&$vars) {
  $current_skin = theme_get_setting('skin');
  if (isset($_COOKIE['nucleus_skin'])) {
    $current_skin = $_COOKIE['nucleus_skin'];
  }
  $vars['classes_array'][] = !empty($current_skin) ? (" " . $current_skin . "-skin") : "";
}

/**
 * Override or insert variables into the page template.
 *
 * @param array $vars
 *   An array of variables to pass to the theme template.
 */
function tb_sirate_preprocess_page(&$vars) {
  if (isset($vars['node'])) {
    if ($vars['node']->type != 'page') {
      $result = db_select('node_type', NULL, array('fetch' => PDO::FETCH_ASSOC))
        ->fields('node_type', array('name'))
        ->condition('type', $vars['node']->type)
        ->execute();
      foreach ($result as $item) {
        $vars['title'] = $item['name'];
      }
    }
  }
}

/**
 * Override or insert variables into the node template.
 *
 * @param array $vars
 *   An array of variables to pass to the theme template.
 */
function tb_sirate_preprocess_node(&$vars) {
  $vars['page'] = ($vars['type'] == 'page') ? TRUE : FALSE;
}

It seems to me that problem is here

    function tb_sirate_preprocess_page(&$vars) {
  if (isset($vars['node'])) {
    if ($vars['node']->type != 'page') {
      $result = db_select('node_type', NULL, array('fetch' => PDO::FETCH_ASSOC))
        ->fields('node_type', array('name'))
        ->condition('type', $vars['node']->type)
        ->execute();
      foreach ($result as $item) {
        $vars['title'] = $item['name'];
      }
    }
  }
}

```

What can I do to pull Russian value of the content type from DB?

Thanks in advance for any help!

# Answer
You can confirm this by looking under the "Overview" tab of the translation interface:

If the percentage in the "Node types" for your second language is ("Norwegian Bokmål" in the image above) is 0%, the translated strings for the Node types has not been imported into the translation interface. This means that even after you enable that language, the fallback English strings will be used.

However, it should now be possible to add these translation by hand. Navigate to the translate tab of the translation interface, and limit search to Node types.

The strikethrough over the string with the two letters in the Languages column means that the translation is missing. Click "edit" to add the missing translation.

This exact procedure fixed it for me as can be seen from the "Overview" tab below. The percentage for "Node types" for "Norwegian Bokmål" in now 100%.
> 0 votes

# Answer
Here is the solution. I am glad to have it resolved

http://www.themebrain.com/question/nodes-page-title-does-not-pick-translated-value
> 0 votes

---
Tags: theming, i18n-l10n
---


title: How to organize my content as timeline

text:
# Question
Title: How to organize my content as timeline
I've started learning Drupal a few months ago and I can say that the community is great and that I haven't had the need to ask a question here until now.

I've started to work on a project and I have a problem with one part.

I need to create something like timeline. There is a requirement for a line where the titles of nodes would be listed according to the date of creating, and I need to list some of the fields of those nodes (like text, image...).

The main problem for me is that I have to show the nodes through views because of some additional filters. I've tried a few available modules and they work great, but the problem with them is that they are vertical, and what I need is a horizontal timeline.

I've tried A Simple Timeline and Ajax Timeline module.

Is there maybe some other module that I haven't found and that could be useful for what I need?

Off course, It would be great if someone more experienced could give me some idea from which I could start working.

I just want to mention that I'm using the latest Drupal version (7.34) and I installed the latest version of Views module (3.8).

Thanks in advance.

# Answer
> 0 votes
Welcome to Drupal Answers.

If you want to pay for a module I have recently found a great module that has all the functions you mentioned above. I bought it and I can say that it has amazing settings for timeline and also works through Views.

Take a look at this page.

# Answer
> 1 votes
I did build a fancy timeline using module 'jQuery timelinr integration', which only is a style for Views letting you render your data as a timeline.

Check the library demo : http://www.csslab.cl/ejemplos/timelinr/latest/horizontal.html

Here the full project : http://www.csslab.cl/2011/08/18/jquery-timelinr/

# Answer
> 1 votes
Here is another example. This example is using Views Timeline JS Integration

---
Tags: nodes, views
---


title: Disable the submission of a form

text:
# Question
Title: Disable the submission of a form
I need to make a form read-only under certains conditions : what I did is to not add the `$form['submit']` button.

This way I can't submit the form. But I wonder if it is enough ...

Do you know if I ca be 100% sure that nobody could find a way to submit the form ?

Thanks !

# Answer
You can set #executes\_submit\_callback as FALSE

eg : $form\['submit'\]\['#executes\_submit\_callback'\] = FALSE;

Drupal Document is here
> 1 votes

# Answer
To make sure nobody submit the form create a custom validate function that always set error on form ,(using form\_set\_error).

In that validate function you have to check for the circunstnaces that makes the form available to submission or not.
> 1 votes

---
Tags: forms
---


# Question
Title: In drupal 7 how to group fields of a view?
I have a view to display latest 10 blog pages. 1. I have a title field 2. I have a author field

now I need to group all the titles in one div and all the author in another div.

But views results always have a nested result where respective node's title and author name are together in a same div. Is there any way to separate them?

# Answer
What about making two separate versions of the view: 1 page view with title fields and an attachement with author fields, or 1 page with titles, and the other a block with authors? So you first create a page view with a fields display. When adding fields, you select titles \*and you make sure you set the field for "This page only".

Afterwards, on the top of the view, you select "add attachment". You will have an attachment versin of the view. In this, you add the "title" field. Again, make sure it's "for this attachment only". Now, go to "Attachment settings and select attach to page.
> 0 votes

---
Tags: views
---


# Question
Title: Add user note in CiviCRM on behalf membership page
I have a CiviCRM contribution page form that is :

* on behalf of an organisation (required)
* used for becoming a member

I need to add the possibility for the member to add a comment on the subscription form.

I tried 2 ways that seems not to work because of current limitations :

* adding a custom field for contribution in the profile - doesn't work because of https://issues.civicrm.org/jira/browse/CRM-15787
* adding the note field in the profile - doesn't work because the note displayed in the receipt is not always the one added by the user.

I need a quick way to fix this while those bugs are resolved. My guess is maybe to remove the note from the receipt to avoid problems but how could i do that ?

Any better way of doing this is welcome. webform is excluded because i am using paypal with redirection for now.

# Answer
a PR has been submitted regarding this issue. Please refer here https://github.com/civicrm/civicrm-core/pull/4884

Hope it Helps!
> 1 votes

# Answer
I would do this by using a CiviCRM integrated webform (using the webform CiviCRM integration module) and the CiviCRM contribution page. Use the webform to collect some of the information, including your comments field, and then on submission of that form take the user to the contribution page where they can initiate the transaction. Its less than ideal, but it works.

Work is going on to enable payment processors like Paypal website payments standard to work with webform\_civicrm, but it's not ready yet, so I use this approach whilst awaiting that feature to be launched.
> 1 votes

---
Tags: civicrm
---


title: How to print out bootstrap menu?

text:
# Question
Title: How to print out bootstrap menu?
I am using the Bootstrap module. In the code I can see this:

```
<?php if (!empty($primary_nav) || !empty($secondary_nav) || !empty($page['navigation'])): ?>
      <div class="navbar-collapse collapse">
            <nav role="navigation">
                <?php if (!empty($primary_nav)): ?>
                    <?php print render($primary_nav); ?>
                <?php endif; ?>
                <?php if (!empty($secondary_nav)): ?>
                    <?php print render($secondary_nav); ?>
                <?php endif; ?>
                <?php if (!empty($page['navigation'])): ?>
                    <?php print render($page['navigation']); ?>
                <?php endif; ?>
            </nav>
        </div>
    <?php endif; ?>

```

The problem is, I can't get it to print it for any other menu. For example, i created a menu called "web design menu". I am able to make it appear as follows:

```
print drupal_render(menu_tree_output(menu_tree_all_data('menu-web-design-menu')));

```

However, this doesn't give it the styling of bootstrap or any of the nice bootstrap benefits. How do I render it so that it renders it the same way the above code does. I.e. with all the correct bootstrap styling and executed javascript etc.

# Answer
> 3 votes
In the boostrap theme there is a file

> theme/menu/menu-tree.func.php

This file contains a function

> bootstrap\_menu\_tree\__primary

This function wraps the menu as following:

```
'<ul class="menu nav navbar-nav">' . $variables['tree'] . '</ul>';

```

So you have to give the wrapper of your menu those classes and make sure the structure is exactly the same as the primary menu.

Hope this helps you out.

---
Tags: theming
---


# Question
Title: Is there a possible/safe way to do a sub-request
In Drupal 8 the Symfony HttpKernel Component offers a nice way to make an internal sub-request (forward a request to another page without changing the URL). I'm wondering if there is an ad hoc way to mimic some parts of this idea with existing Drupal 7 APIs.

I have a use case where I need to provide a central path that delivers XML, but for various reasons that XML must be fetched from embedded content on a separate path, that I don't control, but that's also delivered via the Drupal menu system. The specifics of the use case are probably beyond the scope of this specific question, so I won't elaborate too much there. Anyway, I've had some success creating a menu callback that simply calls `menu_execute_active_handler()` internally, and then renders the output. It gets the path to use for the sub-request via a query string. Something like:

```
// The XML we are looking for will be inside a sub-requested page at path
// xml-source-path and inside a <script id="xml-source-id"> block.
$query = drupal_get_query_parameters();
if (isset($query['xml-source-path']) && isset($query['xml-source-id'])) {
  $source = drupal_render_page(menu_execute_active_handler($query['xml-source-path'], FALSE));
  // Search for the XML within the raw sub-request markup.
  $matches = array();
  preg_match('/<script[^>]*id=\"' . $query['xml-source-id'] . '\"[^>]*>(.*)<\/script>/simU', $source, $matches);
  if (!empty($matches[1]) && strpos($matches[1], '<?xml') === 0) {
    $xml = $matches[1];
    // ----- Misc other processing to fetched $xml -----
    // Set headers and directly print result.
    drupal_add_http_header('Content-type', 'application/xml; charset=utf-8');
    print($xml);
  }
}

```

Though this works great for most of my own tests, I'm really not sure if I'm breaking any best practices here, or worse, introducing any security concerns. Since the callback itself is triggered from within a call to menu\_execute\_active\_handler() (in index.php itself) is a recursive call like this potentially problematic? Also, would the fact that I'm accepting the path for sub-request via a query string provide any way for this menu callback to be used for malicious purposes? I really don't think so, but I'd feel much better if I could confirm, or identify a better way.

# Answer
> 0 votes
I do this as following:

```
// We mimic menu_execute_active_handler().
$router_item = menu_get_item($href);
if ($router_item['access']) {
  if ($router_item['include_file']) {
    require_once DRUPAL_ROOT . '/' . $router_item['include_file'];
  }
  $page_callback_result = call_user_func_array($router_item['page_callback'], $router_item['page_arguments']);
}
else {
  // Access denied.
  $page_callback_result = MENU_ACCESS_DENIED;
}

if (is_array($page_callback_result)) {
  // Render array.
  $output .= drupal_render($page_callback_result);
}
elseif (is_string($page_callback_result)) {
  // Render string.
  $output .= $page_callback_result;
}

```

---
Tags: 7, routes, security
---


# Question
Title: Views: Get nodes of last added Node Reference
I'm working on a online magazine in drupal. I have one content type called *issue* with one field, the title field. And I have a content type called *article* the default drupal content type with a *node reference* field linking to issue.

I first make an *issue* called 'issue 01'. Then I start making some articles linked to 'issue 1' via the *node reference* field.

Then I make a second *issue* called 'issue 02'. And make some articles to go with this issue.

Now I want to make a view to show on the homepage showing all articles of the last added *issue* so for 'issue 02'. And when I would add a new *issue* called 'issue 03' the home page should automatically show the articles from this issue.

I'm trying to make this work via the relationship option and the contextual filter option in Views, the relationship is made. And the view is showing all articles. Now I want it to be filtered to showing articles of the last *issue* only so I thought about using the contextual filter but I can't find out a way to get, for instance, the NID of the last added *issue*.

Any help is welcome! Thanks in advance.

# Answer
> 0 votes
Order by the date DESC and restrict the displayed items to 1 through your pager options.

---
Tags: nodes, views
---


# Question
Title: Has 'Administer content' permission always been required to expose publishing, authoring etc options?
I've been using Drupal full-time for over six years and I always thought you could use the \[content type\] create, edit and delete permissions to allow users to create, edit and delete nodes AND use the 'Publishing options', 'Authoring information' etc settings on the node/#/edit page.

Looking at my most recent build today, this is not the case. Additionally, the 'Update options' dropdown and corresponding checkboxes are missing on the admin/content page.

I know there are third party modules like Override Node Options but I'm sure the above was possible.

Additionally, using the 'Administer content' permission is too aggressive because the user can then administer all content types, not just the ones you specify.

Has 'Administer content' permission always been required to expose publishing, authoring etc options? And is there a way around this other than using third-party modules?

# Answer
> 5 votes
This is from `node_form()` in Drupal 7.0:

```
$form['author'] = array(
  '#type' => 'fieldset',
  '#access' => user_access('administer nodes'),
  '#title' => t('Authoring information'),
  '#collapsible' => TRUE,
  '#collapsed' => TRUE,
  '#group' => 'additional_settings',
  '#attributes' => array(
    'class' => array('node-form-author'),
  ),
  '#attached' => array(
    'js' => array(
      drupal_get_path('module', 'node') . '/node.js',
      array(
        'type' => 'setting',
        'data' => array('anonymous' => variable_get('anonymous', t('Anonymous'))),
      ),
    ),
  ),
  '#weight' => 90,
);

```

Note that `#access` is set to `user_access('administer nodes')`. The revision and options fields have the same access set. So yes, it's always been required, at least as of Drupal 7.

You don't necessarily need a 3rd party module, but you'll need at least a custom module to make changes. You can implement `hook_form_alter()` (or `hook_form_FORM_ID_alter()`) to change the `#access` key of the desired elements in a few lines of code.

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


# Question
Title: Attach file to post using C# RestSharp and Drupal Services
I'm writing a C# app that posts to Drupal using Rest calls to the Services module, I can connect and create new nodes easily but I cannot figure out how to attach files to the nodes. Using the RestSharp library for C#, this is the code:

```
var request = new RestRequest("...node/12/attach_file.json", Method.POST);
request.RequestFormat = RestSharp.DataFormat.Json;
request.AddCookie(my_session_name, my_sessid);
request.AddHeader("X-CSRF-Token", restResponse.Data.token);
request.AddParameter("field_name", "field_done");
request.AddFile("file", @"C:\pathtomyfile.png");
var response = client.Execute(request);

```

No errors are returned, status is 200 but the response is empty and nothing is uploaded in Drupal! And by the way the node date looks like modified, so something worked...!

The AddFile method of RestSharp is multipart and so the attach\_file of Drupal:

> Upload and attach file(s) to a node. POST multipart/form-data to node/123/attach\_file

Any help?

# Answer
> 0 votes
I have figured it out this way, sorry for late posting the answer:

```
// FIRST LOGIN
var client = new RestClient("http://....../");
var request = new RestRequest("user/login.json", Method.POST);
request.AddHeader("Content-Type", "x-www-form-urlencoded");
request.AddParameter("username", username);
request.AddParameter("password", password);
var restResponse = client.Execute<Login>(request);

```

Now upload a picture:

```
public string UploadPic(string path, Login login)
{
    var request = new RestRequest("file.json", Method.POST);
    request.RequestFormat = RestSharp.DataFormat.Json;
    request.AddCookie(login.session_name, login.sessid);
    request.AddHeader("X-CSRF-Token", login.token);
    request.AddParameter("uid", login.user.uid);
    string filevalue = System.Convert.ToBase64String(file_get_byte_contents(path));
    request.AddParameter("file", filevalue);
    request.AddParameter("filename", path.Split(new Char[] { '\\', '/' }).Last());
    var response = client.Execute<DFile>(request);

    return response.Data.fid;
}

static byte[] file_get_byte_contents(string fileName)
{
    byte[] sContents;
    if (fileName.ToLower().IndexOf("http:") > -1)
    {
        // URL
        System.Net.WebClient wc = new System.Net.WebClient();
        sContents = wc.DownloadData(fileName);
    }
    else
    {
        // Get file size
        FileInfo fi = new FileInfo(fileName);

        // Disk
        FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read);
        BinaryReader br = new BinaryReader(fs);
        sContents = br.ReadBytes((int)fi.Length);
        br.Close();
        fs.Close();
    }

    return sContents;
}

```

Where the class Login and DFile are the following:

```
public class DFile
{
    public string fid { get; set; }
    public string uid { get; set; }
    public string filename { get; set; }
    public string uri { get; set; }
    public string filemime { get; set; }
    public string filesize { get; set; }
    public string status { get; set; }
    public string timestamp { get; set; }
}
public class Login
{
    public string sessid { get; set; }
    public string session_name { get; set; }
    public string token { get; set; }
    public User user { get; set; }
}

```

---
Tags: files, services, 8, media
---


# Question
Title: How to update a field in Drupal 7 without saving whole node
I wanted to update a field that is not seen by the user, but I would turn off and on (boolean) quite a lot (and for thousands of nodes). I initially used field\_attach, but this had the unhappy effect of removing a file that was also attached to the node (this is a drupal bug).

It took a lot of searching, but I found the solution combining a couple of other peoples snippets. I put it below so hopefully may save someone some time.

For the record: Apparently it is bad practice to edit fields directly like this, however, I really needed to for this use case and I have yet to find any issues. You have been warned!

# Answer
```
function common_update_db($entity_id, $field_name, $value, $clear_cache) {
  foreach (array('data', 'revision') as $table) {
    $result = db_update('field_'.$table.'_'.$field_name)
        ->fields(array(
            $field_name.'_value' => $value,
        ))
        ->condition('entity_id',$entity_id,'=')
        ->execute();
  }
  if ($clear_cache) {
    cache_clear_all("field:node:" . $entity_id, 'cache_field');
  }
}

```

This will update the field and the revision field. If you send clear\_cache = TRUE, it will also clear that nodes cache. This only works for \*_value fields and nodes, but it's easy to modify.

**Examples:**

```
common_update_db(1234, field_run_cron, 1, TRUE);

```

on node 1234, set field\_run\_cron value to 1 and clear the cache for immediate visible effect to the user.

```
common_update_db(1234, field_run_cron, 0, FALSE);

```

on node 1234, set field\_run\_cron value to 0, don't clear cache as the user doesn't see this field anyway.
> 2 votes

---
Tags: 7, database
---


# Question
Title: Simple drop-down "list" items (inside a html "body") --- content (un)hiding upon click --- Not a navigation bar, no redirect, no menu, no forms
I would like to ask if it were possible to have certain content (nothing too special, just regular lines of text with standard formatting) on a html article, like e.g. ordered in a list, which can be **unfolded (or hidden again) by a mouse-click**?

When searching information on this, I easily come by navigation drop-down menu's; but a navigation side-bar or top-bar is ***not*** what I am looking for. I have found another question asking for something similar, but wanting to be redericted to another page (similar to a navigation menu), that is also ***not*** what I want to do: I do ***not*** want to navigate to another page.

I would simply like a drop-down "list" **inside a html's "body" article**. The visitor should be able to open or close these "frames" or "list items", e.g. by clicking on the title or on a list button. I am just looking for a "1-level-depth" list.

It would be nice if the items had a title and a number, ordered vertically, like a regular ordered list:

1. ***\>click to unfold\<*** List item 1
2. ***\>click to unfold\<*** List item 2
3. ***\>click to unfold\<*** ...

If, for example you would click on list item 1, the content of list item 1 would show:

1. ***\>clicked, click to hide content again\<*** List item 1
*\<\<\< Content of list item 1, which is just standard lines of text, perhaps with standart formatting. \>\>\>*
2. ***\>click to (un)fold\<*** List item 2
3. ***\>click to (un)fold\<*** ...

The text I have put between **"\>"..."\<"**, is just to clarify; isn't specifically needed. This could just be a triangular list bullet for example, which could just change by pointing downwards when clicked.

Is this possible by using a Drupal module, or perhaps just via html code?

Any help on this would be greatly appreciated,

Vincent Verheyen.

P.S.: I am very new to Drupal and understand the basics such as installing modules.

# Answer
> 1 votes
@Wtower's help above makes this pretty straightforward. Drupal (I am using 7) can use these jQuery codes without any additional install.

One can just put the following right inside a drupal "node", such as a standard article. This solution works for list items; the following is to be implemented \[I used ordered lists (ol) in my example\]:

```
<style>#toggler li:hover {text-decoration: underline; cursor: default}</style>
<script type="text/javascript">jQuery(document).ready(function(){jQuery("#toggler li").click(function(){jQuery(this).next().slideToggle("slow"); return false;}).next().hide();});</script>

    <ol id="toggler">
    <li>List tem 1.</li>
    <div>Content of list item 1.</div>
    <li>List item 2.</li>
    <div>Content of list item 2.</div>
    </ol>

```

---

I haven't looked at triangular (changing upon revealing or hiding content) list bullets yet.

If you want other items than list items, look here:

# Answer
> 1 votes
I think you can acheive what you want with the https://www.drupal.org/project/field\_group module. Enable to module and go to you content type, add the different groups you want to collapse/expand and add one or more fields inside.

You can change how you want to users to see the fields groups.

# Answer
> 1 votes
Another possibility just for the record (more intermediate approach) would be to organize the collapsible content into nodes, then use Views in order to present the relevant nodes in a page.

Then you can either:

so that the views rows be collapsible.

---
Tags: theming
---


# Question
Title: Page Title outputting leading/trailing whitespace within H1
My Drupal 7 site is printing out leading and trailing whitespace and a line break within the page title `<h1>`. The following is an exact copy and paste of the HTML that's being delivered to the browser:

```
<h1 class="title" id="page-title">
                I am a Page Title               </h1>

```

Not too big of a deal as most browsers know to ignore whitespace... except Chrome for Windows... where it's making the last word in the page title wrap to the next line (I confirmed this by deleting the whitespace in Chrome's web inspector):

Why is it doing that? Is there a fix? I can think of a handful of ways to trim the the whitespace using Javascript (can it be done with CSS?), but I'd rather fix it at the source.

# Answer
> 0 votes
In the `page.tpl.php` file, the page title bit looks like this:

```
            <h1 class="title" id="page-title">
                <?php print $title; ?>
            </h1>

```

Simply removing the trailing/leading whitespace (tabs and new lines) from the code, did the trick:

```
            <h1 class="title" id="page-title"><?php print $title; ?></h1>

```

---

(*Thanks to @sareed and @slawrence10 for the comments that jogged my memory as to how to deal with this!*)

---
Tags: theming, 7
---


title: Images in CKEditor don't retain size

text:
# Question
Title: Images in CKEditor don't retain size
I can't seem to figure out how to retain image sizes in CKEditor. When an image is sized, and the content is saved, and then edited again, I want the size to stay the same as set originally.

Is there a way to configure this? If not, I can write JavaScript, so is there an implementation I could approach?

# Answer
I was able to do this with the Picture module:

> The proposed HTML "picture" element (see responsiveimages.org, but has not been accepted for HTML 5) is implemented as a display formatter for image fields. This module is a backport of Drupal 8 picture module. This module will deliver alternate image sources based on device capabilities to prevent wasted bandwidth and optimize display for both screen and print.
> -1 votes

# Answer
You are looking for Insert module, using this module you can retain the sizes with the help of image cache.

> Insert is a utility that makes inserting images and links to files into text areas or WYSIWYGs much easier. It adds a simple JavaScript-based button to FileField and ImageField widgets. When used with ImageField and ImageCache, images may be inserted into text areas with a specific ImageCache preset.

* Support for all major WYSIWYG editors, including tinyMCE, **CKeditor**, the WYSIWYG project (the recommended approach), and plain text areas.
* Insert images using ImageCache presets
* Maximum width setting for inserted images (for combined use with the Image Resize Filter module)
* Per-field insert configuration
> 2 votes

# Answer
Look if you have the filter "Limit allowed HTML tags" in your text format, i had the same problem and i fixed it unchecking this field.
> 2 votes

---
Tags: 7, media, wysiwyg
---


# Question
Title: Responsive Grid in Drupal 7 Views with 5 columns
I'm trying to build a responsive Views grid in Drupal 7 and bootstrap3 sub-theme. On Views I am using the Responsive Grid module as format.

In my Views format settings I configured the grid to 5 columns.

In order to support 5 columns in bootstrap I made an addition to my less file, according to this article: https://stackoverflow.com/questions/10387740/five-equal-columns-in-twitter-bootstrap in the answer given by lightswitch05.

My HTML markup created by Views would look like this

```
<div class="row">
    <div class="col-xs-6 col-sm-4 col-md-2-4">...</div>
    <div class="col-xs-6 col-sm-4 col-md-2-4">...</div>
    <div class="col-xs-6 col-sm-4 col-md-2-4">...</div>
    <div class="col-xs-6 col-sm-4 col-md-2-4">...</div>
    <div class="col-xs-6 col-sm-4 col-md-2-4">...</div>
</div>

```

It all works just fine for the 5 column grid in Medium devices Desktops (≥992px) using the col-md-2-4 class.

The problem is for Small devices Tablets (≥768px) using col-sm-4 and Extra small devices Phones (\<768px) using col-xs-6.

Since class "row" is already wrapping 5 elements when trying to display 3 or 2 grid columns there is either 2 or 1 element out of the grid row.

**So the question is:** Is it possible to create a responsive grid with 5 column grid for col-md, a 3 column grid for col-sm and 2 column grid for col-xs, in Drupal 7 Views ?

# Answer
> 3 votes
I think i figured it out.

If I set columns to 1 then I can use any responsive number of bootstrap columns according to the width.

---
Tags: views, theming
---


# Question
Title: Best way of translating fixed text in Drupal 7
I am using `t()` with context to translate strings for a multilingual site. I would need a user to translate all language strings, but she/he does not need to know Drupal, just will feel an Excel. The problem is that I must provide the original string, the context, and the URL where it appears, and I do not know how to extract them from the database, as the string is stored as a BLOB. I am using this trick of function but still do not get the URL. Any help will be appreciated.

In the function I am copying and pasting all t() ocurrences that I have added in modules, template.php, etc.

```
function My_Module_list_translations(){
    $translation[] = t2('All', array(), array('context' => 'listado_sabias'));
    $translation[] = t2('Write one or more words', array(), array('context' => 'formulario_noticias'));
    $translation[] = t2('CATALOGUE', array(), array('context' => 'menu-personalizado'));

    echo "<table border='1'>";
    foreach($traduccion as $value){
        echo '<tr><td>' . $value["contexto"] . '</td><td>' .  $value["es"]  . '</td><td>' .  $value["en"]  . '</td></tr>';
    } // foreach
    echo "</table>";
} // function

function t2($string, $empty, $context){
    $array_dev["contexto"] = $context["context"];
    $array_dev["es"] =  t($string, array(), array('context' => $context["context"] , 'langcode' => 'es'        ));
    $array_dev["en"] =  t($string, array(), array('context' => $context["context"] , 'langcode' => 'en'
       ));
    return $array_dev;
} // function

```

# Answer
> 1 votes
I would recommend looking at the String Overrides Advanced module it allows your Users to search for strings to translate into other languages using a friendly table, which it looks like you're trying to make yourself.

You're providing `context` here but the context you provide is not really the purpose of `context`. Context should describe the context of the string or word to help in the translation (not simply the place on the website the string shows up -- which is largely meaningless). An example of a context is: https://api.drupal.org/comment/44448#comment-44448

which shows "Order" is a `verb` and not to be confused with a Noun for "drupal Commerce Order".

Note: I speak and write English and Spanish, when you write PHP code your php code should be in 1 language and not a mix of languages to be clear to developer(s) what you're code says. You shouldn't need to be bilingual to work on a piece of code. It makes your code needlessly complicated.

---
Tags: i18n-l10n
---


title: Hiding full node display and URL

text:
# Question
Title: Hiding full node display and URL
This is very similar to How do I hide nodes that shouldn't be directly accessed from users and search engines?

I would like to:

* Not have certain nodes be directly accessible at the full URL (ie. at node/1234 or its alias), since they're being used in a view
* Make sure they're not being indexed in search engines

My questions are:

* Does marking a node as "unpublished" have any side effects? other than viewing the node (assuming you're an admin) and seeing the node as unpublished
* Marking a node as published yields a 401 when its viewed (at its full URL) by anonymous users. Does the page still get crawled? Is there a way to redirect the 401 and not get hurt from a SEO perspective?

EDIT: Using Drupal 7.

Thanks!

# Answer
Not publishing the node means that you can't have works in progress, or you need another way to mark them as not ready for the website. I see this as a definite disadvantage.

Do you mean 403 or 404 instead of 401? If the page results in a 404 then it won't be crawled or indexed. Google has no way to distinguish the "invisible node" case from a plain old bad URL. A 401 should only happen in an authorization case. A 403 may result in a page being revisted at a later date. You never want to redirect from one of these, as this requires a 301 or a 302.

For another way to do this on a legacy project, you can set the path alias to

```
no-view/[nid]

```

and then use

```
function MYMODULE_init ()
{
    $path = drupal_get_path_alias(request_uri());

    if (strpos($path, "no-view/") !== false) {
        drupal_not_found();
        exit;
    }
}

```

in a custom module. You can wire in similar functionality via the Node API if you want to avoid adding a hook\_init().

Moving forward, using entities as suggested by @nicoz is the best idea.
> 1 votes

# Answer
One of the biggest changes at the architecture level of Drupal 7 is the introduction of entities as an abstraction for content. The old days of trying to cram everything in nodes is over. In short, you get all of the convenience of nodes without the overhead and unnecessary code (and in your case, the architectural challenge of "hiding" nodes from users, crawlers).

Drupal Commerce uses them for products. This allows the products themselves to be inaccessible to end users, but attached to the product displays and views for the end user to see and purchase.

Utilize the Entity Construction Kit (ECK). It will give you a nice UI to create your entities and then just use views to display them for the end-user.
> 3 votes

# Answer
The Internal Nodes module should do exactly what you want, though I have not tested it myself.

My only issue with it is that you cannot edit the nodes you hide, but that is being worked on (Allow users to edit/delete nodes they cannot view)
> 1 votes

# Answer
If you are not linking to those nodes anywhere on your site then search engines shouldn't even find them.

A more robust approach would be Berdir's suggestion of using hook\_node\_access.
> 0 votes

# Answer
The Rabbit Hole module is awesome for this, you can hide nodes being accessible or re-direct them to a different landing page once. You can choose 'admin' roles to access them normally, and everyone else subject to that generic rule per content type, but also change this on a node by node basis.
> 0 votes

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


# Question
Title: db_query unknown column on where clause?
I am getting this error:

> PDOException: SQLSTATE\[42S22\]: Column not found: 1054 Unknown column 'Weddings' in 'where clause': SELECT id from galleries\_types WHERE name="Weddings"; Array ( ) in catering\_gallery\_add\_image\_submit() (line 195

Why does it think 'weddings' is a column? It clearly is `where name='Weddings'`. What's up with the blank array on the end?

This is the code I am using.

```
$a = db_query('SELECT id from galleries_types WHERE name="'.$form_state['values']['id'].'"');

```

# Answer
> 2 votes
If you're new to Drupal or PHP coding, you've created a nice example of how *not to write an sql query*. What you've written is open to SQL-Injection.

Please review the Database API Examples Documentation page.

A "correct" way to write this query using the API could look like (adapting 1 of the top examples to your code) the following.

```
$result = db_query("SELECT id from {galleries_types} WHERE name = :name", array(':name' => $form_state['values']['id']));

```

You will want to make use of placeholders in PDO to write your queries.

---
Tags: database
---


# Question
Title: $page parameter doesn't appear to contain all the information used to render a page
I'm using hook\_menu to build a series (100+) of pages where the code uses a basic page "master template" and replaces strings in the "master template" node with elements of the URL that reaches the Drupal menu page callback routine.

Once the appropriate strings are replaced, the page callback routine uses node\_view() to create the render array, and returns it for further processing and transmission to the client.

The "master template" page is at URL mysite/whatever-string. The problem is that Drupal sticks whatever-string into the page the client receives, and it looks like this:

```
<div class="content">
    <div id="node-1196" class="node node-page contextual-links-region clearfix"
         about="/whatever-string" typeof="foaf:Document">

        <h2 class="title"> <a href="/whatever-string"></a>
        </h2>
        ....

```

I'm using dd($var, 'description') to look at data structures and elements as a debugging tool. From the callback routine, dumping the unprocessed and processed "master template" node and the render array returned by node\_view() and searching for whatever-string returns no results. The string isn't there. Thinking that perhaps the render array produced by node\_view() didn't have all of the elements that the page contained, I implemented hook\_page\_alter($page) to see if the render array that it gets as a parameter might contain the string. It doesn't. Is there some other hook that's available to a module which will have *everything* that goes into rendering the page ?

As a last resort, I'm sure I can work around this by writing theme/template code to wander through the html (or DOM) and make the changes needed. I've done this a lot before, but I think it's cleaner (and marginally more efficient) to do it all when the page is generated, rather than looking at all the nodes that get rendered to see if it's a generated one, and make the changes to the HTML directly.

# Answer
> 0 votes
I would suggest using hook\_preprocess\_HOOK. In this instance I think hook\_preprocess\_node is what you want but \_page may work as well.

# Answer
> 0 votes
Unfortunately when we try to subvert the Drupal workflow in favor of 'marginally more efficient' cpu/resource utilization, we will constantly run into this kind of problem. ;)

Drupal wants you to override the 'node' template in this case. It sounds like you may already be aware of this.

You may be able to limit the effect of this template override if all your 'interesting' nodes share a content type/s. In which case, you may add a template suggestion to your theme's 'template.php';

```
function THEME_preprocess_page(&$vars, $hook) {
  if (isset($vars['node']->type) && $vars['node']->type === 'my_interesting_type') {
    $vars['theme_hook_suggestions'][] = 'page__' . $vars['node']->type;
  }
}

```

More info on this template suggestion workflow; https://www.drupal.org/node/1089656

---
Tags: 7, theming
---


title: Metatag for each content

text:
# Question
Title: Metatag for each content
I ve used MetaTag module to change the tags in my node . but this changes me to all nodes. I want different tags for different nodes Is there any possiblities to do so?

# Answer
Maybe I'm not understanding your question. You can globally change all metatag information at /admin/config/search/metatags. To change the meta information on a per-node basis, edit the node and click on the Meta Tags tab at the bottom. You can then update the meta information for that specific node:
> 0 votes

# Answer
You can use Meta tags quick module. On every single page you will see link to change meta info for that page.
> 0 votes

---
Tags: 7
---


# Question
Title: Two Body/text areas for a multilingual site
When creating a new node, I want 2 body text areas, each one for one language (one in English, and one in German ).

How can I have 2 body areas when create a node?

# Answer
Edit the content type that you are using or create a new one and add another field to it.
> 0 votes

---
Tags: i18n-l10n
---


# Question
Title: Form submit with radio in table has data in form_state['input'] and not in form_state['values']
While developing a form for Drupal 7, I need a few radio groups, placed inside a table (one radio group per table row). The radios are defined as `'#type' => 'radio'` (not radios) and grouped together using the same name attribute per group. Nevertheless, when the form is submitted, the radio selections are not in the `$form_state['values']` array, but in `$form_state['input']`.

As you can see from the screenshots, all data is stored in `input`, with the radios being outside the `'undefined'` array, even though I placed them in `$form['undefined'][$key][x]`. In `values` only the select and textfield data is retained.

Any ideas? It's been two days now that I'm trying to resolve this :( Thank you in advance.

```
function game_insert_form($form, &$form_state) {
  dpm($form_state, 'form_state');

  $test_data = array(
    '2' => 'Alfa',
    '4' => 'Beta',
    '6' => 'Gamma',
    '8' => 'Delta',
  );

  $header = array(
      t('Name'),
      array('data' => t('Existing'), 'colspan' => 2),
      array('data' => t('New'), 'colspan' => 2),
  );
  $form['undefined'] = array(
      '#tree' => TRUE,
      '#theme' => 'table',
      '#header' => $header,
      '#rows' => array(),
  );
  foreach ($test_data as $key => $data) {
    // Label
    $label = array('#markup' => $data);
    $children = array(&$label);
    $row = array(array('data' => &$label));
    unset($label);
    // radio 0
    $radio0 = array(
      '#type' => 'radio',
      '#return_value' => 0,
      '#value' => 0,
      '#name' => 'undefined-' . $key . '-radio',
    );
    $children['radio0'] = &$radio0;
    $row[] = array('data' => &$radio0);
    // dropdown
    $select = array(
      '#type' => 'select',
      '#options' => array(0 => 'Zero', 1 => 'One'),
      /*'#states' => array(
        'enabled' => array(
          ':input[name="undefined-' . $key . '-radio"]' => array('value' => 0),
        ),
        'required' => array(
          ':input[name="undefined-' . $key . '-radio"]' => array('value' => 0),
        ),
      ),*/
    );
    $children['select'] = &$select;
    $row[] = array('data' => &$select);
    // radio 1
    $radio1 = array(
      '#type' => 'radio',
      '#return_value' => 1,
      '#value' => 0,
      '#name' => 'undefined-' . $key . '-radio',
    );
    $children['radio1'] = &$radio1;
    $row[] = array('data' => &$radio1);
    // textfield
    $textfield = array(
      '#type' => 'textfield',
      '#maxlength' => 40,
      '#size'=> 40,
    );
    $children['textfield'] = &$textfield;
    $row[] = array('data' => &$textfield);

    $form['undefined'][$key] = $children;
    $form['undefined']['#rows'][] = $row;
    unset($radio0);
    unset($select);
    unset($radio1);
    unset($textfield);
  }
  $form['next'] = array(
    '#type' => 'submit',
    '#value' => t('Test'),
    '#weight' => 0,
    '#name' => 'test',
  );
  return $form;
}

function game_insert_form_submit($form, &$form_state) {
  dpm($form_state, 'submit: form_state');
}

```

# Answer
> 3 votes
At last I managed to find the answer (after **a lot** of experimentation). The following code works fine for me. I am not sure if everything is needed, but I won't touch it as long as it works.

* Pay attetion that I use an associative array for the `#rows` array, in order to be able to find the correct row without keeping track of indexes.
* The most bizzare part is that I had to add `$form[$key]['#type'] = 'value';` to hold the selected value.
* The `'#name' => $key,` is obviously used to group the radios together per row.
* The `'#id' => drupal_html_id($key . '[' . $item . ']'),` was also added, but I'm not sure if it's needed.

Obviously one does not need to use a seperate column for the label, but I display it this way because in my code I use drop downs and other controls instead of the labels shown here.

Here is the code:

```
function game_test_form($form, &$form_state) {
  dpm($form_state, 'form_state');
  $test_data = array(
    'alfa' => array(1, 2, 3),
    'beta' => array(1, 2, 3),
  );
  $header = array(
      t('Name'),
      array('data' => t('First'), 'colspan' => 2),
      array('data' => t('Second'), 'colspan' => 2),
      array('data' => t('Third'), 'colspan' => 2),
  );
  $form['undefined'] = array(
    '#tree' => TRUE,
    '#theme' => 'table',
    '#header' => $header,
    '#rows' => array(
      // The keys here are used later on for the correct #row insertion
      'alfa' => array('title' => t('Alfa')),
      'beta' => array('title' => t('Beta')),
    ),
    '#prefix' => '<div id="game_update_table">',
    '#suffix' => '</div>',
  );
  $table = &$form['undefined'];
  foreach ($test_data as $key => $data) {
    // This stores the value in the $form_state['values']. It must be outside the table.
    $form[$key]['#type'] = 'value';
    foreach($data as $item) {
      $element = array(
        '#type' => 'radio',
        // this value will be assigned to the $form_state['values'][$key]
        '#return_value' => $item,
        '#default_value' => isset($form_state['values'][$key]) ? $form_state['values'][$key] : 0,
        // Radio group stored in input[#name] with the selected radio's #return_value as value
        '#name' => $key,
        '#id' => drupal_html_id($key . '[' . $item . ']'),
      );
      // Attach the radio to the logical tree, so as to be included in $form_state['values']
      $table[$key][$item] = &$element;
      // Attach the radio to the render tree, so as to be rendered.
      $table['#rows'][$key][] = array('data' => &$element);
      unset($element);
      // Attach its label to the render tree, so as to be rendered.
      $table['#rows'][$key][] = array('data' => array('#markup' => 'Label ' . $item));
    }
  }
  $form['next'] = array(
    '#type' => 'submit',
    '#value' => t('Test'),
    '#weight' => 0,
    '#name' => 'test',
  );
  return $form;
}
function game_test_form_submit($form, &$form_state) {
  dpm($form_state, 'submit: form_state');
  $form_state['rebuild'] = TRUE;
}

```

---
Tags: forms
---


# Question
Title: CKeditor not working for users only in forums
I Installed CKeditor in drupal 7, and all works fine, except in the forums. If I enter as an administrator, there CKeditor works just fine (in the administrator overlay) but if I log as a standard user CKeditor works in all areas but the forums, where I get the following error: TypeError: $(...).get(...) is undefined as in the following line of code: $("#node-form").get(0).setAttribute('action', '/?q=node/add/forum/0&29e0\_name=0a'+v+'8f52a260a1342d3127\_form');

I'm out of ideas and the solutions offered here are usually for CK editor not working in general, but here the frustration is that it only doesn't work in the forums section and only for standard users.

thanks in advance

# Answer
This looks like a javascript error. Have you tried installing the `jquery_update` module and evaluating what javascript libraries or drupal modules making use of Javascript are installed on the website and looking for conflicts between the modules.

What javascript file is producing the error. Using Chrome Developer Tools or Firebug for firefox and looking at the Console will give you the filename.
> 0 votes

---
Tags: wysiwyg
---


title: Add conditions on Where in Views 3

text:
# Question
Title: Add conditions on Where in Views 3
How can I do to add more conditions on WHERE, like this WHERE view conditions ... **AND ( (sentence 1 AND sentence 2) or (sentence 3 AND sentence 4) or ... )** This view is in a user profile and this conditions depens on profile data.

Thanks

# Answer
> 0 votes
I guess the option you need is in the "Filter Criteria" section, in the dropdown next to the "Add" button. If you fold down that menu you will see the "And/Or, Rearrange" option in which you can create sets of conditions.

---
Tags: views
---


# Question
Title: move $messages div to inside the form tag
I would like to move the $messages div for any webform type away from a div but instead add it inside the tag. I've started with THEME\_preprocess\_page(&$variables) in my template.php but I am stuck because the $variables doesnt set which element (or id/classes) the $messages should be placed in. Any suggestions/help would be appreciated. Thanks!

# Answer
> 0 votes
Copy your webform-form.tpl.php from the contrib webform module folder (under templates) to your themes templates folder and make the modifications there.

Default code:

```
if (isset($form['preview_message'])) {
  print '<div class="messages warning">';
  print drupal_render($form['preview_message']);
  print '</div>';
}

```

---
Tags: webforms
---


title: What is proper way to update D8 DEV?

text:
# Question
Title: What is proper way to update D8 DEV?
I'm not having any luck with Drush (just hangs) to update a (non-production) D8 site, dev branch (from around beta2) to Head. How would one manually update the files db/config?

# Answer
Use documentation provided by Drupal on THIS link. I'm did core upgrade by following steps from this document.
> 0 votes

# Answer
The proper way is "not".

Upgrade path is not supported and not possible.
> 3 votes

---
Tags: 8
---


# Question
Title: How to group all custom modules under one menu using hook_menu?
I just started learning drupal 7 module development. I wanted to group all my custom modules under one category (say custom). I know how to **manually** do that using **"admin/structure/menu/manage/management"**. But is it possible to create a new group and put all my module menus under that group using hook\_menu ?

**For Example :**

```
  function hook_menu() {
  $items['admin/settings/custom/module-name'] = array(
  //other code here
  );
}

```

The above code doesn't create the "custom" menu item instead it creates "module-name" menu. I want to put "module-name" under "custom" ?

# Answer
> 3 votes
Thanks to kalabro for the answer. For those who are new to module development and need the same functionality, I've posted the code below :

```
  function hook_menu() {
  $items['admin/settings/custom'] = array();
  $items['admin/settings/custom/module-name'] = array(
  //other code here
  );
}

```

You can use the **"$items\['admin/settings/custom'\] = array();"** in a separate module also.

**Note :** Be sure to flush the cache. Sometimes you might need to disable and then enable the modules again for this to work...

# Answer
> 2 votes
The answer by Sharan didn't work with the current Drupal 7.34. An empty array will not create a new group, even after disabling and uninstalling and re-enabling the module and flushing caches and so on...

I did some research and found a way that works quite well. It will create an new item (with subitems) in the **'Management' menu**, that has it's own (translatable) title and description. When the group itself is opened in a browser (**'admin/config/custom'** in the example), it will show an **overview page** that lists all the subitems with descriptions. It also integrates as expected with the menu bar from the **admin\_menu module**.

```
function hook_menu() {
  // The new group
  $items['admin/config/custom'] = array(
    'title' => 'Custom settings',
    'description' => 'All the custom settings.',
    // 'position' and 'weight' can be used to place
    // the group in the the parent overview (admin/config).
    'position' => 'right',
    'weight' => -20,
    'access arguments' => array('access administration pages'),
    // This renders the group overview.
    'page callback' => 'system_admin_menu_block_page',
    // 'file' and 'file path' are required for the
    // 'system_admin_menu_block_page' callback.
    'file' => 'system.admin.inc',
    'file path' => drupal_get_path('module','system'),
  );
  // A subitem in the group
  $items['admin/config/custom/module-name'] = array(
    //other code here
  );
}

```

**EDIT:** A cache flush should be enough to enable the group.

---
Tags: 7, routes
---


# Question
Title: How to include Facebook feeds inside my page?
I want to include Facebook feeds from my Facebook page to my Drupal site as a block. How to do that?

# Answer
Go to the Facebook Developers site and configure the kind of feed you would like to have. Save the generated the HTML somewhere.

Create a new block in your Drupal installation with the Full HTML text format. Paste the generated HTML in your the content part of your block.

If you do not want to use the default Facebook feed, take a look at this drupal module.
> 3 votes

# Answer
You can also go with TB Social Feed
> 0 votes

---
Tags: social-network
---


# Question
Title: Trim whitespace from Float fields before validation
I have a content type with a Float field. When my users accidentally enter (or copy/paste) a value with trailing whitespace (e.g. "11 "), drupal gives them the ugly error message:

> Only numbers and the decimal separator (.) allowed in Weight.

But this should be a very easy thing to solve and is not something to bother the user with. However, I can't seem to figure out how to interject code from my module at the right place in order to `trim()` the value before drupal does its field validation.

Help?

# Answer
> 2 votes
Add the following to a custom module:

```
function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
  //dpm($form_id);
  if ($form_id == 'BUNDLE_NAME_node_form'){
    $language_float = $form['MACHINE_NAME_FIELD']['#language'];
    $form['MACHINE_NAME_FIELD'][$language_float]['#after_build'][] = 'MYMODULE_field_float_rectify';
  }
}

function MYMODULE_field_float_rectify($element, &$form_state) {
  $children = element_children($element);
  foreach($children as $child){
    $element[$child]['value']['#value'] = trim($element[$child]['value']['#value']);
  }
  return $element;
}

```

I would think you can also add it to your admin theme's template.php file, but it seems to be more appropriate to add it to a module.

---
Tags: 7, entities
---


# Question
Title: how do I control order of promoted pages?
I have a bunch of pages I have promoted to the front page and I'm wondering how I can control the order the items appear in? This is in Drupal 7.

# Answer
> 2 votes
There is a tutorial at Custom re-ordered front page teasers. It uses the pre-packaged view `Front page` that comes with Views, as well as the Nodequeue module to re-order the teasers.

> The Nodequeue module allows users to collect nodes in an arbitrarily ordered list. The order in the list can be used for a any purpose

# Answer
> 2 votes
Another possible solution is the draggable views module.

You can set up a view of promoted content ordered by the draggable views weight and then add another display to the view for reordering.

There is more detailed information on how to set this up on the draggable views documentation page.

With this you get a little contextual link on your view that will take you to the reordering page, where you can drag and drop your list of content to reorder, than save that order.

It's quite a nice user experience for reordering lists.

# Answer
> 0 votes
It can be achieved by just changing the **Authored on** date & time. Works very well!

---
Tags: nodes
---


# Question
Title: Theming a menu - removing a whitespace between the last <li> and <ul>
I want to alter the HTML of the main menu. I have a manu set up with text-align: justify.
Now in Chrome, the whitespace between the last `li` and `ul` is rendered as 4px, making the last item not aligned to the right margin. See this stackexchange post. I want to remove the whitespace or replace it with and html comment.
I am a bit lost ;-). What should I be overriding? `theme_menu_tree`?
I am using the Omega 3.

# Answer
> 1 votes
Because it sounds like your question is really about how to manipulate the main menu markup in Omega, I guess I'll focus on that. That said however, the "whitespace" issue from the post that you reference is quit strange, as I'm not sure I understand how a newline between an closing `li` and `ul` tag would influence any visible alignment behavior. I'm also not sure that Omega even adds any such newlines to the menu output by default. Still, it sounds like you've isolated this as a cause already.

If you are using the main menu that's automatically inserted within the page by Omega (as opposed to displaying your main menu via a menu block or similar), then I believe the most specific theme hook that applies is 'links\__system\_main\_menu'. Check out the omega/omega/templates/region--menu.tpl.php theme file to see how this is ultimately called.

It's important to note however that 'links\__system\_main\_menu' is not necessarily a hook that you'll find an existing theme function for, it's just a suggested pattern. See this post for more on that. Chances are the theme function that's actually getting used currently is `theme_links()`, or in the case of Omega (which already has an override setup) `omega_links()`.

So if you want to target an override that's *specific* to just the main menu you could use the code from `omega_links()` as a template for your own override called `MYTHEMENAME_links__system_main_menu()`. Then within this new function you could adjust the output to tweak the way "whitespace" is added before and after any `ul` and `li` tags as you deem necessary.

---
Tags: theming, routes
---


# Question
Title: Is there an anti-spam advantage of using reCAPTCHA module instead of just CAPTCHA by itself?
What is the advantage of using the reCAPTCHA module over the plain old CAPTCHA module?

Are spam bots less likely likely to beat reCAPTCHA?

Thanks

# Answer
The biggest advantages of using reCaptcha is the built in support for people who are visually impaired and the ability to evolve without your intervention. ReCaptcha continuously changes to fight of spam bots.
> 1 votes

---
Tags: 7
---


# Question
Title: Is there a way to manage a vocabulary with drag&drop when there are more than 100 terms?
In Drupal 7, out of the box, it looks like the manage vocabulary page at `/admin/structure/taxonomy/myvocabulary` handles 100 terms. My vocabulary has about 500 terms, and I'd like to rearrange it into a parent and child structure. Ideally, I'd like to get it all on one page to manage; is there a way to do this?

Otherwise, how am I supposed to reorganise a vocabulary spread out over 4-5 admin screens?

# Answer
> 1 votes
Have you looked at taxonomy manager?

https://www.drupal.org/project/taxonomy\_manager

---
Tags: taxonomy-terms
---


# Question
Title: How to get teaser break to work with WYSIWYG + CKEDITOR?
I have Drupal 7.7 + WYSIWYG 7.x-2.1 + CKEDITOR 3.6.1 installed.

My goal is to be able to insert a teaser break into my blog posts (blog post content type - body field), in order to specify what goes into the teaser and what goes into the full node view.

When I click the "Separate the teaser and body of this content" button in the CK EDITOR menu bar, the text `<!--break-->` is automatically inserted into my body field. However, this break is not having any effect on the text that remains in the teaser view vs. on the full node view. It simply doesn't seem to be working. I tried using TinyMCE and I had the same problem

Can anybody please advise on how can I get this function working?

Thanks!

---More details about my current setup: ----------------

In the CK editor profile for "Filtered HTML" - in the "CLEANUP AND OUTPUT OPTIONS", the following options are enabled: \- Verify HTML \- Convert tags to styles \- Remove linebreaks

These options are not enabled: \- Preformatted \- Apply source formatting \- Force cleanup on standard paste

# Answer
Switch to Full HTML. I don't believe Teaser Breaks are allowed in Filtered HTML.

More info in link http://old.nabble.com/Wysiwyg-Frustrations%3A-My-Approach%2C-What-is-Yours-to31984379.html#a31984379
> 0 votes

# Answer
Adding `<!-->` to the set of allowed HTML tags for the Filtered HTML format solved this problem for me. To do so, these are the steps to be performed:

* Navigate to `admin/config/content/formats/filtered_html`.
* Within "Filter settings", select the "Limit allowed HTML tags".
* Within the field with label "Allowed HTML tags", add the string `<!-->` (in addition to whatever set of HTML tags you already have).
* Save configuration.
> 6 votes

# Answer
Have you considered just putting your desired teaser into the Summary (under Edit Summary) instead? It may be a more convenient workaround than trying to set up the Teaser Break.
> 1 votes

# Answer
Apply the patch at http://drupal.org/node/881006#comment-5628078. This makes sure the `<!--break-->` comment is not stripped out along with any other comments.

*Aside(?):* I'm using Display Suite and I found my teasers weren't working, even with this patch applied and the break comment in my HTML. I solved this by enabling a custom display for Teaser, and then choosing "Summary or trimmed" as the format at admin/structure/types/manage/page/display/teaser.
> 0 votes

# Answer
I know this is an old question but thought I'd share this anyway. I ran into the same problem but managed to solve it with a module called "Smart Trim"

I had a view display fields and I couldn't get the summary or trimmed values of my node body field to display, but with this module it gives me another display option which seems to work perfectly.
> 0 votes

---
Tags: 7, wysiwyg
---


title: Building taxonomy Selector

text:
# Question
Title: Building taxonomy Selector
I'm building a classified website, on which users can create ads using the custom content type I've created. Each ad has a `category` field which a reference to a multilevel taxonomy, and uses the hierarchical select field type.

When a user creates an ad/classified, I'd like the UI to first ask the user to choose from the the top-level terms of the taxonomy, then from the child terms of what is selected, then the child terms of that, so on so forth.

Here's an example of what I'm trying to achieve:

I've already tried using Conditional Fields with Hierarchical Select, and Simple Hierarchical Select but neither have worked out so far. I'm trying to create something that's user friendly.

Any help is appreciated.

# Answer
> 1 votes
You can try with Hierarchical Select module.

> This module defines the "hierarchical\_select" form element, which is a greatly enhanced way for letting the user select items in a hierarchy.

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


title: Expose the user form into a page

text:
# Question
Title: Expose the user form into a page
I've been thinking for a user-friendly navigation into my website.

I wanted to exposed the user form into a page where they can just easily update their information. I've installed the module profile 2 and added 3 types of profile (Personal Data, Withdrawal Form and Drawing Records), these 3 types of form I want to expose in one page.

Can it be just embedded into a views or do I need to use hook\_form\_alter? Please help... Thank you...

# Answer
Not exactly sure what you want here. But i think i understood that you have 3 profile types defined in profile2 and want to expose these to anonymous users, so that they can sign up?

If this is indeed the case, then i would reccomend you to take a look at the profile2 registration path module

https://www.drupal.org/project/profile2\_regpath

This module allows you to setup a direct menu path to a user registration form that shows the profile types you select
> 0 votes

# Answer
Do you really need 3 different profiles? For me it looks like you can have one profile with fields divided to 3 set of different field Groups using field group module

With your current approach of having 3 different profiles form on one page might be multiple forms module will be of some help to you.
> 0 votes

---
Tags: views, forms, users
---


# Question
Title: Fire Autocomplete after input reaches 4 characters
I am searching for a way, to fire the autocomplete event after 4 characters are in the input-field. What I am doing now is:

```
if(strlen($string) > 3) {

```

in my "page callback", but this is not the way I want it to work. Because now, the event is fireing, but only returns matches after 4 characters.
Is there a way to start the autocomplete only after the input?

# Answer
Check this answer : https://drupal.stackexchange.com/a/143720/30200

In short, you can defined a custom jquery event and associated it to your form\_item. This event would fire only after a certain number of character
> 1 votes

---
Tags: 7, ajax
---


# Question
Title: Categorizing and Sorting Webform Submissions
I'm trying to find an effective way to categorize and sort webform submissions. I already have them displaying in views, but would like to take it a bit further. Here's the goal:

Anonymous users can fill out an employment application on our site (via a webform). Our recruiter would like to be able to sort through these applications and do things such as categorize them (accepted, denied, etc.) by selecting multiple at once, and send batch emails to applicants.

I already have Views Bulk Operations installed, but it doesn't seem to play well with webform submissions, if at all. Does anyone know of a good way to accomplish this?

I'm on Drupal 7, using Views 7.x-3.6 and Webform 7.x-4.0-alpha6.

# Answer
Webform Report module allows users to create simple, dynamic reports based on data collected by the webform module. It adds a new node type that contains the report criteria, and the data displayed is updated automatically as webforms are submitted. The data can be sorted according to the viewer's preference without altering the report criteria.
> 0 votes

# Answer
maybe you should use entityform instead of webforms module. with the subissions as entities there is the possibility to use bulk operations (VBO) on the submissions. You can use VBO to assign a status and also for sending emails via rules module.
> 0 votes

---
Tags: 7, webforms, views
---


# Question
Title: Show first view result, but show next result when the view's cache is cleared
I'm trying to show a featured image on my homepage. This image will be pulled in by a view that returns 1 result. I then change the caching of the view to 1 day.

What I would like is for each time the cache resets the view to return the next row.

Day 1 - image 1
Day 2 - image 2 etc..

I can add the sort criteria: 'Global: Random'. But then you have the chance that some images might be shown on consecutive days and that some are hardly ever shown.

# Answer
I would have used some scheduling mechanism for node publish and unpublish instead of using views chache.

Some thing as schedule a node A to publish today and unpublish tomorrow, node B is unpublished today and will be published tomorrow, meanwhile the view will always pick the published nodes.

Node scheduling can be handled by scheduler module.
> 0 votes

---
Tags: caching, views
---


# Question
Title: How to display specific nodes in an EVA based on common taxonomy
I am trying to display nodes in an EVA, attached to a node type that shares taxonomy. The EVA passes the node ID to the EVA, so I have a contextual filter, but am having trouble figuring out how to filter the EVA nodes by their shared taxonomy values. It seems like I need to create a relationship in some way, but that doesn't work.

How can I filter out the nodes in my EVA that share the same taxonomy terms of the main attached node?

# Answer
Construct your eva field view as follows: view of nodes filtered by your content type.

**Relationships:**

a. Content: terms (field\_YOUR\_TERM\_FIELD). Require this relationship.

b. Taxonomy term: Content with term. Set the Relationship to relationship 'a'. Require this relationship.

**Contextual filters:**

a. Content: Nid. Set the relationship to relationship 'b'.

b. Content: Nid. NO relationship. In more tick exclude.

**Arguments (in Entity content section):**

Select 'Use tokens from the entity the view is attached to'. Then add this as your arguments: `[node:nid]/[node:nid]`

**In OTHER section of views**: click on query settings, and select 'Distinct'.

The reason two almost identical contextual filters are used is as follows: the first one ties up the relationships that you brought in, the second one excludes the current node from the result set.
> 2 votes

# Answer
From the EVA project page:

> In addition, the unique ID of the entity the view is attached to -- as well as any tokens generated from that entity -- can be passed in as arguments to the view.

Pass the Taxonomy terms as arguments to the view attachment. You may then add a `contextual filter` to the view attachment which can make use of these arguments and require the arguments be of terms within the appropriate vocabulary.
> 4 votes

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


# Question
Title: Do some tasks after a simplenews newsletter has been sent
I need to unsubscribe users from a specific simplenews newsletter category after a newsletter of that category has been sent. The best way is to do this action after updating sent status of newsletter. but there are not a hook or event to do this. What is your opinion to implement this task?

# Answer
The best way would be patch simplenews to offer more events.

Second best would be to override simplenews via a custom module to offer more events.

There are other options but those are the best following the Drupal way.
> 0 votes

---
Tags: emails, notifications
---


# Question
Title: 3 separate fields,one views exposed filter
I would like to have a Rent/Sell radio button for 3 content types. Then I want to show this radio buttons on a views exposed filter. How is this possible to do without sharing the radio buttons field on the 3 content types i.e. use a different field on each content type (so as to make easier to upgrade to D8).

# Answer
If you add all 3 fields as exposed filters and hide 2 of them (with CSS or if you set all fields as "hidden" type with `hook_form_FORM_ID_alter()`). Then you can use the visible field as master and alter values of the two others with a `#submit` callback.

```
<?php
/**
 * Implementation of hook_form_FORM_ID_alter().
 */
function mymodule_form_views_exposed_form_alter(&$form, &$form_state) {
    if (isset($form['field_to_expose1'])) {
        // Hide two fields and left one exposed.
        $form['field_to_hide2']['#type'] = 'hidden';
        $form['field_to_hide3']['#type'] = 'hidden';

        // Execute set_value_for_hidden_fields() as first function submit on $form['#submit'] array.
        array_unshift($form['#submit'], 'set_value_for_hidden_fields');
    }
}

function set_value_for_hidden_fields($form, &$form_state) {
  $value = $form_state['values']['field_to_expose1'];

  // Modify form_state values of concerned field.
  $form_state['values']['field_to_hide2'] = $value;
  $form_state['values']['field_to_hide3'] = $value;

  // Modify form_state of concerned field to pass to the view.
  $form_state['view']->display_handler->handlers['filter']['field_to_hide2']->validated_exposed_input = $value;
  $form_state['view']->display_handler->handlers['filter']['field_to_hide3']->validated_exposed_input = $value;
}

```

That's unstested code, but I hope you get the idea.

But is it worth the effort? Is sharing a field between multiple content types really a blocking issue when planning an upgrade? I'm not well informed on upgrade procedures for D7 to 8, but sharing a field between content types seems to be a pretty common thing using D7.
> 1 votes

---
Tags: views
---


title: add jquery to drupal website

text:
# Question
Title: add jquery to drupal website
I want to add 2 jquery scripts to my website that have to be executed on every page.

Smoothstate

```
<script src="jquery.smoothState.js"></script>
<script src="functions.js"></script>

```

If i read some websites I don't understand how to add them. I can call the js file's in my .info file or is there an other way? I also read about template\_process\_html() to add js to my theme but in what file i have to put this?

Can someone help me out with this.

# Answer
I would recommend you to just add it to your theme info file. That is the easiest way really, since you need them on every page.

PS: dont forget to clear caches after you added it to your themes info file.
> 1 votes

---
Tags: theming, javascript
---


title: How to get EMI Calculator module

text:
# Question
Title: How to get EMI Calculator module
I am developing a Real Estate website for that i need EMI calculator Module. From where i can get this.

Is there any module is developed for EMI Calculator

# Answer
A quick google search gives me the impression that there is no such module available just yet.

Feel free to provide it to the community if you want ;-)

You can take a look here if you want:

http://emicalculator.net/emi-calculator-widget

That might give you a good starting point.
> 2 votes

---
Tags: 7
---


title: Default language for role

text:
# Question
Title: Default language for role
I'm building a website in French as default and only front language but I have to figure out how to do this:

I have administrator and manager roles, both are ok using the french language for both front UI and Admin panels but I also have a role "normal-users" for wich I want to set the default front UI and Admin panels to english by default at registration. How can I do this ?

# Answer
Take a look in this topic below

How to set the language for the user while it is created?

Just read it quickly, this seems to be what you need?
> 0 votes

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


# Question
Title: Print a block inside a Views header or Views footer using PHP input
There seems to be multiple ways of printing a drupal 7 block via php input filter. What is the most efficient way of printing a drupal block in Views header or Views footer attachment of a global text php input filter?

# Answer
1. Try this module https://www.drupal.org/project/views\_block\_area \- it allows insert any block into the view's header or footer.
2. Another way using code

```
$blockObject = block_load('module', 'delta');
$block = _block_get_renderable_array(_block_render_blocks(array($blockObject)));
$output = drupal_render($block);
print $output;

```
> 1 votes

# Answer
For Drupal 7 :

$block = module\_invoke('block', 'block\_view', 30); print render($block\['content'\]);

```
@arg 1 : module name
@arg 2 : hook name like block_view, block_info
@arg 3 : id or delta of the block e.g 30, map-block_1

```

Keep in mind that you can't just copy and paste that code and put in just the block\_id number. The module name corresponds to the module's block your are trying to output. In my case my module name was: "dfp" (its an ads related module). And "block\_view" is the hook you have to use that manages the blocks for that module. And the delta id # doesnt necessarily have to be a number, in my case it was this: "smt\_180x150\_2"

Preview of how my views footer looked with custom block output: http://prntscr.com/5qttl8
> 0 votes

---
Tags: 7, theming, blocks
---


# Question
Title: How to troubleshoot errors after successful Drupal update?
Recently, I updated a Drupal core website from 7.31 to 7.34 and the process was successful, without any error during the upgrade.

It's showing the latest version of 7.34 core in the Status Report, BUT if I visit the home page or any other pages, then it's showing different different errors.

I can access the Administration pages BUT I don't know how to solve these issues.

Here you can see the details about it:

I appreciate your help in advance!

# Answer
> 1 votes
According to this comment you should re-upload common.inc file in includes folder.

> I don't use Drupal Commons, but I got the same error when upgrading Drupal Crore from 7.20 to 7.34.
>
> This function was added in Drupal Core 7.33 so check your core version is later than that. https://www.drupal.org/node/2369141
>
> I then fixed it by reuploading common.inc in the includes folder. Must have not uploaded correctly the first time.

---
Tags: upgrading, debugging
---


# Question
Title: PHP snippet: why comparing the term id with a number keeps getting the wrong result?
I have a Drupal 7 site. I have this taxonomy field that I get printed out using tokens and Display Suite Module.

So, if I create a "code field" at `/admin/structure/ds/fields`, I can type: `[node:field-suscriptor-estado1:tid]` in order to get the term id of that particular node. In fact **that outputs correctly the term id. It outputs a number.** field-suscriptor-estado1 is the field of type term reference.

If I add `var_dump($tidNum);` I get `int(0)`.

In order to show some differences between different terms, I try to compare the term ID to the one that I've got stored in database, and if they do match, it shows the result in one color. If they don't, the color is different.

As I know that **the only terms that I will ever get there are 867 and 870** ("abierto" and "cerrado") I've done a quick if statement in order to achieve that:

```
<?php
  $tid = "[node:field-suscriptor-estado1:tid]"; //I assign the term id to a variable
  echo $tid; // I tested to see if I get it printed out using php, and it does print it: 870
  $tidNum = (int)$tid; // I transform the string variable to a number

  //now, if the number that the variable $tidNum has is 869 print the field with the class suscriptor-estado-abierto, else, print it with the class suscriptor-estado-cerrado.

  if ($tidNum == 869) {
    echo "<div class='suscriptor-estado-abierto'>[node:field_suscriptor_estado1]</div>";
    } else {
    echo "<div class='suscriptor-estado-cerrado'>[node:field_suscriptor_estado1]</div>";
    }
?>

```

The only differences are the css classes that I assign to the field. That way, if it is "cerrado" (closed) it's in red and if it is "abierto" (open) the color is green.

My question is, **why if the number that I do get is 870, it keeps printing it out as if the did match?** (with suscriptor-estado-abierto class).

I've tried different ways: ($tidNum == 869), ($tidNum === 869), and ($tidNum != 869). This last one changing the color rules, naturally.

The result is the same. I've tried also with a new if, asking for $tidNum == 870. The result is the same.

Why it isn't working?

If I try this, for the sake of testing, it outputs as it should:

```
  $tid = "870";
  echo $tid;
  $tidNum = (int)$tid;
  if ($tidNum == 869) {
    echo "abierto";
    } else {
    echo "cerrado"; // it prints out cerrado
}

```

# Answer
This happens because you can't use tokens in the snippet itself.

When you `print` the token, PHP outputs the token as-is, but Drupal catches this output with `Output buffering`, and tokens are processed later.

In the field, see if you get the field item or taxonomy term as a PHP variable. Then, use that variable to extract the term ID. You need to refer to the information provided by your module. If you have Devel module, you can inspect those variables using `dpm` function.

You are probably looking for something like this: `$node->field_suscriptor_estado1[LANGUAGE_NONE][0]['tid']`
> 2 votes

# Answer
1. try to add token\_replace function:

$tid = token\_replace("\[node:field-suscriptor-estado1:tid\]");

or 2. another way to get field values is:

```
$values = field_get_items('node', $node, 'field_suscriptor_estado1');
$tid = $values[0]['tid'];

```
> 0 votes

---
Tags: entities, tokens, display-suite
---


title: Credit card type in drupal commerce

text:
# Question
Title: Credit card type in drupal commerce
I need to find out what credit card type was used when someone purchased something from my website.

Is it possible to find this out? I was looking through the database tables and couldn't find anything in there. I also looked in the orders payment tab and still couldn't find anything.

Thanks

# Answer
Drupal commerce does not provide anything for this. Actually it must not do it since payment companies require (and often make it completely impossible) to know the credit card properties.

Your only hope is what might be stored in the *commerce\_payment\_transaction* table by the payment gateway. Often, additional data is stored as a serialized PHP object in the `payload` field.

If you don't find anything there, you might have to dive into the specification of the payment gateway company and check whether they provide this information via the API. If you are lucky this might be integrated into the appropriate commerce payment gateway.
> 2 votes

# Answer
The accepted answer is incorrect. Commerce Payment's credit card functions to identify the type of card (for the vast majority of common card types) in `commerce_payment_validate_credit_card_type()`.

This information is not stored by default but it allows you to identify card types for unsuccessful transactions where your gateway doesn't analyze the card number, or during payment validation, for instance.

You still must be PCI compliant with regards the card number, but the card type as indicated by this function is not protected information.
> 0 votes

---
Tags: 7, commerce
---