# Question
Title: Drupal 7. Custom pages for displaying data
I'm juststarted with drupal and i want to create module for managing data in my custom database tables.
For example, i need to have three pages:
1) list of my subscribers
2) editing subscriber
3) adding subscriber

so, i need three pages for this:
**/subscribers
/subscriber/edit/id
/subscribers/add**

the question is:
do i need to create three Basic pages with such aliases in admin and use specific templates files for each page to manage data? or how to do it properly?

# Answer
Using hook\_menu() should get you the the ability to create those three pages. Then you can use the page\_callback to display the data you are looking to show. For the subscribers/id, you can use %id and then have pass the argument to the page\_callback. Using the db\_query(), db\_update(), db\_select() functions in drupal, you'll be able to add the custom processing of the database.

If you are creating your own module you can use theme functions to decide how the page and that data will display.
> 1 votes

---
Tags: 7
---


title: Hide blocks in node page using context

text:
# Question
Title: Hide blocks in node page using context
i am new to context module and based on some tutorial i have used context. Now my problem is,

Currently, I have created one context which will show default header logo in all the pages. Now got new requirement to show different logo on the node pages with selected taxonomy terms.

For this i created one more context and used taxonomy conditions with selected taxonomy terms for the different header logo. when i visit the page, i got two logos in the header section, so i edited the first context and added the taxonomy condition and selected those taxonomy terms and set the "No" to "Set on node form" option.

You know whats happens, the default logo gets disappear from all the pages but still showing two logos in the node pages with the selected Taxonomy terms pages.

I am not sure what condition to set to show in all the pages except in those selected taxonomy terms pages. Could you please someone guide me on this.

# Answer
> 2 votes
This should work... Context allows contexts to be fired based on the presence of other contexts. So in your "global" context, you can add the condition 'Context(all)' and then add `~[taxonomy_context_id]`. Where `taxonomy_context_id` is the id of the taxonomy context. Make sure that "Require all conditions" is checked. And save.

Now the "global" context should only show when the the other isn't available.

Recommendation: If you are looking to switch logos based on taxonomy term, you can use `template_preprocess_page()` to switch out the path of the logo based on the current menu\_object that is loading. This allows for you to have a global context that persists and doesn't duplicate the work/blocks and provides an override to the `page.tpl.php` variables instead of multiple possibly conflicting context.

---
Tags: 7
---


title: Filter Node Reference options

text:
# Question
Title: Filter Node Reference options
I'm trying to set up the content types for a site and ran into a bit of a problem. Let's say I have a content type called Employee, and a list of taxonomy terms that holds function names. Each employee is linked to a function so to say using a Term Reference to one of the available function. Like this each employee is either a mananger, a desk employee, or a janitor etc.

In a second content type, I wish to add a node reference to these Employee nodes, but I wish to have the option of only selecting the nodes linked to a certain term, such as manager. As such, when creating a new node of this second content type I should only be able to select managers in my overview.

Is there any way of filtering your available options like this? I saw some other questions mentioning the References module, but these questions didn't have an answer.

I hope someone can shed some light on this for me.

# Answer
Using Entity Reference Module you can set up a view that pulls in a list of entities and then use that view to select the nodes. Steps:

1. Create a view of employees
2. Add a contextual filter to the view for has term reference
3. Save view.
4. Add entity reference filed and select use view to show results.

Hope that helps
> 0 votes

---
Tags: nodes, input-formats
---


# Question
Title: How to add an 'operations' link to a custom route?
I'm implementing a custom entity with bundles in Drupal 8.

In the **list of bundle entities** page (i.e. equivalent to Node's Content Types listing page), I would like to provide an extra option to the list of *operations*, which currently include *Edit, Manage Fields, Manage Display, Delete*, to let the user create an entity of that bundle. So if this were on Nodes, then it would be like adding an "Add Content" link for each content type in the content listing page, which would take you to `/node/add/{node_type}`.

Relevant code I have so far:

Added an 'add-entity' option in the links section of the config entity's annotations:

```
* @ConfigEntityType(
*   id = "bloom_stem_type",
*   label = @Translation("BloomStemType"),
*   bundle_of = "bloom_stem",
*   ...
*   links = {
*     "edit-form" = "entity.bloom_stem_type.edit_form",
*     "delete-form" = "entity.bloom_stem_type.delete_form",
*     "collection" = "entity.bloom_stem_type.collection",
*     "add-entity" = "entity.bloom_stem.add_form"
*   }
* )
*/

```

Note that this points to a route in another entity, the actual entity that this is a bundle for.

That route is defined in (routing.yml):

```
entity.bloom_stem.add_form:
  path: '/admin/bloom_stem/{bloom_stem_type}/add'
  defaults:
    _title: 'Add BloomStem'
    _controller: '\Drupal\bloom\Controller\BloomStemController::addForm'
  requirements:
    _entity_create_access: 'bloom_stem'

```

Then I've implemented getDefaultOperations on a custom list builder class:

```
class BloomStemTypeListBuilder extends ConfigEntityListBuilder {
  ...
  /**
   * Gets this list's default operations.
   *
   * @param \Drupal\Core\Entity\EntityInterface $entity
   *   The entity the operations are for.
   *
   * @return array
   *   The array structure is identical to the return value of
   *   self::getOperations().
   */
  public function getDefaultOperations(EntityInterface $entity) {
    $operations = parent::getDefaultOperations($entity);

    $operations['add'] = array(
      'title' => $this->t('Add'),
      'weight' => 10,
      'url' => $entity->urlInfo('add-entity'),
    );

    return $operations;
  }

```

However, when I visit the entity bundles list page, there's an exception thrown about being unable to create a route/path. On step-through debugging this seems to be because Entity::urlInfo() does not appear to use the route set in the annotation, thanks to this line that constructs its own route:

```
$route_name = "entity.{$this->entityTypeId}." . str_replace(array('-', 'drupal:'), array('_', ''), $rel);

```

The only documentation I could find on the `links` part of the annotation just says:

> **links**
> Entity URL definitions, referencing to routes from MODULE.routing.yml. 'canonical' is the default route for the entity. edit-form and delete-form can also be set. These are mostly used for Field UI. Arbitrary keys can set here. For example, User sets cancel-form, while Node uses delete-form.

Which I took to mean ("referencing to routes from MODULE.routing.yml") that if I referenced a route, that route would be used.

Aside: Other things I've tried include creating the URL more directly (clearly not the right way of doing things):

```
$url = \Drupal::getContainer()->get('url_generator')
  ->generateFromRoute('entity.bloom_stem.add_form', ['bloom_stem_type'=>$entity->id()]);

```

That generates a valid path, but a string value is not what `getOperations` is expected to spit out under its `url` key output.

Can anyone fill me in on how this is supposed to work/where I've gone wrong? Thanks.

# Answer
What drupal core version are you using?

Link templates have been changed to links instead of route names a few months ago. See Node and other example entity types.

Another requirement is that link template names and route names need to match.

However, your primary problem is that link templates about the entity or at least entity type that you have, and that's not the case for your example.

Using link templates for operations is convenient when possible but in no way required. It can be any Url object. So your last attempt is actually close, you're just not using the right API yet (and yes, there are definitely way too many ways to generate links/URL's).

Try this:

```
\Drupal\Core\Url::fromRoute('entity.bloom_stem.add_form', ['bloom_stem_type' => $entity->id()])

```

Then use that for 'url'.
> 2 votes

---
Tags: entities, 8, routes
---


# Question
Title: Drupal 7 - Entitiy Reference - Reference field to a conent as a link
I created content - lets call it X - which has a field with the type of entitiy reference (done with Entitiy reference). This field refers to a content that can be selected via select list. When X is shown the reference field appears but not as a link so that I can directly forward to that content. Do I need any additional module for that?

# Answer
> 4 votes
On the **Manage Display** page (Structure-\>Content Types-\>*Your content*), first be sure the display format is set to **Label**. Then, click on the gear on the right. You will see a checkbox with "Link label to the referenced entity". Check that and click Update, then save our display. The label will now link to the entity.

---
Tags: entities, nodes
---


# Question
Title: Adding a specific field of a content type in the display of another content type
Sorry I didn't know how to put my question easily, so I detail my problem here.

I use Entity Reference to reference various fields in my contents, and it works good.

Now, I have a "Fruits" content type, with a field named "Picture".

I have another content type, which contains a reference to the fruit "Name", but I want to display the picture and not only the name.

How can I do ?

# Answer
With entity reference there are a couple ways to go about this.

1. You can select the view mode to display (i.e 'teaser') on the display ui of the other content type and then on the 'Fruits' field display ui for the view mode teaser show only the picture. If you use the title module, you'll be able to hide the title on the teaser. If you don't want to use the title module there are other approaches to hide the title.
2. You can create a view using entity views attach and set up a relationship and then display only those fields. This is more complicated and not as maintainable, I recommend going with #1.

Hope that helps
> 1 votes

# Answer
I used your first solution, and it works like a charm ! Didn't know this Entity Reference function, and now I'll add references everywhere in my website !

Thanks a lot :)
> 0 votes

---
Tags: entities
---


# Question
Title: Rendering Taxonomy Custom Fields in page.tpl.php
Ahoy all, so, having some issues with displaying specific fields related to taxonomy terms in a page I created (page--taxonomy.tpl.php)

Essentially, I am trying to set a background image to a div, to pull from an image field (field\_hero\_image)on the taxonomy term. I have this working for normal nodes just fine with the following code:

```
<div id="herowrap" style="background:url(<?php echo file_create_url($node->field_hero_image[$node->language][0]['uri']); ?>) no-repeat center center;background-size: cover;">

```

However, been having difficulty understanding how to modify this to pull this same image field from taxonomy terms.

It needs to be in page--taxonomy.tpl.php as it is being pulled before the node.tpl.php is being called (if i understand correctly?)

Any reason I can pull this easily from nodes, and not for taxonomy terms?

Thanks for any help!

Dan

# Answer
I suggest taking a look at the 2 answers to this question. I think it's a similar case.
> 1 votes

# Answer
I have actually been developing a site and I have learned an interesting method to do what you want and I think this method would help you here.

I would bypass taxonomy all together and use Content Types, Entity Reference and Views instead.

What you do is create a content type with only two fields:

1) The title field. Rename it to "category" or "taxonomy" or whatever makes sense.

2) An image field.

Then in your article or whatever you use for content, you add an entity reference field to that new content type you just created. The beauty here is that you can be consistent with your terms and you can bring over the image anytime you want because it is part of the referenced content type.

In the views module, you create a block and then make a relationship to the referenced content and a contextual filter based on ID in the URL. Your fields for the view will be the title, content, the "term" and the image (because of the relationship).

You can use re-write rules to style how you like.

So, instead of having a url that looks like www.example.com/term/foo-bar Your URL will be www.example.com/foo-bar and the image will simply follow because of the entity reference.

The biggest benefit to doing this? No coding other than CSS.
> 0 votes

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


# Question
Title: Exclude a free product from total calculation
In Drupal Commerce, how can I exclude a product from partial total calculation? The product is inserted as free product via a Commerce Discount rule, but in total calculation it appears and then is subtracted. I would exclude this insertion/delete operation.

# Answer
> 0 votes
Create a rule with the event *Calculating the sell price of a product*.

There, you can check for the SKU of the product and set its price to zero (using the *Set data value* action).

You can also use the *Subtract an amount from the unit price* action to assign the value to a price component so that it appears in the totals (this will require extra configuration)

---
Tags: commerce
---


# Question
Title: How to get workflow state transition history for a node?
In the admin section, for any given node, I need to add a dropdown field that lets QA assign that node to a developer who had previously made changes to the node's workflow state. I am currently using the workflow module (https://www.drupal.org/project/workflow). This field needs to be populated with users who have changed the node's workflow state before. So, I'm working on a module that can do this. My question is, how do you programmatically get the workflow state transition history for a given element?

For every revision of a given node that has involved a workflow change, I would need the following information:

1. The state or state id (sid) that it was changed to.
2. The uid of the user that made the change.
3. The order in which the workflow state transitions were made.

I tried node\_revision\_list, but it does not include revisions that only change the workflow state. (Because it's not looking at the workflow\_node\_history table).

I can get the information I need directly from the database by running the following query, but I don't want to do any database-hacking if this functionality is already in Drupal somewhere.

```
SELECT sid, uid  FROM `workflow_node_history` WHERE `nid` = ? ORDER BY stamp asc

```

Is there a Drupal function that already does this?

# Answer
The Workflow module has a lot of API calls that you can use to get the relevant information you need.

Here are all the workflow functions you can access

It seems like you might be looking specifically for the workflow\_get\_workflow\_node\_history\_by\_nid function

Here you supply a node ID and it will return the history results as an object where you can find the information you need. It even joins it with the users table so you have all the relevant user information.
> 1 votes

---
Tags: 7, entities, workflows
---


title: Pass a logo to image module

text:
# Question
Title: Pass a logo to image module
How do I pass the logo on my theme to the image module to create different sizes? I'm using domain access to I can't use

```
<?php print theme('image_style', array('style_name' => 'thumbnail', 'path' =>'public://new_ctrl_logo_front1_1.jpg')); ?>

```

as I'm using domain access and using one theme for use on multiple sites. I found this code on another form that works on my theme and need to know if I can pass an image style through it.

```
<?php
if (theme_get_setting('toggle_logo')) {
$image = array(
'path' => theme_get_setting('logo'),
'alt' => 'my logo',
);
print theme('image', $image);}?>

```

Thanks for helping, Gregory S.

# Answer
**Update**

If one needs to obtain "JUST" the filename for theme logo for the active theme for any given domain in a domain access environment (as the OP found he needed to do), then the following code provides the image file name for the theme logo as $img\_file.

```
$global $base_url;
img_path = theme_get_setting('logo');
$str_to_remove = $base_url . '/sites/default/files/';
$img_file = str_replace($str_to_remove, '', $img_path);

```

**Original**

Pass "theme\_get\_setting('logo')" as the path for the first php script?

```
<?php print theme('image_style', array('style_name' => 'thumbnail', 'path' => theme_get_setting('logo'))); ?>

```

or rather - an amalgamation of the two -

```
if (theme_get_setting('toggle_logo')) {
print theme('image_style', array('style_name' => 'thumbnail', 'path' => theme_get_setting('logo')));
}

```
> 2 votes

---
Tags: media
---


# Question
Title: Display a field when it contains a value
In Drupal 6, I can use the following code in the *node.tpl.php* file.

```
<?php if (content_format('field_occupation', $field_occupation[0]) != '') : ?>
  <?php foreach ($field_occupation as $occupation) { ?>
    <strong>Primary occupation: </strong>
    <?php print content_format('field_occupation', $occupation) ?>
  <?php } ?>
<?php endif; ?>

```

This doesn't seem to work in Drupal 7.

How can I make it work?

# Answer
Welcome to d7 - just in time as d6 will soon become unsupported. In D7, content\_format is deprecated.

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

Check out this for how to render entity fields in d7: https://www.computerminds.co.uk/articles/rendering-drupal-7-fields-right-way

You'll have to adapt your existing script to this new rendering method. It might be a good opportunity to clean up the presentation and readability of the script so that you'll be prepared for the inevitable migration to d8!
> 1 votes

---
Tags: 7, nodes
---


# Question
Title: Modules i18n: How to set the default language home page url without alias
I have a standard Drupal 7 installation with the i18n module and 3 languages defined.

* one basic page "node/1" created with the URL alias "home"
* in the Configuration \> System \> Site Information the default front page is "home"
* created other 2 languages (pt-br and it)
* created the translation of the basic page "node/1" to pt-br and it (are created "node/2" and "node/3" pages)
* the 3 pages "node/1, 2 and 3" have the same alias "home"

If I go to mysite/en, I see the defined front page in english and all the site is in english: it's ok!

The problems:

1. If I go to mysite/pt-br/home, I see the site in portuguese and the "node/1" in porguguese: it's ok!
2. If I go to mysite/pt-br, I see the site in portuguese but the "node/1" content in english and not the "node/2" (portuguese version of the basic page): wrong!
3. the same thing to the italian version.

What is wrong? How to set the correct language node for front page in the default language url (mysite/pt-br and mysite/it)?

Note: In the Detection and Selection tab is the original items with the default order (URL, Session, User, Browser and Default) and I have been enabled all (in the Configure page of URL the selected option is the Path Prefix).

# Answer
> 1 votes
Make sure to declare your home page node as a "*multilingual varialable*". For more details on these kind of variables, and how to get this to work, refer to my answer at How to make content translation available for front page?.

I'd be interested to some day hear if this resolved the issue here.

---
Tags: i18n-l10n
---


# Question
Title: Firefox/IE not displaying CSS with Drupal website
In Firefox and IE (and maybe others?) it seems that the blocks that are built by drupal aren't having CSS applied to them.

Any help at all would be wonderful, as the issue I'm having is not knowing where the issue lies. The site is http://confluencenter.arizona.edu/.

p.s. I am very new to CSS and Drupal

# Answer
> 0 votes
It's more like a CSS issue. Your CSS has to be more organize and standard cross browsers. Try not to use "**!important**", because you don't want to over-use it as you will end up causing headaches down when maintaining the site.

Here are some example you can fix.
Under file "**blocks.css**" line 303.

```
.pane-block-4, .pane-block-5, .pane-upcoming-events, .pane-block-6 {
  width: 31.25% !important;
  min-height: 500px;
  float: left;
  overflow: hidden;
  position: relative;
}

```

Since there are 3 classes on each "div"(panel-pane pane-block pane-block-4), you should use something like this instead

```
#mini-panel-front_blocks .panel-pan {
  width: 31.25%;
  min-height: 500px;
  float: left;
  overflow: hidden;
  position: relative;
}

```

Hope this help

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


title: Moving drupal to a subdirectory

text:
# Question
Title: Moving drupal to a subdirectory
I'm trying to move a Drupal site to a sub-directory of the same domain. I'm very experienced with WordPress but not experienced with Drupal sites. How would I move a website from http://example.com to http://example.com/old-website/ ?

I can't figure out what would cahnge so that I can migrate the site.

Any and all help is appreciated!

Thanks!

Austin

# Answer
> 1 votes
Just move the files, you don't need to set a base URL like in Wordpress.

If you do run into any problems, uncomment rewritebase in htaccess

---
Tags: migrations
---


title: Translate string in javascript

text:
# Question
Title: Translate string in javascript
There is a string which gets displayed in the mobile menu.

```
var arrowimages = {
down: 'downarrowclass',
right: 'rightarrowclass'
}, $mainNav = $('#navigation'), $mainList  = $mainNav.find('ul').eq(0), optionsList = '<option value="" selected>Navigate...</option>', $submenu = $mainList.find("ul").parent();

```

I want to make this string translatable using t() function. So edited the JS file like this:

```
var arrowimages = {
down: 'downarrowclass',
right: 'rightarrowclass'
}, $mainNav = $('#navigation'), $mainList  = $mainNav.find('ul').eq(0), optionsList = '<option value="" selected>'.t('Navigate...').'</option>', $submenu = $mainList.find("ul").parent();

```

After that the string was available for translation but the menu option was missing from the mobile view. Is there any solution for this? Or am I doing any mistake?

# Answer
I'm not sure about you question, but for translating string in JavaScript you should use `Drupal.t()` function.

So you code should looks like:

```
var arrowimages = {
  down: 'downarrowclass',
  right: 'rightarrowclass'
};
var $mainNav = $('#navigation');
var $mainList = $mainNav.find('ul').eq(0);
var optionsList = '<option value="" selected>' + Drupal.t('Navigate...') + '</option>';
var $submenu = $mainList.find('ul').parent();

```

You can read more here: https://www.drupal.org/node/323109
> 0 votes

# Answer
`t()` is a PHP function. You are looking for `Drupal.t()` which is the equivalent function Drupal makes available for JavaScript.

These are some example of how `Drupal.t()` and `Drupal.formatPlural()` can be used in JavaScript.

```
var comments = Drupal.t('Comments');
var commentsOnType = Drupal.t('Comments to @type posts', {'@type': typeName});
var commentCount = Drupal.formatPlural(count, '1 comment', '@count comments');
var commentCountOnType = Drupal.formatPlural(count, '1 comment on @type posts', '@count comments on @type posts', {'@type': typeName});

```

Notice what reported in Translating strings in JavaScript:

* For performance reasons, Drupal caches the JavaScript files it has parsed. So, when you add or change strings in a JavaScript file, you have to clear the cache to have Drupal pick up the new strings and make them available for translation.
* Automatic extraction does not work for packed JavaScript files. For this reason, module authors should only include unpacked versions of their JavaScript files. Drupal's JavaScript aggregator will create a packed version from these files anyway.

Just replace `t()` with `Drupal.t()`, and you are done.

```
var arrowimages = {
down: 'downarrowclass',
right: 'rightarrowclass'
};
var $mainNav = $('#navigation');
var $mainList = $mainNav.find('ul').eq(0);
var  optionsList = '<option value="" selected>'+ Drupal.t('Navigate...') + '</option>',
  $submenu = $mainList.find("ul").parent();

```

Your code also contains a syntax error: `.` is not the string concatenation operator, in JavaScript; JavaScript uses `+`, for that purpose.
> 1 votes

---
Tags: javascript, i18n-l10n
---


title: How to store date_popup fileld in mysql

text:
# Question
Title: How to store date_popup fileld in mysql
For some reason I cannot save the value of my date\_popup field (comment\_date) to mysql database. I need to use default value from existing field (field\_due\_date6) and store the new value to this field. So I do the following:

```
function custom_form_alter(&$form, $form_state, $form_id) {
  $form['comment_date'] = array(
      '#date_format' => 'Y-m-d',
      '#date_year_range' => '0:+1',
      '#type' => 'date_popup',
      '#weight'=>1,
      '#datepicker_options' => array('minDate' => 0),
      '#default_value' => $form['#node']->field_due_date6['und'][0]['value']
    );
}

```

Then I'm trying to submit it to database:

```
function custom_support_comment_submit($form, &$form_state) {
  $node = node_load($form_state['values']['nid']);
  $node_wrapper = entity_metadata_wrapper('node', $node);

  if($form_state['values']['comment_date']) {
    $node_wrapper->field_due_date6->set($form_state['values']['comment_date']);
  }
  $node_wrapper->save();
}

```

But when I click Submit button I got the error -

```
EntityMetadataWrapperException: Invalid data value given. Be sure it matches the required data type and format. в функции EntityMetadataWrapper->set() (строка 122 в файле Z:\home\dd1\www\sites\all\modules\entity\includes\entity.wrapper.inc).

```

Could you please specify what I'm doing wrong?

# Answer
> 1 votes
Node Field must be expecting date field value in unixtimestamp format while the custom form will return the value in the format mention as '#date\_format' =\> 'Y-m-d'. View of your form submit values will look like.

You should run the submit date value through strtotime() to get the unxtimestamp value for it before assigning it to node field.

```
$node_wrapper->field_due_date6->set(strtotime($form_state['values']['comment_date']));

```

---
Tags: forms
---


# Question
Title: How can I seperately display a view's exposed filter and its content in page.tpl?
Using `<?php dpm($node) ?>` I found the exposed filter, `$...->view->exposed_widgets`, however I'm not sure how to display it. I tried `<?php echo $node->view->exposed_widgets; ?>` but that returns nothing.

`<?php dsm($form); ?>` and `<?php dpm($form); ?>` both give

> Notice: Undefined variable: form in include() . . . page.tpl.php

Are those deprecated? I see them mentioned sometimes but they've never worked for me.

The only place I see the form in `<?php dpm($page); ?>` is `['content']['system_main']['main']['#markup']`, and that can't be separated, obviously.

# Answer
> 0 votes
As per my understanding, why you want to doing via coding. Create views exposed filter as blocks and place in the sidebar and by default the content will load in the right side of the content area. Now you will get filters and content separately...

---
Tags: 7, theming, views, debugging
---


# Question
Title: Updating content to remove it from the front page shows it as being 'New'
I am removing content from the front page as it is out dated, but I don't want to un-publish it as it remains valid information.

Unfortunately Drupal then labels the old article as 'New' and put it to the top of the content list, exactly the opposite effect of the one intended.

How can I stop this?

# Answer
> 1 votes
You should "uncheck" the checkbox "promoted to the frontpage" (which is shown when you 'edit' such nodes). That way it will not be shown on the frontpage anymore.

# Answer
> 1 votes
Edit the respective node those you want to remove the front page and uncheck the checkbox 'Promoted to the frontpage' and save it. This will remove your out dated content from the front page

# Answer
> 1 votes
That "new"/"updated" label is drupal feature to show users that particular content is new / has changed since his last visit - its "per user", every user can see different content as new.

I would change your "content list" instead of this built-in behavior. I guess content list is view and you can add sorting / filter to that view with "Node: has new content" property.

Edit: but if you want to disable it, you can disable Tracker core module.

---
Tags: nodes
---


# Question
Title: Select selection exposed filter using XML Views Backend
I'm using the Views XML Backend to pull in data from a URL.

I'd like the user to be able to optionally be able to select a value for a single field and display the record for that selection. For example, if the XML had information for different offices, I'd like to show the user the records for all of the offices, but allow them to pick a specific office from the list to see only the record for that office. The URL can take a query string or POST parameter with the search terms, but I'm fine with letting the search be done by Drupal.

How do I achieve this in a way that leverages Drupal's capabilities, as opposed to doing the filtering in jQuery?

I already have the view created, but I only see exposed filter options I saw were *XML: Numeric*, *XML: Text*, and *Global: Combine fields filter*. What I'm looking for is something like *XML: Pick a Value*.

# Answer
The Views XML has no idea of the data in your XML. Have you seen this tutorial video from the project page for Views XML Backend.

http://screencast.com/t/mnfEHRT7

They create a simple exposed filter for 1 xml "field" in the view that is searchable by a text filter. This is the simplest form of what you want. Using the *exact* same type of filter you could:

* use `hook_views_preview` and change text field to a `select list` with options. You would build the options for the list by re-processing your XML file and using xpath queries to find the possible values you want in your select list. You'd likely want to cache these results to a drupal cache table.
* you could also attempt to create your own `Views Filter` that does this; but thats harder too.
> 0 votes

# Answer
Interesting question ... There is an alternative to what is suggested in the prior answer, consider looking at the Forena module. There is no "need" for coding skills (e.g. in a custom module), only site building skills are required. Though you 'could' use Forena hooks from within your own modules if you'd want.

Forena is typically used for all sorts of reporting about external databases in formats such as Oracle, MS SQL, Postgress, MySQL, etc (basically any PDO compliant database). But it can also be used for reporting about data stored in XML files. Such XML related reporting is actually how I first discovered this module. It supports all sorts of things like XPath queries, report parameters, visualization using thigs like dataTables, etc. Refer to it's Community documentation and/or the docu that comes with the module for many more details.

**Notes**:

* Forena has (quite a few) official releases, which seems to not be the case for the Views XML backend yet ...
* Using Forena could also address most, if not all, of what's asked for in the question about Pagination using XML Views Backend ...

Disclosure: I'm a **co**-maintainer of this module,
I hope this does not violate the site's policy on self-promotion.
> 0 votes

---
Tags: views
---


# Question
Title: How to set Cron Job in custom module for specific time in Drupal 7
I am building Drupal 7 Custom Module, my module needs to have cron job running on specific time, instead of the default cron time. How do I implement this?

This is my code for cron :

```
function mymodule_cron() {
    mymodule_data_process();
}

```

# Answer
> 1 votes
You can't. Drupal 7 does not provide this functionality. You have two options:

1. In your `mymodule_cron()`, test if it is after specified time, and at least arbitrary number of hours after previous run (like, 20?). That way your processing will run almost every day, no earlier than specified hour.
2. Make your module require Elysia Cron and use it's scheduling capabilities. That way you will get your code executed everyday, at specified time (5 minutes resolution if Elysia is configured as suggested in their documentation).

**Important:** You cannot assume your task will be executed at specific time. It will be executed at *first opportunity after* the time you specified, whenever, if ever, such opportunity happens. Elysia Cron is pretty good at it, true, but exact time of execution can't be assumed *guaranteed*. Highly probable, to some resolution, maybe. But never guaranteed.

---
Tags: 7, cron
---


title: read only access to prepopulated solr

text:
# Question
Title: read only access to prepopulated solr
I'm new to apachesolr/solr/drupal so please be patient (:

I have running solr-4.10.3 inside tomcat 8 and have "successfully" connected to it from drupal 7 via apachesolr.

The solr core that I've set up is already populated with external data and I can search it successfully from the SOLR web interface. The population was not done through drupal/apachesolr indexing mechanism, but directly into solr.

How can I search my data?

I can see my fields when I go to

http://localhost:8080/site/#overlay=admin/reports/apachesolr/solr

but they are all listed as "NOT INDEXED"

I'd appreciate any help or advice.

Nat

# Answer
> 1 votes
I can recommend taking a look at Sarnia

> Sarnia allows a Drupal site to interact with and display data from Solr cores with arbitrary schemas, mainly by building views. This is useful for Solr cores that index large, external (ie, non-Drupal) datasets that either aren't practical to store in Drupal or that are already indexed in Solr.

I am using to search a solr index with emails imported with the dih

# Answer
> 0 votes
I have a website that uses the apachesolr module with a completely external, read-only index.

What I have done is:

* Indexing happens outside of Drupal.
* I have added all my index fields to the solr schema.xml file.
* I implement hook\_facetapi\_facet\_info() for the fields I want to use facets with. Note that this isn't needed for basic search to work.

and this works fine.

In the report I get legit stats for number of items in the index and it shows my fields. I don't get distinct term counts though because I have more than 20000 items in the index.

I do not see "NOT INDEXED" anywhere.

I also have some customisations to facet blocks and a custom sort block but that is just for my specific use case, it isn't a requirement.

The other part to my setup is my search pages are all custom pages in a custom module that manually run queries using apachesolr\_drupal\_query() and apachesolr\_do\_query().

I'm not sure how feasible it is to use the out of the box search page with an external index.

The apachesolr\_search module is a useful example of search functionality. You might find there are chunks of that module you can copy and paste and modify to suit your needs.

To implement a custom search page you need a hook\_menu() callback for your page, for which there are many examples around the internet.

There are a lot of ways you could implement it based on your requirements and preference but the way I have it is my menu item points to a search results page that by default shows x number of results, not filtered in any way.

If there is a url segment after the search url that is taken as the search keys (entry into search box), just like the default drupal search and apachesolr\_search work.

Then I have the normal drupal search box, which has been form altered to add a custom submit handler that redirects (via $form\_state\['redirect'\]) to my search page with any keys appended.

I then use facetapi facet blocks as usual. The facet blocks should link to whatever the current search is and they pass facets in as query string params (from memory I think that's how it works).

So for those to work the custom search page also checks for any facet query strings to pass into its query.

As mentioned before I have a custom search block, which also passes search options via the query string. This is heavily based on the apachesolr\_search module sort block.

So your custom page really assembles search keys and query string params for facets and sort into a query, runs it, then returns the results. You can return the results in any format you choose. As per hook\_menu() usage you will return a render array or a string of HTML.

I would recommend using custom theme functions to output your results. So you get the results from your query and pass them as variables into your template, which returns the markup.

See hook\_theme() for more information on creating theme templates.

So that brings you to the main part, the solr query.

For this you can use apachesolr\_search\_search\_results() as an example and take from that the parts you find relevant to your usage.

The main parts are:
apachesolr\_get\_solr() to load the search environment you want to use to search on.
apachesolr\_search\_run() to run the actual search.

I found that apachesolr\_search\_run() was not suitable for my needs because it did some things I didn't want, like processing the response in a way that doesn't suit your my data.

So I took the parts from there that I needed instead, which are:
apachesolr\_drupal\_query() to load a query object.
apachesolr\_do\_query() to run the query.
apachesolr\_has\_searched() to tell the system that a search has been run.
This is used for things like facet blocks later in the page load.

So in the end the basis of the search is:

apachesolr\_get\_solr()
apachesolr\_drupal\_query()
apachesolr\_do\_query()
apachesolr\_has\_searched()

Now your use case may mean you want to utilise some other parts of the apachesolr module but if you start from apachesolr\_search\_search\_results() and follow it through you can see how it works and take the parts you want.

I'm sure given more time I could improve my solution but it currently gives the results I require.

I'm not sure how complex your searching is but be aware that there is a fair bit of caching that goes on when running these searches. It is used for things like facets, so that they know what the current page's search was to show you its facets.
If you are doing multiple searches on a single page load you will run into issues, but that's probably outside the scope of this specific question, which is just to get basic searching running.

It's worth noting that my search index structure was very different from a normal drupal content one and my search requirements were very custom, so there may be simpler ways to do this for a simpler setup, but this is definitely one option that works.

---
Tags: search
---


# Question
Title: Display all values in a facet block even when a value is selected
I have facet block which looks like:

```
Categories:
[ ] Category 1
[ ] Category 2
[ ] Category 3
[ ] Category 4

```

Categories are represented with the ss\_category field (single string field). When a category is selected, all the other categories disappear, which makes the block looks like:

```
Categories:
[X] Category 3

```

I need all the other categories to remain displayed even when there is an active category, so that the user doesn't have to unclick the active category first then click another one. In other words the block should look like:

```
Categories:
[ ] Category 1
[ ] Category 2
[X] Category 3
[ ] Category 4

```

How can I achieve this behavior in Drupal 6?

# Answer
> 0 votes
I need the same behavior, with drupal 7.

I know 2 ways :

Use a facet block use minimal facet count rewrite yourself the missing facets

---
Tags: 6, search
---


title: PlaceHolder in comment Form

text:
# Question
Title: PlaceHolder in comment Form
I want to add a placeholder to my all comment form , here is what i did :

**template.php**

```
function ThemeName_form_alter(&$form, &$form_state, $form_id) {
    if ($form_id == 'search_block_form') {
        // HTML5 placeholder attribute
        $form['search_block_form']['#attributes']['placeholder'] = t('Serach ...');

    }

    switch ($form_id)  {
        case 'comment_form':
            $form['name']['#attributes']['placeholder'] = t( 'Name' );
            $form['subject']['#attributes'] = array('placeholder' => t('Subject'));
            $form['comment_body']['#attributes'] = array('placeholder' => t('comment'));

            break;
    }

}

```

nothing happend , Any Help ?

Thanks

**Update**
Finally i could add placeholder to comment form like this

```
function sizin_form_comment_form_alter(&$form, &$form_state)
{
    $form['author']['name']['#attributes']['placeholder'] = t( 'Name' );
    $form['author']['name']['#title']= FALSE;

    //Subject
    $form['your_comment']['subject'] = $form['subject'];
    $form['your_comment']['subject']['#title'] = FALSE;
    $form['your_comment']['subject']['#attributes'] = array('placeholder' => t('title'));
    unset($form['subject']);
    $form['your_comment']['subject']['#weight'] = -10;

    //Comment
    $form['your_comment']['comment_body'] = $form['comment_body'];
    $form['your_comment']['comment_body'][LANGUAGE_NONE][0]['value']['#attributes'] = array('placeholder' => t('comment'));
    unset($form['comment_body']);

}

```

But i couldn't add to textarea(comment Body) ? AnyHelp ?

# Answer
> 1 votes
Reading through Placeholder module I come to know this

> Once FAPI uses HTML5 to render elements, this module can be replaced by the "placeholder" attribute available as part of the HTML5 spec. You can update the FAPI to use the "placeholder" attribute right now by using elements module. This means that this module is only useful if you are concerned about older browsers that do not support "placeholder".

try using elements module so the support for HTML5 attribute can become available in your installation.

Here is the way to add default placeholder attribute.

# Answer
> 1 votes
Thanks @tonystar

Instead of:

```
$form['your_comment']['comment_body'][LANGUAGE_NONE][0]['value']['#attributes'] = array('placeholder' => t('comment'));

```

add this:

```
$form['your_comment']['comment_body'][LANGUAGE_NONE][0]['#attributes']['placeholder'] = t('comment');

```

# Answer
> 0 votes
Install Placeholder Module

Then you can use

```
$form['name']['#placeholder'] = t( 'Name' );
$form['subject']['#placeholder'] = t('Subject');
$form['comment_body']['#placeholder'] = t('comment');

```

---
Tags: comments, forms
---


# Question
Title: Two random blocks displaying different fields from the same node
I have a content type with field\_1 and field\_2. I want to have two blocks displaying different fields from a **one** random node. I can easily create two random blocks via views module, but they wil not be synchronized. Any ideas?

# Answer
1. Define helper function like `_random_node_id()` which stores generated id in the static variable.
2. Use this function as an argument in the view.

This function will return a random node id, but called twice on the same page it would return the same id (because it is static).
> 1 votes

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


# Question
Title: Use 'Contains' in better exposed filters?
I have a taxonomy of Office departments that I am using to filter my contacts which are brought into drupal with Ldap to search people by department. Some contacts have more info in their dept field when brought in from Ldap. For example 'Credit - London' instead of just credit. Is the a way to filter by contains 'Credit'? There are no options on the expose filter

# Answer
> 0 votes
If you use the field as textfield, then you will have options to filters department like above.

---
Tags: 7, views
---


# Question
Title: Javascript only runs when logged in as admin
I created a test site. I put the JS into the template.php:

```
drupal_add_js('jQuery(document).ready(function(){jQuery(".foomo").accordion({ collapsible: true, active: false, animated: true});});', 'inline');

```

File permissions are set as described here.

If I load the website as 'admin' the accordion is collapsed as I want.

But why doesn't open or close the accordion for any other user?

# Answer
I switched to the views\_accordion module, which works perfect: embedded views wrapped by views\_accordion
> 0 votes

---
Tags: users, navigation
---


# Question
Title: Using arguments in addConstraint() for validation
I implemented `hook_entity_bundle_field_info_alter()` to add validation to fields of a node type. I got `$bundle` as an argument in the hook and I need to pass it in `$options` argument like below:

```
$fields['field_tags']->addConstraint('NodeValidate', $bundle);

```

How can I access this argument in `NodeValidateConstraintValidator`? Am I passing the argument correctly?

`$options` provided in `addConstraint` can be accessed in the constructor using `parent::__construct($options)` in `__construct()` function build the options.

`hook_entity_base_field_info_alter()` doesn't contain a `$bundle` argument, as it is defined as `function hook_entity_base_field_info_alter(&$fields, \Drupal\Core\Entity\EntityTypeInterface $entity_type)`. How can I validate the base field for a particular node type?

# Answer
1. Options needs to be an array I think. You can access it on the constraint object in your validator, see `ListStringItem::propertyDefinitions()` and LengthValidator, which then uses it as $constraint-\>max.
2. Base fields are exactly that. Base fields. There is no bundle, they are the same for all bundles of an entity type (they can be overriden per-bundle, but then they become accessible in the bundle hook).
3. You shouldn't ask two different questions together :)
> 1 votes

# Answer
To pass arguments in `addConstraint()` something like:

```
$fields['field_tags]->addConstraint('NodeValidate', array('bundle' => 'article));

```

You should create a constructor in `NodeValidateConstraint.php` and calling the `parent constructor` like below:

**You should need to declare a property name same as the name of the key in the options you passed. In this case it is `bundle`.**

```
class NodeValidateConstraint extends Constraint {
  public $bundle;
  public function __construct($options = null)
  {
      parent::__construct($options);
  }
}

```

Now you could access the $options in `NodeValidateConstraintValidator.php` as

```
$bundle_name = $constraint->bundle;

```

Thanks berdir for guiding me in this and continuously responding to my queries in drupal 8:)
> 0 votes

---
Tags: 8, nodes
---


# Question
Title: Disable or remove permissions for Scald page display
It appears to me that Scald does not have a permission allowing you to set who can view the "page view" of the atom /atom/ATOMID.

Is there some way to restrict access to this page or revoke permissions from roles?

# Answer
This is a partial answer, simply blocks non-logged in visitors:

```
function MYMODULE_init() {
  // Prevent public users from seeing the atom pages
  global $user;
  if(arg(0) == 'atom' && !$user->uid) {
    drupal_not_found();
    exit;
  }
}

```

I would really like it if there was a permission on the scald module, logged an issue on d.o for that https://www.drupal.org/node/2512692.

**Edit**: there is a patch on that d.o issue which adds a permission to 'access atom page view', which is a better solution to the use of hook\_init() above.
> 1 votes

---
Tags: 7, scald
---


# Question
Title: Calculate webform total from select list fields
Like e.g. there are two select options type components that has various amounts of $ to select from. So if user selects in one field $100 and $200 then the next field below it would generate the total which would be $300 in this example.

I did research, and the module Webform Calculation Components does the exact thing I want, but it does that only with numeric fields where user has to type amounts manually. So it's a no-go. In my case user has to select from drop-down list already given amounts.

Cheers

# Answer
> 1 votes
You can use Webform Calculator module for your purpose.

This module provides a formula webform component for computed values, where you can enter a mathematical calculation based on the other fields. E.g. Create a formula field with value formkey1 * 0.1 * formkey2.

Let us know incase of any concern/query regarding this.

Thanks!

---
Tags: 7, webforms
---


# Question
Title: How to let users register with their Facebook accounts?
I would like to let visitors choose between signing up by using Drupal's core sign-up system, or to register using their Facebook account.

I looked at a few Facebook related modules but that was a little confusing, and I couldn't make up my mind on which one to use (I don't use Facebook myself so I guess that doesn't help).

What are the differences between regular registered users and those who signed up using their Facebook account?
Will Drupal have access to their emails?

# Answer
I've tried out all of the current suggestions, have used both Drupal for Facebook and FBConnect on sites in non-trivial ways, and only pain lies down those roads.

If all you need is authentication and maybe a few imported user profile fields (such as e-mail) go with FBOauth. Its newer, but is far easier to set up and use, and far easier to build off of if you're not trying anything too extraordinary.

The relationship between regular users and Facebook users depends a lot on the module you pick. In general all the modules create a table that associates FB ids with drupal user ids. How that happens varies widely. If you need a lot of flexibility in terms of account linking FBConnect is pretty full featured in that area but tends to be buggy elsewhere.
> 3 votes

# Answer
Drupal for FaceBook is the one you need.

You can configure application settings and which information you want to get from users, such as email address.

Unlike other suggestions, this module does not rely on third party providers and registrations other than Facebook.
> 5 votes

# Answer
Facebook Connect works out of the box. I have been using it in a couple of sites.
> 2 votes

# Answer
Use this module Drupal Janrain

You can even get different user information from the social media account depending on his privacy.
> 1 votes

# Answer
I've been a fan of Simple FB Connect which hasn't been mentioned. It's fairly new and it relies on Facebook's PHP SDK so hopefully the team will be able to keep up with API changes. Here's a tutorial for Drupal Facebook login using Simple FB Connect and a roundup of related solutions. FBOAuth, mentioned, is also a good solution.

Ultimately, the trouble with these third party logins is keeping your integration updated with constant API changes from the third party.
> 0 votes

# Answer
Simple FB Connect module allows users to register and login to your Drupal site with their Facebook account. and they provide both choice login through website and login through facebook. And you can find more details through login with Facebook link.
> 0 votes

---
Tags: 7, users, social-network
---


# Question
Title: How to get plain link with views-data-export module in CSV?
I have a view with field that provides a simple link to the content.

**Problem**: When I export the data into a csv file there is only the word `link` instead of a link.

How can I get there the content URL instead of the word `link`?

# Answer
> 1 votes
CSV is not an interactive format. When you export column with literal "link" in it's data, you get link in CSV.

Instead of exporting word column, with link added at rewrite or template level, export column that actually contains the URL you want. For nodes, this issue indicates that you should be able to use 'Path' field, description: 'The aliased path to this node.'.

---
Tags: views, navigation, importing-exporting
---


# Question
Title: Banner block (referenced by url) not displayed when using language extensions
I have a Banner View block that appears on pages using a reference url field.

When the url: `thispage` is entered in the reference field of the banner, it appears on `domain.com/thispage`.

Now that i enabled 2 other languages en + de this reference is not working. Entering the url with the language extension (`en/thispage`) neither.

I looked into the Views Block. Maybe some code needs to be added. The block has this code under Visibility settings:

```
<?php $nids=arg(1); $datas=node_load($nids); if ( $datas->type=='referenced' ) { return false; } else{ return true; } ?>

```

In the View under contextual filter there is some global php. This might be changed to match the path from other languages (de/thispage)

This is the code from Views:

```
$match_path = ltrim($_SERVER['REQUEST_URI'], '/');

```

$match\_path=explode("/",$match\_path); $match\_path=explode("?",$match\_path\[0\]); return $match\_path\[0\]; //return $\_GET\['q'\];

Any suggestions about how to resolve this?

# Answer
You may want to check your configuration at `Configuration -> Languages -> detection and selection`: the order specified there could be what explains the current behaviour in your site.

You'd have to experiment a bit with what the exact order in your case should be. In my experience, I often get these kind of issues to work by using an order like 'URL, Default, User', and not something like 'Default, URL, User'. So try to experiment a bit with the various combinations in this order to see if it helps.
> 0 votes

---
Tags: blocks, i18n-l10n, nodes
---


# Question
Title: Using field api to get key of select list option
I need the safe output of a key from a select list field within a field collection item.

I'm theming a field collection item and one of the fields is a select list like:

```
icon-map|Map
icon-info|Info
icon-pencil|Pencil

```

I'm using the following to create some easy to use variables;

```
$fields = array_keys($content);
foreach ($fields as $field) {
  $field_items = field_get_items('field_collection_item', $content[$field]['#object'], $field);
  $$field = render(field_view_value('field_collection_item', $content[$field]['#object'], $field, $field_items[0]));
}

```

This works fine for all fields except for the select list. I need the `key` of that select list. For this select list field, `$field_items` is an array which looks like:

```
array(1) { [0]=> &array(1) { ["value"]=> string(13) "icon-map" } }

```

However, `$field_icon` (result of `$$field = render(..)` ) is `Map`, which makes sense.

I can get the key by using `$field_items[0]['value']` but I'm not sure that's the best way.

# Answer
> 2 votes
I hope this may help

```
 $key = $form_state['values']['whatever'];
$options = list_allowed_values("field_whatever");
$value = $options[$key];

```

---
Tags: entities
---


# Question
Title: Moving a number of fields into a table on D7 node form
I have a form with three field groups, arranged as horizontal tabs.

On one of these tabs, I have twelve fields. For eight of these fields, I would like to arrange them inside of a table.

These fields are date popup fields.

Each of the fields has its label removed; I'm just trying to have a table where the field labels are in the header and the actual tags are inside the table rows.

I'm using the code below to remove the labels (it was difficult to figure out, so if anyone can use it)

However, I'm not yet sure how to then place the resulting fields into a table format.

My first thought was a theme function for the entire form, but how would I insert the table into one of the tabs? drupal\_render() would not work for that.

Will I just have to go through each item individually?

Thanks for your help.

```
<?php
function MYMODULE_form_recruitment_process_node_form_alter(&$form, &$form_state, $form_id) {
    $date_fields = array(
        'field_special_1',
        'field_special_2',
        'field_special_3',
        'field_special_4',
        'field_special_5',
        'field_special_6',
        'field_special_7',
        'field_special_8',
        'field_special_9',
        'field_special_10',
    );

    foreach ($date_fields as $field_name) {
        $form[$field_name][LANGUAGE_NONE][0]['#title_display'] = 'invisible';
    }
}

function MYMODULE_element_info_alter(&$type) {
    if (isset($type['date_popup'])) {
        $type['date_popup']['#process'][] = 'MYMODULE_date_popup_process';
    }
}

function MYMODULE_date_popup_process($element, $form_state, $complete_form) {
    // Get the field name and create an array of fields we want to change.
    $field_name = $element['#field']['field_name'];
    $valid_fields = array(
        'field_special_1',
        'field_special_2',
        'field_special_3',
        'field_special_4',
        'field_special_5',
        'field_special_6',
        'field_special_7',
        'field_special_8',
        'field_special_9',
        'field_special_10',
    );

    // If it's not the field we want, return it unchanged.
    if (!in_array($field_name, $valid_fields)) {
        return $element;
    }

    $element['date']['#description'] = "";
    $element['date']['#title_display'] = 'invisible';
    $element['time']['#descsription'] = "";
    $element['time']['#title_display'] = 'invisible';

    return $element;
}

```

# Answer
There is an API that will allow you to alter the output of the field group or write your own field group handler. https://www.drupal.org/node/1017962

Using this you could write a custom field group handler that loops through the fields and outputs the data using theme\_table(). This would allow for you to grab the field label and add it to the header array, and then add the fields to the the data array.

After creating your custom field group you can nest the field group under the horizontal tab and nest your fields under the custom group.
> 1 votes

---
Tags: forms, theming
---


# Question
Title: Change order status string from "Completed" to "Shipped"
I'd like to change the order status string from "Completed" to "Shipped" to allow for better communication between us and the customer.

Commerce Custom Order Status would sidestep this problem by allowing me to create a new status, but that isn't the best way around it, because there might be triggers set for "completed".

# Answer
> 3 votes
The best thing for you to do would be to alter the order status info array to give the "Completed" status a new title. The example in the documentation actually demonstrates specifically how to change the title of the completed status. Look for hook\_commerce\_order\_status\_info\_alter() in commerce\_order.api.php.

There are ways to override strings through the user interface, but this is such a small module change that I'd really recommend directly making it in a site-specific module.

# Answer
> 2 votes
I would suggest adding a new order status instead of modifying the "Completed" order status, since that usually means the order is done-done-done. Something like "Pending: Shipping" (in the "Pending" order state) would make more sense given a workflow like this:

* Pending: Pending -- The order is paid and ready for shipping.
* Pending: Shipping\* -- The order has shipped and may have a tracking number attached. \*Note: You would need to add this status value in a custom module.
* Completed: Completed -- The order was delivered, shipping has been fulfilled, no further action required by the store.

See also:

You can certainly add to the "Pending" state as suggested above for something simple. For a more detailed example, you can also have a separate "Shipping" state and statuses:

```
/**
 * Shipping status
 */
define('SHIPPING_PENDING', 'shipping_pending');
define('SHIPPING_SHIPPED', 'shipping_shipped');
define('SHIPPING_DELAYED', 'shipping_delayed');
define('SHIPPING_CANCELED', 'shipping_canceled');
define('SHIPPING_DELIVERED', 'shipping_delivered');

/**
 * Implements hook_commerce_order_state_info()
 */
function example_commerce_order_state_info() {
  $order_states = array();

  $order_states['shipping'] = array(
    'name' => 'shipping',
    'title' => t('Shipping'),
    'description' => t('Orders in the shipping process.'),
    'weight' => 10,
    'default_status' => SHIPPING_PENDING,
  );

  return $order_states;
}

/**
 * Implements hook_commerce_order_status_info()
 */
function example_commerce_order_status_info() {
  $order_statuses = array();

  $order_statuses[SHIPPING_PENDING] = array(
    'name' => SHIPPING_PENDING,
    'title' => t('Shipping: Pending'),
    'state' => 'shipping',
    'weight' => 1,
  );
  $order_statuses[SHIPPING_SHIPPED] = array(
    'name' => SHIPPING_SHIPPED,
    'title' => t('Shipping: Shipped'),
    'state' => 'shipping',
    'weight' => 2,
  );
  $order_statuses[SHIPPING_DELAYED] = array(
    'name' => SHIPPING_DELAYED,
    'title' => t('Shipping: Delayed'),
    'state' => 'shipping',
    'weight' => 3,
  );
  $order_statuses[SHIPPING_CANCELED] = array(
    'name' => SHIPPING_CANCELED,
    'title' => t('Shipping: Canceled'),
    'state' => 'shipping',
    'weight' => 4,
  );
  $order_statuses[SHIPPING_DELIVERED] = array(
    'name' => SHIPPING_DELIVERED,
    'title' => t('Shipping: Delivered'),
    'state' => 'shipping',
    'weight' => 5,
  );

  return $order_statuses;
}

```

# Answer
> 0 votes
You can use the drupalcommerce complete hook to change the $order status:

```
function hook_commerce_checkout_complete($order) {
  // insert code
}

```

---
Tags: 7, commerce
---


# Question
Title: How to add a correlated subquery expression in hook_views_query_alter?
In hook\_views\_query\_alter, how to add a condition which is a correlated subquery in which the value of the condition is an expression?

Given a view the produces this query:

```
SELECT node.nid, node.title, history.state
FROM node n
LEFT JOIN node_revision nr ON n.vid = nr.vid
INNER JOIN history h ON nr.vid = h.vid
WHERE (( (node.type IN ('blog')) ))

```

In order to show only the latest \[state\] for a given version (vid) of a node, we need to add this condition:

```
AND h.hid = (select max(hid) from history h2
where h2.nid = n.nid
and h2.vid = n.vid group by h.nid, h.vid)

```

So here's the statement we'd like to end up with after hook\_views\_query\_alter:

```
SELECT node.nid, node.title, history.state
FROM node n
LEFT JOIN node_revision nr ON n.vid = nr.vid
INNER JOIN history h ON nr.vid = h.vid
WHERE (( (node.type IN ('blog')) ))
AND h.hid = (select max(hid) from history h2
where h2.nid = n.nid
and h2.vid = n.vid
group by h.nid, h.vid)

```

So we can see that our modified sql works, so here's our attempt (not working) to modify the statement on the fly:

```
function mymodule_views_query_alter($view, $query) {
  if ($view->name == 'my_view') {
  $expression = '(select max(hid) from
   workbench_moderation_node_history h
   where h.nid = node.nid
   and h.vid = node.vid
   group by h.nid, h.vid)';

  $condition = array();
  $condition['field'] = 'history.hid';
  $condition['value'][] = $expression;
$condition['operator'] = '=';
$query->where[1]['conditions'][] = $condition;
  }
}

```

This doesn't work (with or without the parenthesis) because the condition is an expression, not a value. To validate that the syntax of adding a condition is correct, this will at least return results:

```
function mymodule_views_query_alter($view, $query) {
  if ($view->name == 'my_view') {
    $condition = array();
    $condition['field'] = 'history.hid';
    $condition['value'][] = '1';
    $condition['operator'] = '>';
    $query->where[1]['conditions'][] = $condition;
  }
}

```

How might we go about coding this constraint?

# Answer
This doesn't answer the question as stated, but provides a very simple approach to get at the result using Views without implementing hook\_views\_query\_alter.

The example provided is for workbench\_moderation, although the principle applies in other scenarios as well:

Creating a new Workbench view showing recently updated content and its state
> 0 votes

---
Tags: database, views
---


# Question
Title: Code for view, and module name in path besides node id
I am using this snip Stefan Lehmann gave me here to have a different image based on node, problem is it works fine with the id, but a couple of the nodes are views, and one is contact, how do I declare those?

```
<?php
$node = menu_get_object();
$menu_image = 'arrow_home.png';
if (!empty($node)) {
  $images = array(2 => 'arrow_home.png', 3 => 'arrow_formazione.png', 4 => 'arrow_workshop.png', 5 => 'arrow_raccontabito.png');
  $menu_image = isset($images[$node->nid]) ? $images[$node->nid] : $menu_image;
}
?>
<div class="fz-menu-bg">
<img src="/sites/all/themes/business/images/fz/<?php print $menu_image; ?>" />
</div>

```

This is the structure:

* example.com/node/2 \<\<\< snip ok
* example.com/node/3 \<\<\< snip ok
* example.com/node/4 \<\<\< snip ok
* example.com/node/**gallery \<\<\< view name/path - what code do I need**
* example.com/node/**contact \<\<\< contact module - what code do I need**

Thank you

# Answer
> 0 votes
In that same block of code, can do an arg() check.

```
$node = menu_get_object();
$menu_image = 'arrow_home.png';
if (!empty($node)) {
  $images = array(2 => 'arrow_home.png', 3 => 'arrow_formazione.png', 4 => 'arrow_workshop.png', 5 => 'arrow_raccontabito.png');
  $menu_image = isset($images[$node->nid]) ? $images[$node->nid] : $menu_image;
}
if (arg(1) == 'gallery') {
  $menu_image = 'arrow_gallery.png';
}
elseif (arg(1) == 'contact') {
  $menu_image = 'arrow_contact.png';
}

```

Note: This will only work as long as the URL structure stays the same.

Also, this code depends on where you are preprocessing the image. If you are using `template_preprocess_node()` the above will not work because those two pages, even though they are located at the node path, are not nodes.

---
Tags: views, 7
---


title: 200 Error on second Ajax request

text:
# Question
Title: 200 Error on second Ajax request
I am creating a custom module. And I'm having trouble with ajax. I've looked for the answer haven't found anyone with a similar problem.

**What's supposed to happen:**

Insert a date on the textfield. Click the button and the data below will change depending on the date. Data is stored on json files.

**What's the problem:**

Only the first request works. From the second request on it gives an error code 200 with an empty response.

**What I've tested**

I have tested with a simpler ajax where I get a specific data from a file and output the data on a div. It stops working when I use the "page" element.

**Here's my code:**

```
$form['dates'] = array(
    '#type'=>'textfield',
    '#title'=>'Choose the date',
    '#id'=>'datepicker',
    '#default_value'=>$selected,
);

$form ['submit'] = array (
            '#type' => 'submit',
            '#ajax' => array (
                    'callback' => 'freports_alunos_dados_callback',
                    'wrapper' => 'dados_content_wrapper',
                    'effect' =>'fade',
            )
            ,
            '#value' => t ( 'Ver Dados' )
    );

    $form['page'] = array(
            '#theme' => 'freports_alunos_tpl',
            '#type' => 'markup',
            '#prefix' => '<div id="dados_content_wrapper">',
            '#suffix' =>'</div>',
            '#dados' => freports_get_dados($selected),
    );

function freports_alunos_dados_callback($form, &$form_state){
    $element = $form['page']; // << FROM MY TESTS THE PROBLEM STARTS HERE
    $element['#dados'] = freports_get_dados($form_state['values']['datas']);
    return $element;
}

function freports_theme($existing, $type, $theme, $path) {
    return array (
            'freports_alunos_tpl' => array (
                    'variables' => array (
                            'dados' => NULL
                    ),
                    'template' => 'tpl/alunos'
            ),
            'freports_curso_alunos_tpl' => array (
                    'variables' => array (
                            'dados' => NULL,
                            'filial' => NULL,
                            'curso' => NULL
                    ),
                    'template' => 'tpl/curso_alunos'
            ),
            'freports_turma_alunos_tpl' => array (
                    'variables' => array (
                            'dados' => NULL,
                            'filial' => NULL,
                            'curso' => NULL,
                            'turma' => NULL
                    ),
                    'template' => 'tpl/turma_alunos'
            )
    );
}

```

**Page TPL:**

```
<?php
drupal_add_js(drupal_get_path('module','freports').'/js/freports.js','file');
?>

<div>
<!-- <strong>Escolher Data: </strong><input type="text" id="datepicker"><button onclick="getData(document.getElementById('datepicker').value)">Go</button><br /> -->
<strong>Atualizado em: </strong><?php print $dados->updated ?><br /><br />
<strong>Total Alunos: </strong><?php print $dados->totalAlunos;?><br />
<strong>Total Gama: </strong><?php print $dados->filial[0]->totalAlunos; ?><br />
<strong>Total Lago: </strong><?php print $dados->filial[1]->totalAlunos; ?><br />
<br /><br />

<table>
    <tr ALIGN=center>
        <td COLSPAN="2"><strong> CAMPUS - GAMA </strong></td>
    </tr>
    <tr>
        <td><strong>Curso</strong></td>
        <td><strong>Total Alunos<strong></td>
    </tr>
<?php $i=0; foreach($dados->filial[0]->cursos as $cursos_gama){ ?>
    <tr style="border-bottom:1px solid black;">
        <td><a href="<?php print 'alunos/filial/0/curso/'.$i ?>"><?php print $cursos_gama->nome; ?></a></td>
        <td style="text-align:right;"><?php print $cursos_gama->totalAlunos; ?></td>
    </tr>
<?php $i++;} ?>
</table>
<br /><br />
<table>
    <tr ALIGN=center>
        <td COLSPAN="2"><strong> CAMPUS - LAGO </strong></td>
    </tr>
    <tr>
        <td><strong>Curso</strong></td>
        <td><strong>Total Alunos<strong></td>
    </tr>
<?php $i=0; foreach($dados->filial[1]->cursos as $cursos_lago){ ?>
    <tr style="border-bottom:1px solid black;">
        <td><a href="<?php print 'alunos/filial/1/curso/'.$i ?>"><?php print $cursos_lago->nome; ?></a></td>
        <td style="text-align:right;"><?php print $cursos_lago->totalAlunos; ?></td>
    </tr>
<?php $i++;} ?>
</table>

```

# Answer
> -1 votes
I solved my problem.

I didn't close the `<div>` while testing the `.tpl.php` page file.

---
Tags: 7, ajax
---


# Question
Title: How to conditionally load javascript file on view page
I'm trying to load some theme javascript only to one view(multiple displays). I've tried to use the views preprocessor funciton, but maybe I'm doing it wrong:

```
function themename_preprocess_views_view__viewname__page(&$variables){
  this doesn't run on view page;
}

```

I've also tried it with the function name `themename_views_view()`. There's not much documentation on this.

# Answer
> 2 votes
This should work:

```
/**
 * Implements template_preprocess_views_view().
 */
function themename_preprocess_views_view(&$vars) {
  $view = $vars['view'];
  if ($view->name == 'view_name') {
    // Standardize the output for rows.
    drupal_add_js(drupal_get_path('theme', 'themename') . '/js/js_name.min.js', array('scope' => 'footer'));
  }
}

```

# Answer
> 1 votes
Place this in your `template.php` and clear cache

```
<?php
function THEME_NAME_preprocess_views_view(&$vars) {
  $view = $vars['view'];

  if($view->name == 'YOUR_VIEW_NAME' && $view->current_display == 'YOUR_DISPLAY') {

    global $theme_path;
    drupal_add_js($theme_path . '/js/myfile.js');
    //OR MAYBE
    drupal_add_library('system','ui.slider');
  }
}

```

---
Tags: views, theming, javascript
---


# Question
Title: Configure Menu Access Visibility and permission
I have a question for Menu Visibility. I have an entire live site in production. I am trying to build editorial workflow for my editors, other editors and approvers. I am using Workbench Access and Node Access module.

I wanted to set access permission for menu. Currently, when user create a content, he can chooses menu item from entire "Main Menu section". I don't want them to add any new page in main menu(Home page) as it will ruin my design.

Currently, my menu structure is:

**\- Main Menu (Home)**

* About (Parent 1)
    + Child item
    + Child Item
* Admissions (Parent 2)
    + Child Item
    + Child Item
* (Parent 3)
    + Child Item
    + Child Item
* (Parent 4)
    + Child Item
    + Child Item

I don't want user to add any content directly in main menu(home page). I want them to just see parent menu items when they create new content and can add them in menu in any parent item or child item. but **NOT** in **Main menu(Home)**.

I also found two modules but not sure if these are right choice or not.

1) Menu Item Visibility

2) Menu Admin per Role

Thanks!

# Answer
If you edit the content type's menu settings, you can see the menus allowed, you can also set the default parent item. You could set up multiple content types with each one representing one parent, then remove the permission to change menu settings. That way each content type will pick the appropriate parent automatically.
> 0 votes

---
Tags: nodes, routes, users, workbench
---


title: Conditional Fields is not working

text:
# Question
Title: Conditional Fields is not working
I m using Conditional Fields for Drupal 7 to create country state relational dropdown in my Field Collection module, but it is not working properly.

I created Country **US** and **Canada** and, depending upon those, **US States** and **Canadian States**; I created the relation, but in the front end all the drop-downs are shown.

Can anyone suggest me what I am doing wrong? If this module does not work, how do I create a country state relational dropdown in my **Field Collection**?

# Answer
> 1 votes
The other option to try is a custom form alter and add the #states key to those fields. This is a code only, no ui approach, but it should work just as well for what you are looking to accomplish.

Here is an article that describes how to use #states. http://randyfay.com/states

# Answer
> 0 votes
You can try the patch Here to enable field collection work with conditional fields. Optionally, instead of the field collection module, you can use the Fieldgroup module with conditional fields and apply This Fix, that personally worked for me.

Alternatively, you can use Hierarchial Select to create relational dropdown (i have suggested this module because you mentioned country and state relationships). Hierrachial select however doesnt work well with views exposed filters, but there is a suggested workaround in this issue

There is also Simple Hierarchial Select which works for nodes and views exposed filters

---
Tags: views, commerce, entities
---


title: Views Field View - No results behavior

text:
# Question
Title: Views Field View - No results behavior
I have a view with 2 fields - one is another view, one is a node field. I do not want to display the parent view header when the inner view result set is empty and the node field does not have a value. "Display even if view has no result" is unchecked on the header settings but does not work because the parent view always has a result regardless of the presence of a value.

I am trying to add a PHP filter that checks for both criteria. I am running into the old issue that the $row object only contains node ids, but the $data object does not seem to work here, either. It only contains two properties, the view and the entity type of the attribute (called field\_data\_field\_electronics\_description\_node\_entity\_type in this case).

So, this does not work for my filter code because the entity type is always set, even when the value is empty:

```
if ($row->view != NULL ||
   $data->field_data_field_electronics_description_node_entity_type != "" )
{
   return FALSE;
}
else return TRUE;

```

This does not work because field\_electronics\_description always contains the node id, regardless of the presence of a value:

```
if ($row->view != NULL || $row->field_electronics_description != "" ) {

```

I don't see anything else in the $data object in devel that I could use. How can I suppress the parent view display?

# Answer
> 0 votes
The answer was - the node fields are not available and you have to reload the node, like so:

```
$nodef = node_load($data->nid);
$el = $nodef->field_electronics_description[und][0][value];

if ($row->view != NULL ||  $el != NULL) {
   return FALSE;
}
else return TRUE;

```

---
Tags: 7, views
---


# Question
Title: How to change color and sidebar menu without using themes
We have a number of different themes on our website as we have different departments with different color styles. However, the only thing that changes are the colors of the sidebar and which menu is displayed on the sidebar; the layout of these pages remain the same almost exclusively. It seems as though having 16 different themes, which we do, is unnecessary if these are the only things changing (sidebar color and menu).

Are there any good modules which could achieve this functionality (changing color and menu depending on department) without having all these different themes? Or are themes the only/best way to go to achieve this functionality? Also is having this many themes the average or is that a lot?

# Answer
There are 16 different departments so 16 different colors are needed. Create one theme for all of them. In your .css file create 16 classes and in each one set a custom background color. Like this

```
.dp—i{ background-color:#abcdef !important}

```

Now using preprocess functions, and based on the department add the css class to the page component. If it is a block use preprocess\_block, if it is region use preprocess\_region. By checking the department and adding approprite css class to the class array it will work
> 0 votes

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


title: How to process the result of a view?

text:
# Question
Title: How to process the result of a view?
I'm working on a publication database, the result should be something like this: http://www.bmj.com/content/350/bmj.h2747 As you can see in authors list and in Author affiliations block, only unique workplaces are listed as footnotes of authors.

I'd like to figure out how this can be reproduced with views (or with other technique)? I created a content types for authors and can filter them for a given article in a view. But the result should be massively process: I have to filter the unique workplaces and assign them to authors in the display.

So as the title asks: How (and where - in the view?) can I process the result of this view?

# Answer
Views can be great for some things, but sometimes it can add more complication then it is worth. Trying to achieve this in views seems like it could be one of those situations.

If you are familiar with coding, it might be easier to process the list of authors, grab the entity\_reference from them, create an array from those where you don't repeat the values and then output the numbers associated with each value.

If looking to do this solely in views, you could use https://api.drupal.org/api/views/views.api.php/function/hook\_views\_pre\_render/7 to grab the results and process them and then output the rows as desired.
> 1 votes

---
Tags: 7, views
---


title: Configure CKEditor plugin

text:
# Question
Title: Configure CKEditor plugin
I have the autosave plugin for CKEditor enabled and working, but I want to change from some of the default settings (specifically save detection selectors and autosave\_delay) and can't get the settings to "stick". I have been editing ckeditor.config.js (in modules/patched/ckeditor/) and, while that's executing, the settings changes aren't making it to the editor instance running on the page. I've also hacked at ckeditor.utils.js because I was able to get closer to the actual instance but I know that isn't best practice and I'll regret it down the road.

Drupal7 fyi

# Answer
You can define (extra) config options in a CKEditor profile. Go to example.com/admin/config/content/ckeditor then select the editor profile(s) in which you have enabled autosave and go to the "Advanced Options".

In the "Custom JavaScript configuration" field you can override config options like

```
config.autosave_saveDetectionSelectors = "a[href^='javascript:__doPostBack'][id*='Save'],a[id*='Cancel']";
config.autosave_delay = 5;

```

No need to alter any of the javascript files.
> 1 votes

---
Tags: wysiwyg
---


# Question
Title: Webform questionnaire with scoring and reports
I've created several long/multipage questionnaires with webform and I need to have a scoring/rating at the end with the results gathered in a report for the user (preferable in pdf). But there are no models available that add a scoring per option and/or per form component.

What would be the preferred way to achieve a score ? Could this be done with Views or with the webform-conditions? or via webform\_validation?

Any recommendation or direction is very appreciated as I'm bit stuck now.

# Answer
If you want to create **charts** from the survey results of the Webform module, there are 2 typical/popular alternatives to pick from:

* Webform Charts (used in about 400 sites), to display Webform results in a graphical manner using a charting library.
* Webform Chart (used in about 220 sites), which integrates with the "Analysis" tab of a Webform (created with the Webform module) to provide charts for each individual component's analytical data.

The Drupal 7 version of both modules, requires the Charts module (dependency).
> 0 votes

---
Tags: views, webforms
---


# Question
Title: How to hide the grid lines from Yaxis and draw only one line from specific Yaxis points?
I am creating a view using the Charts module. I am using the (interactive) Google Charts API as the charting engine.

Is it possible to hide other gridlines and only display one grid line from a specific y axis point?

Just like in this image:

# Answer
> 1 votes
Refer to HowTos about vertical axis, located within the Community documentation of the Charts module. Here is the relevant part of it:

> Refer to #2356053-2: Automatically adjusted value range for vertical axis, which explains how to automatically adjust the minimum and maximum of the Y-axis to fit the available data. Specifying a "Max" and "Min" value is optional. Specifying a minimum of 0 is recommended in the event that numbers will always be positive, while for the maximum value the recommendation is (usually) to just leave it empty.
>
> To experiment with this in your own site, use the column chart with the number of nodes for each content type (located in charts/examples/views ):
>
> * If you do not specify a maximum there, you get a close to perfect chart, no?
> * If however you only have a few nodes (like a dozen or so) but use a huge maximum (like 240 ...), the chart looks not so nice, right?

---
Tags: 7, charts
---


# Question
Title: User photo gallery that another user can view
I'm looking to give my user the ability to to have a personal photo gallery that when another user clicks on their profile they can see said gallery?

I know i can create a content type and view, but not sure where to go from there as far as only exposing the necessary photos for a specific user to another. basically a dumb-ed down version of what Facebook has as far as photos.

# Answer
for some interesting options, take a look at the Album Photos module. I'm not sure if it will do what you're asking OOB, but if you use it, it would change your question so I'll suggest it.

> "Album Photos" is an image album module providing multi-user album features. The module development objective is to provide a comprehensive image album solution for Drupal.
>
> Version 7.x-3.x Highlights
>
> Integrates with core image styles. Uses Libraries API 2.x for Jeditable. Built in support for Colorbox. Vote on images with Voting API. Comment on images. Built in support for Plupload. Upload multiple images with Plupload. Limit the number of albums created per role. Reads image exif parameters. Nice presentation of the images. Views integration. Support for private file system. Drag and drop interface to re arrange photos and albums to sort by custom weight order. Photos Access Included as a sub module. Enable this module to control who has access to the photos and galleries.
>
> Create password protected photo galleries. Create galleries with a list of collaborators who can edit the same gallery. Create private / locked galleries that can only be seen / edited by the gallery owner. photo gallery, image gallery, user managed photo albums
> 1 votes

# Answer
You can add an image field to the profile fields rather than use a node and content type, under configuration and account settings choose manage fields and add it there.

If you do want to use a content type and a node, add a reference to node:author and add a contextual filter with a default value to get user ID from URL, that will only show the images from the node(s) that user has created.
> 0 votes

---
Tags: views, nodes
---


# Question
Title: Drupal 7 Views filter between start and end date
I try to accomplish the following:

I want to create a View, which is automatically listing the newest terms.

There a two terms a year (summer term 01.04.-30.09) and (winter term 01.10-31.03).

Those terms have several Events in it. So i tried to filter them automatically with a reference of "now"

So i set the filters as the following:

start-date is greater than or equal to "now"

end-date is less than of equal to "now"

I also tried to switch the arguments,

just as explained in this article: Drupal 7 Views filter between two dates?

but it didn't do anything.

I made some screenshots, to show you how i configured the view and the event.

(And yes, the other filter criteria s are met.^^)

I hope you can help me with this problem, or tell me another trick to accomplish my goal.

# Answer
Ok, there is nothing wrong, i made a big mistake by myself -.-, I watched over everything carefully, but not over the fact, that the current date is far away from the start date. I thought it would fit, cause the foregoing page has the winter term already in it. But they havent done it automatically but manually. Anyway,sorry for the trouble and thanks for the help.
> 0 votes

# Answer
This module should do exactly what you need: https://www.drupal.org/project/views\_between\_dates\_filter
> 1 votes

---
Tags: views, datetime
---


# Question
Title: how to give the id of image in drupal 7 views?
I have a view in drupal 7 and I am displaying node title and node image . I need to give id for a image. Now I am getting:

```
<img typeof="foaf:Image" src="http://localhost/drupal-7.36/sites/default/files/styles/medium/public/field/image/STF-332.jpg?itok=Kpd_9XUk" width="220" height="220" alt="">

```

But I need Id .Means I need

```
<img typeof="foaf:Image" src="http://localhost/drupal-7.36/sites/default/files/styles/medium/public/field/image/STF-332.jpg?itok=Kpd_9XUk" width="220" height="220" alt="" id="myID">

```

# Answer
> 0 votes
If a unique class is acceptable, you can add a class to a field using built-in features. Under the field settings:

# Answer
> 0 votes
What do you need that ID for? If you need it for some java-script processing on the image you can add a `span` with the image id inside it next to the image with the style `display:none`. To do so add the **NID** field *BEFORE* the image in the fields and then check the Rewrite Results and use this code:

Now you can easily get the image ID by this JS code

```
var nid = $("TheImageSelector").siblings(".image-span").text();

```

But if you have to use the ID you need to use template files. install Image Link Formatter module to get the image link instead of the image object then build the `<a>` .

---
Tags: views
---


# Question
Title: Can I allow a user to create a Node using only an embeded rich text editor
In Drupal 7, I'd like to present the user with a single text box, that when submitted, creates a new node or entity.

I don't want them to have the standard node/add/type link and interface. Rather, I'd prefer a block that has a CKeditor and submit button. Upon submission, the content of this text box will become a new Node (or entity). The title will be auto-generated.

In some way I'm looking to replicate the functionality of Drupal 6's Facebook-style Statuses (Microblog) -- the same patterns now found on larger social sites: G+, Twitter, Facebook. However, instead of saving to a single database table, I'd like to Drupal to create a new node or entity from that content.

From comments below, I've been pointed towards Rules. However, I'm still having issue with how to go from submission of that single rich text area to triggering a Rule. Would the module Rules Forms Support be of help?

# Answer
> 2 votes
I have done this using:

> "auto\_nodetitle" is a small and efficient module that allows hiding of the content title field in the form. To prevent empty content title fields one can configure it to generate the title by a given pattern.

> Welcome to Advanced Form Block Module. With this module you can do the following:
>
> 1) Create any number of blocks with a particular node edit form.
>
> 2) create any number of blocks with a particular node add form of a content type.
>
> 3) Create as many blocks as you like of each kind.
>
> 4) From the content type choose which fields to display on a per block basis.However required fields will be automatically displayed.
>
> 5) All forms will be saved through ajax. So multiple node forms can be independently placed on a single page and worked with simultaneously.

With configuration and some css, you can get it looking really nice, and as a block it can go anywhere you want. You can also use hook\_form\_alter() on the appropriate form:

`$form['actions']['submit']['#value'] = 'BUTTON TEXT';`

to change the text of the submit button

# Answer
> 1 votes
Seems like what you are asking for is a variation of the question in Module that provides Rules action to create node? . And the accepted answer in it, is also what I'd consider doing. I.e. use the Rules module to create such nodes ... Let me further extend this answer to add AbitMORE details on it ...

It isn't clear (yet) from the question how you would want to prezent that "single textbox" to the user. I see 2 possible approaches that you may want to consider to get a rule triggered:

1. Using Field Collection: that will make extra Rules events available like "after saving a new field collection" (or "updating an existing one", etc). So this could work if you think of a way to implement that text box as a field collection.
2. Using Webform Rules: if it would be ok/possible to do so via a (tiny) webform somehow, then via the Webform Rules module you could add the Rules integration with such Webform. That way you could "react" on such Webform submission using Rules. Because Webform Rules makes it possible to catch webform submissions by Rules and do whatever you'd like to do with it (that is: do whatever Rules let you do with it).

I'd try to go with approach '1.', if it doesn't work for you, then consider '2.'.

About using the Rules Forms Support module: make sure to review the Community documentation about that module. It may help to actually "trigger" a rule. The step about "*Select the checkbox Enable event activation messages on forms*" in that documentation seems to be crucial to get the appropriate rules events that you might be looking for.

---
Tags: 7, rules, nodes
---


# Question
Title: view to work for particular set of taxonomy terms
Case: I have a taxonomy vocabulary namely 'categories'. It consists of some parent terms with their child terms as shown.

```
 Parent1

 -p1child-1

 -p1child-2

 Parent2

  -p2child-1

  -p2child-2

```

I want to create a view which work only for a particular set.

Suppose in this case I will create 2 views, each for both parent terms and both will have different set of exposed filters and sort criteria.

So if I visited `taxonomy/term/parent1` or `taxonomy/term/p1child-1` or `taxonomy/term/p2child-2`, it would render that specific view of parent1.

is it possible ?

Please help

# Answer
> 2 votes
You can give Taxonomy Views Integrator module a try.

> The TVI (Taxonomy Views Integrator) module allows selective overriding of taxonomy terms and/or vocabulary with the view of your choice. Using TVI you can easily create custom views to output all terms in X vocabuarly.
>
> TVI will try not to interfere with views or taxonomy/term page displays if no TVI views exist for the current page request.

---
Tags: 7, views
---


# Question
Title: How to create an 'Add item' contextual link for views?
I like the concept of contextual links in D7 and want to push it a bit further: I want views to have an 'Add item' contextual link, so the site administrator can easily add new items.

Of course I could add an 'Add item' button to the view's footer instead. But I need to show it only to users who have the appropriate permission to add items.

Is there an idiomatic way of doing it?

# Answer
> 4 votes
Checkout the Custom Contextual Links module. I haven't personally used it but it looks like it does what you're after. It also supports views as of 7.x-1.1.

# Answer
> 0 votes
You can add the following code to the 'views header'.

It provides links to adding new items to the node collection or reordering.

# 1 Edit view

# 2 'Add' Global: Text area

# 3 set text format to 'PHP code'.

# 4 add the following code.

```
<?php
/* header for list */
global $user;
if (user_access('create document content', $user)) {
  $path = '/news/list';
  $addLink = l(t('Add news'), 'node/add/article', array('query' =>
  array('destination' => $path)));
  print $addLink;
  $viewLink = l(t('View news'), '/news');
  print $viewLink;
  $listLink = l(t('Edit/reorder news'), '/news/list');
  print $listLink;
}
?>

```

---
Tags: 7, views, navigation
---


# Question
Title: Redirect after login for specific role on specific day using Rule
I want to create a rule for specific user to redirect to his profile page on specific day like Monday and Thursday. For this, I used the Rules module, together with the Rules Once per Day module. If you're not familiar with this last module (which is pretty new), here are some quotes from its project page:

> ... to easily enable Rules to be fired once per day at, or soon after, a specific hour.
>
> The module also provides a "Day of the week is a" Rules condition, to further restrict actions to being run on specific day(s) of the week, on working days only, or at weekends only.

But that didn't work so far.

I have also tried with PHP code, but that's not working either.

# Answer
> 0 votes
There is an interesting comment in issue 2495775, related to the "Rules Once per Day" module, from the module owner. It says:

> You specify a trigger hour on the administration settings page for this module. The Rule trigger will then run when cron tasks are first run after the start of that hour. The actual run time will depend on your cron task timings.

The way I understand/Read this (haven't experimented with it yet though) is like so:

* The "Event" will only be triggered when a cron job is run.
* And that event will only be triggered 1 time / day, i.e. "next time cron runs after the trigger hour has passed".

Obviously, by using the "Day of the week is a"-option, an extra condition might be that the day has to match also.

With that in mind, it appears to me that this module can not help you to implement what you're trying to do. You want something to happen "when some user performs login", not "when some cron job is run".

But, maybe there is a way to reach your goal by cutting your problem / question in 2 parts:

1. Create a 1st rule that takes care of "Redirect after login for specific role to "*some URL*".
2. Create a 2nd rule that, using the "Rules Once per Day" module, sets the path for that "*some URL*". To actually set the path, their might be multiple options / modules to consider. I'm think of things like 'global redirect', using some 'token', maybe using the Variable module, etc (more investigation / research needed to find the best fit).

Yes the Rules module is one of those amazing Drupal modules. However it does have some challenges with processing dates ... (= open issues in its issue queue).

If the above doesn't help, then consider using an approach as detailed in the (great) answer to the question about Rule to check if a date value is a specific day of the week ...

Curious to hear if you can get it to work somehow.

# Answer
> 0 votes
I got success to reach my goal by using "Rules Once per Day" module

I created only one rule that take care of "Redirect after login for specific role to "some URL" and for that i set, 'day of the week' and specific user role in condition. See following screen shot.

---
Tags: users, cron, rules
---