# Question
Title: How to configure Workbench to allow author to publish own content without moderation?
I have author role for creating content. This content is moderated by moderators. Now I would like to add second role super author. Super author can published his own content without moderation. How should I configure Workbench for this?

**EDIT**

There is a WB Access permission for this:

> Bypass moderation restrictions

# Answer
> -1 votes
Have a look at this issue, it discusses this topic: https://www.drupal.org/node/1338750

As it seems the requested functionality will not be included.

---
Tags: 7, nodes, workbench
---


title: Custom theming of login form

text:
# Question
Title: Custom theming of login form
I have used drupal built in form `user_login` and `user_register_form`, Is there a way to control label and textbox field separately, because in my markup each label and text field have different wrapping divs. For example, I have render a particular field like below:

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

```

If I apply a wrapping div around this then it is applicable on both label and text field but I have separate divs with different class for each label and field. Is this possible?

# Answer
If I understand you correctly, what you want to do is override the field template field.tpl.php.

To target specific fields you can rename your version of the file as per the template suggestion options for the field template.
> 0 votes

---
Tags: 7
---


# Question
Title: How to grab the values of field collection items in a template file?
I have a field collection `field_plaats_en_aantal` with two fields: `field_plaats` (text) and `field_aantal` (integer). I'm currently displaying this field collection in a node view as an unordered list:

I'd now like to theme the field collection a bit in order to get something like this instead:

It seems fairly easy, but I can't find a way to achieve this. At first, I tried to work with a template file `views-view-field--field-plaats-en-aantal.tpl.php`, but I don't know how to grab the values of the field collection items there. Is this a good way to work on? If yes, how can I get the needed values?

Afterwards, I read some things on the internet about templates for the field collection items themselves and tried using two templates `field-collection-item--field-plaats.tpl.php` and `field-collection-item--field-aantal.tpl.php`, because that seemed an easier solution to me. However, those files aren't scanned and therefore don't affect the theming of the fields. What am I doing wrong?

# Answer
> 0 votes
It turned out that I was making things too complicated: the theming can be achieved with CSS by using the default classes of the field collection. Hopefully, my code underneath can be helpful for others too.

```
.item-list li {
  list-style: none;
}

.field-name-field-plaats:before {
  content: "@ ";
}

.field-name-field-plaats {
  display: inline;
}

.field-items {
  display: inline-block;
}

.field-name-field-aantal:before {
  content: " (";
}

.field-name-field-aantal:after {
  content: "x)";
}

.field-name-field-aantal {
  display: inline;
}

```

---
Tags: theming, entities
---


title: Print Taxonomy Term in block.tpl.php

text:
# Question
Title: Print Taxonomy Term in block.tpl.php
I am using a specific content type as blocks (via Nodeblock Module). The nodes have certain taxonomy terms referenced via a term reference field, which I would like to print out in the corresponding block.tpl.php to use them as block classes. Same procedure as one would print terms as body classes, but only in block classes array. I find solutions for printing the term field in node.tpl and page.tpl but not in block.tpl.php Glad for any help on this thanks Matthias

# Answer
Here is code tested to work on a minimal install with nodeblock. It's well commented but to recap: get the node displayed in the block, get the term, use one the term's field as css class.

```
// change mytheme to your theme's name
function mytheme_preprocess_block(&$vars) {
  // don't do anything if it's not a nodeblock block
  if (empty($vars["elements"]["#node"]) || !is_object($vars["elements"]["#node"])) {
    return;
  }

  // get the node object, already loaded
  $node = $vars["elements"]["#node"];

  // get the linked term's id (change field_term to yours)
  $tid = $node->field_term[LANGUAGE_NONE][0]['tid'];

  // load the term fully to get access to its fields
  $term = taxonomy_term_load($tid);

  // turn one of the term's field into a css class (change name to any field)
  $css_class = drupal_clean_css_identifier($term->name);

  // add the css class to the list of classes for this block
  $vars["classes_array"][] = $css_class;
}

```
> 1 votes

---
Tags: taxonomy-terms
---


# Question
Title: How to resolve error 'Unresolved dependency System ...' encoutered when trying to upgrade Drupal core?
I'm trying to update Drupal core from 7.28 to 7.36. (not using Drush)

When running update.php I get:

> Unresolved dependency System (Version \>=7.33 required) Relation requires this module and version. Currently using System version 7.28

It seems like the Relation module wants a version 7.33 or higher, and yet it won't let me upgrade to a version 7.33 or higher. Not quite sure how to get past this.

Relation ver. 7.x-1.0-rc7 (It didn't seem to have any trouble when I upgraded to 7.28).

How can I resolve this?

# Answer
The reason for your error is because of the last line in the info file of the Relation module, i.e.:

> dependencies\[\] = system (\>=7.33)

In regular English it is something like "This version of the Relation module requires Drupal core to be at a level which is at least 7.33".

To resolve it perform these steps:

1. Disable of the Relation module.
2. Retry your core upgrade again (that error should not show up anymore, as per step "1.").
3. Re-enable the Relation module again.

I'd be interested to hear what result you get in that scenario ...

**Note**: since your site is pre 7.32, you may want to also work on things such as what is in suggested in the answers to Drupal SA-CORE-2014-005 - How to tell if my server / sites were compromised?
> 2 votes

---
Tags: 7, updating
---


# Question
Title: Load a Module versus JavaScript embedded in Theme
I am new to theming Drupal and I am trying to create a responsive website based on Bootstrap with an image slider at the top.

I know that there are modules like Views Slideshow and FlexSlider. However, I don't want to install a module when I don't have to. I would like to just create a content type specific to the slider with just the fields that I need and have the slider that is "embedded" in the theme simply load the content depending on whether it was published or not.

Can this be done? Are there benefits/drawbacks to what I am attempting to do here?

I am not fluent in the Drupal theming lingo yet so I don't know if I am asking the question the right way.

# Answer
> 0 votes
You can do pretty much anything you want with custom code, including this. The question is should you use custom code or an existing module that provides the functionality you're after.

The answer depends on your specific situation.

For example if you have limited time/budget it may be better to go with something that's already available, like views slideshow, and keep as much of your budget as possible for other tasks.
However there *might* be some reason that option isn't ideal, like maybe the modules have lots of functionality you don't need and you want to code something more specific to your requirements.

Another possible issue might be that the existing module doesn't do something exactly the way you need it to, so then you have to decide whether you write a patch to modify that module or if you want to write custom code.

This question deals with pros and cons of using custom code instead of existing modules.

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


# Question
Title: AWS RDS and Multiple Database Installation
Does anyone have experience with setting up a Drupal Multi-Site with multiple Databases onto one RDS instance in AWS?

I was looking into this link below but I was not familiar with the exact formatting: https://www.drupal.org/node/18429

Here is my format:

```
$databases = array (
'default' =>  // main drupal db starts from here
array (
'default' =>
array (
  'database' => 'PubDB',
  'username' => 'PubUser',
  'password' => 'PASSWORD',
  'host' => 'pubtest.amazonaws.com',
  'port' => '3306',
  'driver' => 'mysql',
  'prefix' => '',
),
),'careers' =>  // additional database starts here
array (
'default' =>
array (
  'database' => 'careers', // additional database name
  'username' => 'PubUser', // additional database username
  'password' => 'PASSWORD', // additional database password
  'host' => 'pubtest.amazonaws.com',
  'port' => '3306',
  'driver' => 'sql', //the file is in sql format
  'prefix' => '',
)
),
);

```

And on my database.inc file I have:

```
function db_set_active($key = 'careers') {
return Database::setActiveConnection($key);
}
db_set_active();

```

# Answer
Finally got it. :)

Here are the steps I took on a RDS under a VPC:

1. Created each Database individually on MySQL and then dumped each DB.

To log into your RDS MySQL:

```
mysql -h RDSEndPoint.rds.amazonaws.com -P 3306 -u MasterUser -p

```

To dump

```
mysql -u MasterUser -p -h RDSEndPoint.rds.amazonaws.com DB_Name_on_MySQL < /my/file/location/SQL_FILE.sql (You might need to change the .sql to .mysql)

```
2. Once you have your DB's set up and ready to go, change your /var/www/html/MySiteFolder/sites/default/settings.php file

To

```
$databases = array (
  'default' =>
  array (
    'default' =>
    array (
      'database' => 'DB_Name_on_MySQL',
      'username' => 'MasterUser',
      'password' => 'PASSWORD',
      'host' => 'RDSEndPoint.rds.amazonaws.com',
      'port' => '3306',
      'driver' => 'mysql',
      'prefix' => '',
    ),
  ),
);

```
3. You might receive this error (https://www.drupal.org/node/2394349):

Command updatedb needs a higher bootstrap level to run - you will need to invoke drush from a more functional Drupal environment to run this command. \[error\]

The drush command 'updatedb' could not be executed. \[error\]

A Drupal installation directory could not be found \[error\]

You can run the following two commands on where each of your sites index.php file is located:

```
drush dl rules
drush updatedb

```

You should be able to see your site now! If I'm missing something I would be glad to add it for future reference.
> 1 votes

---
Tags: database, multi-sites
---


title: localhost runs site extremely slow

text:
# Question
Title: localhost runs site extremely slow
I have a Windows 7 computer running MAMP and it works fine, although still a little slow. I have been working on a Druapl site for a few months now and normal page load times are around 3 seconds. I also work from a macbook from time to time. I am used to transferring the database and all the files needed to make my Drupal site operate from one setup to another. My Macbook used to work properly but now its slow as all hell. I'm getting 10-15 second load times for every page.

Recap: Using MAMP on both machines, one is running Mac OSX Yosemite, and the other is Windows 7.

* Windows page load time is 3 seconds. Not bad, but not great.
* Mac page load time is 10 - 15 seconds. Horrible.

I have to use my macbook as it is portable and can be used for my upcoming presentation. It used to work fine but is now ridiculous to work with. I'm sure there could be more optimization and tweaks done to my drupal installation to make it faster, but that can't be the problem with my mac's load times.

Edit:

So I got my site to perform better yesterday. The steps made no sense and it obviously didnt fix the issue because starting work today, the server was hanging on all page loads again. I increased my max memory usage in my php.ini, and now its back to normal page load times. I still dont trust it though and will keep updating this question if anything further happens. Thanks All!

# Answer
> 2 votes
One thing that can easily cause sudden big slowdowns like this is where a module or theme is removed from the code base without having been uninstalled in the database. Drupal then goes searching for it by recursively searching though every possible folder that can contain a module on every page load. This can easily add many seconds to page loads.

If you're synchronising code and DB with your windows environment then it's a possibility that this is the case. you can confirm it by temporarily putting some kind of debugging in file\_scan\_directory() in includes/file.inc. If it fires 100s (or 1000s) of times then that's probably the culprit.

If it is then re-syncing with your other environment may help. Otherwise I'd recommend identifying the missing module, adding it to the code base again and if it's meant to not be there, disabling and then uninstalling it before deleting the files again.

---
Tags: performance
---


title: Open Atrium permission issue

text:
# Question
Title: Open Atrium permission issue
I've added new roles and give it to them a permissions to create content and for some content... and fields but not work with open atrium.

Please help!

# Answer
My guess is that you're using the general drupal roles and permissions rather than the organic\_groups ones. Start by reading https://www.drupal.org/node/2340349, and then if you are still stuck, clarify exactly roles and permissions you've been modifying.
> 0 votes

---
Tags: users, distributions
---


title: custom css for content types in Drupal

text:
# Question
Title: custom css for content types in Drupal
Basing on existing content type (page) I have created another content type (page-without-video). The only one difference between these two types, is that I am looking to skip a video section in the second one. The rest should look the same. After creating the "page without video" content type, I went ahead and adjusted custom css for the newly created content type (basically just changing the node name from "page" to "page-without-video"). From some reason the new content type did not inherit all the css coding of the "page" and has those default weird lines around images etc. Is it a css problem or maybe I should look elsewhere to fix it?

I will appreciate any help with this.

# Answer
> 2 votes
Use Code per Node module, that is the easiest way to add custom CSS or JavaScript on node page, content type or block...

Look at THIS for other ways to add custom css...

# Answer
> 0 votes
Are you working from a purchased or existing theme with subtheme? If so code per node isn't the solution, there is just one file you need to copy from the base theme to the subtheme directory and I'm here looking for the name of that file which I have forgotten. Found it Copy node.tpl.php from the theme to the subtheme directory and BAM there are your CSS settings again.

---
Tags: nodes, theming
---


# Question
Title: EntityMalformedException: Missing bundle property on entity of type taxonomy_term
I have strange behavior that when i visit `www.mysite.com/taxonomy/term/516/sdfsdf`

i get

> EntityMalformedException: Missing bundle property on entity of type taxonomy\_term. in entity\_extract\_ids() (line 7788 of /../includes/common.inc). The website encountered an unexpected error. Please try again later.

while it should load content of

`www.mysite.com/taxonomy/term/516`

Can anyone help?

# Answer
there seems to be an error in

> entity\_extract\_ids()

in some circumstances the entity info for taxonomy term is wrong .. (probably with entity translation in my case)

```
function entity_extract_ids($entity_type, $entity) {
  $info = entity_get_info($entity_type);

  // Objects being created might not have id/vid yet.
  $id = isset($entity->{$info['entity keys']['id']}) ? $entity->{$info['entity keys']['id']} : NULL;
  $vid = ($info['entity keys']['revision'] && isset($entity->{$info['entity keys']['revision']})) ? $entity->{$info['entity keys']['revision']} : NULL;

  if (!empty($info['entity keys']['bundle'])) {
    // Explicitly fail for malformed entities missing the bundle property.
    if (!isset($entity->{$info['entity keys']['bundle']}) || $entity->{$info['entity keys']['bundle']} === '') {
      throw new EntityMalformedException(t('Missing bundle property on entity of type @entity_type.', array('@entity_type' => $entity_type)));
    }
    $bundle = $entity->{$info['entity keys']['bundle']};
  }
  else {
    // The entity type provides no bundle key: assume a single bundle, named
    // after the entity type.
    $bundle = $entity_type;
  }

  return array($id, $vid, $bundle);
}

```

this is 1:1 the code (not patched ..), that needs changes. from common.inc

see here for patches: https://www.drupal.org/node/1270340#comment-9890989

**when using EntityFieldQuery and fe. *node\_load\_multiple* make sure to pass fully loaded entites !** use *node\_load\_multiple* and pass that result.
> 0 votes

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


# Question
Title: Redundant log settings between Drupal and Apache
I'm trying to discover how I can reduce the redundant logs (PHP errors, Drupal messages, debug logs, whatever) that are stored in Drupal's database and in Apache's log folders. I'm primarily a designer, certainly not a sysadmin, but I'd like to use whatever logging methods are most efficient, from a performance perspective as well as a disk space perspective.

I'm not sure if it is relevant to this issue, but I am using Drupal 6.

Is there anywhere I can find an ideal configuration for what to log on which of the two systems? If not, how can I find out exactly what is being logged in which locations, and how to turn off one or the other?

# Answer
> 3 votes
There's a good drupal.org page on how to switch from `dblog` to `syslog` module: see Syslog: using the operating system's logging facility.

> "Because the Database logging module writes logs to the database it can slow down the website. By using Syslog you can improve the performance of the site."

Combine that with a log rotation strategy of some sort. And then you'll soon be knee-deep in sysadmin-esque territories. But probably not neck-deep though if you catch my drift. Lots of good documentation online for log rotation. Also, I've not done this on D6, only D7, but that page referenced above does have instructions for D6.

# Answer
> 0 votes
**Apache logs** would depends base on your OS that you are running your server. For instance, if you are running Ubuntu 14.04 and the latest stable version of Apache your logs would be located at `/var/log/apache2`. In that directory you mostly like are going to find **Error logs** and your **Access Logs.** Errors logs are mainly for "errors" and acess logs are for the users and robots that visit your website.

**Drupal logs** can be found from the Drupal UI at `admin/reports/dblog`.

If you are going to remove any logs from your server I would strongly suggest that you backup everything.

Personally, I do not think you should turn off your logs just because logs can be helpful in case of something goes wrong with your site.

---
Tags: 6, log-messages
---


# Question
Title: Content type term reference field selected or populated from URL parameter
I need to be able to click on a link, that goes to node/add/example. and populate a term reference field with a URL parameter. I thought i could be able to do this through the default value, but i guess it isn't possible. Anyone have any other ideas to try?

# Answer
For drupal 6:You can put a link using following code in your node.

```
function hook_link($type, $object, $teaser = FALSE) {
  $link = array();

  if ($type == 'node') {
    $link['yourlinkname'] = array(
      'title' => t('Your link'),
      'href' => 'node/add/example',
      'attributes' => array(
        'title' => 'Your link',
      ),
    );
  }
  return $link;
}

```

For drupal 7:You can put a link using following code in your node.

```
function hook_node_view_alter(&$build)
{
   $build['links']['node']['#links']['example-mylink'] = array(
    'title' => t('Your linkname'),
    'href' => 'node/add/example',
    'html' => TRUE,
    'attributes' => array(
      'title' => 'Your link',
      ),
   );
}

```
> 0 votes

# Answer
If you want to avoid custom code, two modules exists for this task:

* Entityreference prepopulate: this is IMHO the best solution for your case. When prepopulating you can hide the field or disable it, and you can define what to do if the argument is not passed (do nothing, hide field, set a form error or redirect the user).
* Prepopulate: more "basic" module, it simply fills the forms field with the argument that you put in the URL.
> 0 votes

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


# Question
Title: XHProf not displaying runs but empty table
I'm trying to profile a drupal website using xhprof. I manage to install it and configure drupal to use it (using the devel module) but I have a problem to visualize the result.

First, for some reason I didn't manage to get the access rights to xhprof\_html through apache. Instead of using apache I just cd into xhprof\_html directory and run php -S myhost:8080. I can then see the main page with all the runs, but when I select a run, it's empty. I can see the table and everything but there is no functions displayed. When I look at the run with a text editor it seems ok.

What am I doing wrong ? Is there another tool to visualize xhprof runs ?

# Answer
> 0 votes
I found the problem, the developper module (used to activate XHProf) use the site name to generate the run. The site name contains the `&` character which messes up the URL corresponding to run.

---
Tags: debugging
---


# Question
Title: Add block programmatically in the right region
I have followed the instruction to create a new block here which is basically the same as here on SE. My block is indeed created but the region is wrongly set to "none" instead of "Content Post".

In my module events.module file:

```
function events_block_info () {
    return [
        'events_list' => [
            'info'       => "Events list",
            'region'     => 'content_post',
            'visibility' => BLOCK_VISIBILITY_NOTLISTED
        ]
    ];
}

function events_block_view ($delta = '') {
    $result = false;
    if ($delta == 'events_list') {
        /* ... do my stuff .... */
    }

    return $result;
}

```

This creates a block but the region is set to "none". The drawback is I have to go on each environment and change the region manually back to "Content Post". It is inefficient.

I also find it extremely weird that the creation of a block is done this way. I would expect instead that the creation takes place in the module.install file in the hook\_install() function. Maybe there is way?

# Answer
> 3 votes
I think you need to set 'status'.
eg.

```
function events_block_info () {
    return [
        'events_list' => [
            'info'       => "Events list",
            'status'     => TRUE,
            'region'     => 'content_post',
            'visibility' => BLOCK_VISIBILITY_NOTLISTED
        ]
    ];
}

```

---
Tags: 7, blocks
---


# Question
Title: Change the front page value for logged in users
On my site I have two front pages:

* node/31, for anonymous users
* calendar-node-field-journal-date/month, for logged in users

When a users clicks on the front page (which is rendered as `$front_page` in my `page.tpl.php` file), I want them to be taken to the appropriate front page.

However, if a logged in user goes to `node/31` directly (e.g. by not clicking on the front page link) they should still be able to see the node (and not be re-directed).

After researching, I've found Rules is the best way to do this and there are instructions here. However, this re-directs logged in users when they visit `node/31`. How can I get the Rule to only run when the user clicks on the `$front_page` link and not on the direct `node/31` link?

I don't want to set it up via my theme, as I am sharing the theme on a multi-site. I also don't really want to install other modules, as I am already using Rules for other things.

# Answer
> 5 votes
I would recommend the Front Page module, not rules:

> The Front Page module allows for customised home pages dependant on role. The pages can be of the following types:
>
> Alias (only 2.x branch) - Allows for another Drupal path to be shown as the home page without redirecting the user.
>
> Redirect - Allows you to redirect users to a local or remote URL.
>
> Themed - Allows you to enter some static text that will be placed into the content area \> of a standard Drupal page. Full - Allows for static content to be displayed to the screen as is. This method does not pass through Drupal's theming system.

---
Tags: rules
---


# Question
Title: Auto Increment value for field collection
I have a field collection group to which I am importing values using Field Collection Feeds Importer. This requires a unique identifier field within the field collection. This has posed an issue where the user has to keep track of these identifier fields. One way to avoid this is having an auto increment field so that when a new row is added it automatically auto increments this field without any user interaction. This would also help maintain the correct sequence at all times and avoid any user editing accidental mistakes.

This is how it is right now

Any ideas or existing functionality to use this.

Thanks.

# Answer
> 1 votes
The Serial Field module should be able to do that:

> This module provides an auto-increment (serial) field.
>
> Unlike Drupal's built-in auto-increment node ID, which is global and shared by nodes belonging to all content types, serial fields are managed per content type (D6) / entity (D7). For example, the serial field of an Invoice instance will generate a unique sequential number (starting at 1, then 2, etc.) exclusively for Invoice instances.

---
Tags: entities, ajax, 7
---


# Question
Title: Creating argument to filter multiple NID's in a single filter-criteria
I'm having a rather simple Views issue in Drupal 7, Views version 3.11.7

I'm creating a View of Node-teasers so I need to filter it by the desired nodes NID's.

As you could see in the following image, I just typed their numbers but surly nothing happened.

What should I type there that the filter would work?

# Answer
Eventually I created a Contextual filter **based on NID**, And configured it as "fixed value", gave the values as #+#+#+#+#, and than went to "more" and clicked "allow multiple values". Please see pic.
> 0 votes

# Answer
The "Contextual filter" solution is only needed if you wish to filter your results dynamicly by passing the necessary filters through the URL.

If I understand your question correctly you wish to filter your view on 4 specific nid's only (witch will never change)?

In that case you could modify your views filter setup and split into 4 seperate filters (each filtering on 1 nid). In the dropdown menu (where you have the "add" button to add a new filter) you have a config page where you can rearrange your filters and more importantly you can specify conditionals using filter group's. In your case I would create a second filter group for the 4 nid filters and use the "Or" operator between them.
> 0 votes

---
Tags: views
---


# Question
Title: JS error(s) with Media-7.x-2.0alpha4 and CKEditor
I'm working on a production site that is using Media-7.x-2.0-unstable6, File entity-7.x-2.0-unstable6, and Wysiwyg-7.x-2.2 (with the CKEditor 3.6.3.7474 library installed). This is fine for inserting images into content types that have an image field, but I am attempting to upgrade Media to a more recent version that allows for WYSIWYG integration and insertion of images and other media directly into the body field.

I updated a local copy of the site to Media-7.x-2.0-alpha4 and File entity-7.x-2.0-beta1. Clicking on the "Add media" CKEditor button brings up the media browser in the normal way. Selecting an image and clicking on the "Submit" button brings up the "Embedding \[filename\]" dialog, but clicking on the "Submit" button does nothing. The firebug console shows `TypeError: CKEDITOR.instances[this.field] is undefined` in line 244 of `/sites/all/modules/wysiwyg/editors/js/ckeditor-3.0.js` (i.e. `return CKEDITOR.instances[this.field].getData();`).

I then disabled Wysiwyg and installed CKEditor-7.x-1.16. I still see the same behavior ("Submit" button does nothing), but now the JavaScript error is `TypeError: Drupal.wysiwyg is undefined` in line 45 of `/sites/all/modules/media/modules/media_wysiwyg/js/media_wysiwyg.format_form.js` (i.e. `if (Drupal.wysiwyg.instances[field.key]) {`).

I have disabled almost all contrib modules (except for those required by media and file\_entity, and a few other innocuous ones that are required by some of the content fields), and the problem persists.

Since Media-7.x-2.0-alpha4, File entity-7.x-2.0-beta1, and CKEditor-7.x-1.16 on a Drupal 7 clean install work fine in my hands, I have a sneaky feeling that there may be cruft in the database that is screwing things up. However, my JavaScript is on the weak side, and I have no clue how Drupal and JavaScript interact, so I'm not sure where to even begin looking for the problem. Any hints on how I can solve this issue? (short of doing a complete rebuild of the site, which might not be a bad idea, actually...)

Thanks in advance!

# Answer
> 0 votes
For CKEditor: At first glance, it seems that commenting out the following lines in media/modules/media\_wysiwyg/js/media\_wysiwyg.format\_form.js allows the button to work again...

```
      // Get all the values
      var ret = {};

      $.each($('#media-wysiwyg-format-form .fieldset-wrapper *').serializeArray(), function (i, field) {
        ret[field.name] = field.value;

        // When a field uses a WYSIWYG format, the value needs to be extracted.
        if (field.name.match(/\[format\]/i)) {
          field.name = field.name.replace(/\[format\]/i, '[value]');
          field.key  = 'edit-' + field.name.replace(/[_\[]/g, '-').replace(/[\]]/g, '');

//          if (Drupal.wysiwyg.instances[field.key]) {
//            // Retrieve the content from the WYSIWYG instance.
//            ret[field.name] = Drupal.wysiwyg.instances[field.key].getContent();
//            // Escape the double-quotes and encode it to play nicely within JSON.
//            ret[field.name] = encodeURIComponent(ret[field.name].replace(/"/g, '\\"'));
//          }
        }
      });

  return ret;

```

Be careful though, this is not a permanent solution as you should never hack core.

---
Tags: javascript, wysiwyg, media
---


title: Broken/missing handler views 2 Drupal 6

text:
# Question
Title: Broken/missing handler views 2 Drupal 6
Recently I created a new Content type and Added a bunch of CCK fiekds in it. After that I migrated some contents to the system using node\_save() function.

Everything was fine until I cleared the cache then 3 of my existing views broke and started to say "Views Broken/missing handler" in some of the fields and in filters. Though the fields do exist as the CCK fields in the proper content type.

1. See the attached image
2. When I try to remove or modify the field then it says "An illegal choice has been detected. Please contact the site administrator." Also the field formats is not show. Refer to the below image.
3. These fields though exist in the CCK as per the below image.
4. To make the site working again I have to go to the Content type's Manage Fields page and click on save. Then it starts to show in proper way (Followed: https://drupal.org/node/624826). The problem is if I clear cache then again this happens.
5. I had backed up the database before the migration and once I saw this then I DROPPED the total database and again imported the sqldump in the blank database but then again once I cleared the cache it again showed Broken/missing handler.

I am totally confused here. Searched Google but didn't got a proper solution. After dumping the old database still its happening. Is it that Views and CCK is storing something while I created the CCK? We are using Memcache in the system, but I suppose that has nothing to do with it.

Please help me on this.

# Answer
> 1 votes
I have found that MAX OPEN FILES can have an impact along with maximum size of object, my understanding is this is the case with or without memcache but I have not proved that yet. I created a tool with cURL to log broken views when they occur and use Munin to monitor everything as it happens: https://drupal.org/node/89710#comment-8351855

# Answer
> 0 votes
Just rearrange the order of you content type fields(temporary change) and then save it. That should force a refresh of the field cache. It solved my problem.

# Answer
> 0 votes
I had the same issue, disabling views caching and cache clear solved my problem.

Disable views cache - `admin -> structure -> views -> settings -> advanced -> disable views caching`

---
Tags: 6, entities, views
---


# Question
Title: How To resolve Broken/Missing Handler with Independent views query backend flag links patch?
So, I'm trying to do something that should be relatively simple, show a catalog of products based on a search index to provide a faceted search with some flag links.

I have a view based on a search index of product displays with a required relationship to Indexed Commerce Product: A bridge to node referenced by field\_product\_sku in order to pull the images into the view. My Flag is set to my custom product type (posters), and I can confirm it works.

The closest I've come was using patch #1Independent backend query flag links mentioned here. This works in so far as I now have access to Commerce Product: Flag Link for Entities, and Content: Flag Link for Entities, both of which give me a broken/missing handler message.

So: 1) How do I fix this? 2) is there a better way to get my Flag links into the Search view?

# Answer
> 1 votes
Try disabling views cache. I believe it should remove broken/missing handler.

---
Tags: views, commerce, flags
---


# Question
Title: Can I create a view that combines multiple images from single node with images from other nodes that entity reference the original node?
I have a content type called "exhibition" that contains *many* images added via the standard image field. I also have a separate content type called "video" that uses an entity reference to point to an "exhibition". Each video node has a *single* image field for a thumbnail.

I want to create a block view that will be displayed on each exhibition's page in a sidebar that combines thumbnails of the exhibition's images with thumbnails of any videos linked to that node. **How can I create this sort of combined view?**

For example:
node/100 is an exhibition containing: image\_1.png,image\_2.png,image\_3.png

node/200 is a video linked to node/100 containing: videothumb\_1.png
node/201 is a video linked to node/100 containing: videothumb\_2.png

I want a block to display in the sidebar of node/100 that renders the following:

image\_1.png,image\_2.png,image\_3.png,videothumb\_1.png,videothumb\_2.png

I am experienced enough with Views that I can create a working block that displays image\_1.png,image\_2.png,image\_3.png. I can also easily create a second block using relationships that correctly displays videothumb\_1.png,videothumb\_2.png. What I would like to do now is combine these separate block views into a single block. My attempts to combine the two seems to always lead to repeated images from the exhibition paired with repeated images from the videos.

# Answer
> 0 votes
if you can't get it to work any other way, you could try using Views Field View to combine the two:

> This module allows you to embed a view as a field in a view. A new field handler is made available, so this can also be used in area (header/footer/empty) handlers as well as rows.
>
> This view handler can accept arguments from fields of the parent view using tokens and pass them into the child view for each row. Raw or rendered token values can be used, as well as static values.

---
Tags: 7, views, entities
---


title: How to sort the blog

text:
# Question
Title: How to sort the blog
I am trying to sort blog by title. The blog does not appear at view. Taxonomy does not has any setting related to sort. What else I should check?

# Answer
> 1 votes
The **/blog** path created by the blog module does not have an option sort by title. The easiest way to do this is to use the Views module to create a page view and just build a display of blogs sorted by titles.

Another way, if you're looking to alter the built in **/blog** path created by the blog module, you could use hook\_menu\_alter to alter the page callback from `blog_page_last()` that's in **blog.pages.inc**.

You can place this code in your custom module:

```
function mymodule_menu_alter(&items) {
  $items['blog']['page callback'] = 'mymodule_blog_page_title_order';
  return $items;
}

function mymodule_blog_page_title_order() {
  global $user;
  $build = array();

  $query = db_select('node', 'n')->extend('PagerDefault');
  $nids = $query
    ->fields('n', array('nid', 'sticky', 'created'))
    ->condition('type', 'blog')
    ->condition('status', 1)
    ->orderBy('sticky', 'DESC')
    ->orderBy('title', 'ASC')
    ->limit(variable_get('default_nodes_main', 10))
    ->addTag('node_access')
    ->execute()
    ->fetchCol();

  if (!empty($nids)) {
    $nodes = node_load_multiple($nids);
    $build += node_view_multiple($nodes);
    $build['pager'] = array(
      '#theme' => 'pager',
      '#weight' => 5,
    );
  }
  else {
    drupal_set_message(t('No blog entries have been created.'));
  }
  drupal_add_feed('blog/feed', t('RSS - blogs'));

  return $build;
}

```

---
Tags: 7, nodes
---


# Question
Title: Which module can I use to visualize Drupal log data in the format of a chart?
I installed Better Statistics and Syslog Access. I wonder if there is a module that can take this data and visualize it like a graph, pie chart, etc? I found one but it's a service, any suggestions?

# Answer
> 1 votes
# Native charting modules

Have a look at the Comparison of Charting modules. Here is a quote from it:

> There are a variety of modules that facilitate the creation of charts. When it comes to charting in Drupal, the saying "There's a module for it" doesn't really apply. In this case, it's more accurate to say, "There are plenty of modules for it" ...
>
> These modules support for various charting libraries that may be desirable based on a site's desired appearance, feature-set, and licensing needs.

Here is the shortlist of 'native' charting modules, for which **at least 1 official release** exist (quote from that comparison also):

* Forena facilitates the creation of charts by using the SVG Graph library. Forena does not depend on Views for creating charts, however it can be used as an extra views style plugin.
* Google Chart Tools provides a simple API to build interactive SVG charts, using the Google Chart Tools.
* Chart currently only supports the deprecated Google Chart Tools: Image Charts, which is deprecated as of April 20, 2015. Though issues #2371567, #2371075 and #2368793 are about addressing that. It is the most commonly used charting module today (over 25K reported installs, which is more then double of all other native charting modules together).
* Charts (not to be confused with the charting module with namespace chart !!!) provides an API that can be used as a stand-alone API, and the integration with Views supports building charts with no coding.
* Charts and Graphs, which is an API for developers. It can be extended by third-party modules that want to add their own charting implementations. It does nothing by itself. It should only be installed if some other module requires it. Views Charts is one of the modules using it.
* Flot provides an API and views integration for using the Flot graphing library.

**Note**: there are quite a few additional 'native' charting modules, though they do not have an official release (yet), only dev, alfa or beta versions.

# Forena showcase

Have a look at my answer to "Views Table with Taxonomy Terms for Columns and Rows", which details how I once created a ***crosstab*** report (using the Forena module) that looked like so:

Then look at the video demo "How to create Crosstab Tables and (related) charts" to get an idea what it takes to create a chart from such crosstab tables.

**Disclosure**: I'm the author of the comparison and co-maintainer of the Charts, Chart and Forena.

---
Tags: 7, nodes, charts
---


# Question
Title: Calendar as view's pager (passing arguments between views?)
I have a view paged by week. Users are a bit disappointed by the pager: they find clumsy to navigate to weeks that are far in time (more than 1 month from today's date).

The idea is to keep the weekly pager for small jumps in time and add a month calendar, so when you click a day on the calendar, the corresponding week is shown in the view. If this is too complicated, I think that a drop-down with a list of weeks could be enough, at least for now.

I was thinking that a possible solution could be creating two views and display them in one page. When you click a cell in the first view (which shows the month calendar), the date is passed to the second view (the main view, paged by week), which accepts a date as a contextual filter. But is this possible to do?

# Answer
Your two Views should be possible with the Views Field View module:

> This module allows you to embed a view as a field in a view. A new field handler is made available, so this can also be used in area (header/footer/empty) handlers as well as rows.
>
> This view handler can accept arguments from fields of the parent view using tokens and pass them into the child view for each row. Raw or rendered token values can be used, as well as static values.

or the side by side could be accomplished by integrating the Views into the Panels Module:

> The Panels module allows a site administrator to create customized layouts for multiple uses. At its core it is a drag and drop content manager that lets you visually design a layout and place content within that layout. Integration with other systems allows you to create nodes that use this, landing pages that use this, and even override system pages such as taxonomy and the node page so that you can customize the layout of your site with very fine grained permissions.
> 0 votes

---
Tags: views, paging, datetime
---


title: Reference an Image from a Scald ID

text:
# Question
Title: Reference an Image from a Scald ID
I am using the Services (7.x-3.7) module to provide a REST API to our website content. However I have a problem with returning images. I am using Scald (7.x-1.1) to manage our media items. This means that when I attempt to GET a node (example.com/rest/node/25592) I get each field for the node in question nicely wrapped in JSON but for the image instead of an image path and file-name I get the Scald ID as follows:

```
field_event_image: {
und: [1]
0: {
sid: "15775"
}-
-
}

```

How can a client application reference the image path from the SID? I know I can use example.com/atom/15775 but this gives me back a themed node page containing the image - it contains the menu and default theme elements so it is not trivial or efficient to retrieve the image path from the source - though it could be done with some client side parsing. What I am looking for is a means to reference the image path directly using the SID. I am trying to keep the number of API calls to a minimum. Alternatively is there some way to configure the Services module to return the image path?

# Answer
Found a way – this is how to retrieve image url and image html from given `sid`:

```
if(isset($vars['node']->field_teaserbild['und'][0]['sid'])) {

    $img = $vars['node']->field_teaserbild['und'][0]['sid'];
    $atom = scald_atom_load($img);
    $image_uri = $atom->base_entity->uri;
    $vars['img_style_url'] = image_style_url('my_img_style', $image_uri); // style_url
    $vars['img_html'] = theme('image_style', array('style_name' => 'my_img_style', 'path' => $image_uri)); // html

}

```

Just in case somebody is still hoping for an answer…
> 1 votes

---
Tags: media, services, scald
---


# Question
Title: Redirect, change or replace the "user/register" link
How to redirect, change or replace the "user/register" link to another registration page, such as "civicrm/contribute/transact&reset=1&id=1"?

Why? Because our "Drupal users" are (paid) members, they have to choose a membership type, they get informed about the corresponding fee (and how to pay offline) and have to provide additional member information (postal address, day of birth,...). All this is handled by a civiMember page, which creates also a Drupal user (user name and password), blocked at the beginning (changed to active as soon as payment is received). We probably have to keep the Drupal user login block, for registered users (paid members) to login.

# Answer
The easiest solution I think here is just redirect it at the Apache (.htaccess) level with a rewrite rule:

```
RewriteRule ^user/register$ /civicrm/contribute/transact&reset=1&id=1 [NC,L,R=301]

```
> 2 votes

# Answer
The Drupal Redirect module can push people from user/register to a civi form
> 2 votes

---
Tags: civicrm
---


# Question
Title: How to group two fields while creating content type?
I wanted to a content type which get number of title and links. And I want an option which allows the user to add more title and links. The fields in the content type are

```
   1. Promotional Image
   2. Image Alternative Text
   3. Title
   4. Links

```

In the above mentioned field. I wanted to group only the Title and Links field. I wanted to give add more option for those two fields alone. Can anyone tell me how this could be done. I cant establish a link between those two fields. At present when I select the 'number of values' option in field settings it gives me add more button to each field but I am not able to link those two fields with any relation. Can anyone please suggest me a solution?

# Answer
If you want to group fields together to be accessible as a single field on your form, the easiest way is using the Field Collection module. It:

> Provides a field-collection field, to which any number of fields can be attached.

Using that you can group your Title and Links fields into one, and you'll have an 'Add more' button for the group, rather than for each individual field widget.
> 3 votes

# Answer
Check this too; Field Group module:

> Fieldgroup will, as the name implies, group fields together. All fieldable entities will have the possibility to add groups to wrap their fields together. Fieldgroup comes with default HTML wrappers like vertical tabs, horizontal tabs, accordions, fieldsets or div wrappers.
> 0 votes

---
Tags: entities, nodes
---


# Question
Title: How to theme regions in non-standard themes like Consilium?
So I'm stuck with a theme that is very difficult to work with because it is nonstandard. It seems like it would like to be Omega and put lots of functionality into the admin UI and out of template files but it seems they forgot to actually add that functionality in there.

So the goal is to add regions and edit existing ones. Normally I would do this in page.tpl.php but this theme does not define region order and html inside a template like this. They've provided a Layout section in their appearance settings but there's no way to actually do anything in this section. No drag, no select, nothing.

So my question is that somewhere in some file, these regions have to be defined in a specific order so where? It's not in page.tpl but it has to be somewhere or else drupal wouldn't know what to do with these regions or how to structure their html.

I know a few suggestions would be to contact the theme maintainer but they are horrible on support. Another suggestion might be to choose another theme but my company picked this one and so I have no choice. I also have a Friday deadline and just got to start this week so figuring out this silly theme has been taking up all my time.

# Answer
> -1 votes
regions are normally defined in the \[theme\_name\].info file in the theme directory. Here is an example from the Bartik theme:

> name = Bartik
>
> description = A flexible, recolorable theme with many regions.
>
> package = Core
>
> version = VERSION
>
> core = 7.x
>
> stylesheets\[all\]\[\] = css/layout.css
>
> stylesheets\[all\]\[\] = css/style.css
>
> stylesheets\[all\]\[\] = css/colors.css
>
> stylesheets\[print\]\[\] = css/print.css
>
> regions\[header\] = Header
>
> regions\[help\] = Help
>
> regions\[page\_top\] = Page top
>
> regions\[page\_bottom\] = Page bottom
>
> regions\[highlighted\] = Highlighted

---
Tags: theming
---


# Question
Title: Anonymous users getting same product items in cart
I am using drupal commerce module, i have an issue with anonymous users, when users click on add to cart button, cart is showing extra items which are added by other anonymous users.

I am using custom code for add to cart using ajax. following is the code.

```
    // Add a product to cart on ajax call.
    function mymodule_custom_add_to_cart($product_id,$uid){
        $line_item = commerce_product_line_item_new(commerce_product_load($product_id));
        commerce_cart_product_add($uid, $line_item);
        $order = commerce_cart_order_load($uid);
        commerce_cart_order_refresh($order);
        // loads data array from order object
        $data = mymoudle_custom_cart_load_all_variables($order->order_id);
        $jsonencoded = json_encode($data);
        print $jsonencoded;
    }

```

I dont know why all anonymous users are getting same products in there cart.

Please help me to find out the issue.

**UPDATE 1:**

I have changed the code for anonymous user as following, then i am getting an error: EntityMetadataWrapperException: Unable to get the data property data as the parent data structure is not set. in EntityStructureWrapper-\>getPropertyValue() (line 451 of /entity.wrapper.inc

**CHANGED CODE**

```
    // Add a product to cart on ajax call.
    function mymodule_custom_add_to_cart($product_id,$uid){
        if($uid == 0){

            $order_id = commerce_cart_order_id($uid);
            if($order_id == false){
             $order = commerce_cart_order_new(0, 'checkout_checkout');
            } else {
             $order = commerce_order_load($order_id);
            }

            // Load whatever product represents the item the customer will be
            // paying for and create a line item for it.
            $product = commerce_product_load($product_id);
            $line_item = commerce_product_line_item_new($product, 1, $order->order_id);
            commerce_line_item_save($line_item);

            // Add the line item to the order using fago's rockin' wrapper.
            $order_wrapper = entity_metadata_wrapper('commerce_order', $order);
            $order_wrapper->commerce_line_items[] = $line_item;

            // Save the order again to update its line item reference field.
            commerce_order_save($order);

            // loads data array from order object
            $data = mymoudle_custom_cart_load_all_variables($order->order_id);
            $jsonencoded = json_encode($data);
            print $jsonencoded;
        }else{
            $line_item = commerce_product_line_item_new(commerce_product_load($product_id));
            commerce_cart_product_add($uid, $line_item);
            $order = commerce_cart_order_load($uid);
            commerce_cart_order_refresh($order);
            // loads data array from order object
            $data = mymoudle_custom_cart_load_all_variables($order->order_id);
            $jsonencoded = json_encode($data);
            print $jsonencoded;
        }
    }

```

**UPDATE 2:** ISSUE RESOLVED.

Site is crawling by googlebot, which is clicking addtocart link and its adding an product to anonymous user account automatically, so i removed link for addtocart button and used commerce addtocart form.

# Answer
I would guess it has to do with:

```
$order = commerce_cart_order_load($uid);

```

Since all anonymous users are assigned uid:0, it could be drawing from all products currently associated with that uid (which would be all anonymous users), rather then the products from the current user's session
> 0 votes

---
Tags: commerce
---


title: How to set a value using Rules

text:
# Question
Title: How to set a value using Rules
I want to add an additional field on each orders, and that field can be edited. I've installed the **Field Collections** module. I've added a field in the **order settings** using the **Field Collection** field type. Inside that field, I've created a textarea, **created by** and **edited by** field. I've used entity reference in **created by** and **edited by** to check which user created the field and who edited the field.

How can I set a default value (created by and edited by) when the order has been edited/newly added using rules? or if not possible to do this in rules, is it possible to achieve this in hook\_form\_alter?

# Answer
> 0 votes
I don't know if it's simpler, it really depends on your set up, but you could look at the Field default token module:

> This module enables to use tokens as field default values.

with this you can assign default values using tokens, such as current user, etc.

---
Tags: commerce, rules, entities
---


title: modifying bartik

text:
# Question
Title: modifying bartik
I'm in progress of designing a new theme based on the `Bartik responsive` theme. Now I would like to move my navigation all the way in the top left corner but I can't get it there, I don't find the property that keeps it centered. Can anyone help? My design so far looks like: http://www.spabc.com/drupal/ I'm still in the very early process of building the theme.

# Answer
its easy, for `#header` set

```
#header{
    display : inline-block;
    width : 100%;
}

```

and for the `DIV` below it,

```
#header > div:first-child{
    float : left;
}

```

or

```
#header > div:nth-child(1){
    float : left;
}

```

it is the result
> 1 votes

---
Tags: theming
---


title: Where do I add imagemap in drupal 7

text:
# Question
Title: Where do I add imagemap in drupal 7
I'm using `marinelli` theme and the rotating images. Now, I'm looking to add `usemap` to some of the images, as the images are rotating images and are not within a specific node. Moreover, I'm adding the banners through `admin->apperance->settings->marinelli->banner management`. So, I couldn't add the `usemap` html tag within the body or some-other place as within blocks/nodes. I tried various ways to add but couldn't get any idea.

I have found some module `jQuery Map Hilight`, where i can add features to the usemap not really adding `usemap` to an image.

Is there any way to add `usemap` tag? Is there any way like adding some code in `page.tpl.php`?

# Answer
As none of my attempts were working, I tried a completely new approach using views.

I've created a new content type named 'banner'. And in the body field, I've added an html `img tag` and `map tag`(for image mapping). Now, I've created a `view` with format as `slideshow` and field as `content:body`. Creating a `block` for this view and adding it in the advertise region (in marinelli theme) replaces the rotating banner image in `Marinelli` theme.

Before adding the view in advertise region, we need to disable the original theme banner. For this, goto `admin->appearence->settings->marinelli->Banner configuration` and choose 'Drupal region (advertise) for the question `Do you want to use marinelli banners or a classic drupal region?`
> 3 votes

# Answer
There is if you're willing to break apart some theme code. You'll need to stitch together a few changes to make this happen.

1. Map Generation.

You're going to need some front-end tool to select your geometry and map it to hyperlinks. It sounds like plugin/module you found may do this. Failing that, it's pretty easy to find existing online tools to do this: Example #1, Example #2, Example #3. It should generate some `map` & `area` elements for you.

2. Storing Maps

Here you're going to be altering the form array/submission-handler in **theme-settings.php** & **template.php** so you can store the maps for each image. There are few parts of this to change:

* `_marinelli_banner_form($image_data)`: This generates the subform that contains all the image form elements. For simplicity, you can add a textfield form element called `image_map` that will contain the map/area markup for each image.
* `marinelli_settings_submit($form, &$form_state)`: This submission handler will need to be altered so you can store the map/area data. A likely area would be the 1st foreach block where you can take each `image_map` and store it into the `$settings` array.

This should be it here. The get/set functions `marinelli_get_banners`/`marinelli_set_banners` are creating a complex array that gets stored into `theme_marinelli_banner_settings` so no additional data structure altercation should be needed. All you need to do is add the image\_map element for each stored image.

3. Displaying Maps

Here we're looking at **logics/banners.inc** to alter the rendering. This PHP include contains the banner element markup in the **template.php**:`marinelli_preprocess_page(&vars)` \> **page.tpl.php**:`$banner_image` rendering pipeline.

* `marinelli_banner_markup($banners)`: Here each `$banner` should have an array element `image_map` that we defined before. It's using theme\_image to generate the image. It should be pretty easy to add the `usemap` element, and output the `map/area` markup we've stored. There is also some logic for wrapping the image in a link that needs to be scrubbed out.
* `marinelli_banners_add_js($num_banners)`: This function adds all the JS sources/settings to fire up the slideshow. It may need to be tweaked to make sure the maps cycle correctly when the changing images.
> 1 votes

---
Tags: theming, media
---


# Question
Title: Entity form in ctools modal popup, whilst passing in values from current node
I need to open an entityform in a modal popup. I have got this working using 'Modal operations' and 'Modal forms' modules following this guide: http://julian.pustkuchen.com/en/comment/reply/599. My link looks like the following:

```
<a href="modal/entityform/job_application/nojs/0" class="ctools-use-modal ctools-modal-modal-popup-large btn"><?php print t('Apply') ?></a>

```

The problem now is that I need to pass certain data (e.g. the nid) of the currently viewed node into the entityform.

I am happy to use hook\_form\_alter or similar, but obviously hooking the entityform has no knowledge of the currently viewed node. My other, pretty hacky, idea was to grab data with javascript and put it in that way, but I need some sort of popup event to work from, which I don't think exists.

Is there another approach to this I could be using, or am I going down the right track?

# Answer
> 0 votes
If anyone's interested in the answer, I just appended ?nid=5 to the end of the link url. Then I could just hook\_form\_alter to get the nid:

```
if($form['#id'] == 'whatever-entityform-edit-form'){

        $nid = $_GET['nid'];
        $node = node_load($nid);

        $form['field_whatever'][LANGUAGE_NONE][0]['target_id']['#default_value'] = "$node->title ($node->nid)";

    }

```

Might not be the best way, but it works.

---
Tags: entities, chaos-tool-suite
---


# Question
Title: Search a content type based on certain criteria
I am faced with a challenge for my company's new website. We are using Drupal 7 and here is the situation: We have approximately 250 doctors in our group and I am tasked with creating a custom search page where users can search our doctors based on certain criteria (e.g. specialty, gender, location, etc.).

I have created a content type of "doctor" and entered all of the physician data that will be needed. My question is: how is the best way to go about setting up the search that I want to give my visitors? I would assume that I need to restrict a search based on content type, but how can I throw the additional search parameters in there? Are there some modules that give very granular options like I'm looking for, or am I looking at having to create and code a custom module??

I'm a little lost and any direction would be very helpful.

# Answer
> 2 votes
You will need to make use of the views module to create the functionality you are looking for.

* Create a new display of type page
* Then select show content of type \[Your content type\]
* Add fields you want users to be able to search on
* Create filters and expose the filters

# Answer
> 0 votes
i am sure this is so easy option rather than generating a view .

```
/** nice snipet to restrict search content type **/

   function mymodule_search_query_search_node_alter(&$query) {
   $query->condition('n.type', 'article', '=');
   }

```

---
Tags: nodes, search
---


title: 406 error on ajax calls in Drupal 8

text:
# Question
Title: 406 error on ajax calls in Drupal 8
Yesterday I upgraded from drupal 8 beta 3 to beta 10. I noticed all my ajax calls are now getting error 406 (Not acceptable).

This is my route:

```
switch_customer.user:
  path: '/profile/get/{template}'
  defaults:
    _controller: 'Drupal\switch_customer\Controller\CustomerController::renderDisplay'
    _title: 'User Info'
  requirements:
    _permission: 'access content'

```

Controller:

```
$content = array(
            '#theme' => $templateName,
            '#items' => $items
        );

        $content = render($content);
        return $content;

```

Ajax call:

```
    jQuery.ajax({
        type: "GET",
        url: '/profile/get/info',
        success: function (data) {
           jQuery(".profile-sidebar-info").empty().append(data);
            if(cb){
                cb();
            }
        }
    });

```

I can't figure out what I'm doing wrong? All my calls were fine in the previous beta. Can someone assist me?

Thanks!

# Answer
Your controller must return an array or a Response object.

If you want to return the content as-is (no "drupal" around it):

```
return new Response($content)

```

If you want to return a normal, full page, then just return the render array.
> 2 votes

# Answer
Always return the Symfony\Component\HttpFoundation\JsonResponse

```
class MyController extends ControllerBase {
  public function handleAjax(Request $request) {
    $string = $request->query->get('something');
    render($output);
    return new JsonResponse($output);
  }
}

```
> 0 votes

---
Tags: ajax, 8, routes
---


# Question
Title: Need to add meta tags in custom page created by custom module
I have installed "Tagadelic" module.Then I created one custom module to display tag clouds in a page.
Now I need to add/modify meta description for this page only. So what is the process for it?

# Answer
You can also install the context module and the metatag context module to set meta tags by URL.

Just specify the URL, and enter the meta tags you wish to display.
> 2 votes

# Answer
A programmatical solution could be to use something like this. you could put it in a preprocess hook in your template.php

```
$path_alias = drupal_get_path_alias();

  if ($path_alias == 'thepathofmypage') {
    $meta_head_blog = array(
      '#type' => 'markup',
       '#markup' => '<meta name="title" content="My metatag title"><meta name="description" content="My metatag desc">',
);
drupal_add_html_head($meta_head_blog, 'metaHeadBlog');

```
> 2 votes

---
Tags: 7
---


# Question
Title: How to re-activate the Drupal administrator account that got accidently blocked?
The admin user account of my Drupal site accidently got deactivated. Because of that, I have no more access to Drupal administration.

How can I change the status of that user account to active again?

# Answer
> 3 votes
Open the *users* table and in the admin row, check the *status* column. 0 means blocked and 1 means active. Make sure it is set to 1.

# Answer
> 2 votes
hope you have an access to the db.

goto table users-\>edit for your admin profile-\>change status from 0 to 1-\>now your admin acc is activ.

---
Tags: users
---


title: Can't delete Relation module

text:
# Question
Title: Can't delete Relation module
I'm trying to disable or delete the Relation module (and about to pull what's left of my hair out).

Relation and Relation Endpoints Field are checked, but greyed out so I can't uncheck them. I don't see anything that's dependant on these, and I don't see anything in the Field List related to this module.

All of the other Relation modules (Relation Dummy Fields, etc) have been uninstalled and I've run cron 40 or 50 times as well as

```
DELETE FROM field_config WHERE field_config.deleted = 1;

```

which someone suggested on another post on the topic, but no success.

The reason I'm trying to delete Relation is that I'm trying to update Drupal core from 7.28 to 7.36 (long story) and getting an unresolved dependency as Relation isn't compatible with 7.28. Someone suggested I disable the module before doing the update, and I'm trying to do that. However, I'm wondering if per-chance this problem has to do with the incompatibility.

I don't seem to be able to move forward or back and I'm not sure what to try next.

Currently:
Drupal 7.28
Relation 7.x-1.0-rc7

# Answer
> 1 votes
One thing to check is if there are still fields using this field? Take a look at admin/reports/fields to see if there is anything using the relation fields.

**Once you are certain...**

If you are certain that there are no dependencies relying on this module, then you can open phpmyadmin, and look at the system table.

Look for /sites/all/modules/relation.info and change the status from "1" to "0". Do the same for relation endpoints as well.

This will disable the module manually.

I would recommend doing a good backup, or even better, recreate your environment away from your production site and test there.

---
Tags: entities
---


title: Vote from list of existing nodes

text:
# Question
Title: Vote from list of existing nodes
I have a Content Type "Picture". The contentmanager now wants to choose specific nodes of this ContentType and put them in a voteable list. The voting list should be auto generated if possible. Users can vote one this list. A user can only vote once and give exactly one vote. After voting, the user should see the ranking results and within his profile he should be able to see for what he voted.

Whats the best way to achieve this? I thought about using flags, but I would need to restrict a flag to a number of nodes and not per node. And with standard polling I don't see a way of generating the voting list.

# Answer
> 0 votes
You need to distinct those specific nodes using taxonomy or a custom field, like a boolean field, say, `0` means no vote and `1` means needs voting. Then use the the flag module to filter those nodes. like this

---

**UPDATE :**

The basic idea is, when user `flags` a content, you can set all of the `1`s to `0` in this way no more content will be votable. To do so you need to use hook\_flag\_flag function. in this function use node\_load to load the nodes of boolean value `1`, set it to `0` then use node\_save to save the node.

---
Tags: flags, rating, polls
---


# Question
Title: How to load taxonomy terms from user profile field using entityfieldquery()?
I want to write hook\_node\_form\_alter() and limit taxonomy terms with only user checked terms on his profile in field\_companies. I can't pass the 1st step - load array of user checked terms from field\_companies using entityfieldquery. This code does not work:

```
$query = new EntityFieldQuery();

$result = $query
  ->entityCondition('entity_type', 'user')
  ->entityCondition('bundle', 'user')
  ->fieldCondition('field_companies', 'entity_id', $user->uid)
  ->execute();

```

The error message is:

```
PDOException: SQLSTATE[42S22]: Column not found: 1054
Unknown column 'field_data_field_companies0.field_companies_entity_id' in 'where clause':
SELECT DISTINCT field_data_field_companies0.entity_type
AS entity_type, field_data_field_companies0.entity_id AS entity_id, field_data_field_companies0.revision_id AS revision_id, field_data_field_companies0.bundle AS bundle
 FROM {field_data_field_companies} field_data_field_companies0
WHERE (field_data_field_companies0.field_companies_entity_id = :db_condition_placeholder_0)
AND (field_data_field_companies0.deleted = :db_condition_placeholder_1)
AND (field_data_field_companies0.entity_type = :db_condition_placeholder_2) ;
Array ( [:db_condition_placeholder_0] => 1 [:db_condition_placeholder_1] => 0 [:db_condition_placeholder_2] => user ) in function field_sql_storage_field_storage_query()
(line 632 in file modules/field/modules/field_sql_storage/field_sql_storage.module)

```

This query does not give terms, but only array with user\[uid\]=1 :

```
$query = new EntityFieldQuery();
$term_entities = $query
  ->entityCondition('entity_type', 'user')
  ->entityCondition('bundle', 'user')
  ->entityCondition('entity_id', $user->uid)
  ->fieldCondition('field_companies', 'tid', 0, '>=')
  ->execute();

```

# Answer
SOLVED with my module user\_referenced\_taxonomy\_terms code has quality 60%. you need to read it and correct if your fields has other names. this code works in my site.

```
/*displays only user checked companies in node addition form in field_company*/
/* field_companies - user profile field  */
/* field_company - node field */

function profile_taxonomy_on_node_addition_form_node_form_alter(&$form, &$form_state, $form_id) {

  global $user;
  //if current user has roles administrator or editor return
  foreach ($user->roles as $role) {
      if (($role == 'administrator') || ($role == 'editor')) return;
  }
  if (isset($form['field_company'])) {
    //get user checked terms companies
    $terms = db_select('field_data_field_companies', 'c')
       ->fields('c', array('field_companies_tid'))
       ->condition('c.entity_id', $user->uid)
       ->execute()
       ->fetchCol();
    if ($terms) {
        //forming array of firms using $terms array
        $count=count($terms);
        foreach ($form['field_company']['und']['#options'] as $key=>$value) {
            if ($key == '_none') continue;
            $delete=true;
            for ($i=0;$i<$count;$i++) {
                if ($key == $terms[$i]) $delete = FALSE;
            }
            if ($delete) $form['field_company']['und'][$key]= array('#access' => FALSE);
        }
    }else {
        //hide field firm if user has no access to any term
        $form['field_company']['#access'] = FALSE;
    }
  }
}

```

PS: with ur comment i optimized this code. fetchAll() gives array of objects i do not need in objects and this is not optimal. fetchCol() gives array that exactly i need. but fetchAllKeyed() gives only one element. thank you Paul!
> 0 votes

---
Tags: database, taxonomy-terms
---


title: Adding Extra weight to order total

text:
# Question
Title: Adding Extra weight to order total
Am working on an ecommerce site and am using ubercart module for that. Now am stuck with an issue which is ' if the weight of order total is \>=1kg, i want to add an extra 150g to the order total and final amount calculated should include this extra grams aaded. for example if i have an order for a product worth 1kg, in the checkout page the final weight of order is 1.150 kg. but the product weight should not be increased.only the final order has an extra weight added. can anyone help me to solve this issue?

Thanks in advance..

# Answer
> 0 votes
Using code we can calculate total weight using product quantity and weight from uc order. Then its possible to add additional weight according to your conditions and pass the calculated total weight according to your need.

---
Tags: ubercart
---


# Question
Title: Is it necessary to use "Correct faulty and chopped off HTML"
I'm allowing the users of the site to add comments in "filtered html" form. And the input is in NicEdit though Wysiwyg.

Currently I'm using "Correct faulty and chopped off HTML" option in admin/config/content/formats/filtered\_html

Is it still necessary for my site?

I feel it's an overhead!

# Answer
> 0 votes
Yes it is required if you have user inputed HTML. For example if someone writes

```
<div> HI!

```

Or

```
</div> Bye :(

```

It can cause issues with your website layout. But that depends on what tags you allow, if you only allow span and p then you are fine as they will auto close themselves.

# Answer
> 1 votes
It is not required when you are using the NicEdit though Wysiwyg. Because, you are not using any tags in them. I you are concern to use the tags. Then, It is better to use this option. It will auto-complete and correct the faulty tags.

for example : if you forget to use the closing tags. It will add those tags.

---
Tags: comments, theming
---


# Question
Title: Help with a dynamic select list of flags for webform
so I've been trying to implement a 'sample request' feature on my site. I had tried to use the webform views module, which worked except that I couldn't add checkboxes to the view that displayed and webform views doesn't play well with the latest release of webform.

I found this Sample Request w Views, Flag, and Webform tutorial, which is basically exactly my use case.

I've created my own module, and am stuck with some of syntax in the view and options parsing array function. The article mentions that I need to reference the title of the nodes 'owner' but I'm not 100% on how this applies to my implementation.

I've altered the code so the function names reflect my custom module, my predefined view of my flag, but I can't get the list to show up in my predefined lists options. I think this is because I don't have the right field referencing my node's title, but I'm not sure. Also the dpm() statement didn't fire.

I know this is a lot, thanks in advance.

```
 function webform_hook_select_options_info() { $items = array(); if (function_exists('_MODULE_user_flag_sample_requests')) {
 $items['MODULE_user_flag_sample_requests'] = array(
  'title' => t("Sample Requests (User Flag list)"),
  'options callback' => '_MODULE_user_flag_sample_requests',
 );}return $items;} function _MODULE_user_flag_sample_requests() {$view = views_get_view('webform_flag_views', TRUE);$view->set_display('webform_options');$view->execute();$options = array();dpm($options);if ($view->result) {$row_class = $view->style_options['row_class'];$attributes = $row_class ? " class='$row_class'" : '';
 foreach($view->result as $item) {
   $options[$item->nid] = '<a' . $attributes . '>' . render($item->field_field_img[0]['rendered']) . ' ' . $item->field_ref_node_title . ' (' . $item->node_title . ')' . '</a>';
 }}else {
 $options[0] = t("Nothing");}return $options;}

```

# Answer
> 1 votes
It is not `webform_hook_select_options_info()` it is `webform_hook_webform_select_options_info()`.
(If your module name is webform\_hook)
The `MODULE` parts are the places, where you should enter your modul name.
Inside the `foreach` you need to enter valid fields from your content that listed inside the view.
Be sure that the Flag Modul is working.

---
Tags: views, webforms, flags
---


title: Role expire in drupal 7 issue

text:
# Question
Title: Role expire in drupal 7 issue
I have installed Role Expire module but how can I set its expire date?

Can anybody please help me because I don't get any clue to write expire date for a particular role?

# Answer
> 3 votes
From admin, when create users and assign roles i.e. `admin/people/create`, there is a textbox open where admin can insert the expiry date.

---
Tags: 7
---


title: Role expire module in drupal 7

text:
# Question
Title: Role expire module in drupal 7
When I assign custom role to any user here `impact protection user` then after its expiry date it automatically assigns role to authenticated user. How can I remove or disable that option to not automatically assigns to authenticated user. If specified date expires then user will unable to login for that specified role `impact perfection user`?

# Answer
Authenticate user being selected won't make a difference as the expiry date is on your other role of impact protection user.

Every user by default is an authenticated user, of which you can't make expire.
> 1 votes

---
Tags: 7
---


# Question
Title: Drupal 7 Views Multiple Jump Menus in single page not working
I have two Jump Menu block (views driven) into single page.

The first Jump Menu block is working fine - Drop Down Content type - Using Ajax

While on Second Jump Menu showing an error of "An Illegal Choice has been detected. Please contact the site administrator." - Drop Down of Taxonomy Term Id

Do any one know how to resolve this issue ?

# Answer
> 0 votes
I did not get any help from community as well for the solution of this. I have to customized the code which resolved my issue. I have to put the form\_alter hook for that jump menu form and apply

```
$form['jump']['#attributes']['onChange'] = 'javascript:location.href = this.value; return false;';

```

Hope this helps you guys.

---
Tags: views, chaos-tool-suite
---


# Question
Title: Is there any way to clone a content type
My site has a lot of different content types, they all have the same fields, the only difference is the name of the content type. Is there any way to clone those content types other than create them one by one. Thanks.

# Answer
No need to clone content type. I had the same issue but I handled it this way, create all of the common fields and then create one more extra field of type `list` and you can call it `Field Type`, this field is a list of content types. When you are entering content, you only need to select an item from list to distinct among content types.
> 3 votes

---
Tags: nodes
---


# Question
Title: The best way to render field content without any <div> wrapper
I have a content type with filefield "ttf" wich I want to render as Url to the file . with this url to file I want to create an link :

```
<a href="<?php print render($content["field_ttf"]); ?>">Download</a>

```

But this output a wrapper around the url

I know that there is a function field\_view\_field() that do the Job but I'm looking for a better solution

# Answer
> 2 votes
You can do this with the combination of 2 contrib modules :

# Answer
> 4 votes
Look in the core modules/field/theme/ folder, copy the field.tpl.php file to your theme then rename it to whatever the system name for the field is. i.e field--body.tpl.php

Edit the file to remove the surrounding divs and anything else you don't want. All you actually need is the foreach and the render($item);

Don't forget to clear the cache so it will pick up the new file, hope that helps.

# Answer
> 1 votes
The proper solution for controlling rendering of a field, is a formatter. You can change the formatter and it's settings under the content types "Display settings". I believe file fields come with a formatter for rendering as direct links.

It looks to me like you are attempting to do this to late in the page cycle, but if you need to hack it together, provide some more context on where you are doing the rendering, and I'll try to be more specific.

---
Tags: 7
---


title: Hide Alt and Title for image field

text:
# Question
Title: Hide Alt and Title for image field
How to hide Alt and Title fields for anonymus users when they upload images? I use tokens for these field that's why I need to hide them.

# Answer
Here a solution for hide the alt and title fields:

```
/**
 * Implements hook_field_widget_form_alter().
 */
function MYMODULE_field_widget_form_alter(&$element, &$form_state, $context) {
    // If this is an image field type
    if ('image' === $context['field']['type'] && 'MY_FIELD' === $context['instance']['bundle']) {
    // Loop through the element children (there will always be at least one).
    foreach (element_children($element) as $key => $child) {
        // Add the new process function to the element
        $element[$key]['#process'][] = 'MYMODULE_image_field_widget_process';
    }
    }
}

function MYMODULE_image_field_widget_process($element, &$form_state, $form) {
    $element['title']['#access'] = FALSE;
    $element['alt']['#access'] = FALSE;

    // Return the altered element
    return $element;
}

```

Et voila :)
> 0 votes

# Answer
This could work with Field Permissions module...
> -1 votes

---
Tags: 7, entities, media, files
---


# Question
Title: using hook_query_alter with fieldcondition()
I want to use hook\_query\_alter to alter a query constructed by a module. This is the code I use:

```
function MYMODULE_query_alter($query) {
  if ($query->hasTag('agent')) {
    $query->fieldCondition('field_area', 'tid', 10, '=');
  }
}

```

The code above gives a 500 error: Call to undefined method SelectQuery::fieldCondition()

What is the proper way to add a field condition to the query?

# Answer
> 0 votes
This was solved using the $query-\>innerJoin()

# Answer
> 0 votes
To use condition in query simply use:

```
$query->condition('field_area', 'tid', 10, '=');

```

---
Tags: hooks, database
---


# Question
Title: How do I make computed fields visible when other fields are presented?
I have been spinning my wheels for hours. I added a computed field to a content type and it simply wouldn't show up in the result. I made an all new content type with nothing in it and the computed field showed up fine. Once I added an additional field, the computed field vanished. Is this a bug or a feature?

# Answer
> 1 votes
No reason why it shouldn't show up just because there are other fields in that content type. Are you sure there is data to show?

---
Tags: entities
---


# Question
Title: Add captcha to last step of multi-step form
I have a multi\_step form which contains four steps. I want to add captcha to last step of the form.

# Answer
use this code in your `template.php`, you need to know what the ID of the last form is,

```
<?php
function MYTHEME_form_alter( &$form, &$form_state, $form_id ){
    if ($form_id == "YOUR_FORM_ID") {
            $form['my_captcha_element'] = array(
                '#type' => 'captcha',
                '#captcha_type' => 'Math',
            );
        }
}
?>

```

you can also replace the `Math` with `image`
> -1 votes

---
Tags: forms, captcha
---


# Question
Title: Suddenly I can't use the "Media" file uploader in Full HTML CKeditor edit screen but can do in Filtered HTML edit screen
I Use D7, CKeditor v 1.16.7 and Media v 1.5.7, all other modules are up2date and the site itself works fine.

I don't recall any special change at the site that would avoid this module of working, yet suddenly it's **upload button** was removed from CKeditor's Full HTML palette (img 1) while appearing fine in Filtered HTML palette.

Facts:

1. The CKeditor "Full HTML" profile's settings seems just fine (img 2).
2. Permissions are fine (I'm the Admin, img 3).
3. Rebuilding type information for media, didn't help.

Any ideas?

# Answer
> 0 votes
Solved! For some reason (most probably a bug) the **Media module button** wasn't added automatically to the Full toolbar even after I check-marked "Plugin for inserting images from Drupal media module" in "Editor appearance" at the desired profile's settings page.

So, What I did was after I check-marked "Plugin for inserting images from Drupal media module" I just went on to add the button manually from "Available buttons" to "Current toolbar" (see img), saved, cleared cache, and Vwalla - it worked again!

---
Tags: javascript, wysiwyg, media
---


# Question
Title: How do I add a link to an operations dropdown menu in views?
I am using Commerce Kickstart 2.

There is a view that lists all of the orders. On each order, there is a dropdown menu with the options of 'Quick Edit' 'Payment' and 'Delete'. I want to add my own operation on that order to view just the list of line items plus some custom information in a view.

However, I can't seem to figure out what I need to do to add a link to this dropdown menu and then go to my view when it is chosen.

# Answer
> 1 votes
Add the following to your hook\_menu in your module to add an operation to the dropdown pulldown of commerce orders.

```
$items['admin/commerce/orders/%commerce_order/<your operation>'] = array(
    'title' => 'Your Title',
    'page callback' => 'your_callback_for_the_operation',
    'page arguments' => array(3),
    'access callback' => 'your_access_callback',
    'access arguments' => array(3),
    'type' => MENU_LOCAL_TASK,
    'weight' => 30,
    'context' => MENU_CONTEXT_INLINE,
);

```

---
Tags: views, commerce
---


# Question
Title: hook_views_data TIMESTAMP field is empty
I'm using hook\_views\_data in my custom module to show the formatted date of a table in mysql. Using the example in the api I have text working but my TIMESTAMP in the donationDate column shows up blank.

MySql reports it is a TIMESTAMP field and it's showing me '2015-04-16 18:41:09'. When I change out the below to the string options it shows me the string representation so I know it's passing data from that column. I've played with the options in setting up this custom view but none of the date options seem to make a difference. I've looked at Google but none point me to what I might be doing wrong. How should I troubleshoot it?

```
function manage_donations_views_data() {
  $data['GeneralDonations']['table']['group'] = t('Donations');
  $data ['GeneralDonations']['table']['base'] = array(
    'field' => 'donationId',
    'help' => t('List of recent donations'),
    'title' => t('All donations'),
    'weight' => -10,
  );

  $data['GeneralDonations']['donationForm'] = array('title' => t('Form'),
    'help' => t('Form and type'),
    'field' => array(
      'group' => 'donations',
      'handler' => 'views_handler_field',
      'click sortable' => TRUE,
      ),
      'sort' => array(
        'handler' => 'views_handler_sort',
      'filter' => array(
        'handler' => 'views_handler_filter_string',
      ),
      'argument' => array(
        'handler' => 'views_handler_argument_string',
      ),
    ));
  $data['GeneralDonations']['donationId'] = array('title' => t('ID'),
    'help' => t('id'),
    'field' => array(
      'group' => 'donations',
      'handler' => 'views_handler_field',
      'click sortable' => TRUE,
      ),
      'sort' => array(
        'handler' => 'views_handler_sort',
      'filter' => array(
        'handler' => 'views_handler_filter_string',
      ),
      'argument' => array(
        'handler' => 'views_handler_argument_string',
      ),
    ));
  $data['GeneralDonations']['donationDate'] = array('title' => t('Date'),
    'help' => t('Date'),
    'field' => array(
      'group' => 'donations',
      'handler' => 'views_handler_field_date',
      'click_sortable' => TRUE,
      ),
    'filter' => array(
        'handler' => 'views_handler_filter_date',),
    'sort' => array(
        'handler' => 'views_handler_sort_date',
      ),
    );

  return $data;
}

```

The column was set up in MySql this way: donationDate TIMESTAMP

I've been using drush to clear all my cache after each code change. I have used all the options. The only one that seems to show anything is the "ago" as it shows 45 years, 4 months so it appears it recognizes the unix epoch?

Still struggling with this. Is it something wrong with how I defined the mysql field, or is it views\_handler\_field\_date? I see some methods but unsure how to troubleshoot this. I'm unsure which to dig into? thx, sam

thx, sam

# Answer
> 0 votes
It appears the API is looking for an integer, particularly Unix timestamp and not the MySql timestamp which is transformed into a string. Looking at how Drupal handles the node table was key to grasping this and the hook\_views\_data documentation indicates that the field is an integer as well.

---
Tags: views, 7
---


title: Archive block for nodes using Views

text:
# Question
Title: Archive block for nodes using Views
How can I create an archive block like this, only for Drupal 7 (views 3) http://chrisshattuck.com/blog/how-create-monthly-archive-block-drupal-blog-views

# Answer
> 4 votes
I think you can use the "Contextual Filter" for this. Choose the "Content: Created date" as the contextual filter. Then in the filter settings, choose "Display a summary" and save the view. Maybe this helps you to start with this.

# Answer
> 0 votes
I found this through searching. So for the completeness of the thread, here is a full tutorial covering how to create an archive block om Drupal 7: http://www.webbykat.com/2012/02/creating-monthly-archive-block-drupal-7-views

# Answer
> 0 votes
These are all fine and correct answers but fail to address the need for a Year to Month drill down. A client has a Views Accordion archive which has months as the top level. It has been difficult to turn this archive into one which nests the months inside of a specific year, such that the accordion shows years as the top level, and subsequently has each month of the year nested inside. There are a few template based solutions out there but none that seem to work with an accordion UI. Contextual filters don't seem able to handle this scenario.

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


title: Add Clear Button to Comment Field?

text:
# Question
Title: Add Clear Button to Comment Field?
Use Case: User wants to clear his comments to rewrite it.

When the User is populating the Comment field, I would like to offer a Clear or Cancel button that will remove the content.

# Answer
**OPTION 1**

1. Use hook\_form\_alter to add a Clear or Cancel button/anchor tag(blank)
2. Add simple JS code to clear the fields

**OPTION 2**

1. Use hook\_form\_alter to add a Clear or Cancel button/anchor tag(blank)
2. Use Drupal AJAX Framework

**UPDATE**

You can use the `hook_form_alter()` inside your **template.php** file which is better based on your comment being more on the front-end side.

Next is you just need to get the ID of the form you want to alter/update by its form id value and just converting the dashes to underscores. An example would be:

```
<form id="leo-form">
  // form elements here
</form>

```

then you need to target it in your hook\_form\_alter() like so:

```
// Implements hook_form_alter.
function themename_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'leo_form') {
    // place your code to add the clear button here
  }
}

```
> 1 votes

---
Tags: entities
---


title: Use math in the fields

text:
# Question
Title: Use math in the fields
I want to use some math function in the field. Is there any editor to support all of the mathematics functions? For Example log,Radical and etc?

# Answer
You could use the Computed Field module, which allows you to write custom PHP functions to determine field values. You will of course need to be familiar with PHP.
> 1 votes

# Answer
The new Math Field module may do what you want. It is a simpler alternative to Computed Field that does not require PHP knowledge or the insecure PHP Filter module.

> The Math Field module defines a new field type to dynamically calculate values on entity forms. This is an alternative to Computed Field that does not require the use of PHP Filter.
>
> Math fields are dynamically updated on the entity form as soon as any required fields are populated. The result is stored in the database when the form is submitted.
>
> Math Field uses the cTools math expression library and supports all the basic operators (+-\*/^) as well as constants 'pi' and 'e' \[…\]
> 1 votes

---
Tags: entities
---


# Question
Title: Remove the resizing of images that are bigger then the max resolution. (reject instead)
I'm using a very specific theme on the site where an image need to be exactly 1110x540. I've set up the min and max resolutions and everything works perfectly, except when I upload an image that's bigger then 540px. Then the image rescales.

Is there a setting that rejects these images instead of resizing them ? I'm using Drupal 7 btw.

# Answer
> 1 votes
Set min/max on the FIELD ITSELF, under content types. Not on the image style.

# Answer
> 0 votes
I know it's too late... you asked this 2 years ago hahaha

The scale filter is in includes/file.inc line 1809, specifically it tries to resize the image when is bigger than your setting... if it can't do it then returns the error "The image is too large; the maximum dimension...". So you have to comment the condition... you just return the error. I know editing that kind of files is not a good idea but at least for me it worked. I'm not pretty sure but maybe you can use hook\_field\_validate to override that condition.

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


# Question
Title: Changing Pagination based on screen size
Is it possible to change the amount pagination displays based on screen size? For example: I have a products page that I want to show 30 items on desktop, but on mobile I'd like it to only show 10 items.

I'm currently using the Loads More Views module, but that doesn't do what I need.

Thanks!

# Answer
Short answer: No.

Long answer: The server doesn't know the screen size before it generates the HTML. The only way to do what you are suggesting would be to detect the screen size first, then redirect to one of two different views based on that.
> 0 votes

---
Tags: views, paging
---


# Question
Title: When I try to modify a view, I get a screen full of odd text
I have just installed views, and every time I attempt to change a setting (or cancel) I receive a white screen with paragraphs of strange info:

```
[{"command":"settings","settings":{"basePath":"\/forms\/","pathPrefix":"","ajaxPageState":{"theme":"blogon_responsive_theme","theme_token":"cD6VFX2j18jV0Gu1-xq10ADeBk_yP4V57yKYNYhNnhs"}},"merge":true},{"command":"viewsDismissForm"},{"command":"viewsShowButtons"},{"command":"viewsTriggerPreview"},{"command":"insert","method":"html","selector":"#views-tab-page","data":"\u003Cdiv id=\u0022edit-display-settings-details\u0022\u003E\u003Cdiv id=\u0022edit-display-settings-top\u0022 class=\u0022views-ui-display-tab-actions views-ui-display-tab-bucket clearfix\u0022\u003E\u003Cdiv class=\u0022ctools-no-js ctools-button ctools-dropbutton\u0022\u003E\u003Cdiv class=\u0022ctools-link\u0022\u003E\u003Ca href=\u0022#\u0022 class=\u0022ctools-twisty ctools-

```

CAn anyone tell me whats wrong and how to fix this?

# Answer
This is caused by a JQuery AJAX failure. Several different things could be causing this. You will probably need to research the current active theme and any modules that you are using in or around that view (especially ones that use AJAX) to see if they have a history of AJAX related failures (and related fixes or patches.) A few things to try:

* Enable, disable or change the settings within the jQuery Update module (some versions of jquery are not compatible with some modules.)
* Change the theme used on admin pages to a generic theme (included in the Drupal download)
> 1 votes

# Answer
Neither of Hoytman's suggestions fixed the issue for me. The only way I could get around it was by going to /admin/structure/views/settings/advanced and enabling the "Disable JavaScript with Views" option.
> 0 votes

---
Tags: 7, views
---


title: Mark New Nodes in Views via Template

text:
# Question
Title: Mark New Nodes in Views via Template
I have a portfolio view that displays all items in the portfolio. The fields are set via template so I do not have access to the fields area in views to select the parameter there, I have to do it within my node template.

The issue is I can't figure out what code to stick in there to display the "New" tag if the visitor has not yet viewed the node.

This is the code I have in the template:

```
<div class="portfolio-name">
  <h3><a href="<?php print $node_url?>"><?php print $title;?></a></h3>
  <span><?php print strip_tags(render($content['field_portfolio_categories'])); ?></span>
  <span><!-- PUT **NEW** FLAG HERE --></span>
</div>

```

I have googled and found the info here (https://api.drupal.org/api/drupal/includes!theme.inc/function/theme\_mark/7) but I just can't figure out how to translate it to what code I put in my actual template file to make it happen.

Thank you so much for your help.

---

Thank you for your answer! I am primarily a themer and php just is not my strong suit.

I have changed my code to be:

```
<div class="portfolio-name">
  <h3><a href="<?php print $node_url?>"><?php print $title;?></a></h3>
  <span><?php print strip_tags(render($content['field_portfolio_categories'])); ?>   </span>
  <?php
    if (node_last_viewed($node->nid) > 0) {
       print '<span>' .  theme('mark', array('type' => MARK_NEW)) . '</span>';
    }
  ?>
</div>

```

This code displays the "new" text, but only if I am logged in as the administrator and it displays on all items, not just ones I have not visited yet. Any ideas?

# Answer
```
<?php print theme('mark', array('type' => node_mark($node->nid, $node->changed))); ?>

```

this is how it is done on the content overview page. give it a try, it will display read for anonymous users' - probably ..,

here's the code from node\_mark, where node\_last\_viewed is used:

```
function node_mark($nid, $timestamp) {
  global $user;
  $cache = &drupal_static(__FUNCTION__, array());

  if (!$user->uid) {
    return MARK_READ;
  }
  if (!isset($cache[$nid])) {
    $cache[$nid] = node_last_viewed($nid);
  }
  if ($cache[$nid] == 0 && $timestamp > NODE_NEW_LIMIT) {
    return MARK_NEW;
  }
  elseif ($timestamp > $cache[$nid] && $timestamp > NODE_NEW_LIMIT) {
    return MARK_UPDATED;
  }
  return MARK_READ;
}

```

so for you maybe this could be used (statistics module needs to be enabled)

```
 <?php
      if (node_last_viewed($node->nid) == 0) {
        print '<span>' .  theme('mark', array('type' => MARK_NEW)) . '</span>';
      }

```

**best to call this theme function (and any logic) in the preprocess method, and use a variable in the template ..**
> 0 votes

---
Tags: theming
---