# Question
Title: expose filter work with ajax only on inner pages but work with button submit on front page
What I want is to work expose filter with ajax only on inner pages but work with button submit on front page i.e when I want my expose filter on front page to work like normal form but on inner page i want it to work with ajax

# Answer
> 0 votes
Disable Use ajax in View settings, in `THEME_OR_MODULE_form_views_exposed_form_alter(&$form, &$form_state)` function do like this:

```
function THEME_OR_MODULE_form_views_exposed_form_alter(&$form, &$form_state) {
  // dpm($form)
  // dpm($form_state)
  if ($form['#id'] == 'MY-VIEWS-FORM-ID') {
    if (!drupal_is_front_page()) {
      $form_state['view']->use_ajax = true;
    }
  }
}

```

flush the cache.

---
Tags: views, ajax
---


# Question
Title: Multi-value form widget in a system settings form
I'm building a form for a modules configuration page. The last line of the form callback is the following:

```
return system_settings_from($form);

```

I want to add a textfield to the form, but I want to be able to enter multiple entires into the field using the same widget you get when manually creating a field of this type (where cardinality \> 1) where you get the text field with an "add another item" button.

How can I use that type of widget in a form for a module configuration page?

# Answer
You won't be able to use the multi-value functionality used in the Field API in your custom forms.

However, with the Form API and Ajax you should be able to create dynamic form fields. See Ajax Example in the Examples for Developers project.

```
<?php
/**
 * Form manipulation through AJAX.
 */
function ajax_example_autocheckboxes($form, &$form_state) {

  // Since the form builder is called after every AJAX request, we rebuild
  // the form based on $form_state.
  $num_checkboxes = !empty($form_state['values']['howmany_select']) ? $form_state['values']['howmany_select'] : 1;

  $form['howmany_select'] = array(
    '#title' => t('How many checkboxes do you want?'),
    '#type' => 'select',
    '#options' => array(1 => 1, 2 => 2, 3 => 3, 4 => 4),
    '#default_value' => $num_checkboxes,
    '#ajax' => array(
      'callback' => 'ajax_example_autocheckboxes_callback',
      'wrapper' => 'checkboxes-div',
      'effect' => 'slide',
    ),
  );

  ...

  for ($i = 1; $i <= $num_checkboxes; $i++) {
    $form['checkboxes_fieldset']["checkbox$i"] = array(
      '#type' => 'checkbox',
      '#title' => "Checkbox $i",
    );
  }

  ...

  return $form;
}

/**
 * Callback for autocheckboxes.
 *
 * @return array
 *   Renderable array (the checkboxes fieldset)
 */
function ajax_example_autocheckboxes_callback($form, $form_state) {
  return $form['checkboxes_fieldset'];
}

```

Another, quick solution that may work (or not) for your case is using an entity (e.g. a single node of a new content type) to store that configuration.
> 10 votes

---
Tags: 7, forms
---


# Question
Title: How to convert a command line table (drush output) to any spreadsheet? (csv,excel,ods)
I often use commands like `drush pm-list` or drush `views-list` to get some listings of what my current project is using and for sake of usability I would like to import that stuff in a spreadsheet programm (I dont care which, csv can be imported bascially everywhere).

I digged into drush code and find out that it uses `Console_Table` for generating table like output. Maybe someone has an idea how to implement/ find a generic way to get a csv output from it.

# Answer
Check out this new feature from the latest dev version of Drush 8.x-6.x:

```
$ drush @dev pm-list --format=csv
Administration,Actions permissions (VBO) (actions_permissions),Module,Not installed,7.x-3.1
Administration,Administration Development tools (admin_devel),Module,Not installed,7.x-3.0-rc4
Administration,Administration menu (admin_menu),Module,Enabled,7.x-3.0-rc4
Administration,Administration menu Toolbar style (admin_menu_toolbar),Module,Not installed,7.x-3.0-rc4
Administration,Administration views (admin_views),Module,Enabled,7.x-1.1
CCK,CCK (cck),Module,Enabled,7.x-2.x-dev
CCK,Content Migrate (content_migrate),Module,Disabled,7.x-2.x-dev
CCK,Location CCK (location_cck),Module,Enabled,7.x-3.0-alpha1
... etc.

```

If you are at all wary about using a dev version of Drush, you could check it out following the version control instructions at http://drupal.org/project/drush/git-instructions. Then, you can use `git checkout 7.x-5.8` to go back to latest stable, and `git checkout 8.x-6.x` to go back to latest dev, and use stable most of the time, and the dev version when you want to output something in another data format.

**Update:** Note also that Drush 8.x-6.x-rc4 is out now, which is pretty well fit for general consumption.

**Update 2:** Note that this is a standard feature now in Drush 6 and Drush 7 (master branch of Drush on github)
> 7 votes

# Answer
Worth noting that as at this date, both the CSV and table formatted outputs won't copy/paste in a friendly fashion into a Google Spreadsheet.

Open a spreadsheet, click A1 cell and then File \> Import... and load the file directly from your Desktop (eg).
> 1 votes

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


# Question
Title: How to convert a complex select query to Drupal dynamic query?
I read online that db\_query is faster than db\_select for complex queries. I wanted to check this for one of the queries I have written.

Following is the code with db\_query:

```
$query = "SELECT og_users_roles.uid
        FROM {og_users_roles} AS og_users_roles
          LEFT JOIN {og_role} AS og_role
            ON og_users_roles.rid = og_role.rid
          LEFT JOIN {users} AS users
            ON og_users_roles.uid = users.uid
        WHERE og_users_roles.gid = :gid
          AND og_role.name =  :role_name
          AND users.uid <> 0
          AND users.status = 1";

$placeholders = array(
  ':gid' => $group_entity->nid,
  ':role_name' => OG_ADMINISTRATOR_ROLE,
);

$results = db_query($query, $placeholders)->fetchAll();

```

Now, before testing the performance I need to change above to user db\_select.

This is what I have done:

```
$query = db_select('og_users_roles', 'o_u_r')
  ->leftJoin('og_role', 'o_r', 'o_u_r.rid = o_r.rid')
  ->leftJoin('user', 'u', 'o_u_r.uid = u.uid')
  ->fields('o_u_r', array('uid'))
  ->condition('o_u_r.gid', $group_entity->nid)
  ->condition('o_r.name', OG_ADMINISTRATOR_ROLE)
  ->condition('u.uid', 0, '<>')
  ->condition('u.status', 1);

$results = $query->execute()->fetchAll();

```

However, this seems to fail with a WSOD. Can someone point the error?

# Answer
> 3 votes
Give a try to Query coder module ( https://www.drupal.org/project/query\_coder ): Convert SQL query to Drupal Database abstraction layer code.

---

Otherwise to debug the error turn on the error reporting, and check the error log which will point you to the suitable path.

---
Tags: 7, database
---


# Question
Title: What is the correct way to translate variable_get string values entered in admin input fields?
I'm developing a simple module with and admin page, where admin can fill some textfields with custom strings that will generates a piece of html to be used later.

So for example I have fields like this in admin page:

```
function MYMODULE_admin_page_arguments() {
  $form = array();

  $form['MYMODULE_link'] = array(
    '#type' => 'textfield',
    '#title' => t('Conditions link path'),
    '#default_value' => variable_get('MYMODULE_link', 'conditions'),
  );
  $form['MYMODULE_link_text'] = array(
    '#type' => 'textfield',
    '#title' => t('Conditions link text'),
    '#default_value' => variable_get('MYMODULE_link_text', 'conditions'),
  );
  $form['MYMODULE_link_target'] = array(
    '#type' => 'textfield',
    '#title' => t('Conditions link target'),
    '#default_value' => variable_get('MYMODULE_link_target', '_blank'),
  );
  $form['MYMODULE_prefix'] = array(
    '#type' => 'textfield',
    '#title' => t('Conditions link prefix text'),
    '#default_value' => variable_get('MYMODULE_prefix', 'I agree to the '),
  );
  $form['MYMODULE_suffix'] = array(
    '#type' => 'textfield',
    '#title' => t('Conditions link suffix text'),
    '#default_value' => variable_get('MYMODULE_suffix', '.'),
  );

  return system_settings_form($form);
}

```

Then the above values are managed after by my module to compose an output like:

```
// Create label
$prefix = variable_get('MYMODULE_prefix', 'I agree to the ');
$suffix = variable_get('MYMODULE_suffix', '.');
$path = variable_get('MYMODULE_link', 'conditions');
$text = variable_get('MYMODULE_link_text', 'conditions');
$target = variable_get('MYMODULE_link_target', '_blank');

$label = $prefix . l($text, $path, array('attributes' => array('target' => $target))) . $suffix;

```

Now I need that all these values are available for string translation, so the first think I thought was to pass all of them through t(), for example:

```
$label = t($prefix) . l(t($text), $path, array('attributes' => array('target' => $target))) . t($suffix);

```

but I read here https://api.drupal.org/api/drupal/includes!bootstrap.inc/function/t/7 that I should never pass variables directly to t(), so for e.g t($prefix) is a bad stuff.

So, what is the correct Drupal way to accomplish this?

# Answer
You should use the Variable translation module, part of Internationalization.

1. Enable the Variable translation module included with the *Internationalization* package
2. Go to *Administration \> Configuration \> Regional and language \> Multilingual settings*
3. Click on the *Variables* tab
4. Select the variables that will be multilingual
5. Click *Save configuration* button

Then, you'll be able to select language for which you are configuring your variable:

Advice taken from this community documentation.
> 2 votes

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


# Question
Title: Change workbench_moderation_state from select to radio
I have workbench installed, and want to change the moderation status dropdown in the add node form to a radio. But I don't get it. I have a custom module with a hook\_form\_alter hook which prints the $form array via

> dsm($form)

This does NOT print any workbench\_moderation\_state variable. If I print it via print\_r($form), I get a

```
 [...]
 [workbench_moderation_state_new] => Array (
   [#title] => Moderation status
   [#type] => select
   [#options] => Array (
     [needs_review] => Current: Needs Review
     [draft] => Draft
     [published] => Published
   )
   [#default_value] => needs_review
   [#description] => Moderationsstatus für diesen Inhalt setzen.
   [#access] => 1
 )

```

So it **has** to be there.

1. Why is the `workbench_moderation_state_new` Array not displayed in krumo via `dsm()`, but printed via `print_r()`
2. (more important) Why the f\**k does a simple
> $form\['workbench\_moderation\_state\_new'\]\['#type'\] = 'radio';

not change the select into a radio, but introduce a new empty radio button in the form? I tried to follow the Drupal form API.

---

Argh. As almost always, I found the answer myself 5 minutes after posting here. Cost me 3 hours of searching and try-and-error before. `workbench_moderation_state_new` is a sub-array of `options`.

So a `$form['options']['workbench_moderation_state_new']['#type'] = 'radios';` does the trick. Mind 'radios' instead of 'radio' as well. For anyone interested. Problem solved.

# Answer
> -1 votes
`$form['options']['workbench_moderation_state_new']['#type'] = 'radios';` does the trick. I just forgot the `['options']` array.

---
Tags: forms
---


# Question
Title: Is it possible to publish/unpublish content by language?
I have enabled the the "multilingual with translation" option for the content type.

I have created the node and translate it in 2nd language. In 2nd language I want to unpublish the content but when I unpublished it, it also unpublished the content in the 1st language.

Is it possible to publish/unpublish content by language?

# Answer
I found the solution.

In your Content type settings Synchronize Translations --\> Status should be unchecked.
> 0 votes

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


# Question
Title: How to change the order in which Views SQL joins are executed?
Views creates certain JOINs behind the scenes, e.g. for fields or filders added via the UI.

I have a view with such an implicit join based on an entityreference field. In order to get the desired results I need this join to be the first one, but Views happens to place it as the last JOIN (other joins in the query come from other fields and Views relationships).

Can I change the order of the joins, while keeping all fields and filters configured via the Views UI?

As a workaround I can explicitly add a relationship based on the entityreference field in question and order it as the first one. This works, but it adds an extra join that I don't need, which has a performance impact.

# Answer
Following lexicant's advice to just re-order the array, I implemented it as follows. I found explicitly ordering the array keys easier than trying to remove and re-insert an element.

```
<?php
/**
 * Implements hook_views_query_alter
 */
function MYMODULE_views_query_alter(&$view, &$query) {
  if ($view->name == 'my_view') {
    // Explicitly order all existing table_queue array elements
    $table_queue_sorted_keys = array(
      'node',
      'field_data_field_example2',
      'field_data_field_example1',
      'node_field_data_field_example1',
      // ...
      // Add all tables used by the view. You can inspect the query
      // object by enabling the Devel module and adding `dsm($query);`
      // in your hook_views_query_alter
    );
    $table_queue_sorted = array();
    foreach ( $table_queue_sorted_keys as $key ) {
      $table_queue_sorted[$key] = $query->table_queue[$key];
    }
    $query->table_queue = $table_queue_sorted;
  }
}

```
> 1 votes

# Answer
You are looking for the following: https://api.drupal.org/api/views/views.api.php/function/hook\_views\_query\_alter/7 It will work roughly as follows: You will find that there is a clauses array in your query object among others that will contains your restraints. Remove the particular element, and insert it into the correct order in the array. They will be executed 0 through N
> 1 votes

---
Tags: 7, views
---


# Question
Title: Views Infinite Scroll Set default page with position
There is a view page with views\_infinite\_scroll paging. This page is being used for list products.

Everything is working as I needed, but the problem is:

Suppose I'm on 5th page(Note: with scroll pagination) and I click on product to go to it's detail page, the detail page have a link to return back to the product listing page. So, when user clicks on "Back to previous Page" link on product detail page, it should display the 5th page with exact page view position.

Please help how should we achieve this?

Thanks In Advance

# Answer
> 0 votes
I know this answer seems to be (might be) a bad solution but it works. Use the code `window.history.back()` for "Back to previous Page" link like follows

```
<input type="button" value="Back to previous Page" onclick="window.history.back()" />

                             OR

<a href="#" onclick="window.history.back()"> Back to previous Page </a>

```

As far as I know this is browsers default behavior. So it works.

I've tested it and working on latest version of all major browsers.

Hope it helps.

---
Tags: views
---


# Question
Title: How to pass node ID argument to Drupal 7 div auto update ajax script
EDIT: There seems to be a ready-to-use http://drupal.org/project/block\_refresh module available as @albertski indicated, so no need to struggle to develop a new module.

I've implemented the code on https://stackoverflow.com/questions/8144436/refreshing-a-div-in-drupal to get a Drupal 7 node page division auto-updated. Here is the code outputting simple time() function:

Hook menu:

```
$items['autoupdate'] = array(
'title' => 'Resize',
'page callback' => 'block_update',
'access callback' => TRUE,
'type' => MENU_LOCAL_TASK,
  );

```

Function itself:

```
function block_update(){
$html = time();
print drupal_json_encode(array('html' => $html)); exit(); }

```

Javascript:

```
    function autoupdate() {
  //alert('autoupdate is running');
  jQuery.ajax(
  {
    type: "POST",
    url: "/autoupdate",
    cache: false,
    success: function(data) {
      var result = JSON.parse(data);
      jQuery("div.autorefresh").fadeIn("slow").html(result['html']);
    }
  });
  //alert('autoupdate is complete');
}
setInterval("autoupdate()", 2500);

```

However, instead of time() I would like to use node variables and having troubles to make the module to see $node. Even if I put my div on a node page and call menu\_get\_object() the javascript sees only the content /autoupdate page:

```
function block_update(){
  $html = arg(0);
  print drupal_json_encode(array('html' => $html));
  exit();
}

```

shows: `autoupdate`

I tried to change the path in both hook menu and javascript from `autouptade` to `node/%node/update`, but unfortunately javascript doesn't want to recognize `%node` as argument. I am afraid it recognizes only static URLs. But then how is it possible to pass node ID to javascript?

# Answer
> 1 votes
I probably would have done this differently but than again I'm not a hundred percent sure what you are doing.

In response how can you pass the node id to javascript. Perhaps in hook\_page\_alter():

```
$node = menu_get_object();
if ($node) {
  drupal_add_js(array('your_module_name' => array('nid' => $node->nid), 'setting');
}

```

Then in your ajax code get the nid via:

```
Drupal.settings.your_module_name.nid

```

---
Tags: 7, ajax, javascript
---


# Question
Title: D7 Views: Hide field if empty after being rewritten
In a node type, I have three fields: (1) methods, (2) geography, (3) keywords. On node view, I have a views block showing these values. However, I want all of the content to appear as single field with a label. This was easy to achieve: (a) exclude methods and geography from display, (2) rewrite keywords to display the content of methods and geography.

This works like a charm as long as any of the three fields is not empty. However, if all three fields are empty, the block still displays the label (Keywords).

**How should I setup the view to hide the label if there is no data in any field?**

I've been playing around with all sorts of combinations of the hide options, besides "Hide when empty" and "Hide rewriting when empty" it seems like I would need an option "Hide IF rewrite is empty".

More details reagarding the view:

Format: Unformatted list

Show: Fields

Fields

* Methods: no label, exclude from display
* Geography: no label, exclude from display
* Keywords: label "Keywords", rewrite results: \[keywords\]\[methods\]\[geography\]

# Answer
> 1 votes
Go to your view and Click on Keywords to configure the field.

Go to *No results behavior* and check *Hide if empty*

That's it. I've tested it and it's working fine. Let me know if you stuck anywhere.

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


# Question
Title: what is starting point of any drupal module.?
Only beginner can ask this type of question. as i am learning drupal recently. what is the first function that executes in .module file..how can i understand which function or hook executed.I just want to analyse the execution..please help me out.

# Answer
*what is the first function that executes in .module file?* \- none in the C sense. If you came from C, C++ or C# environment, think of modules like you think of dll / so files. If you came from Java, think of them like you think of libraries. Piece of code that is hooked by the program if needed, and provides functions that can be called as needed.

So which function is called first? One that implements hook that, by accident, happens to be needed first.

Drupal modules provide functions that react to certain events. These functions are called hooks. Introduction to hooks is in the Develop for Drupal documentation.

*Note:* As Ayesh K helpfully pointed, PHP code placed in module file will usually be executed at every call. But Drupal expects there is no code outside functions in .module files. Placing direct PHP code may cause unexpected behaviour, so please don't do it.
> 5 votes

---
Tags: 7
---


# Question
Title: How to delete a view programatically in D7?
How to delete a view programatically?

It's crazy I can't find proper answer for such a simple question.

# Answer
> 5 votes
Views has a function in it called views\_delete\_view, it takes a view object as a param. Try views\_delete\_view($yourloaded\_view), that should do the trick.

# Answer
> 13 votes
Give a try to the following code to delete the view:

```
// Check the view id the one that you are looking for.
if ($view = views_get_view($name)) {
  // Delete the view if it is the one that you are looking for.
  views_delete_view($view);
}

```

---
Tags: views
---


# Question
Title: Views filter referenced content when end date is over
This view is the result of a given postcode. how could I hide/filter referenced content when its end date is over? The referenced content should disappear but the non referenced content should still be displayed.

# Answer
> 0 votes
I'm not so sure this is possible through the views interface. But, you can easily do this through your theme layer.

In your view admin area, under advanced there's the page: Theming information. Clicking on that will give you a list of available tpl.php names that can be used to create your own tpl.php files that can be added to your theme. Your probably gonna wanna use a row style output. The list of those files go from general to specific, so the last time will only be applied to your view. Clicking on the link of row style will give you the content of the default file.

All you would need to do is just print the fields as normal, with the exception of the fields you want to exclude. Just use a standard if to check to make sure they're still valid, if not, don't print them.

# Answer
> 0 votes
My suggestion would be that you display your Starts/Ends timer in another view as an attachment (or you could bring it in using views field view module).

Create this second view as your timer interface, but set your *Filter Criteria* to only show results when Current Time \> Start Time AND Current Time \< End Time

I've done something similar where I only wanted to show something based on a property within the view

In my example above, the first date/time is set to greater than or equal to now, the second is set to less than or equal to now. In the setup, you set the relative date as 'now' and it will work on what time the page has loaded

Then you can pull this second view in as mentioned above, but it should mean that this second view will return no results outside of the times you specify. However, unless you have an AJAX method that will refresh the table when the timer reaches 0, it will show a result based on when they first load the page

---
Tags: views, entities, datetime
---


# Question
Title: Drupal Json Output strange characters when pulling from other language
Hi Fellow drupal experts,

I have a problem, I developed a custom page intended to do a drupal json output :

and here is the code : `function blogpull_menu() {`

````
$items = array();

$items['blogpull'] = array(
    'page callback' => 'blogpull_view',
    'delivery callback' => 'drupal_json_output',
    'access arguments' => array('access content'),
    'type' => MENU_CALLBACK,
);
return $items;

```

}

function blogpull_view() {
 global $base_url;
 global $language;
 $query = new EntityFieldQuery();
 $query->entityCondition('entity_type', 'node')
 ->entityCondition('bundle', 'blog')
 ->propertyCondition('status', 1)
 ->propertyCondition('language', $language->language, '=') // filter by current language
 ->range(0, 5)
 ->addMetaData('account', user_load(1)); // Run the query as user 1.
 $result = $query->execute();
 if (isset($result['node'])) {
 $blog_items_nids = array_keys($result['node']);
 $blog_items = entity_load('node', $blog_items_nids);
 }

```
foreach ($blog_items as $key => $blog_item) {
    $arr = array('date' => date('M. j, Y', $blog_items[$key]->created), 'title' => $blog_items[$key]->title, 'description' => $blog_items[$key]->body['und'][0]['value'], 'href' => $base_url.'/node/'.$blog_items[$key]->nid);
    $arrs[] = $arr;
}

return $arrs;

````

`}`

and some how when it's loading the japanese language it is showing this strange characters : ã‚¯ãƒ©ã‚¦ãƒ‰ã‚²ãƒ¼ãƒ äº‹æ¥ã®æ–°ä¼šç¤¾ã€Œã‚·ãƒ³ãƒ©ãƒ»ãƒ†ã‚¯ãƒŽãƒã‚¸ãƒ¼ã€ç™ºè¶³

I tied using utf-encoding, mb\_encoding and so on but nothing happen

can someone help?

thank you!

# Answer
just check HTTP response headers it should have utf-8 charset.
> 0 votes

---
Tags: ajax, i18n-l10n
---


# Question
Title: How to displaying translate tab in the node
I have Multilingual and internalization Module installed on a Drupal installation. I need to have the translate link option on every node as the following screenshot:

Also I need if the content (node) in some language has no translated version in other language, when clicking to the language choose bar, it go to the default home page in the other language or Page Not found.

# Answer
> 3 votes
This tab does show when:

1. You have more than one language installed. **Locale** module needs to be enabled.
2. You have **Content Translation** or **Entity Translation** modules enabled (not **i18n**)
3. You have set up the content to be translatable, in the the content type settings page (if it's a node). When using Entity Translation, prior to that, you should define the entity type (e.g. node) to be translatable.
4. Your user has permissions to translate content.

---
Tags: 7, i18n-l10n, nodes, forms
---


# Question
Title: Drupal 7 - Add Items to multiple places in a menu
I'am trying to set up a menu layout which has two links to /our-public-awareness-campaign; one under "Voter", and one under "News centre". The problem I'am running into is that although I can have two links in different parts of the menu, when looking at the page it will always try to open the menu to only one of them. This means that if you are looking under "Voter", and you go to "Our public awareness campaign", suddenly you're in a different location of the site. Any ideas on how I can fix this?

Thanks, Ruslan

# Answer
> 2 votes
Unfortunately, this is a feature not available in Drupal core. The issue is being worked on, but does not currently have a solution: http://drupal.org/node/609542

In the meantime, one potential solution is to use path aliases to the same node. Thus you might have /voter/our-public-awareness-campaign and /news/our-public-awareness-campaign which both point at a particular node. Drupal should treat the two menu entries as unique/separate then, and thus only the one you want to show as the menu should be activated.

# Answer
> 1 votes
NodeSymlinks

> NodeSymlinks allows you to display the same content to users at multiple locations in the Drupal menu system with unique URL path, unique navigation breadcrumb and without the SEO penalty that usually occurs with multiple copies of the same content.
>
> This is useful when you want to have the same page reachable though multiple menu items, each with its own URL, menu trail and breadcrumb path.

# Answer
> 0 votes
For one off thing like this, I tend to just use jQuery to change the active trail.

# Answer
> 0 votes
I can confirm that NodeSymlinks does the job perfectly. We had the problem that we have a submenu in the sidebar. If you put the node into the menu twice, only in one location the Submenu opens correctly. In the other location the same submenu is shown as in the first one.

When you install Menu Symlinks, you have to manage the alternate menu entries through the node form. This had me baffled for a while. It is neither on the Node Symlinks Admin page, nor in the Menu Admin Section.

This is the settings form inside the Node Menu settings:

---
Tags: 7, routes
---


title: Page Arguments Not Getting Passed

text:
# Question
Title: Page Arguments Not Getting Passed
My code was working perfectly, but at some point my hook\_menu page arguments stopped getting passed.

I am using versioning and can revert back to the previous code, but the page arguments are still broken.

Is there some change that could be causing page arguments to not get passed?

Thanks a million!

Disclaimer: Sorry, I am not a Drupal developer, so the code is an attempt at injecting plain php into a site.

Inventory.module

```
    function inventory_menu() {
  $items = array();

  $items['admin/commerce/inventory'] = array(
    'title' => 'Inventory',
    'description' => 'View inventory reports for your store.',
    'access arguments' => array('access commerce reports'), // Inherited by children.
    'page callback' => 'inventory_reports_dashboard',
    'page arguments' => array( '10', 'DESC', 'false', 'admin@sltwtr.com', 'false'),     // page_arguments = threshold amount,  sort direction, hide zero inventory, email report to, save_to_email bool, download_csv
    'file' => 'inventory.dashboard.inc',
    'weight' => 0,
  );

  $items['admin/commerce/inventory-download-csv'] = array(
    'page callback' => 'inventory_download_csv',
    'access arguments' => array('access commerce reports'),
    'file' => 'inventory.dashboard.inc',
    //'type' => MENU_CALLBACK,
  );

  return $items;
}

```

Inventory.dashboard.inc

```
/**
 * Renders the inventory reports.
 */
function inventory_reports_dashboard( $threshold='10', $sort_direction='DESC', $hide_zero_inventory='false', $email='admin@sltwtr.com', $save_to_email = 'false') {
  drupal_add_js(drupal_get_path('module', 'commerce_reports') . '/theme/js/dashboard.js', 'file');
  drupal_add_css(drupal_get_path('module', 'commerce_reports') . '/theme/css/commerce_reports_dashboard.css');

  // on first load we want to grab all of the default values
  // after first load, we want updated values to pass through
  //$threshold = 18;
  $render = file_get_contents('http://' . $_SERVER['HTTP_HOST'] . "/sites/all/modules/inventory/inventory.php?threshold=$threshold&sort_direction=$sort_direction&hide_zero_inventory=$hide_zero_inventory&email=$email&save_to_email=$save_to_email");

  return $render;
}

function inventory_download_csv(){
  $file = './inventory.csv';
  $filename = 'inventory.csv';
  //drupal_set_header('Content-Type: text/csv');
  //drupal_set_header('Content-Disposition: attachment; filename=' . $filename);
  drupal_add_http_header('Content-Type: text/csv');
  drupal_add_http_header('Content-Disposition: attachment; filename=' . $filename);
  if($file) {
    //file_transfer($file, array('Content-disposition', 'attachment; filename='.$filename));
    $csv_contents = file_get_contents('http://' . $_SERVER['HTTP_HOST'] . "/sites/all/modules/inventory/inventory.csv");
  }
  else {
    return drupal_access_denied();
  }
  $fp = fopen('php://output', 'w');
  //$csv_text = array2csv($db_result);
  fputs($fp, $csv_contents);
  fclose($fp);
  exit();

}

```

Inventory.php

```
<?php

define('DRUPAL_ROOT', $_SERVER['DOCUMENT_ROOT']);

require_once DRUPAL_ROOT . '/sites/all/modules/myfunctionlib/myfunctionlib.module';
require_once DRUPAL_ROOT . '/includes/bootstrap.inc';

//require_once DRUPAL_ROOT . '/includes/common.inc';
//require_once DRUPAL_ROOT . '/includes/module.inc';
//require_once DRUPAL_ROOT . '/includes/unicode.inc';
//require_once DRUPAL_ROOT . '/includes/file.inc';

//drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);
drupal_bootstrap(DRUPAL_BOOTSTRAP_DATABASE);
clean_dump($_GET);

```

When I change the url:

mysite.gotpantheon.com/admin/commerce/inventory/12/DESC/false/admin@sltwtr.com

The get parameters no longer reflect changes

```
array(6) {
  ["threshold"]=>
  string(2) "10"
  ["sort_direction"]=>
  string(4) "DESC"
  ["hide_zero_inventory"]=>
  string(5) "false"
  ["email"]=>
  string(16) "admin@sltwtr.com"
  ["save_to_email"]=>
  string(5) "false"
  ["q"]=>
  string(0) ""
}

```

# Answer
> 0 votes
I would change your code to (as @J.Reynolds specified):

```
  $items['admin/commerce/inventory/%/%/%/%'] = array(
    'title' => 'Inventory',
    'description' => 'View inventory reports for your store.',
    'access arguments' => array('access commerce reports'), // Inherited by children.
    'page callback' => 'inventory_reports_dashboard',
    'page arguments' => array(3,4,5,6),     // page_arguments = threshold amount,  sort direction, hide zero inventory, email report to, save_to_email bool, download_csv
    'file' => 'inventory.dashboard.inc',
    'weight' => 0,
  );

```

---
Tags: commerce, routes
---


# Question
Title: How do you define an arbitrary sort sequence for views?
Take a look at the Drupal issues queue and the Priority column. If sorted in descending order you get critical, major, normal, and minor issues, in that order. Since "normal" would not go between "major" and "minor" in alphabetical order, they've obviously defined a custom sequence to use for sorting. How is this done in Drupal?

Is it merely sorting based on a numeric value that is not displayed? Or is it more clever than that?

# Answer
> 9 votes
Views has `hook_views_query_alter`, which lets you mess with the query object that it maintains. It gets called before the query object gets converted to SQL. You can change the sorting that is set in the UI with something like:

```
function mymodule_views_query_alter (&$view, &$query)
{
  $query->orderby = array('node.nid ASC');
}

```

Basically, the value you use is what would be after the `ORDER BY` in a normal query. You should be able to use an `ORDER BY CASE`,

```
function mymodule_views_query_alter (&$view, &$query)
{
  $orderby = "
    CASE
      WHEN node.type = 'page' THEN 1
      WHEN node.type = 'article' THEN 2
    END ASC
  ";
  $query->orderby = array($orderby);
}

```

You will need to enable previewing the SQL in Views (it's in the main views settings, not with the settings for a particular view) to see the names to use.

# Answer
> 5 votes
The key piece is found in the url:

```
http://drupal.org/project/issues/views?page=3&order=priority&sort=desc&text=&status=Open&priorities=All&categories=All&version=All&component=All

```

where it says `order=priority&sort=desc` which tells Views to order by priority in descending order. If you click on the Priority header to resort the table based on that column, it shows this link:

```
http://drupal.org/project/issues/views?order=priority&sort=asc&page=4&text=&status=Open&priorities=All&categories=All&version=All&component=All

```

where once again the important bit is `order=priority&sort=asc`.

But no magic, this just means that there is a numeric field in the issue queue called priority that can and is sorted upon.

A confusion certainly is coming from the dropdown for Priorities mentioned by @Anil Sagar but that is different from the priority and is rather used within `priorities=All` or `priorities=#` whose numeric fields don't seem to align with those of priority.

# Answer
> 2 votes
I don't think it's based on numeric sort. You can see the values in inspect element as shown below.

```
<select name="priorities" class="form-select" id="edit-priorities">
    <option value="All" selected="selected">- Any -</option>
    <option value="1">critical</option>
    <option value="4">major</option>
    <option value="2">normal</option>
    <option value="3">minor</option>
</select>

```

If it is based on numeric sort then it should show critical on top and major on last which is not ! So, i guess it is more clever than that !

# Answer
> 0 votes
Somehow, I couldn't get to use the answer given from @mpdonadio. This is the solution that worked for me after debugging it through `dpm()`.

```
function custom_shop_view_views_query_alter(&$view, &$query) {
  if ($view->name == 'products' || $view->name == 'uc_catalog' ) {
    // Traverse through the 'orderby' part of the query.
    foreach ($query->orderby as &$orderby) {
      if ($orderby['field'] == 'uc_products_model') {
        $orderby = array(
          'field' => 'field_data_field_product_tag_node_entity_type',
          'direction' => 'ASC',
        );
      }
    }

    $query->add_orderby('node', 'changed', 'DESC');
  }
}

```

If addressed the orderby array by 'field' and 'direction', no SQL syntax errors were thrown.

---
Tags: views
---


title: Drupal Image and GalleryFormatter

text:
# Question
Title: Drupal Image and GalleryFormatter
I am using the `Image` and the `Galleryformatter` module. I am getting these two errors on configure media page:

```
Warning: Division by zero in theme_image_style_preview() (line XXX of /.../modules/image/image.admin.inc).

Warning: array_intersect_key(): Argument #1 is not an array in theme_image_style_preview() (line XXX of /.../modules/image/image.admin.inc).

```

# Answer
> -1 votes
Found a solution. Just run the following on shell:

```
sudo chmod -R 777 files

```

http://drupal.org/node/873838

# Answer
> 0 votes
I found @Sohail to be almost right. I did:

`chmod 777 drupal/sites/example.com/files/styles`

and the error went away and my drupal 7 new image-style worked. I did not have a `styles` or even a `files` folder in `druapal/sites/all/files`

---
Tags: media
---


# Question
Title: Can customizable products work out price based on the number of uploaded files?
I'm using Drupal Commerce and would like to develop an online photo printing service like shutterfly.com and snapfish.com.

I wonder if it's possible using customizable products to count each uploaded file/photo and charge accordingly? If not, what other way can I achieve this requirement?

# Answer
The answer is "yes"

I originally posted the answer here: https://drupalcommerce.org/questions/16291/can-customizable-products-work-out-price-based-number-uploaded-files

Export of the rule that proves it's possible:

```
   { "rules_files_price_multiplier" : {
      "LABEL" : "Files Price Multiplier",
      "PLUGIN" : "reaction rule",
      "OWNER" : "rules",
      "REQUIRES" : [ "rules", "commerce_line_item", "commerce_product_reference" ],
      "ON" : { "commerce_product_calculate_sell_price" : [] },
      "IF" : [
        { "entity_is_of_type" : { "entity" : [ "commerce-line-item" ], "type" : "commerce_line_item" } },
        { "entity_has_field" : {
            "entity" : [ "commerce-line-item" ],
            "field" : "field_upload_all_the_files"
          }
        },
        { "list_count_is" : {
            "list" : [ "commerce-line-item:field-upload-all-the-files" ],
            "op" : "\u003E",
            "value" : "0"
          }
        }
      ],
      "DO" : [
        { "variable_add" : {
            "USING" : { "type" : "integer", "value" : "1" },
            "PROVIDE" : { "variable_added" : { "file_multiplier" : "file_multiplier" } }
          }
        },
        { "LOOP" : {
            "USING" : { "list" : [ "commerce-line-item:field-upload-all-the-files" ] },
            "ITEM" : { "list_item" : "Current list item" },
            "DO" : [
              { "data_calc" : {
                  "USING" : { "input_1" : [ "file-multiplier" ], "op" : "+", "input_2" : "1" },
                  "PROVIDE" : { "result" : { "result" : "Calculation result" } }
                }
              },
              { "data_set" : { "data" : [ "file-multiplier" ], "value" : [ "result" ] } }
            ]
          }
        },
        { "commerce_line_item_unit_price_multiply" : {
            "commerce_line_item" : [ "commerce_line_item" ],
            "amount" : [ "file-multiplier" ],
            "component_name" : "fee",
            "round_mode" : "1"
          }
        },
        { "drupal_message" : { "message" : "[commerce-line-item:line-item-id]: File Multiplier = [file-multiplier:value]" } }
      ]
    }
  }

```

**NOTE**: This will still not update the price as the person is uploading files.
> 0 votes

---
Tags: commerce, media
---


# Question
Title: How to add a new CSS class to a Link Badge if the value is 0?
I'm using the small module Link Badges to display a badge with the amount of flagged nodes next to a link to the View in question. It works great and I've styled the badge to my needs. This is the current HTML code:

```
<a class="menu__link menu__link link-badge-wrapper">
  <span class="link-badge-text">My View</span>
  <span class="link-badge-badge-wrapper">
    <span class="link-badge link-badge-menu_badges_execute_view">0</span>
  </span>
</a>

```

Now, I'd like to display the badge a little bit differently (other colors etc.) when the value is 0. I thought about doing this by adding a new CSS class `link-badge-zero` to the value.

```
<a class="menu__link menu__link link-badge-wrapper">
  <span class="link-badge-text">My View</span>
  <span class="link-badge-badge-wrapper">
    <span class="link-badge link-badge-zero link-badge-menu_badges_execute_view">0</span>
  </span>
</a>

```

How can I achieve this?

# Answer
Thanks to @Ramis Wachtler at Stack Overflow, I got the following JQuery code:

```
if($(".link-badge").text() == "0"){
    $(".link-badge").addClass("link-badge-zero");
}

```

Possible easier solutions are always welcome.
> 0 votes

---
Tags: 7
---


title: How long does variable_set last?

text:
# Question
Title: How long does variable_set last?
Is variable\_set just creating a session variable or can I retrieve this variable from a cron job?

I can load the page over and over, but I always get this output. It seems as though the data is not pulled from the variables table, but set only manually each page load.

```
$default_vals = get_defaults_variable_get();
clean_dump($default_vals);

save_defaults_variable_set();

$default_vals = get_defaults_variable_get();
clean_dump($default_vals);
clean_dump($_GET);

function get_defaults_variable_get(){
    $content[sort_direction] = variable_get('inventory_sort_direction');
    $content[threshold] = variable_get('inventory_threshold');
    $content[hide_zero_inventory] = variable_get('inventory_hide_zero_inventory');
    $content[email] = variable_get('inventory_email');
    return $content;
}

function save_defaults_variable_set(){
    //echo 'save defaults';
    variable_set('inventory_sort_direction', $_GET[sort_direction]);
    variable_set('inventory_threshold', $_GET[threshold]);
    variable_set('inventory_hide_zero_inventory', $_GET[hide_zero_inventory]);
    variable_set('inventory_email', $_GET[email]);

}

```

output

```
array
  'sort_direction' => null
  'threshold' => null
  'hide_zero_inventory' => null
  'email' => null
array
  'sort_direction' => string 'DESC' (length=4)
  'threshold' => string '5' (length=1)
  'hide_zero_inventory' => string 'true' (length=4)
  'email' => string 'e@sltwtr.com,bsaltzman@gmail.com' (length=39)
array
  'threshold' => string '5' (length=1)
  'sort_direction' => string 'DESC' (length=4)
  'hide_zero_inventory' => string 'true' (length=4)
  'email' => string 'e@sltwtr.com,bsaltzman@gmail.com' (length=39)
  'save_to_email' => string 'true' (length=4)
  'q' => string '' (length=0)

```

# Answer
> 1 votes
Straight from the docs:

> Sets a persistent variable.

Yes, it will be available across different requests.

# Answer
> 1 votes
It will be saved in the variables table and will stay there until it's either deleted or overwritten.

---
Tags: configuration
---


# Question
Title: Create a responsive email at Drupal for phone
does anyone successfully create a responsive email at drupal? I mean, with @media rule, but not just using width percentage(like 100%) to control element width.

We got one request to build two different email styles for pc and phone. We need different font size and different element width for this email. Now the email for pc is done, but I can't figure out an appropriate way to do the email for phone. I tried @media rule in css, but the @media rule will overwrite the regular css rule in pc too.

I sense it might be the reason that I have converted css class to inline css, so media rule is not working. However, inline css in email is recommended to meet most of the email clients out there, and I see the good email, like email from linkedin, uses the inline css too. The email from linkedin displays differently in phone and works perfect as an example of responsive email, having smaller image size, font size, element width and so on.

I tried this email template from this article https://www.emailonacid.com/blog/details/C13/emailology\_a\_free\_responsive\_email\_template\_using\_media\_queries\_-\_part\_i# It doesn't work for me. The email at phone email client looks the same way as the email showing at pc. Not sure why this email template works for others, but not for me, or not for drupal?

For the record, I'm using mimeemail in Drupal6 and writing the code to send email directly.

Does anyone has idea to solve this issue? Any help will be appreciated, thanks!

# Answer
Okay, this issue is solved by this module https://www.drupal.org/sandbox/dmitriytrt/1939698.

The issue happens because default "mimemail css compressor" module has excluded @media rules in email, so we need a different way of converting css to inline styles.

Another possible solution is to use emogrifier https://github.com/jjriv/emogrifier. This library's latest version has supported @media rules.
> 1 votes

---
Tags: emails
---


title: How can i know who has created user?

text:
# Question
Title: How can i know who has created user?
I have created some roles and these role's user also can create certain type of user.so how to know who is creator i.e, user author name.

# Answer
> 1 votes
By default Drupal don't save anything about who create a user.
If you want do it, go to user account fields `admin/config/people/accounts/fields` add entity\_reference with select list widget, then in your custom module in `hook_form_alter` set default value for field with get current user uid and then hide it there, in this manner the current user id (the user that create user) saved in fields without he/she know that this, also you can dont use `hook_form_alter` just get `$user->uid`(the current user that create user ) form global $user in `hook_user_insert`

shortly

* add a entity reference field to user save creator uid in
* `hook_form_alter` when or `hook_user_insert`

# Answer
> 0 votes
You can add a new text/entity\_reference field in User and save current user in hook\_user\_presave.

---
Tags: users
---


# Question
Title: Taxonomy terms view sorting results numerically
I have a taxonomy that's comprised entirely of numeric term names, 1 through 1200 (with a few numbers missing in between). I created a new "Taxonomy terms" view to show all terms in this vocabulary. When I look at the view results, I'd like to see the terms sorted numerically, however the view is displaying the terms alphabetically. I understand the reason for this is because term names are strings, but I'm hoping someone has an answer of how to make the query treat the term names as integers.

Here's an example of the view results as they are displayed now:

* 1
* 10
* 100
* 1000
* 1001
* 1005
* 101
* 1014
* 1015
* 1016
* 1019
* 102
* 1020
* 1024
* 103
* 1034
* 104

Normally in MySQL, you could write `SELECT name FROM {taxonomy_term_data} ORDER BY CAST(name AS UNSIGNED)`. Is there a way to get this same type of `CAST()` happening in views?

# Answer
> 1 votes
I found a solution which requires a little code. The idea is that we make the term weights the same as the term names. Then we can use views to sort against the term weights.

Using `hook_taxonomy_term_presave()`, we can update the term weight to match the term name for all terms saved from now into the future. It uses `intval($term->name)` which nicely gets any numbers at the beginning of a term name (or 0 for alphabetical term names).

```
/**
 * Implements hook_taxonomy_term_presave().
 */
function mymodule_taxonomy_term_presave($term) {
  // For all terms, make the weight equal to the term name. We can then use weight for
  // numerical sorting to fix the bug where numeric term names sort in character code order.
  $vocab_name = 'vocab_machine_name';
  $vocab = taxonomy_vocabulary_machine_name_load($vocab_name);
  if ($term->vid == $vocab->vid) {
    $term->weight = intval($term->name);
  }
}

```

The above code will only work for terms that are saved from now into the future.

If you want to update all existing terms, try this function. It only took about 1 second to update 1,000 rows on my development machine:

```
/**
 * Update existing taxonomy term weights.
 */
function resave_numeric_term_weights() {
  // Get vid from machine_name
  $vocab_name = 'vocab_machine_name';
  $vocab = taxonomy_vocabulary_machine_name_load($vocab_name);

  $result = db_select('taxonomy_term_data', 't')
    ->fields('t', array('tid', 'name'))
    ->condition('t.vid', $vocab->vid)
    ->execute();
  $terms = $result->fetchAll();
  foreach ($terms as $term) {
    // Make the weight equal to the intval() of the term name.
    db_update('taxonomy_term_data')
      ->fields(array('weight' => intval($term->name)))
      ->condition('tid', $term->tid)
      ->execute();
  }

  drupal_set_message(t('Updated term weights for @num terms', array('@num' => count($terms))));
}

```

# Answer
> 3 votes
Try using Views Natural Sort

This allows you to emulate MYSQL's behavior of CAST() in order to treat the integers as pure values to sort by.

From the documentation:

```
Natural Sort also supports Numbers.

Normal Sort:

1 apple
10 apples
2 apples

Natural Sort:

1 apple
2 apples
10 apples

```

---
Tags: 7, views
---


# Question
Title: Applied JS to Drupal theme doesn't work correctly, but it works fine outside Drupal
Applied this JS http://jsfiddle.net/tbq8eo8b/10/ to webforms. As you can see in fiddle, it calculates total amount. When in Drupal, it gives `0` no matter what amounts you select, it always prints `0`. What's wrong?

Drupal code:

```
(function ($) {
Drupal.behaviors.bartik = {
attach: function(context, settings) {

/*Add your js code here*/
    var $selects = $("select").change(function (e) {
        var total = 0;
        $selects.each(function() {
            var val = this.value.match(/\$(\d+)/);
            total += val ? +val[1] : 0;
        });
        $(".total").val(total);
    });

}

};
}(jQuery));

```

Also console prints:

```
TypeError: $ is not a function
$("select").change(function ()

```

# Answer
```
}(jQuery));

```

should be

```
})(jQuery);

```

in your last line of code.
> 1 votes

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


# Question
Title: Is it possible to restrict access to anonymous user to specific content types based on the author?
I've been looking for a module that could support my requirement for hours now and failed.

What I want to do is to restrict anonymous user to viewing content type pages based on a specific users. Lets say I have user1,user2 and user3. Anon should be able to view contents created by user1, but not user2 and user3.

I'm thinking of using node\_access\_hooks but I'm very new to drupal and I have no idea where to start with that. Can anyone help me with this?

# Answer
I don't think it looks like the best idea - sometimes you have to fire an author and get someone new. Author-based solutions may get complicated in such situations. Usually I use Taxonomy Access Control \- I'm restricting users to view only content with particular term, and only give access to that term to particular authors. Simple, and without need of any custom coding.

Note one important restriction:

> While Drupal 7 makes support for additional databases possible, TAC does not currently support databases other than MySQL/MariaDB/etc. or Postgres. See #1266674: Support other databases for more information.
> 1 votes

# Answer
You can do it with Node access user reference module. Gives content access permissions to users for content that references the users with User reference or Entity reference.

> This is great if you want your content authors to be able to choose additional authors, or choose who can view their content, as well as being able to display the list of authors or viewers within your content, or in views displays.
> 1 votes

# Answer
I can't be sure this is a good idea, but in case you want to implement this in code you could create a small custom module. Let's say your content type is called "blog" and you want to prevent user with uid=897 to view that specific node type.

```
/**
 * Access control for specific node type and specific user IDs.
 *
 * Implements hook_node_access().
*/
function yourmodulename_node_access($node, $op, $account) {
  global $user;

  // find out the content type of the node
  $type = is_string($node) ? $node : $node->type;

  // only affect certain types of nodes
  if ($type == 'blog') {
    // We only need to consider the 'view' case as the rest is presumable handled by content type permissions in your site
    if ($op == 'view') {
      if ($user->uid == 897) {
        return NODE_ACCESS_DENY;
      } else {
        return NODE_ACCESS_ALLOW;
      }
    }
  }

```

Please note that:

* access control needs to be tested, as there may be another module that overrides this permission
* instead of hard coding the uid 897 you can add a function to look up users blocked by a certain criteria
* using roles for this is a good idea, e.g. adding a "antiblog" role, adding those users you want to prevent reading the blog to that role, and then without custom coding you could user role-based permissions for that content type
* I haven't tested this code, but it probably works if you just create the .module and .info files
> 1 votes

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


# Question
Title: How to limit the products from the compare in drupal?
I am working with the Drupal Commerce and the Commerce product comparison module. Here I need to limit the products.

How do I limit the products from the comparison?

# Answer
You may solve this through Rules module.

Event: After udpdating an already existing line item

Conditions: 1/ data comparison: commerce-line-item:type = product 2/ data comparison: commerce-line-item:commerce-product:type = Your given product type 3/ data comparison: commerce-line-item:quantity is greater than 1

Action: \- set data value: commerce-line-item:quantity 1 \- display custom message
> 0 votes

---
Tags: commerce
---


title: Creating a language in code

text:
# Question
Title: Creating a language in code
I want to set create a language in PHP code (for example, using a hook\_update\_n implementation) so I can deploy and automate it.

How?

# Answer
> 1 votes
Note that Features module supports exporting languages.

Answering the question:

```
// Example language: fr.
$language = (object)array(
  'language' => 'fr',
  'name' => 'French',
  'native' => 'Français',
  'direction' => 0,
  'enabled' => 1,
  'plurals' => 0,
  'formula' => '',
  'domain' => '',
  'prefix' => 'fr',
  'weight' => 0,
);

locale_add_language($language->language,
  $language->name,
  $language->native,
  $language->direction,
  $language->domain,
  $language->prefix,
  $language->enabled);

// Additional params not implemented in locale_add_language().
db_update('languages')
  ->fields(array(
    'plurals' => $language->plurals,
    'formula' => $language->formula,
  ))
  ->condition('language', $language->language)
  ->execute();

```

---
Tags: updating
---


title: Drupal Pop-Up Image on page load

text:
# Question
Title: Drupal Pop-Up Image on page load
With simple css and javascript code i have created image pop-up which loads automatically after page load, i want to load the pop-up between two specific days (example from date and to date) please help me with this, is there any module in drupal

# Answer
You can achieve that using the Popup On Load module.

> The module allows to display a popup once after a certain delay on a page load. This fills a gap in popup modules family (Popups, Popup), which are designed to show popups only after a click on an HTML element, or to implement a complex behavior like modal dialog forms.
>
> If you want to just display a popup after a page load, the Popup On Load module possibly fits your needs

The following are one of the module's main features. See project page for more.

* Create an action for popup display, which can be easily integrated into Rules system.
* Create a default rules set for popup display.
> 2 votes

---
Tags: updating, javascript
---


# Question
Title: Apply condition between two fields in drupal 7 by using JQuery
This is updated JQuery code I have created condition between two fields in drupal 7 i.e. If we select item from first field then as per there selected item, some items of second field is going to hidden. But problem is that : If first I select item from second select field & after that I have select same item in first field then in this condition my created condition is wrong. Please Help to solve this. Thanks

Please check this DEMO

**Below is my my updated JQuery code**

```
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
$(function(){
abc();
$("#edit-main-field-i-am-field-und").change(function() {
    var value = $(this).val();
    var optionText = $(this).find('option[value='+value+']').val();

    $('#edit-main-field-look-for-field-und').find('option').show();

       if(optionText=="sbf" || optionText=="smf" )
       {

           $('#edit-main-field-look-for-field-und').find('option').filter(function(){
               if($(this).val()=="sbf" || $(this).val()=="smf")

                 return true;
              else
                 return false;
           }).hide();
       }
      else
       {

           $('#edit-main-field-look-for-field-und').find('option').filter(function(){
               if($(this).val()=="sdm" || $(this).val()=="sbm")
                 return true;
              else
                 return false;
           }).hide();
       }

    });
});

function abc()
{

   var value = $('#edit-main-field-i-am-field-und').val();

if(value=="sbf" || value=="smf" )
       {

           $('#edit-main-field-look-for-field-und').find('option').filter(function(){
               if($(this).val()=="sbf" || $(this).val()=="smf")
                 return true;
              else
                 return false;
           }).hide();
       }
      else
       {

           $('#edit-main-field-look-for-field-und').find('option').filter(function(){
               if($(this).val()=="sdm" || $(this).val()=="sbm")
                 return true;
              else
                 return false;
           }).hide();
       }

}
</script>

```

# Answer
I have tried your code and got a quick solution i.e. reset second select box every time first is changed.

look how I have implemented the same:

```
$(function(){
$("#edit-main-field-i-am-field-und").change(function() {

    $('#edit-main-field-look-for-field-und').val("_none"); // added to reset second select box on chanage of first one

       var value = $(this).val();
       var optionText = $(this).find('option[value='+value+']').text();
    $('#edit-main-field-look-for-field-und').find('option').show();
       if(optionText=="A" || optionText=="C" )
       {
         //alert("12345");
           $('#edit-main-field-look-for-field-und').find('option').filter(function(){
               if($(this).text()=="A" || $(this).text()=="C")
                 return true;
              else
                 return false;
           }).hide();
       }
      else
       {
           //alert("98765");
           $('#edit-main-field-look-for-field-und').find('option').filter(function(){
               if($(this).text()=="B" || $(this).text()=="D")
                 return true;
              else
                 return false;
           }).hide();
       }
    $('#edit-main-field-look-for-field-und option:visible:eq(1)').prop('selected',true);
   // alert($('#edit-main-field-look-for-field-und').val());
    });
});

```

I have just added `$('#edit-main-field-look-for-field-und').val("_none");` in .change function.
> 1 votes

---
Tags: entities, javascript
---


# Question
Title: Drupal features recreate issue with CCK fields
I have created a form using CCK with conditional fields. If I use the features module to recreate and export the new settings to my staging machine the form comes out flat.

So for example my form is set up to expand other options based on a selection (second option on a drop down box will show different form fields).

After re-creating and sending the files over to staging, same deployment, version and all that for some reason the CCK form appears flat. All the fields that are supposed to be hidden behind certain field selections now appear flat.

So the files that I might have transferred for example after downloading the feature:

```
support_tickets_v2.features.conditional_fields.inc
support_tickets_v2.features.content.inc
support_tickets_v2.features.fieldgroup.inc
support_tickets_v2.info
support_tickets_v2.strongarm.inc
support_tickets_v2.views_default.inc

```

# Answer
> 0 votes
I faced the same issue today. After a lot of searching, I found the following patch. https://www.drupal.org/node/2210241

I was able to solve this using the patch provided. Can export the conditional field settings (along with content-type & fields) in a feature. In my case the dependent is a Date field & dependee is a boolean field.

Conditional field 7.x-3.0-alpha1 features 7.x-2.2

---
Tags: 7, entities, features
---


title: Field API - which hook to use?

text:
# Question
Title: Field API - which hook to use?
I have successfully created a field with my module and managed to show it on user registration form. The next step would be validating my field. There are two hooks for this, and I'm confused as to which one to use. One is hook\_field\_validate and the other is hook\_field\_attach\_validate. I'm also confused as to how to refer to the field. **$instance\['user'\]\['field\_tckn\_no'\]**? (This is what dpm(field\_info\_instances('user') shows me. Also, one thing that confuses me is that hook\_field\_validate iterates over the fields but all I have is one field. Is it still the one to use?

Regards, K.

# Answer
Well, at last I was able to figure it out. Since the field was part of the form after creating the instance, I thought I could use hook\_form\_alter, and I was right!
> 0 votes

---
Tags: entities
---


# Question
Title: Internal/External JS don't work with Drupal, but works fine in static HTML/JSFiddle
Continued from here Applied JS to Drupal theme doesn't work correctly, but it works fine outside Drupal

Working JSFiddle: http://jsfiddle.net/tbq8eo8b/10/ (it calculates total, in Drupal it calculates zeros - why?)

Raw:

```
$(document).ready(function () {
    var $selects = $("select").change(function (e) {
        var total = 0;
        $selects.each(function() {
            var val = this.value.match(/\$(\d+)/);
            total += val ? +val[1] : 0;
        });
        $(".total").val(total);
    });
});

```

Drupal:

```
(function ($) {
Drupal.behaviors.totalAmount = {
attach: function(context, settings) {

/*Add your js code here */
    var $selects = $("select").change(function (e) {
        var total = 0;
        $selects.each(function() {
            var val = this.value.match(/\$(\d+)/);
            total += val ? +val[1] : 0;
        });
        $(".total").val(total);
    });
}
};
})(jQuery);

```

2nd attempt with internal Drupal:

```
  <script src="http://code.jquery.com/jquery-1.9.0.js"></script>
  <script>
  $(document).ready(function () {
    var $selects = $("select").change(function (e) {
        var total = 0;
        $selects.each(function() {
            var val = this.value.match(/^\$(\d+)$/);
            total += val ? +val[1] : 0;
        });
        $(".total").val(total);
    });
});
  </script>

```

As you see the code is identical (except Drupal wrappings), so why it's not working on Drupal? Why it prints zeros in .total field, but in JSFiddle it works fine?

# Answer
I've rebuilt the scenario and my guess now is that you don't want the value of the select field but the option text for your parsing purpose. Thus, the script should probably be something like this:

```
(function ($) {
Drupal.behaviors.totalAmount = {
attach: function(context, settings) {

    /*Add your js code here */
    var selects = $("select").change(function (e) {
        var total = 0;
        selects.each(function() {
          var val = $("#"+this.id+"  option[value='"+this.value+"']").text().match(/\$(\d+)/);
          total += val ? +val[1] : 0;
        });
        $(".total").val(total);
    });
}
};
})(jQuery);

```

This is how it looks like working:

This is how the first select's options are setup as a webform component

To retrieve prices, one would need to change the regex line to

```
var val = $("#"+this.id+" option[value='"+this.value+"']").text().match(/\$(\d+(\.\d{2})?)/);

```

Working example:

To have the total always be display with trailing zeros, replace the last script line with

```
$(".total").val(total.toFixed(2));

```

To make the script also work with thousands separator, change the script into

```
(function ($) {
Drupal.behaviors.totalAmount = {
attach: function(context, settings) {

/*Add your js code here */
    var selects = $("select").change(function (e) {
        var total = 0;
        selects.each(function() {
                var val = $("#"+this.id+" option[value='"+this.value+"']").text().match(/\$(\d{1,3}(,\d{3})*(\.\d{2})?)/);
                        total += val ? +parseFloat(val[1].replace(/,/g,'')) : 0;
        });
        $(".total").val('$'+total.toFixed(2));
    });
}
};
})(jQuery);

```
> 4 votes

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


title: Drush hangs while executing any command

text:
# Question
Title: Drush hangs while executing any command
I am experiencing a strange problem while running drush commands on newly installed server and newly installed drush(it's been installed with composer). Exact the same configuration works fine on my local machine (composer, drush-dev, memcached with 11212 port), but for some reason it doesn't execute any command on my production server. I've already read this post, but it did'nt help, I am sure problem is not coming from my memecached config, I can open it from browser without any error (`Memcache Storage: server 127.0.0.1:11212 (default cluster) - Connected` \- message from status report).

So, I properly installed composer (globally), successfully installed a drush-dev version, env PATH has been added to .bashrc file, I can only run `drush` command which outputs this help messages.. But if I run any other command in my drupal root driectory it just hangs with this debug output (for ex: `drush status -vvvv -d`).

Some addition info: 1. I digged into the drush files to find something and I found that drush calls `_drush_bootstrap_drupal_login` after `_drush_bootstrap_drupal_full` to login as uid=0, but somehow it can't login.. 2. I am using Memcache Storage module as cache backend, It shows Successfull connection in admin report page, but somehow it doesn't see pecl memcache extension I think.. If I remove `$conf['lock_inc'] = 'sites/all/modules/memcache_storage/includes/lock.inc';` from settings.php file drush does WORK, but the same configuration is working on my local machine.. Very strange..

How can I solve this?

# Answer
> 2 votes
I finally managed to work it, the issue was ralated to Memcache Storage module somehow, as it's `lock_inc` config is not compatable with pecl memcache extension, so the solution was a removing pecl memcache and install php's memcache module.

I think I need to post this to Memcache Storage Module's bug report..

---
Tags: 7, drush
---


title: Abstract submission with COD

text:
# Question
Title: Abstract submission with COD
I would like to be able to let people submit abstracts with the Conference Organising Distribution. Is there a way already implemented? I did not see this.

The idea would be that people can enter information about themselves, the abstract and upload the tex file and select the session/track that they want to present in.

AND that we can approve the abstracts and add them to the schedule.

Is there an easy way for this? Seems like a pretty (academic) conference requirement.

Thanks!

# Answer
> 0 votes
this question was cross-posted on drupal.org and it got an answer there. it basically explains that *session submission* is meant for this.

---
Tags: webforms, distributions
---


# Question
Title: Deleting modules from the database that aren't on the filesystem
How do I remove modules that are referenced to in the database but have already been deleted from the filesystem?

This occurred because I had extra modules in my staging site, and I pushed the db to production. I would like to know how to clear out any modules from the db that aren't found on the filesystem.

# Answer
Try the Schema module.

This module compares the live database structure with the schema structure declared by all enabled modules, reporting on any missing or incorrect tables

> The Schema module provides additional Schema-related functionality not provided by the core Schema API that is useful for module developers. Currently, this includes:
>
> * Schema documentation: hyperlinked display of the schema's embedded documentation explaining what each table and field is for.
> * Schema structure generation: the module examines the live database and creates Schema API data structures for all tables that match the
> live database.
> * Schema comparison: the module compares the live database structure with the schema structure declared by all enabled modules, reporting
> on any missing or incorrect tables.
> 2 votes

---
Tags: 7
---


# Question
Title: How to theme a flag for different pages?
I want to theme a flag for different pages like on user profile page the html of the flag will be different then on the view page . I can make use of the flag.tpl.php and theme it but, I don't how to theme it for different pages.

Any suggestions?

# Answer
Something like this will work for user pages. You can adapt for other pages. Put it in your theme's template.php file.

```
function MYTHEME_preprocess_flag(&$variables) {
  if ($variables['flag']->name == "MACHINE_NAME_OF_FLAG") {
    if (arg(0) == 'user') {
        $variables['theme_hook_suggestions'][] = 'flag__user_page';
    }
  }
}

```

and the template file name then becomes

```
flag--user-page.tpl.php

```
> 2 votes

# Answer
In the display option of the flag (admin/structure/flags/manage/yourflag =\>#DISPLAY OPTIONS), you can check "Display link as field". then you will find your flag display option in admin/config/people/accounts/display. If you use the module field formatter class you can specify a class just for the field display in the user profile.

It is also possible to display flags button and flags result using views which allows you to add a specific class as well.
> 1 votes

---
Tags: 7, theming, flags
---


# Question
Title: Updating to PHP 5.4 breaks Drupal 7.25 with Strict warning: Declaration on bootstrap.inc
I tried updating to PHP 5.4, but got a few errors. These aren't critical errors right? seems like its only warnings.

I'm using Drupal 7.20 What do the following errors mean exactly? And how can they be resolved? Can I just upgrade my Drupal 7 to the latest 7.31 as of 2014-09-24 to fix these issues?

```
Strict warning: Declaration of Messaging_User_Destination::validate_address() should be compatible with Messaging_Destination::validate_address($address, $type = NULL) in _registry_check_code() (line 3080 of /home/xxx/public_html/includes/bootstrap.inc).

Strict warning: Declaration of Messaging_User_Destination::format_address() should be compatible with Messaging_Destination::format_address($address, $format = MESSAGING_FORMAT_PLAIN, $type = NULL) in _registry_check_code() (line 3080 of /home/xxx/public_html/includes/bootstrap.inc).

Strict warning: Declaration of Messaging_Mail_Address::validate_address() should be compatible with Messaging_Destination::validate_address($address, $type = NULL) in require_once() (line 208 of /home/xxx/public_html/sites/all/modules/messaging/messaging_mail/messaging_mail.inc).

```

# Answer
> 2 votes
> These aren't critical errors right?

No, it's just a warning. Not fatal. It comes from the `E_STRICT` error constant, which as of PHP5.4 was included in `E_ALL`. It's quite common to see those errors after upgrading 5.3 to 5.4 (not just for Drupal), as most people copy the bulk of their config from the previous version.

The constant itself provides this to error reporting:

> Enable to have PHP suggest changes to your code which will ensure the best interoperability and forward compatibility of your code.

---

> What do the following errors mean exactly?

In Drupal terms, it means one or more contrib modules you have installed contain code that targets older version of PHP (or at least hasn't been updated recently). Specifically, PHP is complaining that the arguments or access modification of a method on a child class doesn't match the same method on the parent class.

> Can I just upgrade my Drupal 7 to the latest 7.31 as of 2014-09-24 to fix these issues?

In your case the warning is being caused by the messaging\_mail module, so updating core won't do anything (though you should update ASAP, you're a long way behind). You could disable strict errors if you just want to hide the warning, but the best way forward is to report this as a bug to the appropriate module.

---
Tags: 7
---


title: Drupal 7 views page path/url matching?

text:
# Question
Title: Drupal 7 views page path/url matching?
Our former website (that was hooked with Google Analytics) had the following URL (i.e. Example URL) for a staff member:

```
http://www.example.com/research/teams/staffname.html

```

I have recently re-designed the website using Drupal 7 (Views 3) and other required modules. While designing the website, the structure of the most URL addresses changed.

Google already had indexed the old website and had/have the old URL addresses. After the complete re-design of the website, I did the following:

1. Enabled the Google Analytics module (supplied it the same Google Analytics ID used for the former website)
2. Installed/Enabled the xmlsitemap module, configured the content types to provide URL for and generated a new sitemap.xml file
3. Created Google Webmaster Tools (and Bing Webmaster account) and uploaded the sitemap.xml

Google has so far indexed 23 URL out of 63 (More indexing to be done!). At the moment googling the site, show up the website with some new links (probably the recently indexed links) and some older links. Clicking the OLD links of course display

```
"The requested page "/studentships/studentships1.html"

```

Hopefully by the time Google index all 63 links, there will be no OLD links left however, there happen to be another issue.

In the new website, I have a View page which is composed of a few View Attachments where each attachment lists a group of Scientists/staff. Visiting Research page

```
http://www.example.com/research

```

Renders four/five Science types sections and then under each section there is a list of Scientists. Each staff/scientists profile has a custom URL (yes I do use pathauto but, not for staff content type) as follow:

```
/research/group/{staffusername} hence http://www.example.com/research/group/{staffusername}

```

If you notice there is a partial match in the URL of old website and new website

```
  http://www.example.com/research

```

The problem I am having with the above URL is that, requesting any of the following URL variation would work (View Page is rendered) as if the above URL is requested

```
  http://www.example.com/research/*
  http://www.example.com/research/*/*
  ....

```

When I click the old URL for accessing a staff profile which looks as follow :

```
 http://www.example.com/research/teams/{staffusername}.html

```

That executes the following

```
http://www.example.com/research

```

Even though after /research there is no match (I should see an error there for URL mismatch). Why I want strict URL matching:

1. Accessing a staff profile using old link and ending up in the research page where all the staff is listed, is not a good navigation
2. Google bot will never come across a 404 hence, will consider the OLD staff URLs as valid and probably will never get rid of them from their search index/history (Google has listed most of the links of Old website as 404 but, not listed any of the OLD staff profile URLS).

What should I do to instruct the View page to only display /research page when the URL perfectly matched?

The view should run only when the request URL is exactly as follow

```
http://www.example.com/research

```

The staff content type nodes has the following Custom URL

```
research/group/{staffusername}

```

The Research View Page path is research, this issue of not doing strict URL matching is true for all of the Views of type Page in the new Drupal site. For example, the following is valid Career view URL

```
http://www.example.com/career (with View Page path as "career"

```

But any of the following URL requests work

```
http://www.example.com/career/*

```

Is this default behaviour of views?

Sorry for the level of details, probably too much. Thanks anyway.

# Answer
This isn't Views behaviour, it's standard for the Drupal menu system. Extra path components (separated by slashes) are ignored if they don't match a more specific menu entry. So if you have a menu entry for path xxx/yyy it'll also receive requests for xxx/yyy/zzz and xxx/yyy/zzz/aaa.

Rather than a 404, why not serve a 301 redirect? That's better for SEO. If you can't do that at the server level (always preferable for performance) then a module such as https://www.drupal.org/project/match\_redirect might help.

See: https://api.drupal.org/api/drupal/includes%21menu.inc/group/menu/7

> When responding to a page request, the menu system looks to see if the path requested by the browser is registered as a menu item with a callback. If not, the system searches up the menu tree for the most complete match with a callback it can find. If the path a/b/i is requested in the tree above, the callback for a/b would be used.
> 1 votes

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


# Question
Title: How to reset 'new' and 'updated' flags without visiting a node page?
In my drupal site I have a content type that has its nodes visible only in a view and they have always the '*new*' (or '*updated*') flag up for all users.

How can I reset the flags without visiting the node page?
Is there a function to tell drupal "*this user has seen this node*"?

# Answer
You can use `node_tag_new()` for that

> Updates the 'last viewed' timestamp of the specified node for current user.

e.g.

```
node_tag_new($node);

```
> 1 votes

# Answer
Check out the theme function theme\_mark:

```
function theme_mark($variables) {
  $type = $variables['type'];
  global $user;
  if ($user->uid) {
    if ($type == MARK_NEW) {
      return ' <span class="marker">' . t('new') . '</span>';
    }
    elseif ($type == MARK_UPDATED) {
      return ' <span class="marker">' . t('updated') . '</span>';
    }
  }
}

```

You can use that in a module to override the marking of your nodes. So if you define mymodule\_theme\_mark like:

```
function mymodule_theme_mark($variables) {
  $type = $variables['type'];
  global $user;
  if ($user->uid) {
    if ($type == MARK_NEW && (NOT YOUR NODE VIEW TYPE) ) {
      return ' <span class="marker">' . t('new') . '</span>';
    }
    elseif ($type == MARK_UPDATED && (NOT YOUR NODE VIEW TYPE)) {
      return ' <span class="marker">' . t('updated') . '</span>';
    }
  }
}

```

That should get you close to where you need to be.
> -2 votes

---
Tags: views, nodes
---


# Question
Title: How to hide flag link if current user and author are same?
I need to hide flag link if the logged in user and the author are same. Please find below codes.

```
function MODULE-NAME_views_pre_view(&$view, &$display_id, &$args)
{
    global $user;
    if ($view->name == 'VIEW-NAME' && $display_id == 'DISPLAY-ID') {
        $node = node_load(arg(1));
        if($node->uid == $user->uid){
            //echo 'hide flag';
        }else{
            //echo 'show flag';
        }
    }
}

```

# Answer
> 2 votes
If it is a flag on nodes, you just need to set "Users may only flag content of others" in the **Flag access by content authorship** paragraph of the **FLAG ACCESS** options.

---
Tags: flags
---


# Question
Title: I cannot log in, and I am said I have 5 failed logins
I've setup a virtual host on one of my machines. The front page shows fine, but the other pages don't. When I put in my login information, and I click the "Log in" button, I get the "page not found" error.

If I go to www.example.com/?q=user, I get that page, but when I try logging in, I see the following error message:

> Sorry, there have been more than 5 failed login attempts for this account. It is temporarily blocked. Try again later or request a new password."

How can I solve this problem?

# Answer
> 8 votes
The quick solution is to login in your database `mysql -u <username> -p<password>` or `drush sql-cli`

and execute this query

`truncate flood;`

Thats it and you'll able to login again.

# Answer
> 0 votes
Disable clean URLs. Configure your server / drupal for clean URLs, then enable clean URLs. How to configure clean url on an server depend on kind of server setup you are running.More info on clean urls http://drupal.org/getting-started/clean-urls

# Answer
> 0 votes
The issue can be resolved by either removing the entries in the flood table (as stated by user8012) or installing a module to assist with removing the entries. Please read http://bri-space.com/content/how-fix-drupal-7-blocked-account-after-5-incorrect-password-attempts for more details.

# Answer
> 0 votes
You can use phpMyAdmin to delete the entries in the "flood" table.

1. Go to your phpMyAdmin page and login
2. Select the database of your Drupal website from the left sidebar
3. Click on the "SQL" link on the top horizontal menu
4. Copy the following SQL query:

```
DELETE FROM flood;

```

paste it in the text area of the "SQL" page and click on the "Go" button.
5. The entries in the "flood" table will be deleted and you will now be able to login to your Drupal website.

OR

You can use terminal.

1. Connect to your server with ssh

```
ssh root@URLofYourWebsite.com

```

alternatively you can use the IP address of your website

```
ssh root@xxx.xxx.xxx.xxx

```
2. Start the MySQL prompt by typing

```
mysql -uroot -p

```

and give your password.
3. Select the database that you want to use

```
USE yourDatabaseName;

```
4. And delete the entries from the "flood" table

```
DELETE FROM flood;

```
5. Exit from MySQL and from the server and now you'll be able to login again.

```
exit;

```

---
Tags: users
---


title: Adding a form to the admin menu

text:
# Question
Title: Adding a form to the admin menu
Ive followed 3 tutorials and I cant seem to crack this. My goal is to create a form in the admin section to store some information.

I have used the following to create the form and call it from a url but I seem to be missing something

```
    function read_more_news_admin() {
  $form = array();
   //link field
      $form['link_container'] = array(
        '#type' => 'container',
        '#attributes' => array('class' => array('some-class')),
        '#tree' => TRUE,
      );
      $form['link_container']['link'] = array(
        '#type' => 'link_field',
        '#field_name' => 'link_field',
        '#language' => 'und',
        '#field_parents' => array(),
        '#delta' => 0,
        '#default_value' => array(
          'title' => variable_get('link_title', ''),
          'url' => variable_get('link_url', ''),
        ),
      );
  return system_settings_form($form);
}

function read_more_news_menu() {
  $items = array();
  $items['admin/settings/readmorenews'] = array(
    'title' => 'Read More News Module Settings',
    'description' => 'Set read more news outgoing link here',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('read_more_news_admin'),
    'access arguments' => array('administer readmorenews settings'),
    'type' => MENU_NORMAL_ITEM,
   );
  return $items;
}

```

Any help would be appreciated

# Answer
try this:

```
function read_more_news_menu() {
    $items = array();
    $items['admin/settings/readmorenews'] = array(
        'title' => 'Read More News Module Settings',
        'description' => 'Set read more news outgoing link here',
        'page callback' => 'drupal_get_form',
        'page arguments' => array('read_more_news_admin_form'),
        'access arguments' => array('administer readmorenews settings'),
        'type' => MENU_NORMAL_ITEM,
    );
    return $items;
}
function read_more_news_admin_form($form, &$form_state) {
    $form = array();
    $form['link_container'] = array(
        '#type' => 'container',
        '#attributes' => array('class' => array('some-class')),
        '#tree' => TRUE,
    );
    $form['link_container']['link'] = array(
        '#type' => 'link_field',
        '#field_name' => 'link_field',
        '#language' => 'und',
        '#field_parents' => array(),
        '#delta' => 0,
        '#default_value' => array(
            'title' => variable_get('link_title', ''),
            'url' => variable_get('link_url', ''),
        ),
    );
    return system_settings_form($form);
}

```

Or check this url: https://www.drupal.org/node/1111260

```
function read_more_news_permission() {
  return array(
    'administer my module' => array(
      'title' => t('administer readmorenews settings'),
      'description' => t('Administer read more news settings.'),
    ),
  );
}

```
> 1 votes

---
Tags: forms, hooks
---


title: tb_blog main area left padding

text:
# Question
Title: tb_blog main area left padding
I'm using tb\_blog theme for my website, demo site: http://demo.themebrain.com/#blog

I want to remove the padding from left side of page without corrupting whole structure of website, I'm terrible with HTML and CSS stuff. I want a full page expanded blog.

Also I'm open to suggestions, including totally changing my blog theme to something new which by default have a full page blog theme and it's easy to customize or tell me which CSS files to fix in tb\_blog theme to make it full page blog. Thanks

# Answer
> 1 votes
That theme is using a grid, looks like a base of 24. It's not the padding that's causing the blog to not display in the full page, but the grid (IE, the grid widths).

If your uncomfortable with updating the css of this theme, you may want to switch to a theme that's not grid based. Though it's not full page, business or something like it might be more suited to what you want to do.

---
Tags: theming
---


# Question
Title: hook_form_alter function to make field visible and required?
I'm trying to build a hook\_form\_alter function to make field visible and required.

The form is the checkout form at **http://example.com/en/checkout/33**

The targeted field are Customer Profile Billing fields that I added at: **http://example.com/en/admin/commerce/customer-profiles/types/billing/fields**

I tried with:

```
function MY_MODULE_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'commerce_checkout_form_checkout') {
    $form['field_cif_nif_id'] = array(
         // This #states rule says that the "field_cif_nif_id" fieldset should only
         // be shown if the "field_dispongo_de_" form element is set to "CIF/NIF/ID".
        '#states' => array(
           'visible' => array(
               ':input[name="field_dispongo_de_"]' => array('value' => 'CIF/NIF/ID'),
            ),
        ),
  );

 }
}

```

it simple doesn't work. No errors.

I need to make the 'field\_cif\_nif\_id' visible and required only if 'field\_dispongo\_de\_' has value 'CIF/NIF/ID'

UPDATE: I forgot to mention that 'field\_dispongo\_de\_' is a '**radio**' type field and 'field\_cif\_nif\_id' is a '**input text**' type.

UPDATED CODE

It is closer but not working yet.

```
function MY_MODULE_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'commerce_checkout_form_checkout') {
    $form['customer_profile_billing']['field_cif_nif_id'] = array(
       '#states' => array(
           'visible' => array(
               ':input[name="field_dispongo_de_"]' => array('value' => 'CIF/NIF/ID'),
            ),
       ),
    );
 }
}

```

# Answer
Try changing the selector from `':input[name="field_dispongo_de_"]'` to the id of the field (`#edit-customer-profile-billing-field-dispongo-de-und`) as below:

```
/**
 * Implements hook_form_alter().
 */
function MODULE-NAME_form_alter(&$form, &$form_state, $form_id) {
  // Check if the form is commerce checkout form.
  if ($form_id == 'commerce_checkout_form_checkout') {
    // Verify the field names are as per the form.
    $form['customer_profile_billing']['field_cif_nif_id']['#states'] = array(
      // This #states rule says that the "field_cif_nif_id" fieldset should only
      // be shown if the "field_dispongo_de_" form element is set to "CIF/NIF/ID".
      'visible' => array(
        '#edit-customer-profile-billing-field-dispongo-de-und' => array('value' => t('cif')),
      ),
    );
  }
}

```
> 2 votes

---
Tags: forms, commerce
---


title: Backing up logs

text:
# Question
Title: Backing up logs
I've been looking at my site logs recently. I have the limit of logs set to 10,000. The problem is, due to the amount of traffic we get, that number will only represent, at best, half a day of logs. Most of these are ether from access denied (I'm guessing spam bots trying to create nodes) or page not founds. The rest are items from custom modules I've built that I use to monitor how those modules are functioning (Like a notification that a queue is being run, or nodes are being created, etc.).

I've toyed with the idea of bumping the log messages to keep up to 100,000 or 1,000,000, but I'm not sure if this will cause performance issues or if it will drastically increase the size of my db.

Ultimately though, that would only really be a band-aid at best. As it would be nice to be able to keep a longer track of error messages, say weeks or months, so that I can further analyze what my site is doing, what areas need to be improved, etc. Is there any way to create a back up of log files so I don't loose them forever once they hit that ceiling?

# Answer
> 5 votes
I believe it's a best practice to not enable the core `Logging` module for Production Drupal websites (eg, outside of your development environment) and to setup server (host) based logging -- or offload the logging to a remote service.

See the Syslog documentation page. Which is what I mean by "host based logging".

> The Syslog module logs events by sending messages to the logging facility of your web server's operating system. Syslog is an operating system administrative logging tool that provides valuable information for use in system management and security auditing. Most suited to medium and large sites, Syslog provides filtering tools that allow messages to be routed by type and severity.
>
> It is not suitable for shared hosting environments.
>
> It might not be as user friendly as Database Logging but will allow you to see logs and troubleshoot if your site is not accessible. Because the Database logging module writes logs to the database it can slow down the website. By using Syslog you can improve the performance of the site.

An example of a remote log is Redis Logging, there are numerous other 3rd party logging modules.

**EDIT**

A common practice for webservers is to Rotate Logfiles which builds an archive of compressed logfiles after your logfile has accrued to a certain size or after X days. By using Syslog you can configure your webserver to then rotate logfiles.

---
Tags: 7, backups
---


# Question
Title: D7 Views: Rewrite multiple field into one with custom separators
This is a follow-up to a recent question of mine, that was solved easily. The construct is very similar, but this time I need to add conjunction characters (in my case a comma and a space: ", ") when rewriting the field.

Here's the setup: In a node type, I have three fields: (1) methods, (2) geography, (3) keywords. All three fields are textareas where comma-separated values are entered. These fields are hidden on normal node view (node type -\> manage display), but there is a views block showing these values.

Now, I want all of the fields' content to appear as a single field with a label with additional commas between.

An example: a node has the following values (1) methods: "evaluation, regeneration" (2) geography: "Denmark, Germany" and (3) keywords: "rivers, restoration".

If all (or at least keywords) fields are filled, the desired result is easy to achieve in the block:

* Methods: no label; exclude from display; no result behaviour: hide if empty, hide rewriting if empty; rewrite results: ", \[methods\]"
* Geography: no label; exclude from display; no result behaviour: hide if empty, hide rewriting if empty, no result output: "\[methods\]"; rewrite results: ", \[geography\]\[methods\]"
* Keywords: label "Keywords"; no result behaviour: hide if empty, hide rewriting if empty, no result output: "\[geography\]"; rewrite results: "\[keywords\]\[geography\]"

For the above example this produces

* Keywords: rivers, restoration, Denmark, Germany, evaluation, regeneration

Thus, the required commas (between restoration and Denmark as well as between Germany and evaluation) are added correctly. This also works, if either methods or geography are empty or even both, output looks like:

* Keywords: rivers, restoration, evaluation, regeneration
* Keywords: rivers, restoration, Denmark, Germany
* Keywords: rivers, restoration

Now the culprit. If keywords' field is empty, there are two scenarios.

1. Both geography and methods are empty, also. Then the whole (rewritten keywords) value is also empty and label is not displayed.
2. Either or both geography and method have values. Then there is a superfluous comma at the start of the value like
    * Keywords: , Denmark, Germany
    * Keywords: , evaluation, regeneration
    * Keywords: , Denmark, Germany, evaluation, regeneration

The actual question: **How should I setup the view to avoid this starting comma if keywords' field is empty?**

The only easy way I found is to make the keywords' field required so there is always a value present. But I'd like to set it up without marking fields mandatory and without changing the fields' types or widgets.

# Answer
> 1 votes
My solution to overcome the issue now is not purely through views settings but involves some CSS. First, I removed all commas and instead rewrote the fields to

```
<span class="methods">[methods]</span>
<span class="geography">[geography]</span>
<span class="keywords">[keywords]</span>[geography][methods]

```

Next, I added a single CSS rule:

```
span.keywords + span.geography:before,
span.keywords + span.methods:before,
span.geography + span.methods:before {
  content: ', ';
}

```

Et voilà, commas are only added to following elements.

# Answer
> 1 votes
You could rewrite the output of the field with your comma (but without conditions), then exclude from display and use a global textfield to output the field again with your conditions, so if the field is empty it won't show the comma.

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


# Question
Title: What are the functions of the callbacks in the commerce payment method info hook?
Can someone explain me the differences, maybe with some examples, between the callbacks in the hook\_commerce\_payment\_method\_info()?

The callbacks are these: settings\_form, submit\_form, submit\_form\_validate, submit\_form\_submit, redirect\_form, redirect\_form\_validate, redirect\_form\_submit.

I'm trying to implement a payment module and I need to know how to use the callback of the above-mentioned hook.

Thanks

# Answer
> 1 votes
You can find Contributed Modules API Documentation in http://drupalcontrib.org/ portal.

Please find link to above hook documentation hook\_commerce\_payment\_method\_info .

Callbacks Documentation links below...

CALLBACK\_commerce\_payment\_method\_settings\_form() CALLBACK\_commerce\_payment\_method\_submit\_form() CALLBACK\_commerce\_payment\_method\_submit\_form\_validate() CALLBACK\_commerce\_payment\_method\_submit\_form\_submit() CALLBACK\_commerce\_payment\_method\_redirect\_form() CALLBACK\_commerce\_payment\_method\_redirect\_form\_validate() CALLBACK\_commerce\_payment\_method\_redirect\_form\_submit()

Check out commerce\_payment\_example module to find out how to write a payment method for more information.

# Answer
> 1 votes
I found this example of a callback, which puts up a little form to enter a card number:

http://drupalcontrib.org/api/drupal/contributions!commerce\_kickstart!modules!commerce\_kickstart!commerce\_kickstart\_payment!commerce\_kickstart\_payment.module/7

```
    function commerce_kickstart_payment_submit_form($payment_method, $pane_values, $checkout_pane, $order) {
      module_load_include('inc', 'commerce_payment', 'includes/commerce_payment.credit_card');
      $fields = array(
        'type' => array(
          'visa',
          'mastercard',
          'amex',
        ),
      );
      $default = array(
        'number' => '4111111111111111',
      );
      return commerce_payment_credit_card_form($fields, $default);
    }

```

---
Tags: hooks, commerce
---


title: Issues with a form validate hook

text:
# Question
Title: Issues with a form validate hook
I'm encountering an issue tying in a #validate hook into the Drupal registration form. In a custom module, I have a call to the User Register form (the form that is used on Account Creation) and an addition to #validate that should run an outside validation function.

```
/**
 * Implements hook_form_FORM_ID_alter()
 * Form ID: user_register_form
 */
function mymodule_form_user_register_form_alter($form, &$form_state) {
  $form['#validate'][] = "mymodule_validate_register_form";
}

function mymodule_validate_register_form($form, &$form_state) {
  //validation code
}

```

And on running a dpm of the Register Form, the validate statement is in place. However, it appears that the functions is never being run.

When I look at the #validate array, its the last option, predated by user\_account\_form\_validate, user\_validate\_picture, and user\_register\_validate. Is it possible that its never being run due to the order of the other validate statements, or is there something wrong in my logic? Are there other approaches to validating the data during User Registration over the hook\_form\_FORMID\_alter function?

# Answer
This:

```
function mymodule_form_user_register_form_alter($form, &$form_state) {

```

needs to be this:

```
function mymodule_form_user_register_form_alter(&$form, &$form_state) {

```

Notice `$form` is by reference in the second snippet.
> 1 votes

---
Tags: 7, hooks, users
---