# Question
Title: How can I move a view from one feature to another?
I have a view that I added to Feature A that I would instead like to move to Feature B. I re-created Feature A using the admin interface, but even after re-creating the feature, clearing the cache, and reverting the feature, the view still appears in the database in code and I am unable to attach it to Feature B.

How can I remove a view from one feature and add it to another?

# Answer
> 2 votes
Disabling and then re-enabling the Feature A after you detach the view from it might solve this issue.

If you still can't attach the view to Feature B after you disabled and re-enabled Feature A, then you can export the view using the Views interface (not Features) copy the code to a text file, then delete the View by typing the URL to the delete page manually into the address bar (I assume Views UI won't give you a delete link because it will still assume it's coming from code). The delete page url is: admin/structure/views/view/**view\_name**/delete

After that Import the view again through the Views UI and attach to Feature B.

I had a similar problem before, not exactly the same but similar issue with a certain element assuming it's coming from code after I detached it. Hope this helps.

# Answer
> 3 votes
I was able to do this by editing the respective view and causing the feature to go overridden.

Once the feature is overridden (aka. view settings/config saved in DB) we can recreate the respective feature w/o the view and drop that feature back into our site. Revert it, clear the cache (although when I did this, I didn't need to do either...still never a bad idea).

If all went according to plan you will now see the view is available to use in another feature, add it in, drop it back into your site and off you go!

This can also be done solely in code... Navigate to your feature module via the CLI, you will notice 2 files: .info and views\_default.inc

Find the declaration in your .info file for the respective view and move it to the .info file of the feature you want it a part of.

Next you will want to find the section of code in the views\_default.inc defining your view and move that to the views\_default.inc file of your new feature. It will begin with `$view = new view();` and end with `$export['your_view'] = $view;`

You will want to revert your features to put the ordering correct in the files.

# Answer
> 0 votes
Another way to solve this issues is by cloning the from Feature A View. This will generate another UUID and Features B is going to be able to recognize the view.

---
Tags: 7, views, features
---


# Question
Title: How to make a field required using JavaScript injector
I have a **field** that is part of a **content type** that I need to make required by using a JavaScript injector. The reason that I can't just make it required while setting the rules for that field is because I have to parse a string that will display on the same page whether or not I need to make it required. Any thoughts?

# Answer
> 1 votes
Matt -

I would recommend looking into `hook_node_validate()`. This is a function hook provided by Drupal core that allows you to add custom validation into the form. While you cannot select "required" from the field UI, perhaps you can validate it here and then return an error if the form doesn't provide the correct information for that specific field.

Other things to investigate: `hook_form_alter()` and `hook_validate` \- where you can add custom validation functions into the Drupal form array itself.

Helpful links: https://api.drupal.org/api/drupal/modules%21node%21node.api.php/function/hook\_node\_validate/7

https://api.drupal.org/api/drupal/modules%21system%21system.api.php/function/hook\_form\_alter/7

---
Tags: nodes, javascript
---


# Question
Title: insert read-only multilingual text to user registration form
I've added a 'Term of use' read-only description into the Drupal user registration form, but I would like to make it **multilingual**. The corresponding code is in the begin of template.php (responsive is the theme name):

```
function responsive_form_alter(&$form, &$form_state, $form_id){
switch($form_id) {
case 'user_register_form': // the value we stole from the rendered form
$multi_regform = array(
'#type' => 'checkbox',
'#title' => t("Elfogadom a moderálási elveket"),
'#description' => t("A Magyar Térinformatikai Társaság (HUNAGI) hivatalos honlapján való publikálás és kommentelés lehetőségét a HUNAGI regisztrált tagjai ..... A közzététellel a regisztrált felhasználó lemond a bejegyzés feletti rendelkezés jogáról, későbbiekben anyagi vagy más jellegű követeléseket ezekre alapozva nem támaszthat. - A HUNAGI vezetősége - "),
'#required' => TRUE,
'#localize' => TRUE, // Does not function...
'#weight' => 1, // Adjust so that you can place it whereever
);
$form['terms_of_use'] = $multi_regform;
break;
}
}

```

You can check it here: http://hunagi.hu/hu/user/register

Now the text is Hungarian, can I add an English one someway?

*ps: I've already tried this by Field addition by Field Group, Field Permissions modules, that did not work.*

# Answer
> 1 votes
You should be able to translate your strings at `admin/config/regional/translate/translate`, just search a word contained in the two hungarian strings (case sensitive!), click on the edit link of the relevant string and you should be done.

---
Tags: forms, i18n-l10n
---


title: Edit tabs missing on Views block

text:
# Question
Title: Edit tabs missing on Views block
I'm new to Drupal and despite making progress over the last few days I've hit a problem.

I've got two custom content types linked with an entity reference. I'm using the Views module to create a relationship between them and output the results as a block. The block also uses a contextual filter.

All of this is working ok, I add the block to a page and the content is shown exactly as expected, except I don't get the edit/view tabs that I usually see above nodes.

If I navigate to the node by itself via the 'find content' page the edit tabs are there, but once inside the block they're missing.

I found one post mentioning that edit tabs don't appear as standard when contextual filters are used, but the post was three years old, had no solution or discussion, and and nothing to confirm whether it was actually true.

I know I can add an edit link from the Fields menu in Views but it makes the UI look inconsistent.

I'd appreciate if someone could let me know:

1. What exactly stops them from appearing.
2. What to read up on to get them working again.

Thanks.

# Answer
You found the answer already. The contextual links you're looking for are just not provided by the views module when using fields (except when you add them explicitly). If you use the node row style in views they're provided through the node system of drupal. For convenience and many more options there's a module for it: Custom Contextual Links
> 3 votes

# Answer
Thanks for confirming. The editing behaviour seemed so obviously inconsistent (always visible tabs for some things and hover menus for others) that I wasn't sure if I'd made an error somewhere. I guess my question should be 'how do I make the admin UI more consistent'. It looks like the module you recommended might help me with that. If I can get rid of tabs completely and have hovers for everything it should be a bit more intuitive to use.

Incidentally, it looks like this has been addressed in Drupal 8. Some discussion here for anyone interested: https://www.drupal.org/node/1874664
> 0 votes

---
Tags: blocks, entities, views
---


# Question
Title: Views block with the terms referenced by a node
I've got a working email notification system built with flags and rules. The missing part in my puzzle is how to create a Views block showing the Flag links of the terms I've tagged a node with.

Example:

> A node tagged with a Taxonomy Term - When users access that node I want a block displayed enabling them to flag/unflag the Term(s) in the node.

Here's a blog post mockup. It's the subscription block in the left side of the screen that I'm talking about.

I've got a block with all the Terms and their flag links but I can't figure out the right relationships and contextual filters to have only the used terms appear.

Here's the view I've created. The relationships and filters fail to only show the 1 term a node is tagged with. Instead it shows 3 of each term in the entire vocabulary.

```
$view = new view();
$view->name = 'subscription_block';
$view->description = '';
$view->tag = 'default';
$view->base_table = 'taxonomy_term_data';
$view->human_name = 'Subscription block';
$view->core = 7;
$view->api_version = '3.0';
$view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */

/* Display: Master */
$handler = $view->new_display('default', 'Master', 'default');
$handler->display->display_options['title'] = 'Subscription block';
$handler->display->display_options['use_more_always'] = FALSE;
$handler->display->display_options['access']['type'] = 'perm';
$handler->display->display_options['cache']['type'] = 'none';
$handler->display->display_options['query']['type'] = 'views_query';
$handler->display->display_options['exposed_form']['type'] = 'basic';
$handler->display->display_options['pager']['type'] = 'none';
$handler->display->display_options['style_plugin'] = 'default';
$handler->display->display_options['row_plugin'] = 'entity';
/* Relationship: Taxonomy term: Content using Artist */
$handler->display->display_options['relationships']['reverse_field_artist_tags_node']['id'] = 'reverse_field_artist_tags_node';
$handler->display->display_options['relationships']['reverse_field_artist_tags_node']['table'] = 'taxonomy_term_data';
$handler->display->display_options['relationships']['reverse_field_artist_tags_node']['field'] = 'reverse_field_artist_tags_node';
$handler->display->display_options['relationships']['reverse_field_artist_tags_node']['required'] = TRUE;
/* Field: Taxonomy term: Name */
$handler->display->display_options['fields']['name']['id'] = 'name';
$handler->display->display_options['fields']['name']['table'] = 'taxonomy_term_data';
$handler->display->display_options['fields']['name']['field'] = 'name';
$handler->display->display_options['fields']['name']['label'] = '';
$handler->display->display_options['fields']['name']['alter']['word_boundary'] = FALSE;
$handler->display->display_options['fields']['name']['alter']['ellipsis'] = FALSE;
$handler->display->display_options['fields']['name']['link_to_taxonomy'] = TRUE;
/* Contextual filter: Content: Has taxonomy term ID (with depth) */
$handler->display->display_options['arguments']['term_node_tid_depth']['id'] = 'term_node_tid_depth';
$handler->display->display_options['arguments']['term_node_tid_depth']['table'] = 'node';
$handler->display->display_options['arguments']['term_node_tid_depth']['field'] = 'term_node_tid_depth';
$handler->display->display_options['arguments']['term_node_tid_depth']['relationship'] = 'reverse_field_artist_tags_node';
$handler->display->display_options['arguments']['term_node_tid_depth']['default_argument_type'] = 'fixed';
$handler->display->display_options['arguments']['term_node_tid_depth']['summary']['number_of_records'] = '0';
$handler->display->display_options['arguments']['term_node_tid_depth']['summary']['format'] = 'default_summary';
$handler->display->display_options['arguments']['term_node_tid_depth']['summary_options']['items_per_page'] = '25';
$handler->display->display_options['arguments']['term_node_tid_depth']['specify_validation'] = TRUE;
$handler->display->display_options['arguments']['term_node_tid_depth']['validate']['type'] = 'taxonomy_term';
$handler->display->display_options['arguments']['term_node_tid_depth']['validate_options']['vocabularies'] = array(
  'artist_subscriptions' => 'artist_subscriptions',
);
$handler->display->display_options['arguments']['term_node_tid_depth']['depth'] = '0';
$handler->display->display_options['arguments']['term_node_tid_depth']['break_phrase'] = TRUE;
/* Filter criterion: Taxonomy vocabulary: Machine name */
$handler->display->display_options['filters']['machine_name']['id'] = 'machine_name';
$handler->display->display_options['filters']['machine_name']['table'] = 'taxonomy_vocabulary';
$handler->display->display_options['filters']['machine_name']['field'] = 'machine_name';
$handler->display->display_options['filters']['machine_name']['value'] = array(
  'artist_subscriptions' => 'artist_subscriptions',
);

/* Display: Block */
$handler = $view->new_display('block', 'Block', 'block');

```

# Answer
I went from the other side, may work for you.

From Structure - Content type - Manage field; add existing field type Term reference and select the vocab. (you may already have done this)
--\> Manage display, and set your term field to visible here. If you need, create a new display, say 'PagePlusTerms'.

Now in your View where you pull your data,
FORMAT-format= Unformatted list(whatever) and
FORMAT-show= Content | PagePlusTerms (where you pick the display you made just before for 'How should each row in this view be styled')

contextual filter: Content: Has taxonomy term ID (with depth):: Depth (0) : Allow multiple : Specify validation criteria - Term ID
and
Configure contextual filter: Content: Has taxonomy term ID depth modifier

see if that works for you

---

EDIT after more info:

Using your extra info and approach you can try (assumption: your node type(say Artist Node, has a field where taxonomies are added);

Create a new View with the 'Master'
**Format** \- Show - Fields
and
**Fields** \- Content: All taxonomy terms (Display all taxonomy terms associated with a node from specified vocabularies)
and
**Filter Criteria** \- Content: Type(=Artist Node)

then add a 'Block' dispaly for the view, say 'Subscription blockII'
on which you add
**Contextual filters:** \- Content: Nid
Configure contextual filter: Content: Nid
When the filter value is NOT available
Provide default value - type: Content ID from url

the block 'preview' in View may be blank, that's OK.
You can then add the block to your page on 'Artist Nodes'.

Basically you will then have a block that you can place anywhere on a node, which will look at the node id, then look for the taxonomies on that id and then print them in the block.
Hope I understood you correctly.
> 1 votes

# Answer
Had a friend help me out, so posting his solution in case anyone else needs something similar. He got it working by doing a taxonomy term contextual filter with the following php in 'provide default value'

```
$node = menu_get_object(); return $node->field_artist_tags['und'][0]['tid'];

```

field\_artist\_tags is the machine name of my term field

That makes the term referenced by a node appear including the flag:)
> 0 votes

---
Tags: taxonomy-terms, views, flags
---


title: Setting OG with Services module

text:
# Question
Title: Setting OG with Services module
I am trying to `POST` a node to my site and make it group member.

POST body looks like this:

```
{
   "title":"Update",
   "type":"mesurement",
   "uid":"4",
    "og_group_ref": {
        "und": [{
            "target_id": "20"
        }]
    },
    "field_records": {
        "und": [{
            "value": "22"
        }, {
            "value": "25"
        }, {
            "value": "65"
        }, {
            "value": "12"
        }]
    }
}

```

Yet every time I get an error saying:

```
{
    "form_errors": {
        "og": "You must select one or more groups for this content."
    }
}

```

**Edit**:

Field settings are:

Default widget type: Select list

Administrator widget type: Autocomplete

Number of values: 1

Mode: Organic groups

# Answer
I was having the same troubles. Seems to me as far as my limited debugging skills go, that when drupal\_process\_form calls

```
$form = form_builder($form_id, $form, $form_state);

```

the values for `$form_state[‘input’][‘og_group_ref’]` don’t get passed through into `$form`. So I suspect I need to understand `form_builder` better to figure out why the values coming in aren’t getting transferred through. Ultimately when we get to `og_form_group_reference_validate`, `$form_state['values’][‘og_group_ref’]` doesn’t exist.

So, what I’m going to try for now (and seems to be working) is let `og_form_group_reference_validate` look in `$form_state[‘input’]` in addition to `$form_state[‘values’]`, as `og_group_ref` still exists there.

Here’s a gist of my patch:

https://gist.github.com/housser/ba03c50f670dc5310520
> 1 votes

# Answer
The JSON that you need to send for `og_group_ref` is dependant on the *widget* you have selected on your **manage fields** page for your content type. For example, if you're using an Autocomplete widget, then you need to send JSON like this:

```
"og_group_ref": {
    "und": [{
        "target_id": "... (123)"
    }]
}

```

You can put anything in place of the `...`, but the entity id must be wrapped in parenthesis.
> 0 votes

---
Tags: organic-groups, services
---


# Question
Title: How do you go about using contexts and a menu page callback?
Currently we have a page that is generated by a hook menu page callback. The path is structured like `menu/%location_name/menu/%parent_category/%child_category`. The function requires at least one of the category wildcards to properly work.

In the page callback we then set up our context's condition which is to determine which of the categories we're in. See code below:

```
  if(empty($term_parent) == FALSE || empty($term_parent) == FALSE) {
    if ($plugin = context_get_plugin('condition', 'ss_menu_core_condition_default')) {
      if(empty($term_parent) == FALSE && empty($term_child) == TRUE) {
        $context_term = $term_parent->tid;
      } elseif(empty($term_parent) == FALSE && empty($term_child) == FALSE) {
        $context_term = $term_child->tid;
      }
      $plugin->execute($context_term);
    }
  }

```

Everything up until this point makes a bit of sense to me. And currently it validates fine and I can actually see the context when using `context_active_contexts()`. Although the gotcha that I must be missing is how do i go about allowing the metatags context module's reaction to use this term for token replacement?

At first the tokens avaliable were pretty generic default site wide things such as current page, current user, date, etc... It wasn't until i found a patch that taxonomy terms ended up showing up as token replacements. But none of them seemed to work as it seemed the context didn't know of what term to use.

This leaves me at a point where I felt like the only solution was to do something hackish and just set my values in the active context as follows:

```
  $context = context_active_contexts();
  $context['ss_menu_core_menu_sections']->reactions['metatag_context_reaction']['metatags']['und']['description']['value'] = $context_term->description;

```

This still doesn't feel right at this point since we can't actually use the metatags reaction form to populate the values. If anyone has any ideas that would be amazing.

Thanks.

# Answer
> 1 votes
Take a cue from `metatag_context_entity_prepare_view()` in that patch. You need to stuff your desired term entities into the metatag\_context\_entities static variable in your page callback like so:

```
drupal_static('metatag_context_entities', array('taxonomy_term', $terms));

```

---
Tags: entities, 7, routes
---


# Question
Title: Adding Contextual Links to Ctools Custom Content Type Plugin
Ctools custom content type called Custom Panes shows contextual links when you have access permission and you hover over the pane (much like a block shows the contextual links) which allows you to easily configure the content of the pane. After creating my own plugin that is similar to Custom Panes content type (with a few custom fields), I noticed that I do not have contextual links when I hover over my custom panes. I'm wondering if I can set that in the $plugin definition to show contextual links or what the work around would be. I found the template function the panels uses to `template_preprocess_panels_pane(&$vars)` which actually looks for `$vars['content']->content['#contextual_links']`. I'm wondering if there is a way to add contextual links to custom ctools content type plugins?

Any advice would be great!

# Answer
> 0 votes
You don't need to do that, what you can do is you can implement a `hook_menu_alter` and do this.

```
function YOUR-MODULE_menu_alter(&$items) {
  $items['YOUR-PLUGIN-PATH/%ctools_export_ui/edit']['context'] = MENU_CONTEXT_PAGE | MENU_CONTEXT_INLINE;
}

```

and then add your contextual link to your object. If it a block you can add below code in to your `hook_block_view`.

```
$block['content']['#contextual_links'] = array(
  'YOUR-CUSTOM-PLUGIN' => array('YOUR-PLUGIN-PATH', array($delta, 'edit'))
);

```

# Answer
> 0 votes
Inside the render callback of your custom CTools Content Type include file you can provide `admin_links`.

Here is an example pane that has a companion edit page at URL `admin/config/custom/my_custom_pane_settings`

```
<?php

$plugin = array(
  'title' => t('Custom Pane'),
  'single' => TRUE,
  'render callback' => 'my_custom_pane_render',
  'defaults' => array(),
  'category' => t('Page elements'),
  'edit form' => 'my_custom_pane_edit_form',
);

function my_custom_pane_edit_form($form, &$form_state) {
  return $form;
}

function my_custom_pane_render($subtype, $conf, $args, $context) {

  // Output.
  $block = new stdClass();

  // Define pane title & content.
  $block->title = 'Default pane title';
  $block->content = 'My custom pane content';

  // Add custom contextual links.
  $block->admin_links = array(
    'my_custom_pane' => array(
      'title' => t('Edit my custom pane'),
      'href' => 'admin/config/custom/my_custom_pane_settings',
      'query' => array(
        'destination' => current_path(),
      ),
    ),
  );

  return $block;
}

```

---
Tags: chaos-tool-suite, navigation
---


title: Fetch Drupal nodes as json by url/title

text:
# Question
Title: Fetch Drupal nodes as json by url/title
Our Drupal system has the Services module enabled and is able to return nodes as json using the following url format

http://www.example.com/my\_endpoint\_path/node/123.json

But I want to retrieve a node using the URL alias I set in the URL path settings tab. I hoped the following would work

http://www.example.com/my\_endpoint\_path/my\_pages\_URL\_alias.json

But it does not. Is there a way to configure Drupal/Services to fetch nodes by that URL rather than the node id?

# Answer
In Service Module API, Some hooks are presents to help you. You need to alter or add your own implementation of this service.

The second link is a file where you have the default service implementation. You can try to alter this configuration with your own by using "hook\_services\_resources\_alter".

I can't test but you can try and custom this snippet :

```
function YOUR_MODULE_services_resources_alter(&$resources, &$endpoint) {
    $['node']['operations']['retrieve']['callback'] = '_your_retreive_method';
    $['node']['operations']['retrieve']['args']     = array(
        'name' => 'node_alias',
        'optional' => FALSE,
        'source' => array('path' => 0), // Put your path index here
        'type' => 'string',
        'description' => 'The alias node to get',
    );
}

function _your_retreive_method($node_alias){
    // transform your alias to nid
    $path   = drupal_get_normal_path($node_alias);
    if($path !== $node_alias && ctype_digit($nid = str_replace('node/','',$path))){
        return _node_resource_retrieve($nid);
    }
    return false;
}

```

Links :
> 2 votes

# Answer
Payou's answer worked for me with some additions. In the `YOUR_MODULE_services_resources_alter` function I also needed to specify a custom access function:

```
  $resources['node']['operations']['retrieve']['access callback'] = '_YOUR_MODULE_node_resource_access';
  $resources['node']['operations']['retrieve']['access arguments append'] = TRUE;

```

And add the access function:

```
<?php
function _YOUR_MODULE_node_resource_access($op, $node_alias)
{
  $path = drupal_get_normal_path($node_alias[0]);
  if ($path !== $node_alias && ctype_digit($nid = str_replace('node/', '', $path))) {
    return _node_resource_access($op, array($nid));
  }
  return services_error(t('Content could not be found.'), 404);
}

```
> 0 votes

---
Tags: 7, services
---


title: Webform Localization does not work

text:
# Question
Title: Webform Localization does not work
I have downloaded the Webform Localization module from Drupal.org, but it is not working to translate form, and I want to keep a single webform across all nodes.

How can I do that?

# Answer
> 0 votes
If you create webform first and then install webform localization module , the module will see only new components in webform , so try to open each component and save it then go to Regional and language \> translate interface \> strings , check "webform localization" and "fields" then "Refresh strings" , then back to translate interface \> translate , search for your components labels and translate them

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


# Question
Title: How to have a language switcher that allows you to select the country and then the langauge within the country?
We are looking to have a menu at the top right that allows users to select the country they want to view and then once the country is selected, we want them to pick a language that they can view the site in. How is it possible and what are the recommended modules?

Example:

# Answer
Check Language Switcher module or Language Switcher Dropdown module.

But as of now there is no contrib module that does exactly as you wanted.
> 2 votes

# Answer
I think you need to built your own solution. there is not relation in Drupal between languages and countries.
> 1 votes

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


# Question
Title: FormAPI cannot get checkboxes return value from AJAX call via external database query
I have not been able to get the return #options value when using AJAX for a dependent checkbox after selecting a value from select. My AJAX isn't great, and I've searched all over, I'm hoping someone can point me in the right direction.

There have been many iterations and I have moved things around, used drupal\_map\_assoc() with $options2 and without, tried just pulling the COURSE\_NAME as a single value and mapping it with drupal\_map\_assoc() and without. I put the line `$options2 = array('' => 'No Courses Available');` in as a test to see what it would return on the form, and it will create a single checkbox with the value of "No Courses Available". I also included an array that did work, the original `$options` that is commented out toward the bottom of the code snippet. If I enable that, it will show those two courses every time. Even when I do `dvr($options2)`, the response text shows an array similar to the hardcoded $options array but no checkboxes will display on the form whatsoever.

I have sanitized the code snippet and changed the name of the Oracle view I am querying, it is not really called oracle.view. Can anybody please tell me where I am going wrong?

Thank You!

```
$form['xyz']['existing_credits']=array(
    '#title' => t('How many credits do you have?'),
    '#type' => 'select',
    '#options' => drupal_map_assoc(array('' => '-- select # of credits --','0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15')),
  );

  $db = "(DESCRIPTION=
        (ADDRESS=
          (PROTOCOL=TCP)
          (HOST=192.168.1.1)
          (PORT=8003)
        )
        (CONNECT_DATA=
          (SERVER=dedicated)
          (SERVICE_NAME=TEST)
        )
      )";

  $conn = oci_connect('username', 'password', $db);
  if (!$conn) {
    $e = oci_error();
    trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
  }

  $stid = oci_parse($conn, "select * from oracle.view order by course_title, registration_start_date");
  oci_execute($stid);

  $options1 = array();
  $options1[] = '- select a school -';
  $xyz = array();
  $selected = isset($form_state['values']['school']) ? $form_state['values']['school']: key($options1);
  while (($schools = oci_fetch_array($stid, OCI_ASSOC+OCI_RETURN_NULLS)) != false) {
    // put the contents of the db records in a persistent array
    $xyz[] = $schools;
  }
  // looping through the $hsa array, pulling out DISTINCT school names and
  // adding them to the School select field
  for ($x = 0; $x <count($xyz); $x++) {
    $school = $xyz[$x]["SCHOOL_NAME"];
    if(!in_array($school, $options1)){
      $options1[$school] = $school;
    }
  }
  $form['xyz']['school'] = array(
    '#title' => t('School'),
    '#type' => 'select',
    '#options' => $options1,
    '#default_value' => $selected,
    '#ajax' => array(
      'callback' => 'xyz_ajax_callback',
      'event' => 'change',
      'wrapper' => 'xyz-courses',
    ),
    '#states' => array(
      'invisible' => array(
        ':input[name="existing_credits"]' => array(
            array('value' => t('-- select # of credits --')),
            array('value' => t('13')),
            array('value' => t('14')),
            array('value' => t('15')),
        ),
      ),
    ),
  );

  $form['xyz']['courses'] = array(
      '#type' => 'checkboxes',
      '#title' => t('Select Course(s)'),
      '#options' => _xyz_get_courses($selected),
      '#default_value' => isset($form_state['values']['courses']) ? $form_state['values']['courses'] : '',
      '#prefix' => '<div id="xyz-courses">',
      '#suffix' => '</div>',
      '#states' => array(
        'invisible' => array(
          ':input[name="school"]' => array('value' => '0'),
        ),
      ),
    );

function xyz_ajax_callback($form, &$form_state) {
  return $form['courses'];
}

function _xyz_get_courses($key=NULL) {
  $options2 = array('' => 'No Courses Available');

  $db = "(DESCRIPTION=
        (ADDRESS=
          (PROTOCOL=TCP)
          (HOST=192.168.1.1)
          (PORT=8003)
        )
        (CONNECT_DATA=
          (SERVER=dedicated)
          (SERVICE_NAME=TEST)
        )
      )";

  $conn = oci_connect('username', 'password', $db);
  if (!$conn) {
    $e = oci_error();
    trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
  }

  $stid = oci_parse($conn, "select COURSE, COURSE_TITLE from oracle.view WHERE school_name = '$key'");
  oci_execute($stid);

  while (($course_list = oci_fetch_array($stid, OCI_ASSOC+OCI_RETURN_NULLS)) != false) {

    $course_id = $course_list["COURSE"];
    $course_title = $course_list["COURSE_TITLE"];
    $options[$course_id] = $course_title;

  }

  //$options = drupal_map_assoc(array('EDUC648GUB' => 'Dmsns of Lrng & Ltrcy', 'EDUC532GUL' => 'Tchng Stdnts with Dsblts 7-12'));

  $options2 = drupal_map_assoc($options);
  //dvr($options2);
  return $options2;
}

```

# Answer
> 1 votes
So, I had a difficult time finding examples that showed me how to interact with an external database like Oracle. I wound up solving my own problem and wanted to post my corrected code here in case anybody ever wants to use it for reference.

```
$form['xyz']['existing_credits']=array(
    '#title' => t('How many credits do you have?'),
    '#type' => 'select',
    '#options' => drupal_map_assoc(array('' => '-- select # of credits --','0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15')),
  );

  $db = "(DESCRIPTION=
        (ADDRESS=
          (PROTOCOL=TCP)
          (HOST=192.168.1.1)
          (PORT=8003)
        )
        (CONNECT_DATA=
          (SERVER=dedicated)
          (SERVICE_NAME=TEST)
        )
      )";

  $conn = oci_connect('username', 'password', $db);
  if (!$conn) {
    $e = oci_error();
    trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
  }

  $stid = oci_parse($conn, "select * from oracle.view order by course_title, registration_start_date");
  oci_execute($stid);

  $options1 = array();
  $options1[] = '- select a school -';
  $xyz = array();
  $selected = isset($form_state['values']['school']) ? $form_state['values']['school']: key($options1);
  while (($schools = oci_fetch_array($stid, OCI_ASSOC+OCI_RETURN_NULLS)) != false) {
    // put the contents of the db records in a persistent array
    $xyz[] = $schools;
  }
  // looping through the $hsa array, pulling out DISTINCT school names and
  // adding them to the School select field
  for ($x = 0; $x <count($xyz); $x++) {
    $school = $xyz[$x]["SCHOOL_NAME"];
    if(!in_array($school, $options1)){
      $options1[$school] = $school;
    }
  }
  $form['xyz']['school'] = array(
    '#title' => t('School'),
    '#type' => 'select',
    '#options' => $options1,
    '#default_value' => $selected,
    '#ajax' => array(
      'callback' => 'xyz_ajax_callback',
      'event' => 'change',
      'wrapper' => 'xyz-courses',
    ),
    '#states' => array(
      'invisible' => array(
        ':input[name="existing_credits"]' => array(
            array('value' => t('-- select # of credits --')),
            array('value' => t('13')),
            array('value' => t('14')),
            array('value' => t('15')),
        ),
      ),
    ),
  );

  $form['xyz']['courses'] = array(
      '#type' => 'checkboxes',
      '#title' => t('Select Course(s)'),
      '#options' => _xyz_get_courses($selected),
      '#default_value' => isset($form_state['values']['courses']) ? $form_state['values']['courses'] : '',
      '#prefix' => '<div id="xyz-courses">',
      '#suffix' => '</div>',
      '#states' => array(
        'invisible' => array(
          ':input[name="school"]' => array('value' => '0'),
        ),
      ),
    );

function xyz_ajax_callback($form, &$form_state) {
  return $form['uft']['courses'];
}

function _xyz_get_courses($key=NULL) {
    $course_id = array();
    $course_title = array();

      $db = "(DESCRIPTION=
            (ADDRESS=
              (PROTOCOL=TCP)
              (HOST=192.168.1.1)
              (PORT=8003)
            )
            (CONNECT_DATA=
              (SERVER=dedicated)
              (SERVICE_NAME=TEST)
            )
          )";

  $conn = oci_connect('username', 'password', $db);
  if (!$conn) {
    $e = oci_error();
    trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
  }

  $query = "SELECT * FROM oracle.view WHERE school_name = '$key'";

  $stid = oci_parse($conn, $query);

  oci_execute($stid);

  $courses[] = oci_fetch_all($stid, $res);
  $course_id = $res["COURSE"];
  $course_title = $res["COURSE_TITLE"];
  $course_options = array_combine($course_id, $course_title);
  $options = drupal_map_assoc($course_options);

  oci_free_statement($stid);
  oci_close($conn);

  return $options;
}

```

---
Tags: forms, ajax, database
---


# Question
Title: Change Entityqueue autocomplete to an entity widget
I have an Entityqueue and whenever a user wants to add an item to queue, he/she should write part of title in Autocomplete to add it to queue.

I want to change this autocomplete with a widget that list entities with pagination and when user clicks on an Entity title to add it to queue.

# Answer
Finally i solved it using Entity API & Entity reference view widget.

Entityqueue is prefect but it suffers from lake of good UX.
> 1 votes

# Answer
Have you tried altering the form and change the autocomplete with select list. If not try that once and render theme table for every 10 titles and also ADD Item (Use Default). In form submit get entity id and append to $form\_state\['values'\]\['eq\_node'\]\[LANGUAGE\_NONE\]. Only these changes will help you, rest will be same as default. If you face any issues please share the errors you got(if any).
> 0 votes

# Answer
I recommend you to dont use nodequeue, i used that module allot and i surrender for the end users sucks, i recommend you: Flag & Flag Weights Create a view called My queue and add the contents all what you want and the flag, just try it would be much better for end user and alot personalizable with normal views end.
> 0 votes

---
Tags: entities, nodes
---


title: Wrap a field in html from template

text:
# Question
Title: Wrap a field in html from template
I have an *Article* content type that has `related_news` field. It displays inside the article text as a box.

In `node--article.tpl.php` I have the following code:

```
<?php
  // We hide the comments and links now so that we can render them later.
     hide($content['comments']);
     hide($content['links']);
     hide($content['field_addthis']);
     print render($content);
?>

```

I found that I can hide the `related_news` field using `hide` as:

```
hide($content['field_related_news']);

```

Is there any function like `hide` that could able to wrap the that field in custom *HTML* like `<div class="custom">...</div>`?

I tried the following:

```
//$content['field_related_news'] = "***". $content['field_related_news']."***";

```

But it causes to hide the field from the node.

# Answer
You could easily achieve that in your node file by using the `field_view_field()` function and hiding it from the default `render($content)`.

To do that just set the display options in your custom content type to hide the title or whatever you want and put the following php code in your template:

```
<?php $related = field_view_field('node', $node, 'field_related_news'); ?>
<div class="custom"><?php print render($related); ?></div>

```

Don't forget that you will need to hide your field in the `render($content)` otherwise you will see it twice.
> 2 votes

# Answer
You can achieve this by creating field tpl file.

Refer field.tpl.php

Create tpl file named as **field--field\_related\_news.tpl.php**
> 3 votes

---
Tags: 7, nodes
---


title: Previewing another template online?

text:
# Question
Title: Previewing another template online?
Always when I want to check another template on my online site I have to download it to a local server, fix the blocks in that template, and set it as default. Only by that I could check it without changing the looks of the site online.

Let's say I want to preview this template online, without a local copy of the site, but also without switching the default template. Is this possible?

My final aim is to fix all the blocks in my new theme, and then preview it without setting it as default (So if visitors come in the same time they will see the site with the "old" template).

Thanks,

# Answer
> 2 votes
Yes, you can install the ThemeKey module. One of its features is to provide:

> content, user, or role -specific themes

So you can upload a new theme and try it out for certain users roles, without affecting what how the site looks for regular users.

---
Tags: theming
---


# Question
Title: Restricted access on certain files in Open Atrium
I have a situation where I have individuals that belong to a certain group and they want to have a sub-folder in the documents subspace that is restricted to only a few members of that space.

In my research I have come across a private file system that you can configure/set up, but that solution is not ideal as we still want to keep all the documents for that space in one central location.

Is it possible to break permissions down to level of special access on individual folders/files?

Information:

1. Using latest version of Open Atrium.
2. Have no other modules installed.
3. Current users are used to working with SharePoint as their CMS.

I apologize if I am missing something obvious or have holes in my basic understanding of Drupal, as I have been forced to dive in head first with out testing the waters.

# Answer
> 0 votes
Maybe you could create 2 files sections. The first one, accessible to everyone. Then another one, in a subspace, that would be private (check settings upon creation).

Maybe you could display then the whole structure using only one "files and folder" widget if this is what you need

---
Tags: files, distributions
---


# Question
Title: Features not reverting field instances, only field bases
I'm having issues with the latest version of Features. I'm trying to revert a content type but it's not reverting the field instances.

The Content type is created and I can see the field tables in the database. The field\_config table contains the fields but the field\_config\_instance table is empty.

Everything works well if I drop a dev dump of my field\_config\_instance table into the database I'm reverting to. There are no errors shown or anything.

Any ideas?

# Answer
> 0 votes
I had similar issue with the latest features.

The solution for me was to run the field\_cron. It purges some staff and after that I was able to revert the feature with the field\_instances and this time the revert worked and the field was added to the entity.

Hope that could help anybody with similar problem.

---
Tags: entities, features
---


# Question
Title: Customize content page in backend with more filters
I need to add more filters like content type, Taxonomy to back end content() in drupal. Hacking the core is not a good method. Is there any alter hooks are available?. Can create a new view page with exposed filters and do a views bulk operation on it?

# Answer
> 1 votes
There's a module for it! :) You should take a look at Administration Views. This module gives you all you need. Just create views for nodes or users or use the default ones that come with the module. It has a dependency to Views Bulk Operations as it can perform customizable tasks, like mass deleting or changing values.

---
Tags: views
---


# Question
Title: How to get a separate form_id for each of the taxonomy/term/%term exposed form?
I'm trying to combine in a smart way `Contextual filters Has taxonomy term ID` with `Remember the last selection` feature of exposed form filters in a view.

## Context

* A taxonomy vocabulary called destinations (countries & regions)
* A view of content tagged with *destinations* terms : `Contextual filters : Content: Has taxonomy term ID (with depth)`
* Exposed filters such as travel duration, price...
* Important point, **Remember the last selection** is ticked for all the filters
* Ajax enabled, and the whole thing displayed as a content pane

## The issue

Let's say I visit `taxonomy/term/spain` and filter the view by *price \< 700$*, then go to `taxonomy/term/india` e.g, the view will be already filtered by *price \< 700$*, and may return empty result, which is an unwanted behaviour.

This is because across all the `taxonomy/term/%` paths, the exposed form form\_id remains the same `views_exposed_form`.

How could I get a separate form\_id for each of the `taxonomy/term/%` exposed form, so that the last selection would be kept for each term ?

Or setup my view in order to get the expected features ?

# Answer
Without patching the module you can't...but the View object is always available in the form state, so you can use that to check where you are. e.g.

```
function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'views_exposed_form') {
    $view = $form_state['view'];
    if ($view->name == 'foo' && $view->current_display == 'bar') {
      // ...
    }
  }
}

```
> 2 votes

---
Tags: views
---


title: Entity Translation and Field Collection

text:
# Question
Title: Entity Translation and Field Collection
Entity Translation exposes a checkbox on fields, entitled:

> Users may translate all occurrences of this field

When dealing with a Field Collection field, which of the following should I check the box for?

* Only the field collection field
* Only the child fields
* Both the field collection field, *and* its child fields

# Answer
Field Collection doesn't support Entity Translation, so my advice is to find another way to achieve your aim.

There is a patch available which has been under development for a long time, use at your own risk.

The Drupal.org issue with it's accompanying patch can be found here: https://www.drupal.org/node/1344672
> 1 votes

---
Tags: entities, i18n-l10n
---


title: Migrate both public and private files

text:
# Question
Title: Migrate both public and private files
I am using Migrate Drupal-to-Drupal and migrating a D6 database to D7.

In D6, I have private and public files. They are in one field. In D7, I have a public file field and a private file field. Migrate d2d MigrateNode class puts the source file field info in the 'upload' field which can only be mapped to one destination field: public or private attachments.

My question is: Is there any way to conditionally check the value in the upload field in order to map the 'upload' to either the public or private field based upon that value?

# Answer
> 2 votes
I could not figure out a way to conditionally map content to public and private fields in one migration.

But, I did figure out how to resolve the issue.

1. I migrated all d6 files, public and private, to the d7 public attachments field.
2. I created a query that finds all the private files migrated into the public attachments field:

SELECT * FROM migrate\_map\_f43b6e55cfile mm inner join`field_data_field_attachments` fa on mm.destid1 = fa.field\_attachments\_fid inner join file\_managed fm on fa.field\_attachments\_fid = fm.fid where fm.uri like '%private%' and fa.entity\_type = 'node' order by fm.filename

The private files can be identified because they will have 'private' in their URI.

3. I iterate through the query results and switch the private files from the public attachments field to the private attachment field.

This process, while requiring an additional step after the actual migration, works perfectly.

---
Tags: files, migrations
---


# Question
Title: How to implement Slider Effect for pages?
I have few pages in my site and I want 4 specific pages to be rendered as **slider** with the full content of the node appeared as a slide.

On a desktop I want the slides to change using `html` arrows and on mobile I can `swipe` the slides.

I checked for contributed modules but mostly which I came across have been developed for photo galleries.

Is there a way to implement swipe for pages in mobile view and slider for specific pages?

# Answer
> 1 votes
It depends on the JavaScript library a module uses.

I use the Flex Slider https://www.drupal.org/project/flexslider that it have both arrows for desktop and swipe for mobile.

I can't understand what you want to achieve (static?), but:

* I think the best way it to create a new content type (let's say slider) to upload images that will be used by the slider plus a taxonomy field that you will specify the slider you want to display the image.
* Then create a slider view with a filter based on that taxonomy.
* Finally render the view as a block.

-- EDIT --

So, you want to create a slider that will present nodes.

Let's say we have two content types Article & Basic, with fields: Title, Description, Image, Taxonomy.

1. Create a View
2. Format: FlexSlider, Show: Fields
3. Fields: Title, Description, Image etc
4. Filter criteria: Content type-\>Article, Basic
5. Save
6. Edit the appearance of the slider with css
7. Enjoy

The nodes will be pre-loaded and there will be no waitting time from slide to slide (but it will take longer to load the page).

---
Tags: nodes
---


# Question
Title: How to add some JavaScript functions before Ajax begins
How do I add some JavaScript functions before Ajax begins, with FAPI?

```
$form['submit'] = array(
  '#type' => 'submit',
  '#value' => 'Upload',
  '#ajax' => array(
    'callback' => 'ajax_submit_key_dump'
  ),
);

```

# Answer
You can add a javascript file to a form using the `#after_build` property:

```
$form['#after_build'] = array('my_js_add_function');

....

function my_js_add_function($form, &$form_state) {
  drupal_add_js(...);
  return $form;
}

```

Using `#after_build` instead of adding the js in the form definition makes sure that the JS is added even if the form is gotten from cache.

In the JavaScript file you can add whatever jQuery you want to, a click handler on the submit button should do what you want.
> 0 votes

# Answer
"beforeSubmit" handler attached that way will be executed right before Ajax request:

```
(function ($) {
  Drupal.behaviors.ReplaceWithAnyTextYouWant = {
    attach: function (context, settings) {
      // 'edit-submit' is the element ID where you execute the #ajax.
      Drupal.ajax['edit-submit'].options.beforeSubmit = function(form_values, element_settings, options) {
      // If cancel is clicked, do not continue submitting.
      if (!confirm('Are you sure you want to continue?')) {
          return false;
      }
    }
  };
})(jQuery);

```

You could perform some pre-submit validation of the user input, and even cancel form submission by returning false

Here is a good example

'edit-submit' - is the element html ID of submit button with '#ajax' settings. 'edit-' prefix is attached to the key of your form array item containing triggering element (submit button in your case). For $form\['my-submit'\] = array(...), html ID of the resulting button will: "edit-my-submit".

JS file with code shown above, could be attached to your form in form constructor:

```
$form['#attached']['js'][] = drupal_get_path('module', 'your_module') . '/js/file.js';

```
> 6 votes

# Answer
I have created a custom module; using hook\_form\_alter() I have added a JavaScript file to one of my content type forms. If you need more details, say it.
> 0 votes

---
Tags: 7, forms
---


title: Change "From" element in drupal mail

text:
# Question
Title: Change "From" element in drupal mail
While sending registration success e-mail in Drupal system, I want to update "from" element.

**Ex:** My admin e-mail is "hello@gmail.com". While sending e-mail to user, I want to change it as "Myname \<(hello@gmail.com)\>"

Can we do it through hook\_mail\_alter?

I have tried below code. But din't work as expected.

```
function mymodule_mail_alter(&$message) {
 print_r($message); // I din't get any response here
}

```

Want to append Name before email ID.

**Edit**: `hook_mail_alter` its not triggering neither module nor `template.php`. Module is enabled. I have cleared cache too.

Existing comment : https://api.drupal.org/comment/59119#comment-59119

# Answer
We can easily change the From with hook\_mail\_alter using '**from**' key from $message.

```
function mymodule_mail_alter(&$message) {
  $message['from'] = 'Your Name ('. $message['from'] . ')';
}

```

Also, Please check hook\_mail function https://api.drupal.org/api/drupal/modules%21system%21system.api.php/function/hook\_mail/7 which needs to be written for your module and then you need to call drupal\_mail function.

hook\_mail\_alter is just for modifying the variables passed to drupal\_mail.
> 1 votes

---
Tags: emails
---


# Question
Title: How to build a specific administrable page layout?
I have a HTML layout provided from a template and I need to make an administrative page to fill the template with a content.

The page layout looks like this:

I want to have an admin page where can I (the user) preferably change all the blocks at once. Also there can be arbitrary many of those small blocks at the bottom, so there must be an option to add the bottom block in the admin page.

Also the page requires some custom HTML markup.

I know how to do this with 2 custom content types and 2 views (one for the frontend, one for the admin backend). But is there an easier or more drupal-way to solve this?

# Answer
Sounds like a job for Panels

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

---
Tags: 7, nodes, theming
---


title: Form States conflict

text:
# Question
Title: Form States conflict
I've two forms in a page, one of the field name is same in both forms.

```
<form id="form1">
   <div class="div1">
        <select id="field_a" name="field_a_name"> ... </select>
    </div>
</form>

<form id="form2">
   <div class="div2">
        <select id="field_a" name="field_a_name"> ... </select>
    </div>
</form>

```

In hook form\_alter, i assign the states to the field:

```
 $field_state = array( 'visible' => array(':input[name="field_a_name"]'
 => array( array('value' => 'H') ))       );

 $form['field_a_name']['#states']   = $field_state;

```

The state does not work as expected, i believe it's caused by the same field name, most likely because of the jquery selector confused with the two fields with same name.

It works fine if the field name are different.

How to solve this?

# Answer
In states you can use jQuery selectors. For example add form id to state selector:

```
$field_state = array(
  'visible' => array(
    '#form1 :input[name="field_a_name"]' => array(
      array('value' => 'H'),
    ),
  ),
);

```
> 0 votes

---
Tags: 7, javascript
---


# Question
Title: How do I override LoginTobbogan so that it redirects to Front Page on 403?
We have a Commerce Kickstart 2 site using LoginToboggan.

What we want is this: if an anonymous visitor goes directly to a node which is unpublished we want them to be redirected to the front page.

We do NOT want them to get a 403 (Access Denied) or to see a login form ... which seem to be the only two options available.

I've tried using Rules, but unfortunately Logintoboggan seems to take precedence over Rules.

Is there a way to override Logintoboggan's 403 behaviour?

OR is there another login module we can use which allows for login by either user name OR e-mail address that doesn't hijack 403? (That's basically the only reason we're using LT--people have gotten used to using e-mail addy to login.)

# Answer
# Option 1: Use the CustomerError module

As per the "*... is there another login module ...*" part of your question, you may want to look at the CustomError module. Here is a quote about it (from its project page):

> ... allows the site admin to create custom error pages for HTTP status codes 403 (access denied) and 404 (not found), without the need to create nodes for each of them.
>
> Main features:
>
> * Configurable page title and descriptions.
> * There are no author and date/time headers as with normal nodes.
> * Any HTML formatted text can be be put in the page body.
> * The error pages are themable.
> * Users who are not logged in and try to access an area that requires login will be redirected to the page they were trying to access after they login.
> * Allows custom redirects for 404s.

More specific, related to the LoginToboggan module, this is how the CustomError module integrates with it (quote from its README.txt, bold markup added here):

> If this module is enabled, it can enhance CustomError's handling of access-denied messages, but you have to be careful to set them up to work together correctly.
>
> These two modules both attempt to take over handling of system 403 ("access denied") messages, and can conflict. CustomError does it by asking you to go to "admin/config/system/site-information" and manually setting the "Default 403 (access denied) page" to "customerror/403", whereas LoginToboggan sets that same field to "toboggan/denied" automatically (overwriting any other value that was there), when you enable its "Present login form on access denied (403)".
>
> If you are using CustomError with LoginToboggan, you should allow LoginToboggan to perform this take-over (in other words, don't set the "Default 403 (access denied) page" to "customerror/403"). This way, if someone attempts to access a page that they don't have access to, LoginToboggan will first give them a chance to log in if they haven't yet. **If they still don't have access to the page, CustomError then takes over from LoginToboggan (by overriding one of its theme functions), displaying its customisable messages for access-denied errors.**

So using what is described in this last (bold) sentence, you may get it to work the way you'd want to (or at least come closer to the solution you're looking for).

# Option 2: Retry with the Rules module

Your (failed) attempt to use the Rules module, might be because you have NOT used event "Drupal is initializing". You may want to retry, using this "Drupal is initializing" event. That might help to ensure that the rule gets trigger '***BEFORE Logintoboggan has a chance to take precedence***' (so that you are NOT too late).

For a sample of a Rule (in export format) using this "Drupal is initializing", refer to my answer to the question "How to redirect user using Rules when user visits a link with view?".
> 1 votes

---
Tags: redirection, authentication-authorization
---


title: Nothing is showing in my FAQ View

text:
# Question
Title: Nothing is showing in my FAQ View
I installed the Frequently Asked Questions module and have created questions and answers.

I navigate to /faq-page and all I see if the title of the page "Frequently Asked Questions", but I don't see the actual questions.

I made sure:

1. The content is published
2. Permissions have been set
3. There is a valid 'Views' page

I even tried creating a menu item and that 's not working.

Can anyone help?

# Answer
It appears to me that you are missing something in the setup of your FAQ. E.g., if you're using categorized faq nodes, then you also need to do some taxonomy vocabulary setup. Without doing so, you might suffer an issue similar to this issue.

Here are some links to Community documentation you may want to verify:
> 1 votes

---
Tags: views, 7
---


# Question
Title: How to create a view grid that changes content type per row
Goal: **Create a Grid that shows mixed content types and have control how those types are added to grid (ie. by row)**

I have 3 content types and would like control over how they are added to a view.

Case 1: inject a row of Content Type B or C into a view of Type A based on row number.

Case 2: intersperse view with (possibly random) Content type C (think adding images to liven it up.)

Some approaches I've explored:

For case 1 I could just create seperate blocks but then I need to keep the view order consistent (perahps using nodequeue?) across blocks. Do I need to pass the current node queue position as an argument to each block?

For case 2 how do I insert Content Type C images every few rows? (I could even use css but need the grid to wrap around it.)

**Important note: I'm a system builder, not a developer so prefer something that can be maintained without managing custom code but a basic views template would be fine.**

**Case 1**

Content Type A Content Type A Content Type A Content Type A Content Type A Content Type A Content Type A Content Type A Content Type A Content Type A Content Type A Content Type A Content Type B Content Type B Content Type B Content Type B Content Type B Content Type B Content Type A Content Type A Content Type A Content Type A Content Type A Content Type A Content Type C Content Type C Content Type C Content Type C Content Type C Content Type A

**Case 2**

Content Type A Content Type A Content Type A Content Type A Content Type A Content Type A Content Type A Content Type C Content Type A Content Type A Content Type C Content Type A Content Type B Content Type B Content Type B Content Type C Content Type B Content Type B Content Type A Content Type A Content Type C Content Type A Content Type A Content Type A Content Type A Content Type A Content Type A Content Type C Content Type A Content Type A

# Answer
> 1 votes
sounds doable with Views Field View, I have done something a bit similar using Views Field View with Contextual filters. if it did't work the way you want, so you need to code it checkout this answer

---
Tags: views, display-suite, nodes
---


# Question
Title: Getting Feed Aggregator to ignore certain incoming data
EDIT: So originally I posted the below, but I've found other issues and I have some more information. I noticed today that sometimes the links are wrong as well but correct when I view the feed. I looked at the XML being sent by the feed we're bringing in and for one thing, the extra timestamp is being sent in a tag called \<updated\>. I'm not sure why it's being appended to the body text though. Similarly, other tags are being interpreted/appended in such a way as to mess up some other things.

So my new question is: is there any way to have more control over how feed aggregator is arranging this incoming stuff? I want to get rid of that stuff from \<updated\> and a couple of other tags and tell it to link the header with the appropriate link (right now it doesn't always do that).

*Previous Post text:*

In Drupal 7 I've got a view to show some news items that another developer set up through aggregator. The fields are Link, Title, Timestamp, and Body (although Link is hidden; long story that doesn't seem to affect this). Everything looks good except there's an extra timestamp at the end of the body text. Here's an example:

> # Orange County (CA) Register SEILER: Legislature could ignite rush to smuggle cigarettes
>
> Wednesday, August 19, 2015 - 11:19
>
> But higher taxes here would push us in the direction of New York City, meaning more smuggling, more crime and less policing... California already has the nation’s second-lowest rate of tobacco use, after Utah. It should leave higher taxes and other nann 2015-08-19T15:19:16+0000

The '2015-08-19T15:19:16+0000' is what I want to get rid of. I have looked all around but I'm not able to figure out what's causing this. I thought maybe it had something to do with the feed we're using but I looked at the link (http://www.tobacco.org/tagged/new-york.atom) and it doesn't seem to include this.

I'm fairly new to Drupal but I did try to figure this out on my own and I'm at a loss. After extensive Googling I can't even find another example of this happening so I know I'm missing something. Any help is greatly appreciated; thanks.

# Answer
OK, so I'm considering deleting this but it was such a source of frustration for me I guess I'll leave it up in case someone else ever comes across this. This answer, to me, seems like more a workaround (mainly because I am still lacking a basic understanding of why it's happening) so if anyone else has a better answer or more information please do post your own answer.

It seems like you can't have complete control over how Views or Aggregator arranges elements from the XML feed. It also seems (from my fruitless Googling) that this isn't usually a problem. I don't really know if this is an issue with how the RSS feed we have to use is configured or if it's a Drupal thing but I know the answer is in gaining control over where and when the different XML elements appear.

Most people seem to use a module called Feeds to gain control over this type of thing (and do other stuff). From superficially looking into it, it seems like it could fix my problem but it creates a separate node for each incoming item, which is not ideal for my special case. The feed on the site I'm working on just keeps up with the latest 20 items and then discards them so I didn't want to have to deal with a separate node for each thing.

I've decided to try a different module called Views RSS which sounds like it can simply solve my problem (here's some more info). I haven't tried it yet but it looks promising. Thanks to anyone who read this and to anyone who might be able to contribute in the future.
> 1 votes

---
Tags: 7, views, feeds
---


# Question
Title: How to add a view with contextual filters in a panel
I created a view with some contextual filter and relationships. When i add this view to a menu tab from a node, the view is working ok. But when i add this view to a panel, it gives me the message that there are no items added yet (my own custom text when the view is empty).

Like it should be:

And how it is through panes:

Can somebody help me with this? Tnx!

# Answer
> 1 votes
I added %1 to arguments and it seems to be working now. But can someone explain what this is exactly? I don't really understand why its working with this.

---
Tags: views
---


# Question
Title: How can I alter the HTML output of the default 403 and 404 error messages without hacking core?
How can I alter the HTML output of the default 403 and 404 error messages without hacking core?

I know I can create custom pages via the UI, but this doesn't work for me because I need to deny access to all published pages to anonymous users.

**Notes**:

* I believe the default 403 and 404 messages come from lines 2624 and 2653 on common.inc. This is what is generating my output at the moment - I assume. I don't think I can use a node for my output instead because anon users don't have permission to view published content.
* I wanted to alter/override the default 403/404 messages outputed by common.inc. I can't redirect to a node because anon users don't have permission to view nodes.

# Answer
Implement a custom module providing the 403/404 markup as a page callback. Note that access can be granted to anybody by setting the `access callback` in the menu router items to `TRUE`.

After enabling the custom module, you simply set the error pages in *Configuration » System » Site information* to the paths you defined in your `hook_menu` implementation.

```
/**
 * Implements hook_menu().
 */
function acme_menu() {
  $items['acme_404'] = array(
    'page callback' => 'acme_404',
    'access callback' => TRUE,
    'type' => MENU_CALLBACK,
  );
  $items['acme_403'] = array(
    'page callback' => 'acme_403',
    'access callback' => TRUE,
    'type' => MENU_CALLBACK,
  );
  return $items;
}

/**
 * Page callback for custom page not found.
 */
function acme_404() {
  return filter_xss(variable_get('acme_404_markup', 'custom 404 markup'));
}

/**
 * Page callback for custom access denied page.
 */
function acme_403() {
  return filter_xss(variable_get('acme_403_markup', 'custom 403 markup'));
}

```
> 2 votes

# Answer
Other solution is create 2 pages for 403 and 404 message error. Apply your themming with your CSS.

Then, go to "Site Information" (admin/config/system/site-information) and put the URL for your custom pages errors.
> 0 votes

# Answer
The CustomError module allows the site admin to create custom error pages for HTTP status codes 403 (access denied) and 404 (not found), without the need to create nodes for each of them. Some more details about its features (from its project page):

> * Configurable page title and descriptions.
> * There are no author and date/time headers as with normal nodes.
> * Any HTML formatted text can be be put in the page body.
> * The error pages are themable.
> * Users who are not logged in and try to access an area that requires login will be redirected to the page they were trying to access after they login.
> * Allows custom redirects for 404s.
> 0 votes

---
Tags: theming
---


# Question
Title: Sorting orders by name rather than by order number
On my orders page you can search orders by order number only - how do I change this so I can also sort by name, date, ect. When we have customers come in that do not know their order number, we cannot search for their name! The name column on our orders table also does not sort correctly, you can sort by most recent or oldest date, but you cannot sort names alphabetically. Not sure how to change this. Thanks!

# Answer
> 0 votes
Assuming you are using views to build your table, take a look at the table settings. In there you can set default sort, and there is a checkbox to make columns sortable.

---
Tags: commerce
---


# Question
Title: How to fix the garbled text in my text editors?
When editing my nodes all of my saved data is displayed garbled. This is the warning I get on my node/edit pages: "Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience. For more help, check http://xhr.spec.whatwg.org/." The other odd part is that the contents of the database field and the contents of the output are correct. Just the contents of the text editor is garbled. How can I fix this?

UPDATE: I have another content type that has a file field, and I have some pdfs loaded in those fields and those pdfs are the ones that are showing up in my text editor. Does anyone know why that would happen?

# Answer
> 0 votes
I had the exact same issue with aGov distro. I had to swapped from ckeditor module to WYSIWYG module + ckeditor lib.

That fixed the issue with ckeditor. However, today I got the garbled text again while having batched processes running which preventing them to complete. Thinking back, I realised the problem started when I installed Devel themer & simplehtmldom API (7.x-1.12). Uninstalling simplehtmldom fixed the issue for me.

---
Tags: javascript, wysiwyg
---


title: Commerce orders - header

text:
# Question
Title: Commerce orders - header
On the orders admin page you have options to change fields in your table and sort fields, ect. In the headers option I have 'global: view order form' selected, and above the table there is a box where you can search for order numbers. I want to be able to not only search for order numbers, but also search for customer names, dates, money amounts, ect. Can you add in search criteria to that header?

# Answer
Did yout try simply add new filters?

For example, user:

* Add Filter Criteria
* Chose Filter - User
* Search for "name" field
* Select "User: Name"
* Check "Expose this filter to visitors, to allow them to change"
* Click "Apply"

That's all you need to do. I should notice that for amount and date you can expose operator for your own needs.

In the same way you can add SORT CRITERIAS
> 0 votes

---
Tags: commerce, search
---


# Question
Title: Send multilingual emails notifications with Checkout Rules in Commerce module?
I have an on-line store using the Drupal Commerce module. When the checkout is done the buyer get an **email notificatio*\*n. So far so good.

My problem is that the website is multilingual (english, french and spanish) then I need to send the **email notification** in the correct language.

**To accomplish with this I think of:**

1) creating 3 different rules, one for each language at: **admin/commerce/config/checkout/rules**.

2) Each rule would have a condition to compare the user current language and an action to send the email notification in the correct language

3) Then when checkout is done the correct rule should be fired to send an email in the appropriated language

Is there any other way to do it?

# Answer
> 1 votes
Look at Commerce Email:

> * Adds a configuration page for the order email
> * Email content can be entered into textarea/wysiwyg (if available) form
> * Email content can also be set to be loaded from a template file: commerce-order-email.tpl.php
> * Allows the insertion of the order items into the email, token addition: \[commerce-email:order-items\]
> * Supports Commerce Shipping
> * **Allows different language versions of each email**
> * Optional administrator email

# Answer
> 0 votes
I think Commerce Message is a better alternative now. It allows messages to be translated, and sent using the current site language (with Rules)... so it won't be necessary to create 3 different rules. It requires message and message\_notify so it is free from variable & htmlmail.

---
Tags: rules, commerce
---


title: Drupal 7 theme for specific page

text:
# Question
Title: Drupal 7 theme for specific page
I have one page mortgages/%/view that needs to have it's own custom theme. I have the HTML created and it's ready to go. In my 'mortgage' module I have a mortgage.tpl.php file with this HTML in it.

My hook\_menu looks like this:

```
function mortgage_menu() {

  $items = array();

  $items['mortgage/%/view'] = array(
    'page callback' => 'mortgage_callback',
    'page argument' => array(3), //pass 3rd argument of url -- 1. drupal 2. mortgage 3. %
    'access callback' => TRUE,
    'type' => MENU_CALLBACK,
  );
  return $items;
 }

```

Then my callback function and mortgage\_theme function look like this:

```
function mortgage_callback() {
 return theme('mortgage');
}

 /*
 * Implementation of hook_theme().
 */

function mortgage_theme(){
  return array (
    'mortgage' => array (
      'template' => 'mortgage' ,
      'arguments' => array(),
    ),
  );
}

```

This successfully calls my mortgage.tpl.php file into my mortgage/%/view page. HOWEVER, it only displays in the middle of my "content" section instead of correctly overriding the theme. Obviously this isn't correct.

How would I get this mortgage.tpl.php file to be THE theme file for this specific page?

e/ Mortgage is NOT a node. It's a custom module which allows users to get a full page view of mortgage details.

# Answer
> 2 votes
In your module

```
function custom_theme($existing, $type, $theme, $path){
      return array(
        'mortgage_page' =>  array(
          'template' => 'theme/mortgage',
          'render element' => 'page'
        ),
      );
    }

function custom_preprocess_page(&$variables, $hook) {
  if ( preg_match("/mortgage\/.*\/view/", drupal_get_path_alias($_GET['q'])) ) {
   $variables['theme_hook_suggestions'][] = 'mortgage_page';
  }
}

```

Check for path alias to be correct and change theme\_hook\_suggestions to your theme.

# Answer
> 0 votes
This working as designed, if you want to override the whole page markup, you might consider custom page.tpl.php, Also you would use template\_preprocess\_page to add theme\_hook\_suggestions to let that page pickup your custom\_page.tpl.php

```
Yourtheme_preprocess_page(&$vars) {
   if(something) {
      $vars['theme_hook_suggestions'][] = 'page_your_custom_page_tpl';
   }
}

```

---
Tags: theming
---


title: How to store user location

text:
# Question
Title: How to store user location
I use Smart IP module to track user location with option IPInfoDB.com. But as I understand Smart IP does not store by default user location in database. Is there any option to configure this or I need to make own module? Ultimately I need to show user who is in the same city or region.

# Answer
No. Smart IP is solely for IP geolocation, it doesn't not touch storage of user location addresses.

Depending on your needs, Location (with the User Location submodule) or a combination of GeoField/Address Field on your a profile (you might want to guess the location while letting the user determine what his address) will get your location storage needs.

None of those modules have Smart IP integration so you'll have to build some custom code to add IP geolocation to either of those storage options.
> 1 votes

---
Tags: users
---


# Question
Title: How do I prevent a page from reloading after form submit?
Im trying to edit the poll module to prevent the page reloading after every form submit. no matter where I put

```
$form_state->disableRedirect()

```

when the button is clicked the whole page reloads.

I cant find a redirect or reload anywhere in there. Is there some function of how forms work that would force it to reload?

```
<?php

/**
 * @file
 * Contains \Drupal\ban\Form\BanAdmin.
 */

namespace Drupal\poll\Form;

use Drupal\Core\Entity\EntityManagerInterface; //Maybe we dont need this line?
use Drupal\poll\Form\PollViewForm;
use Drupal\Component\Utility\SafeMarkup;
use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Url;
use Drupal\poll\PollInterface;
use Symfony\Component\HttpFoundation\Request;

/**
 * Displays banned IP addresses.
 */
class PollViewForm extends FormBase {

    protected $poll;
  /**
   * {@inheritdoc}
   */
  public function getFormId() {
    return 'poll_view_form_' . $this->poll->id();
  }

  /**
   * Set the Poll of this form.
   *
   * @param \Drupal\poll\PollInterface $poll
   *    The poll that will be set in the form.
   */
  public function setPoll(PollInterface $poll) {
    $this->poll = $poll;
  }

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state, Request $request = NULL) {
    // Add the poll to the form.
    $form['poll']['#type'] = 'value';
    $form['poll']['#value'] = $this->poll;

    if ($this->showResults($this->poll, $form_state)) {

      // Check if the user already voted. The form is still being built but
      // the Vote button won't be added so the submit callbacks will not be
      // called. Directly check for the request method and use the raw user
      // input.
      if ($request->isMethod('POST') && $this->poll->hasUserVoted()) {
        $input = $form_state->getUserInput();
        if (isset($input['op']) && $input['op'] == $this->t('Vote')) {
          // If this happened, then the form submission was likely a cached page.
          // Force a session for this user so he can see the results.
          drupal_set_message($this->t('Your vote for this poll has already been submitted.'), 'error');
          $_SESSION['poll_vote'][$this->poll->id()] = FALSE;
        }
      }

       $form['results'] = $this->showPollResults($this->poll);
    }
    else {
      $options = $this->poll->getOptions();
      if ($options) {
        $form['choice'] = array(
          '#type' => 'radios',
          '#title' => t('Choices'),
          '#title_display' => 'invisible',
          '#options' => $options,
        );
      }
      // Add the poll to the form.
      $form['poll']['#type'] = 'value';
      $form['poll']['#value'] = $this->poll;

      $form['#theme'] = 'poll_vote';
       $form['#entity'] = $this->poll;
      // Set a flag to hide results which will be removed if we want to view
      // results when the form is rebuilt.
      $form_state->set('show_results', FALSE);
    }

    $form['actions'] = $this->actions($form, $form_state, $this->poll);

    $form['#cache'] = array(
      'tags' => $this->poll->getCacheTags(),
    );

    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {

  }

  public function showResults(PollInterface $poll, FormStateInterface $form_state) {
    $account = $this->currentUser();
    switch (TRUE) {
      // The "View results" button, when available, has been clicked.
      case $form_state->get('show_results'):
        return TRUE;
      // The poll is closed.
      case ($poll->isClosed()):
        return TRUE;
      // Anonymous user is trying to view a poll they aren't allowed to vote in.
      case ($account->isAnonymous() && !$poll->getAnonymousVoteAllow()):
        return TRUE;
      // The user has already voted.
      case ($poll->hasUserVoted()):
        return TRUE;
      default:
        return FALSE;
    }
  }

  protected function actions(array $form, FormStateInterface $form_state, $poll) {
    // Remove all actions.
    $actions = array();
    if ($this->showResults($poll, $form_state)) {
      // Allow user to cancel their vote.
      if ($this->isCancelAllowed($poll)) {
        $actions['#type'] = 'actions';
        $actions['cancel']['#type'] = 'submit';
        $actions['cancel']['#button_type'] = 'primary';
        $actions['cancel']['#value'] = t('Cancel vote');
        $actions['cancel']['#submit'] = array('::cancel');
        $actions['cancel']['#weight'] = '0';
      }
      if (!$poll->hasUserVoted() && $poll->isOpen()) {
        $actions['#type'] = 'actions';
        $actions['back']['#type'] = 'submit';
        $actions['back']['#button_type'] = 'primary';
        $actions['back']['#value'] = t('View poll');
        $actions['back']['#submit'] = array('::back');
        $actions['back']['#weight'] = '0';
      }
    }
    else {
      $actions['#type'] = 'actions';
      $actions['submit']['#type'] = 'submit';
      $actions['submit']['#button_type'] = 'primary';
      $actions['submit']['#value'] = t('Vote');
      $actions['submit']['#validate'] = array('::validateVote');
      $actions['submit']['#submit'] = array('::save');
      $actions['submit']['#weight'] = '0';

      // view results before voting
      if ($poll->result_vote_allow->value) {
        $actions['result']['#type'] = 'submit';
        $actions['result']['#button_type'] = 'primary';
        $actions['result']['#value'] = t('View results');
        $actions['result']['#submit'] = array('::result');
        $actions['result']['#weight'] = '1';
      }
    }

    return $actions;
  }

  /**
   * Display a themed poll results.
   *
   * @param \Drupal\poll\PollInterface $poll
   * @param bool $block
   *
   * @return false|string
   */
  function showPollResults(PollInterface $poll, $block = FALSE) {

    // Ensure that a page that shows poll results can not be cached.
    \Drupal::service('page_cache_kill_switch')->trigger();

    $total_votes = 0;
    foreach ($poll->votes as $vote) {
      $total_votes += $vote;
    }

    $options = $poll->getOptions();
    $poll_results = array();
    foreach ($poll->votes as $pid => $vote) {
      $percentage = round($vote * 100 / max($total_votes, 1));
      $display_votes = (!$block) ? ' (' . \Drupal::translation()
          ->formatPlural($vote, '1 vote', '@count votes') . ')' : '';

      $poll_results[] = array(
        '#theme' => 'poll_meter',
        '#prefix' => '<dt class="choice-title">' . SafeMarkup::escape($options[$pid]) . "</dt>\n" . '<dd class="choice-result">',
        '#suffix' => "</dd>\n",
        '#display_value' => t('!percentage%', array('!percentage' => $percentage)) . $display_votes,
        '#min' => 0,
        '#max' => $total_votes,
        '#value' => $vote,
        '#percentage' => $percentage,
        '#attributes' => array('class' => array('bar')),
      );
    }

    $output = array(
      '#theme' => 'poll_results',
      '#raw_question' => $poll->label(),
      '#results' => $poll_results,
      '#votes' => $total_votes,
      '#block' => $block,
      '#pid' => $poll->id(),
      '#vote' => isset($poll->vote) ? $poll->vote : NULL,
    );

    return $output;
  }

  /**
   * Cancel vote submit function.
   *
   * @param array $form
   * @param array $form_state
   */
  public function cancel(array $form, FormStateInterface $form_state) {
    $form_state->setRedirect('poll.poll_vote_delete', array(
        'poll' => $form_state->getValue('poll')->id(),
        'user' => \Drupal::currentUser()->id(),
      ),
      array(
        'query' => array(
          // Ensure that the cancel form will redirect back to the current page,
          // as the poll might be displayed as a block on any page.
          'destination' => Url::fromRoute('<current>')->getInternalPath(),
        ),
      )
    );
  }

  /**
   * View vote results submit function.
   *
   * @param array $form
   * @param array $form_state
   */
  public function result(array $form, FormStateInterface $form_state) {
    $form_state->set('show_results', TRUE);
    $form_state->setRebuild(TRUE);
  }

  /**
   * Back to poll view submit function.
   *
   * @param array $form
   * @param array $form_state
   */
  public function back(array $form, FormStateInterface $form_state) {
    $form_state->set('show_results', FALSE);
    $form_state->setRebuild(TRUE);
  }

  /**
   * Save a user's vote submit function.
   *
   * @param array $form
   * @param array $form_state
   */
  public function save(array $form, FormStateInterface $form_state) {
    $options = array();
    $options['chid'] = $form_state->getValue('choice');
    $options['uid'] = $this->currentUser()->id();
    $options['pid'] = $form_state->getValue('poll')->id();
    $options['hostname'] = \Drupal::request()->getClientIp();
    $options['timestamp'] = REQUEST_TIME;
    // Save vote.
    $poll_storage = \Drupal::entityManager()->getStorage('poll');
    $poll_storage->saveVote($options);
    drupal_set_message($this->t('Your vote has been recorded.'));

    if ($this->currentUser()->isAnonymous()) {
      // The vote is recorded so the user gets the result view instead of the
      // voting form when viewing the poll. Saving a value in $_SESSION has the
      // convenient side effect of preventing the user from hitting the page
      // cache. When anonymous voting is allowed, the page cache should only
      // contain the voting form, not the results.
      $_SESSION['poll_vote'][$form_state->getValue('poll')->id()] = $form_state->getValue('choice');
    }

    // No explicit redirect, so that we stay on the current page, which might
    // be the poll form or another page that is displaying this poll, for
    // example as a block.
        $form_state->disableRedirect();
  }

  /**
   * Validates the vote action.
   */
  public function validateVote(array &$form, FormStateInterface $form_state) {
    if (!$form_state->hasValue('choice')) {
      $form_state->setErrorByName('choice', $this->t('Your vote could not be recorded because you did not select any of the choices.'));
    }
  }

  /**
   * Checks if the current user is allowed to cancel on the given poll.
   * @param \Drupal\poll\PollInterface $poll
   *
   * @return bool
   *   TRUE if the user can can cancel.
   */
  protected function isCancelAllowed(PollInterface $poll) {
    // Allow access if the user has voted.
    return $poll->hasUserVoted()
      // And the poll allows to cancel votes.
      && $poll->getCancelVoteAllow()
      // And the user has the cancel own vote permission.
      && $this->currentUser()->hasPermission('cancel own vote')
      // And the user is authenticated or his session contains the voted flag.
      && (\Drupal::currentUser()->isAuthenticated() || !empty($_SESSION['poll_vote'][$poll->id()]));
  }

}

```

# Answer
> 1 votes
That's how form submissions work, I don't think you can't prevent that.

What you likely want instead is extend it to use #ajax for submission so that you can just update that part of the page.

I'm one o the maintainers of poll in 8.x, pages to do this are certainly welcome.

---
Tags: forms, 8, polls
---


# Question
Title: Alter all images styles to add a particular effect before all others?
I just downloaded the manual crop module: https://www.drupal.org/project/manualcrop

It must be added as an image style effect before it is applied.

I would like to apply it to all image styles before others are executed.

Is there any hook\_preprocess\_image\_style that can add an effect to the stack before others are processed?

Or anybody have any other good ideas about how to do this programmatically other than manually adding the style?

Thanks!

# Answer
> 3 votes
Yes, you can do this with hook\_image\_styles\_alter.

I'm not so sure it's a great idea since you'll be enforcing adding your effect no matter what the user might try to configure via the interface, but it will definitely let you do what you want to do.

---
Tags: media
---


# Question
Title: Is there is any module which creates new users by reading a spreadsheet/excel file?
Could anyone tell me if there is any module which creates new users by reading a spreadsheet/excel file? I have added few more fields to the user registration form, and that might make this a bit tricky! Any suggestions would be helpful.

# Answer
Try out the user import module

> Import users into Drupal, or update existing users, with data from a CSV file (comma separated file). Provides a wide range of features out of the box, and a comprehensive API to customise imports.
> 2 votes

# Answer
Well, from my experience, importing users could be a tricky task. The user import module is nice and easy, but if you'll need more features, you'll end frustrated. Some field types aren't supported (e.g. date fields). Importing Profile2 fields, if you'll need them, is almost impossible. The last patch is one year old (it's mine), it's not 100% working, and no other tried to continue working on it. But if you can switch to CSV, it'll get you up and running very quickly. You can send an email to the new users so they can activate their account, you can automatically generate usernames and roles etc.

If XLS is mandatory you should switch to Feeds and the Feeds XLS parser. By adding Feeds Profile2 you can also easily import Profile2 fields. Just remember that if you use Feeds, you won't be able to automatically enable and mail users. You'll have to modify Drupal's registration mail template to suit you needs, and then manually enable the imported users. At that point they'll receive the signup email.

Since I've started my site using User Import I'm continuing with it, but after importing basic user info I'm passing the CSV again to the Feeds module in order to update the users with the Profile2 info and with the fields that aren't supported by User Import. I'm also considering to totally switch to the Feeds module, but at the moment I don't have time, plus I'm too lazy.

So: if you want an easy module, CSV is OK and you have simple fields to import, go for User Import. If you need XLS, you have advanced fields or Profile2 info and you don't mind having some extra complexity, Feeds is the way.
> 0 votes

---
Tags: users
---


# Question
Title: Exporting from Field Collections and Importing to New Content Type
So here's a high-level overview of the situation: we're running into a lot of issues with the field collections module, but a lot of content has already been created for a content type that uses two fields within a field collection. We've tried to overcome some of the problems we're experiencing with field collections, and at this point it's been over a month, so we're just going to have to give up on field collection for this project.

So here's what we have. A content type like this:

* Title Field
* Field Collection field containing:
    + Subtitle Field
    + Body Field

And we want to export from that and create nodes in a content type that looks like this:

* Title Field
* Subtitle Field
* Body Field

I don't really need past revisions or anything like that. I'm just looking for advice about how best to accomplish this.

# Answer
> 1 votes
Some time ago I did something similar, but with normal fields. I used Views Bulk Operations.

First I've created a view which listed all the nodes of the particular node type and added the VBO checkbox to execute arbitrary PHP code.

On the view's page I've checked all the nodes and pasted in the PHP textbox the code which updated field B values based on the field A values. In your case you should create a new node based on the field collection.

Finally, when VBO finished executing the code for all my nodes, I went to the content type fields page and deleted field A (in you case the field collection).

Done!

# Answer
> 0 votes
After creating your new content type you can try to use either Rules, Feeds or the Migrate module to move the existing content into new nodes.

I've successfully used the Migrate module to create Field Collections for example (and update a node with Field Collections). I know the other 2 approaches are doable too. Unfortunately, I dont have any simple code examples to share with you.

---
Tags: entities
---


# Question
Title: Table not created at the time of installing a custom module
### my\_register.install

```
<?php

  function my_register_schema() {
  $schema['my_register'] = array(
   'description' => 'Registered users detail',
   'fields' => array(

  'rid' => array(
    'type' => 'serial',
    'not null' => TRUE,
    'description' => 'unique ID',
  ),

  'my_register_uname' => array(
    'type' => 'varchar',
    'length' => 255,
    'not null' => TRUE,
    'description' => 'Some description here.',
  ),

  'my_register_fathername' => array(
    'type' => 'varchar',
    'length' => 255,
    'not null' => TRUE,
    'description' => 'Some description here.',
  ),

  'my_register_phone' => array(
    'type' => 'varchar',
    'length' => 10,
    'not null' => TRUE,
    'description' => 'Some description here.',
  ),

  'my_register_email' => array(
    'type' => 'varchar',
    'length' => 50,
    'not null' => TRUE,
    'description' => 'Some description here.',
  ),

  'gender' => array(
    'type' => 'varchar',
    'length' => 10,
    'not null' => TRUE,
    'description' => 'Some description here.',
  ),

  'my_register_address' => array(
    'type' => 'varchar',
    'length' => 255,
    'not null' => TRUE,
    'description' => 'Some description here.',
  ),

  'Education' => array(
    'type' => 'varchar',
    'length' => 50,
    'not null' => TRUE,
    'description' => 'Some description here.',
  ),

  'my_register_language' => array(
    'type' => 'varchar',
    'length' => 50,
    'not null' => TRUE,
    'description' => 'Some description here.',
  ),
),
'primary key' => array('rid'),
);

return $schema;
}

```

# Answer
I have found that if you update hook\_schema() while your module is enabled there seems to be an issue getting Drupal to generate your tables even after disabling and enabling your module. To get around this:

1. disable the module
2. uninstall the module (via the modules page)
3. enable the module

Your updated schema should now be reflected in the database. Hope this helps someone because I was scratching my head for a while at this.
> 1 votes

---
Tags: 7
---


# Question
Title: How can I sum up fields that reside in multiple nodes?
I am using Drupal as an inventory management system and wanted to know how can I sum up fields to get a net total?

Say I purchased 10,000 widgets over 2012, and I want to be able to sum up all the fields in those nodes to get a final total then have it displayed in a block giving me a summary of how much I spent during 2012. I want to be able to archive this data into a type of report.

I know I should use the Views module, but I want to know how others would accomplish this situation.

What kind of performance roadblocks could I run into, if I had 1 million nodes? Would my site crash? can this be lazy loaded. if needed?

# Answer
The **SUM** functionality is actually built into Views for D7.

If you go to your Advanced settings and enable Aggregation, you will see the Aggregation settings applied to each field.

Click on '**Aggregation settings**' for the field you'd like to do the SUM functions for and you can select 'SUM' from the 'Aggregation type' dropdown as shown in this screenshot

Taken from Source Sum a field
> 4 votes

# Answer
The views calc module allows you to have total/sum values at the end of a list of results.

If the layout it provides isn't what you are after you could then tweak it using template overrides & css.

If you just want the total I would do a custom block that uses a bit of custom sql. If it is a reasonably basic sql statement it will run pretty fast.

I would also implement a caching method so that the sql is not run every time, but maybe once a day or week or whatever is sensible for the use case.

You can use drupal's cache system for this, which is pretty straight forward, with a cache\_set() and cache\_get().

If it wasn't something that could be cached you could use the method from Oleg's answer and write the sums to a database table whenever content is added, edited, removed, etc. and then just pull in that value. You could do this using node api hooks.

If the result is different per user then you have to store the values per user in the cache or store a value per user in the database.
> 1 votes

# Answer
Another module that can be used for addressing these requirements is the Forena module. Here is a quote from one of its community docu pages, i.e. Reasons for considering Forena:

> "Why not use views instead of forena?" ... The answer is generally something along the lines of "Most forena users love views, views is great! If you want to report against external data though, or you want to do **aggregation or analytics**, Forena is much more suited to address these requirements."

For an illustration (demo) of the kind of reporting (and charting ...) features it offers, which seem pretty close to what you might be looking for, refer to its Sample reports and graphs, such as:

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

# Answer
I see two possibilities. Correct me If I am wrong.

1. In views, you add a footer PHP field, that calculates the sum. You can dpm() the variable $view, $row , etc.
2. Create custom database table and a script (in a custom module) that calculates the thing and writes it to the database.After that make it a cron task, to overwrite the value and then again in the footer, make a call to this database field.
> 0 votes

---
Tags: views, entities
---


# Question
Title: Sort a view by price using commerce price?
I have a custom view (created with Views) that is working fine. But when I add a price field to it and sort the view with same field in descending or ascending order, it is not working.

Any suggestions to get this to work?

# Answer
> 2 votes
Follow the below steps and share the output:

1. Create a views with the same content type in which the field exists from which you need to filter easily with "filter section" in views.
2. Select the same field of content which you want to filter.
3. Select the same fields in filter with sorting order "ASC" or "DESC".

Mention please use Commerce Views plugin for the same.

Thanks.

---
Tags: commerce
---


# Question
Title: How to exclude an item from a view if it appears in another view on the same page?
I am very new to Drupal and now I am trying to build some small website to try different things out.

I made my website's homepage a Panel, and in it there is a "Promoted News" View, and under this view there is a "Latest News" View.

I want to be able to exclude from "Latest News" any news item that appears in "Promoted News".

Is that possible to do without having to write code? And if not, how can it be achieved?

# Answer
> 1 votes
So you have 2 views: "Promoted News", and "Latest News" View.

To exclude any view results ('items' as you call them) from "Latest News", add a 'filter' in that view with as criteria the opposite (negation) of the 'filter' criteria that are used in your "Promoted News" views.

E.g. if "Promoted News" is implemented with a filter like "published to frontpage", then in "Latest News" the filter o be added should be "NOT promoted to frontpage".

**Note**: If you're new to Drupal, you might also want to review the set of 30 video tutorials about the Views module to become more familiar with the Views module.

---
Tags: views, panels
---


# Question
Title: hook_node_presave() fires twice when adding a new node
In a custom module I use `hook_node_presave($node)` on node objects with referenced fields.

When creating a new node, `ddebug_backtrace()` shows that `entity_save` is called first and then `node_save`. Which leads to two new nodes. At the end of `hook_node_presave()` I have one correctly created node and one with only partially filled fields.

How can I prevent `node_save` to fire in `hook_node_presave()` when `entity_save` was already executed? Or maybe the solution is to prevent `entity_save` to fire?

Could anybody please explain how to correctly use `hook_node_presave()` on node objects with attached referenced fields?

# Answer
> 1 votes
Just in case anybody else experiences the same strange problem. In my case the reason was module CER (Corresponding Entity References) 7.x-3.0-alpha7. For any reason after a complete uninstall and clean reinstall hook\_node\_presave() now works fine with entity referenced fields.

---
Tags: entities, nodes
---