title: Get IP address of submitter

text:
# Question
Title: Get IP address of submitter
I'm actually testing a website with Drupal 7.

I am searching a way to get the visitors' IP, when they submit a new node; the users can also be not logged-in, as anonymous users are allowed to submit new content.

I can't find a module to do that, and I don't know how to use hooks or PHP to achieve this.

What should I do?

# Answer
I haven't found a module which does this yet. You can do these steps:

1. Create a text field named ip\_address
2. Manage display: make the field hidden
3. Use Display Suite or a custom hook (or even CSS) to hide the field when filling out the form
4. Create a Rule on event "Before saving content"
5. Set a condition of content type: your content type
6. Set a condition of Data comparison: \[node:is-new\], Data value: True (check the checkbox)
7. Set an action of Set a data value, and set the field to be:

PHP Code

```
<?php
  print ip_address();
?>

```

That should do it.

You could also accomplish this by creating a module and using some hooks
> 11 votes

# Answer
There is a simple way to do this. Install the Computed Field module.

Add a computed filed (for IP address) to your content type and add the following line in **Computed Code (PHP)** textarea to get current ip address of the author

```
$entity_field[0]['value'] = ip_address();

```

That's it.You will get submitted author ip address. No need to install any other modules
> 4 votes

# Answer
I wrote simple module for saving author ip address. With this module you can add field to content type, which filled with ip address author on node creation.

https://drupal.org/sandbox/drupaladmin/2191469
> 1 votes

---
Tags: 7, nodes
---


title: Commerce Dynamic Address Field Issue

text:
# Question
Title: Commerce Dynamic Address Field Issue
I've got a problem with the dynamic address field. Maybe it is a problem with the feed-importer, not quite sure about that.

I've imported customers to my database, in the view, name and address are displayed correctly but when i click on edit, those fields are empty. Seems like they are correct in the database.

# Answer
Addressfield module depends on the country for displaying the right structure of the form that is configured by the plugin, I'm afraid country is mandatory so you can just select one in the field settings so you don't have the selector, then you'll need to do some theming magic for hiding it when it's displayed
> 2 votes

---
Tags: commerce, entities
---


title: Where is the index file?

text:
# Question
Title: Where is the index file?
I've made a drupal site using acquia Dev desktop 7.16.16 and i would like to know where the index.HTML or index.php file is stored? I found an index.php file at /Sites/acquia-drupal/ directory but it seems to need a root to work.

# Answer
Drupal is a dynamic application, having an index.html file wouldn't make much sense.

There is an index.php file at the root of the install (the one you've already found). All requests are sent to that script, and the Drupal bootstrap takes over and routes them to the PHP function responsible for serving the appropriate content.

If you want to change the content on the front page, the simplest way would be to create a new node (of whatever type you feel is appropriate), visit /admin/config/system/site-information, and set the "Default front page" to the page of that new node.
> 3 votes

# Answer
Drupal has mainly one index.php file that is at the root of your installation. There can be many other files in the other directories.

But there is no use of editing this file because only includes the bootstrap files, rest of the things are handled dynamically.
> 0 votes

---
Tags: acquia-dev-desktop
---


title: Send email before role expiration

text:
# Question
Title: Send email before role expiration
after long searching and many attempts I definitely need your help.

On the website I am currently working on, people can buy a "Participant" role for 1 year. I'm using ubercart to handle the purchasing process.

I am trying to set up an automatic email which is sent when the Participant role is about to expire. Lets say 1 month before.

I know there is the Role module in UberCart, but I really don't like it and I also think it is not flexible enough. I also know about the User Expire module, but I am not sure I can do what I want to with it.

I was trying to create a Rule which:
\- runs on every Cron run
\- scan all the users Expiry Date field
\- send an email to all the user with expiration closer than 1 month

Please give me some help...I am really out of ideas.

I hope I am missing a very easy way to implement it.

Thank you in advance,
guidout

# Answer
Create a custom module, implement `hook_cron()`, it is nothing but a function which will be called whenever cron runs.

Here is an article explaining what are hooks.

For code reference install examples module.

1. Implement `hook_cron()`
2. Load all the instance of the computed field, where you store the expiry date
    * Either you can directly query the database using `db_select()`
    * Or, use `field_attach_load()` to load only that field instances, instead of loading whole user object. Here is an example of how to use `field_attach_load()`.
3. Check the expiry date.
    * Send a mail using `drupal_mail()` if the role is going to expire.

Note: You probably want this cron to run only once a day, for that install `Elysia Cron` and configure this hook to run once everyday by 12:00 am.
> 2 votes

---
Tags: users
---


# Question
Title: How to set number of articles per page on the Blog module?
I came across a 6.15 drupal site that I had to modify one simple thing: put instead of 3 articles per page , 5 on the front page the blog resume is shown, and it seem that the blog module doesn't have any setting to do that.. It isn't made with views, nor is it a block.. I don't even know how they get to the front page (probably by being promoted..)

here a snapshot of what I see on the front page...

how can I set the number of articles? I can't find it anywhere... I was thinking of defining a view or something and renounce of this built-in functionality...

# Answer
Looking at blog\_page\_last and node\_page\_default, I see that both use the persistent variable called "default\_nodes\_main" (which defaults to 10) for the number of nodes per page. That variable can be set on the form at /admin/content/node-settings, under "Number of posts on main page".

The above means that both the /node and /blog pages use the same value. If you want different values for both pages, you probably need to rebuild one (or both) of them as a view.

I hope that answers your question.
> 4 votes

# Answer
For Drupal 7, there is a setting on admin/config/system/site-information to control post numbers on pages like blog called *Number of posts on front page*.

As its description says, the setting is:

> The maximum number of posts displayed on overview pages such as the front page.

There is a similar setting for the Views module, which is for each view you create with this module.
> 4 votes

# Answer
in blog.pages.inc,under blog\_page\_last() function,replace

```
->limit(variable_get('default_nodes_main', 10)) to ->limit('YOUR CUSTOM VALUE').

```

i think it will help you.
> -1 votes

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


# Question
Title: Is it possible to use a sort of constant or a custom token in the rewrite section of a views field?
My use case.

I have a portion of a URL of another site (www.example1.com) under each of my nodes (let's say node type B).

Each of these nodes can be related with another node (let's say node type A).

I need a view which show informations of A nodes and get the URL portions from B nodes using the relationship section of the view.

That's ok, I get what I want but I would like to create a URL with this URL's portion adding a constant/token at the beginning (www.example1.com) so that it can changed in a simple way (let's say www.example2.com) instead of modify each field of the view.

My best bet should be probably to rewrite the template of the view and using a constant (variable\_get/set should be fine) but I would like to have this field configurable with the UI.

Thanks

# Answer
If I'm understanding the question properly, you can either use a hidden field on a node to create a node specific value which you can rewrite as a link if desired, or create a Global:Custom Text where you can include whatever static or variable data you desire, so long as the fields containing the information are present (visible or not).
> 0 votes

---
Tags: views, tokens
---


# Question
Title: How Change the Style of views based on user option
I have a set of products into grid view. I need to create a two tabs one for grid view and list view(swipe view). How to create like this using views in drupal 7?

# Answer
Sounds like this will need to be done programmatically.

Use hook\_views\_pre\_render() to be able to change the settings of a view based on certain conditions.

https://api.drupal.org/api/views/views.api.php/function/hook\_views\_pre\_render/7

Then using the global $user definition to lookup the logged in user, use that to create a condition and alter the settings of the actual view.
> 0 votes

---
Tags: views, theming
---


title: How to check node permission rules?

text:
# Question
Title: How to check node permission rules?
I'm using drupal commerce and I added a new product (and product display). I can see it in the listing, but when a user click on the product page, it's saying : permission denied. All the other products works fine, it's only the last one which doesn't.

I tried to rebuild the permissions but that doesn't changed anything. How can I check what is "denying" the page ?

# Answer
Devel module has a submodule called Devel node access, it is really useful to evaluate and track permission problems on nodes. Enable it and place the blocks on a region you're using in your template.
> 1 votes

---
Tags: commerce
---


# Question
Title: How to show the ip address in revision listing?
When I see all the revisions of a particular node through in my site, say, `http://www.mysite.com/node/1/revisions`, I see an html table representing our data having two columns mainly REVISION and OPERATIONS. I have a requirement to add another column called IP Address from where the content originated for tracking purpose. I have already added a field in ip\_address in the database, but don't know how to show the ip address in the revision listing? Plz help.

# Answer
> 1 votes
You could do this using rules and views. First to create the rule:

> * Create a text field named ip\_address
> * Manage display: make the field hidden
> * Use Display Suite or a custom hook (or even CSS) to hide the field when filling out the form
> * Create a Rule on event "Before saving content"
> * Set a condition of content type: your content type
> * Set a condition of Data comparison: \[node:is-new\], Data value: True (check the checkbox)
> * Set an action of Set a data value, and set the field to be:
> * PHP Code:

```
<?php
  print ip_address();
?>

```

Above taken from here: Get IP address of submitter

For your purposes the 6th bullet (your rule condition) can be set-up like this:

And for the final action (7th bullet) if you don't want to use the php you can first add and action

> 'Add a variable' -\> Value IP Address

and use that as in a second 'set a data value' action...

Now you can create a view that displays in a table format the fields 'Content Title' 'Revision Log' (i'm guessing this is what the operations column is recording?) and 'IP\_Address', sorted by 'Node revision ID (desc)', or similar....

As it stands I am aware that this answer might not work for multiple revisions, rather only displays the IP for the latest revision. I imagine that when setting up your initial (hidden) IP\_address field if you allow multiple values the rule will simply add values rather than over-write them. Maybe someone else on here has guidance on that...

---
Tags: 7
---


title: How to keep track of unique node views?

text:
# Question
Title: How to keep track of unique node views?
I'd like to display the number of unique node views (= how many times the full node page is visited by a unique user) in my nodes' teasers. I've tried to use the Statistics module, but in that case, *all* reads are stored.

Is there a way to only count the unique views? Which code should I use in my `node.tpl.php` file to display this information?

# Answer
> 2 votes
You can try Node View Count module.

> Node View Count module allows to count node views. Unlike statistics module, this module records each view of node with user uid and timestamp. So now you can know how many times a user viewed node by day, week, month and etc.

To print the count in teasers.

1. Implement `hook_node_view()`
2. Check the `$node->type` and `$view_mode`
3. Call `nodeviewcount_db_count_node_views($node, $user = NULL, $distinct_users = FALSE)` to get the count
4. Add the count to `$node->content`
5. In your template file print the count that you added.

**Update:**

**You cannot rely on IP for uniqueness**, but if you want to count unique views based on IP then follow one of the below steps.

1. The `accesslog` table will contain all the access logs with IP details, you can query this table for path like `node/nid` and group by IP to get the count, One thing to note is that accesslog will be cleared periodically, if you are going to use this table then you have to make sure that it won't be cleared by selecting **never** in **Discard access logs older than**. I will not suggest doing this way because this table will contain access log for all pages, though there is a moule Better Statistics using which you can restrict statistics to log access details only for node pages.
2. Or, you can create a custom module and create a custom table somewhat similar to `accesslog` and then implement `hook_node_view()` to populate the table, later you can query the table to get the count.

---
Tags: 7, nodes
---


# Question
Title: compare terms from userterm and node term
I have users and nodes. bith have the same term referende field:

field\_area

goal is to display a message in node.tpl.php when: \- user has term 'south' \- node has term 'south'

i have used the field extract module to get id term ID from the node. $tid\_node = field\_extract\_value('node', $node, 'field\_bedrijf', 0, array('key' =\> 'tid')); term id is .e.g: 5

Now i would like to find the term id using the user-\>field\_area field.

I would utlimately have a code like:

```
if $tid_node == $tid_user {
print "a custom message" ;}

```

# Answer
Found the solution after seaching around. node term id:

```
$node_tid = field_extract_value('node', $node, 'field_your_taxonomy_reference_field', 0, array('key' => 'tid'));

```

user term id:

```
//load current user
$user_info = user_load($user->uid);
$user_term_id = $user_your_taxonomy_reference_field['und'][0]['tid'];

```

now set logic if ($node\_tid == $user\_term\_id) { print "show link"; }
> 0 votes

---
Tags: theming, entities, taxonomy-terms
---


# Question
Title: Wrap a single html tag around each block that's generated from a single view
I'm sure this isn't difficult, but I can't seem to figure it out. I have about 10 block displays generated from one view that needs a single html wrap (Setting the css property in the view itself is not what I'm looking for). Devel themer module is suggesting block--views.tpl.php, however that obviously affects all blocks generated by views. I assume a preprocess function would be best. The function below works, but I need to target a specific view.

Thanks in advance.

```
  function mytheme_preprocess_block(&$variables) {
    if ($variables['block']->module == 'views') {
      $variables['classes_array'][] = drupal_html_class('semester-container');
    }
  }

```

# Answer
> 1 votes
Thanks, but I was able to figure it out using the preprocess\_block function.

```
  function mytheme_preprocess_block(&$variables) {
    kpr($variables); //Find a common element then add to the conditional below
    if ($variables['block']->module == 'views' && $variables['block']->context == 'curriculum_semester_breakouts') {
      $variables['classes_array'][] = drupal_html_class('semester-container');
    }
  }

```

# Answer
> 1 votes
The answer suggested by madhurjya is correct, but I would point out that it is possible to create a template that is applied to all block displays of a certain view. E.g. for a view Blog with Unformatted type of output you can use `views-view-unformatted--blog--block.tpl.php` to alter all blocks only from that view.

Explore the Theme:Information in the Advanced settings of a view to see all your options.

# Answer
> 0 votes
Use function hook\_views\_pre\_render to customize the html, or u can use the view theme templates which u will get for each view block display by clicking on advance tab of view configuration page and for documentation on views template you can read this link.hope this will help u.

Following is one of my view, array of `$view`, Here you can see under the `display`, i have total five display between that i have two blocks block\_1 & block\_2 each block has its id as unique so you can modify ur code based on this `$view->display['block_1']->id` so on.... Hope this will. help you.

---
Tags: theming
---


# Question
Title: Can't see error messages when creating Drupal form in a separate file
Suppose, I want to use Drupal libraries inside a separate php file to generate a form. I created 3 functions:

1. function add\_form
2. function add\_form\_validate
3. function add\_form\_submit

And then used `drupal_get_form` / `render` to get the HTML code. But when I insert invalid data, I don't see the error message - just the red border of the text input. Here is the minimal example to reproduce the error (file is called test.php and is located inside Drupal directory):

```
<?php
//including Drupal libraries
define('DRUPAL_ROOT', $_SERVER['DOCUMENT_ROOT']);
require_once(DRUPAL_ROOT . DIRECTORY_SEPARATOR . 'includes'.  DIRECTORY_SEPARATOR . 'bootstrap.inc');
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);

//form with 1 text field and submit button
function add_form($form, &$form_state)
{
    $form['text'] = array(
        '#type' => 'textfield',
        '#title' => 'Insert text',
        '#required' => true,
        '#attributes' => array('autofocus' => 'autofocus'),
        );

    $form['submit'] = array(
        '#type' => 'submit',
        '#value' => 'Submit',
        );

    return $form;
}

//text must be 'aaa'
function add_form_validate($form, &$form_state)
{
    if ($form_state['input']['text'] != 'aaa')
    {
        form_set_error('text', t('Text is not aaa!'));
    }
}

function add_form_submit($form, &$form_state)
{
    print "I am inside add_form_submit<br>";
    var_dump($form_state['input']);
    exit;
}
?>
<!DOCTYPE html>
<html>
  <head>
    <title>element</title>
    <link type="text/css" rel="stylesheet" media="all" href="/modules/system/system.base.css">
    <link type="text/css" rel="stylesheet" media="all" href="/modules/system/system.theme.css">
    <link type="text/css" rel="stylesheet" media="all" href="/modules/system/system.messages.css">
    <meta http-equiv="Content-Type" content="text/html;charset=utf-8" >
  </head>
  <body>
<?php
//here is the problem: I don't know, how to output the error message
print theme('status_messages');

$content = drupal_get_form('add_form');
$content = render($content);
print $content;
?>
  </body>
</html>

```

# Answer
It is working fine for me, only thing is that I get the error message only when submitting for the second time, that is because you are printing the `status message` before the `drupal_get_form()`. So if I print the message after `drupal_get_form()` then it is working as expected.
> 2 votes

---
Tags: 7, forms, status-messages
---


# Question
Title: Way to Configure IP Geolocation Views & Maps Module via Script
The module IP Geolocation Views & Maps has a ton of great features. By default, the data collection option: *Employ the Google Maps API to reverse-geocode HTML5 visitor locations to street addresses* is turned on.

**Is there a way to turn off this option via a drush command, or through some code?** I have automated our site setup process, and would like to ensure this option is turned off without requiring admins to click off the option in the admin UI.

# Answer
> 1 votes
You can use the `drush variable-set` command for this:

```
~$ drush help variable-set
Set a variable.

Examples:
 drush vset --yes preprocess_css TRUE      Set the preprocess_css variable to
                                           true. Skip confirmation if variable
                                           already exists.
 drush vset --exact maintenance_mode 1     Take the site offline; skips
                                           confirmation even if
                                           maintenance_mode variable does not
                                           exist. Variable is rewritten to
                                           site_offline for Drupal 6.
 drush vset pr TRUE                        Choose from a list of variables
                                           beginning with "pr" to set to
                                           (bool)true.
 php -r "print                             Set a variable to a complex value
 json_encode(array('drupal',               (e.g. array)
 'simpletest'));"  | drush vset
 --format=json
 project_dependency_excluded_dependencies
 -

Arguments:
 name                                      The name of a variable or the first
                                           few letters of its name.
 value                                     The value to assign to the variable.
                                           Use '-' to read the object from
                                           STDIN.

Options:
 --exact                                   The exact name of the variable to
                                           set has been provided; do not prompt
                                           for similarly-named variables.
 --format=<boolean>                        Format to parse the object. Use
                                           "auto" to detect format from value
                                           (default), "string", "integer" or
                                           "boolean" for corresponding
                                           primitive type, and "json" for JSON.
 --yes                                     Skip confirmation if only one
                                           variable name matches.

```

To use this, you need to figure out the machine name for the variable. On system settings forms, this will be the `$form` key in the builder function. You can also poke through the variable list from the Devel module, and look for the variable name there. If you use Inspect Element (or whatever it is called in your browser), it will be the `name` attribute on the input or select element.

# Answer
> 0 votes
You can always add it to your settings.php and set it to off.

Look in "variables" table for the value you need and add, something like this:

$conf\['name\_of\_variable'\] = 'value\_you\_want';

Simple example: $conf\['maintenance\_theme'\] = 'bartik';

---
Tags: drush, location
---


# Question
Title: browscap.ini is not configured in php.ini
In my status report I'm still getting this error:

```
Browscap data   /   browscap.ini is not configured in php.ini.

```

When I searched on the internet I found this topic that suggested this:

```
[browscap]
; http://php.net/browscap
browscap = "C:\xampp\php\extras\browscap.ini"

```

I've download full\_php\_browscap.ini file on browscap.org and placed it in the root where my php.ini is also located (also changed the name to browscap.ini).

Then I've placed this in my php.ini file:

```
[browscap]
browscap = "/domains/mydomain.be/public_html/staging/browscap.ini"

```

But I'm still getting the error ... . My php.ini file is located in the same directory as the browscap.ini file.

# Answer
> 0 votes
I fixed this with the module Browscap.

---
Tags: javascript
---


# Question
Title: Showing different page layouts based on form data
I'm trying to build a multi step form. Before the second step I have to process the data inserted in step one and render different layout and form fields based on the results.

I use "drupal\_get\_form" callback in \_menu hooks to display the form, but I think I have to use a different approach, because I can't find a way to specify a template and\or HTML code this way.

What can I do? Thanks!

MENU DECLARATION:

```
/**
 * Implementation of hook_menu().
 */
function clientform_menu() {
    $items['clientform/step1'] = array(
        'title' => "Estimate",
        'type' => MENU_CALLBACK,
        'access arguments' => array('access content'),
        'page callback' => 'drupal_get_form',
        'page arguments'=>array('clientform_step1'));

    return $items;
}

function clientform_step1($form, &$form_state){
    if(isset($form_state['values'])) {
        $currstep = $form_state['step'] + 1;
    }else {
        $currstep = 0;
    }

    $form_state['step'] = $currstep;
    $allsteps = getForm();
    $currform =  $allsteps[$currstep];

    return $currform;
}

function clientform_step1_submit($form, &$form_state){
    $form_state['storedvalues'][$form_state['step']] = $form_state['values'];
    if($form_state['step'] + 1 != getNumberOfSteps()) {
        $form_state['rebuild'] = TRUE;
    }else {

        //Reached end of multipage form

    }
}

```

# Answer
> 0 votes
You can set a "theme callback" in a menu declaration, but that would only work if you had some way to distinguish which page/step the user is on.

The only other way I can think of would be to have some if/then statements in your form that check for what step the user is on, and alter the form how you need.

# Answer
> 0 votes
just an idea:
what if you split you form in 2 forms
The first form will be composed of the first 2 steps
Then you create a Rule which, on Form1 Submission, Elaborates the data and redirect the user to the second form.

If you don't need extremely complex thing, this should work just fine. I used this strategy in one case and it worked nicely. Not to mention that it is very flexible and can be modified also by inexpert users.

---
Tags: views, 7, forms
---


# Question
Title: Drupal: showing different page layouts based on form data
I'm trying to build a multi step form. Before the second step I have to process the data inserted in step one and display different layout and form fields based on the results.

I use "drupal\_get\_form" callback in \_menu hooks to display the form, but I think I have to use a different approach, because I can't find a way to specify a template and\or HTML code this way.

What can I do? Thanks!

# Answer
> 0 votes
I think you should try ctools multistep wizard to generate the multi step form in Drupal. To start with Ctools wizard form a great example is given at the following link http://internetdevels.com/blog/ctools-multistep-wizard-example

---
Tags: forms
---


# Question
Title: How to create user like drop-down filters for a custom module in admin side
Drupal 7 admin panel, when clicked on people, a form with drop-down filters is visible.

user filters http://www.imagesup.net/?di=914041271981

How can we create above filters in our custom modules ?

I have tried goggling, but when searched filter in Drupal, it returns text filters which replaces text.

I have a custom module in which list of items are show, I want to filter items based on different fields.

Any help would be appreciated, thanks !!

# Answer
Well you have 2 options:

1. Declare your custom tables with Views. This can be tricky, and take some trial and error, but gives more flexibility going forward.
2. Declare a custom page in your module (using hook\_menu). Then just build a form with the search options you want and build a query. See the Examples modules if you're not sure how to build a page.
> 0 votes

---
Tags: 7
---


title: Contextual Filters via Taxonomy

text:
# Question
Title: Contextual Filters via Taxonomy
I am in the process of creating a View for my Drupal site and I am attempting to add a contextual filter by Taxonomy so I've added the `Content: Has Taxonomy term ID (with depth)` filter and selected the `Specify validation criteria` option and selected the Taxonomy that I wanted to work with. I also used the filter value type of `Term name converted to term ID` yet when I attempt to preview the filtered elements, I get the no results behavior. What should I be typing to call the filtered elements correctly?

Atm, to provide a concrete example, I have tried `my_view/mississippi-river` to call all nodes tagged with the Mississippi River taxonomy term via hierarchical select. Again, this leads me to the no results behavior. Additionally, how would I call a child of the Mississippi River Taxonomy term? Any ideas?

# Answer
> 0 votes
Contextual filters are just the term. So in the contextual filter input box for the Views Admin you would put `mississippi-river` as an example. In addition to `Term name converted to Term ID` you want to be sure you check the box for `convert spaces to dashes` further down in the `specify validation criteria` or else "mississippi-river" will not be found because it's expecting a space and you're providing a dash.

For the parent/child filters you're trying to achieve look at Taxonomy Edge. The -dev release contains some contextual filters for "parents" and "children" of stuff.

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


# Question
Title: Override locale_block_view in custom module
In the locale.module file there is:

```
function locale_block_view($type) {
  if (drupal_multilingual()) {
    $path = drupal_is_front_page() ? '<front>' : $_GET['q'];
    $links = language_negotiation_get_switch_links($type, $path);

    if (isset($links->links)) {
      drupal_add_css(drupal_get_path('module', 'locale') . '/locale.css');
      $class = "language-switcher-{$links->provider}";
      $variables = array('links' => $links->links, 'attributes' => array('class' => array($class)));
      $block['content'] = theme('links__locale_block', $variables);
      $block['subject'] = t('Languages');
      return $block;
    }
  }
}

```

I would like to alter this function in my custom module. I've created a custom module named `custom` (module is enabled). I've tried to alter the function with this function : hook\_block\_view.

But when I do that it doesn't work:

```
function other_block_view($delta = '')
{
    die;
}

```

Nothing happens ... . The module works because `hook_block_view_alter` works. But I need to change the $links variable in that other function .. .

# Answer
> 0 votes
I've fixed it like this:

```
function theme_links__locale_block(&$variables) {
    $links = array();

    foreach($variables['links'] as $link)
    {
        $link['title'] = $link['language']->language;
        $links[] = $link;
    }

    $variables['links'] = $links;

    $content = theme_links($variables);
    return $content;
}

```

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


title: WSOD with Devel module

text:
# Question
Title: WSOD with Devel module
A website I am working on is having a WSOD problem, but only on the permissions page. I narrowed this down to the devel module, because when enable, WSOD permission page, devel module unenabled, clean permission page. Any idea what is causing this?

# Answer
> 1 votes
The solution to this problem was to un-enable the Devel module, uninstall the Devel module, clear the cache, and rebuild permission, then re-enable the Devel module. Not sure that clearing the cache and rebuilding permissions was necessary, but this solution did allow the Devel module to be enabled and view the permission page.

---
Tags: users, debugging
---


title: Panels with multiple rows?

text:
# Question
Title: Panels with multiple rows?
I've got a Node/Page Panel that consists of 2 columns. What I would like to do is to have 2 rows/sections in one of the columns. I haven't found that option in layout designer, only to have a section on each side of the already existing column.

Have I missed something here?

# Answer
Just put extra panes in the column you want extra content in. Row span is something that went the way of the table ;)

If you really have to have panel sections use mini panels to add a panel with two rows within your panel with two columns.
> 0 votes

---
Tags: nodes, panels, 7
---


# Question
Title: I would like to create a view where I can add tags to content
I am pretty new to Drupal and have not created a module yet. I think the solution I am looking for will have to be a custom module and would like some tips on how to get started. Basically I have a content type of beverages. In that content type I have a term reference field that points to a term called featured. Basically I can check the Featured check box and that content will be displayed in a featured slider. The featured beverages need to be changed periodically. I would like to create a view that lists all of the beverages and from within the view I can change which ones are featured. Can anyone help me with at least a starting point on how to accomplish this? I am using Drupal 7

# Answer
First off, if all you need is a check box on your node form which toggles something as on or off - basically, a "Featured" state in this case - using taxonomy to achieve this is overkill. All you really need is an instance of a "Boolean" field.

Second, you can use Views Bulk Operations to operate on the results of a View. Basically, you can create a View with a column of check boxes much like the default content list in Drupal core. You can check a list of items - Beverage nodes in this case - and then select an operation to apply to the items you've checked. So yes, you'd need a custom module - a fairly simple one which would define "Make Featured/Unfeatured" actions, then implement callbacks to programmatically set/unset the "Featured" values on the selected nodes. See the VBO development guide for instructions on how to implement this.
> 1 votes

---
Tags: 7, hooks
---


title: Memory Exhausted after Drush install

text:
# Question
Title: Memory Exhausted after Drush install
I've made a drush install of drupal 7.28 on my AWS server. I can confirm that the memory is set to 128M, all green on the reports -\> site status page. The website will function normally and sporadically return no data, looking at the logs a tremendous amount of memory is trying to be allocated (assuming an infinite loop somewhere). Given that this is a basic install, no modules have yet been added what might be causing this?

```
PHP Fatal error:  Allowed memory size of 134217728 bytes exhausted (tried to allocate 140008587493184 bytes) in Unknown on line 0

```

# Answer
> 4 votes
Note that Drush and Drupal use different php.ini files. This behavior is inherited from php, which allows for different configuration for commandline tools vs. web servers, so that your web server can be more locked down than your dev tools.

Use the `drush status` command to see the path to the php.ini file that Drush is using.

Use the `drush status-report` command to see the commandline equivalent of the reports -\> site status page. This will show you the real memory limit that is set for Drush.

Odds are, all you will need to do is change the memory limit setting in the php.ini file that Drush is using, and all will be well.

---
Tags: 7, drush
---


# Question
Title: Current Password issue for New Register User
My registeraion is set to "Require e-mail verification when a visitor creates an account" on Drupal 7. Any user who register will automatically receive a confirmation email with "One time login url". However the problem is, user does not have the "Current Password" to set their new password. How can I fix this?

**PS: user does have current password on database "users" table**

**added info:**
**using module logintoboggan**

---

**added on July 2nd:**
I found a similar issue from Durupal.org, but i dont wanna use another module to solve this issue.

# Answer
> 0 votes
with the one time login the user is logged in automatically and he can set the password without inserting the current one.

---
Tags: 7, users
---


# Question
Title: What is the best method to allow a user to attach dynamic, custom content sections to a node?
I am looking for a recommended approach for a customization in Drupal I am building.

The desired workflow: A user will be able to attach N number of custom content sections (CCS) to a node. A user will be able to select the type of CCS (see example below), customize it, and arrange it's order amongst all other CCSs attached to a specific node.

Example CCS: Enter in the URLs for several Flikr images and the site outputs this as a nice gallery.

I know how to build the individual functionality for each CCS, but I'm wondering if there is any approach you would recommend for the broader functionality.

# Answer
Looks like the answer was the excellent Field Collection module for D7. This let me create a collection of fields that could be repeated (like one collection is a title (text, x1) and image (file, n times).

You assign the fields in the collection to have the limits you want (only 1, unlimited, etc), and then you assign the collection to the content type, can you can define how many collections can be attached.
> 0 votes

# Answer
looks like you need to use comments module for it, you will modify comments by adding more fields to it (for rating etc), then you can attach unlimited such content to your node. if you're in D6 you need to convert your comments to node (using some module) and then add more fields to it by CCK, and if you're using D7 you can attach fields directly (i guess - b/c its entity now)
> 0 votes

# Answer
Another solution in D7 would be to add textarea field to your node and enable unlimited values to it, in this way your node's field will hold multiple unlimited instances of your text/section. May be you might need to create your own field type to add a rating dimension to it (b/c you also want to sort the content section)
> 0 votes

# Answer
## 1. Option: Paragraphs

Check out Paragraphs module.

> Instead of putting all your content in one WYSIWYG body field, your content will exist of a paragraph field containing multiple paragraph items. Paragraph items can contain multiple fields and have different types of field sets(bundles),

You create a few paragraphs bundles with fields, and then add one paragraphs field to the page content type.

## 2. Option: Nestedbox + Inline entity form + Entity reference

An alternative to Paragraphs is Nestedbox in combination with Inline entity form. There is an issue discussing the differences to Paragraphs.

Nestedbox itself just defines an entity type. You could use regular nodes or any other entity type instead. but the benefit of nestedbox is that this entity type has no other side effects.

## 3. Option: Bean + Inline entity form + Entity reference.

Instead of the nestedbox entity type, some people might prefer Bean for the entity type. The downside is that every bean is also a block, so it would spam the form at admin/structure/block.

The benefit is that you can reuse the same bundles definitions.

## Common techniques with all these options

Field types that are very useful in paragraphs / nestedbox (besides the basic field types):

* Block reference to embed blocks.
* View reference to embed views displays.
* The paragraphs field type itself, which allows you to embed paragraphs within a paragraph. E.g. for a multi column layout.
* Or instead, the entityreference field type, allowing you to embed nestedbox entites within a nestedbox entity.

For the paragraphs or nestedbox display you can use Display suite. You can create custom layouts to achieve e.g. multi-column sections. Field formatters are also a thing you should play with. And Field templates are awesome.

You can export paragraphs and nestedbox and bean bundles with Features, so you can reuse them on another site.
> 0 votes

---
Tags: 7, nodes
---


# Question
Title: how to connect android app to drupal database?
I have a Drupal Site with content. I now want to make an Android App. Obviously, I would like Android App to access my Drupal site database - has anyone tried this?

From what I have read (from Google), it seems that I could use something like the phonegap module, or the Services module.

Am I on the right path? Are there other modules/tools/features I should be researching?

# Answer
> 1 votes
Here is a module that will help in this venture, for Drupal 6.x and 7.x sites:

DrupalGap

It leverages PhoneGap (Cordova), Drupal + Services + Views Datasource (Views JSON). It provides a starting point for creating multi platform (Android, iOS, etc) mobile applications for Drupal websites.

# Answer
> 1 votes
One possible approach would be to make a view and output data as JSON (If you only need to get data from the drupal website) . For that , this module might be handy.

```
https://www.drupal.org/project/views_datasource

```

There can be other methods as well, but if you only need to read data, then above module is a life saver!

# Answer
> 0 votes
Yes You are on the right path what you can do with Phonegap and DrupalGap module is

1) Drupal Authenticaiton 2) Add Content (By Default Article Content Type) 3) View Articles

This are the basic functionality so far Provided By PhoneGap and DrupalGap modules

To work with this you will require following

1) JDK(6) 2) Eclipse 3) ADT(For Developing Android apps) 4) Set your Enviornment variable from the following links http://docs.phonegap.com/en/2.2.0/guide\_getting-started\_android\_index.md.html#Getting%20Started%20with%20Android

Open Eclipse and create new android project and paste the code provided from this link into asset directory http://code.google.com/p/drupal-phonegap/downloads/list so the final path will be assets/www/ and run as android project i better advice you to dnt use emulator instead copy apk file from your project/bin directory and run on your own android Enjoy !!!

---
Tags: theming, mobile-tools
---


# Question
Title: Switch to admin theme based on path using hook_init() or template.php in Drupal 7
I'm running a site that uses a separate admin theme. I'd like to include a couple additional pages that use the admin stylesheets. How can I apply the theme selectively to these pages. I'd rather do this in hook\_init() or template.php. I don't want to add any more contrib modules to the site at this point. Thanks for any illumination.

# Answer
The Administration theme module will do it, but given you'd like to do it yourself, it does cast some light on that path by suggesting the `hook_admin_theme_check()` and `hook_admin_theme_info()` hooks.
> 3 votes

# Answer
You can use the module Administration theme for that but if you just want to use the admin theme for a single path you can define it in hook\_init

```
/*
 * Implements hook_init().
 * Use the admin theme on path 'batch'
 */
function MODULENAME_init() {
  if (arg(0) == 'batch') {
    global $custom_theme;
    $admin_theme = variable_get('admin_theme', 'garland');
    init_theme();
  }
}

```
> 0 votes

# Answer
If you don't want to enable more modules (like the admin\_theme module), and prefer to write a few lines of code to achive the same thing, you can use hook\_custom\_theme().

e.g. This snippet switches the user to the admin theme when they're viewing the revision comparison report from the diff module.

```
function MODULENAME_custom_theme() {
  global $conf;
  $args = arg();

  // Set the admin theme when viewing a diff comparison with the diff module.
  if (isset($args[3]) && $args[3] == "diff") {
    return array($conf['admin_theme']);
  }
}

```
> 0 votes

---
Tags: 7, theming
---


# Question
Title: Only admin can see products page for Drupal Commerce
I created a subscription product with Drupal Commerce and commerce\_sp modules. I then created a view to display the product subscription I want and as Administrator I can see the product on the product page just fine, but as an authenticated user the page is available to view via a link in a menu, but the page doesn't show the list of products, just white space. I've gone into the permissions to make sure the user can purchase an item and go through the check out forms, and the view has no access control on it.

I'm pulling my hair out over this, I have no idea why no one but the admin can see the products listed on the page.

# Answer
Go to Admin menu \> People \> Permission:
Check 'Authenticated User' for:

1. 'View any product of any type' from 'Product' group
2. 'Access checkout' from 'Checkout' group
> 1 votes

---
Tags: users, commerce, notifications
---


# Question
Title: Anonymous Flag with boost module enabled
I have a node type which allow anonymous to use flag (Non global flag).

The problem is with Boost enabled, all anonymous users have the same flag status at the cached page.

For eg, anonymous A Bookmarked a node and the page get cached, when anonymous B visited the page she has the Bookmarked status as well which is undesirable.

How should i update the flag status by user?

Any suggestions are welcome!!

# Answer
I'm not too sure, but you'd need to look into how Flag is handling the anonymous user session cookies. You may have to hack the code to add your own user-id and add it to the cookie...
> 0 votes

---
Tags: 7, flags, caching
---


# Question
Title: How can I configure CKEditor to show content in 'plain text editor'?
I would like to configure my `CKEditor` to show content that I edit in `plain text editor` by default as I have some widgets on my site (e.g. Twitter) that get removed by `CKEditor`'s rendering to rich text - how can I avoid that?

Thanks!

# Answer
Assuming Drupal 7 - goto admin/config/content/formats and change the order of the text formats, placing Plain Text at the top of the list. This will default the edit format, however content that is already created would default to whatever format was used to create it in the first place.

This will however filter quite restrictively the output. If you mean to include a text format that does not perform any formatting at all, on the same page, you can 'Add Text format', label it unaltered or whatever title you prefer, set roles to administrator (very high security risk with giving this format to untrusted persons), and leave everything else blank. This will create an unaltered format which allows things like direct html, javacript and php writing in blocks, etc.
> 1 votes

---
Tags: wysiwyg, entities
---


# Question
Title: Best Method to Separate Drupal Website from Customized Scripts
I currently have 2 small cloud servers: (1) database server; (2) web server.

The web server hosts my Drupal 7 website plus a lot of continually running scripts that process data and hook into Drupal's API functions (e.g. node\_save, taxonomy\_term\_save).

I would like to split up my web server into two servers so that now I have 3 servers: (1) database server; (2) Drupal website server; (3) data processing server.

Since my custom scripts tie into Drupal's API functions, I am not sure how to actually run these scripts from a completely separate server without essentially cloning the web server and just blocking public access to the website on the data processing server.

Any ideas would be greatly appreciated! Thanks!

# Answer
There's no way to use Drupal Apis from a separate server. Your best bet would be to use the web service module and process your request via json.

You'll have to do more work but on second hand, you'll end up with a nifty setup that'll allow you to leverage many other frameworks such as angularjs, backbone, and even mobile development.
> 1 votes

---
Tags: 7
---


title: Remove classes from field display

text:
# Question
Title: Remove classes from field display
When fields are rendered they have classes. For example here is the template for a taxonomy term reference field:

```
<div class="<?php print $classes; ?> clearfix"<?php print $attributes; ?>>
  <?php if (!$label_hidden) : ?>
    <div class="field-label"<?php print $title_attributes; ?>><?php print $label ?>: </div>
  <?php endif; ?>
  <div class="field-items"<?php print $content_attributes; ?>>
    <?php foreach ($items as $delta => $item) : ?>
      <div style="display:inline;" class="field-item <?php print $delta % 2 ? 'odd' : 'even'; ?>"<?php print $item_attributes[$delta]; ?>>
        <?php
          print render($item);
          // Add comma if not last item
          if ($delta < (count($items) - 1)) {
            print ',';
          }
        ?>
      </div>
    <?php endforeach; ?>
  </div>
</div>

```

In the first line you'l see `<?php print $classes ?>`, in that $classes string there are some classes and I don't want. Obviously I can use php to str\_replace in the tpl file to remove the classes I want, but that seems like a very wrong solution. What's the correct way to modify $classes?

# Answer
> 2 votes
You can implement `hook_preprocess_field()` in your `template.php` and remove the classes you want after checking the field name .

**Update:** As @tenken suggested you can also look into `Display Suite` module.

# Answer
> 1 votes
You can try to redefine theme function or catch and remove these classes in hook\_form\_alter (in some cases, classes are available only in after\_build function).

# Answer
> 1 votes
You can use either of this options

* **hook\_preprocess\_field()** in the **template.php** of your theme where hook is your **theme name**
* Creating a template file in your theme with the same code (that you have mentioned above) with your customisation in the html.

e.g. We have **user.tpl.php** in core folders, we can override it by putting this file in our theme folder with our changes.

---
Tags: entities
---


title: filter navigation, site content, etc

text:
# Question
Title: filter navigation, site content, etc
I am really new to Drupal, so this is a beginners question. I need to create a website with a dropdown within the header, where visitors can choose a region (not a language, just a region, like "Europe", "US", ...). The entire page should be filtered according to this selection, so if the visitor chose "US", some parts of the navigation or parts of the content should not be visible.

Is this possible with drupal?

And, more importantly: how would you go about this? The only thing I could think of is create a taxonomy for each "region" and assign content items and navigation items. Is that a good idea? Is there a better way to go?

I'd be thankful for any suggestion. Thank you.

# Answer
I'd try this link. So install that then apply some classes to the menu items that you can use in JQuery to target the links and have the dropdown links trigger them to show/hide. I'm willing to provide further explanation if there's something you're unclear of. Sadly there is no current module or plugin to provide this functionality that I know of.
> 0 votes

---
Tags: navigation
---


title: How can i remove and edit comment item

text:
# Question
Title: How can i remove and edit comment item
how to remove or edit comment item like `fieldset-wrapper`. just i want the form-type-select show and or edit description in `fieldset` wrapper. tnx for all

# Answer
> 1 votes
You will want to duplicate one of the files with extension .tpl.php in modules/comment directory and place the dup' in your theme. Then clear cache and edit the file you dup'd and placed in your theme.

The File you want is /modules/comment/comment.tpl.php

---
Tags: comments, forms
---


# Question
Title: Changing a dropdown based on another one
I've got a content type with a dropdown with some states. And I've got another list (radio buttons) which should change the dropdown based on the selected item. Is that somehow possible?

I've tried Conditional Fields, but that didn't do what I want. Maybe rules? I'm kind of newbie with Drupal.

# Answer
> 3 votes
If you want to do this hardcoded, you might try to use the #ajax property of the Form API

You can reload your second dropdown on change of the value of the first dropdown and change the value while reloading the form.

I made a little example to give you an idea :

```
$form['number'] = array(
  '#type' => 'select',
  '#title' => t('Select Number'),
  '#options' => array(
      0 => 1,
      1 => 2,
      2 => 3,
  ),
  '#default_value' => 0,
  '#ajax' => array(
    'callback' => 'ajax_replace_dropdown_default_value_callback',
    'wrapper' => 'wrapper-dropdown',
    'method' => 'replace',
    'effect' => 'fade',
  ),
);

$default_value = !empty($form_state['values']['number']) ? $form_state['values']['number'] : 0;

$form['open_closed'] = array(
  '#type' => 'select',
  '#title' => t('Open / Closed ?'),
  '#options' => array(
      0 => t('Open'),
      1 => t('Closed'),
      2 => t('Progress'),
  ),
  '#value' => $default_value,
  '#prefix' => '<div id="wrapper-dropdown">',
  '#suffix' => '</div>',
);

function ajax_replace_dropdown_default_value_callback($form, $form_state) {
  return $form['open_closed'];
}

```

In your case you will have to do it in a `hook_form_alter` and add the `#ajax property` to your first dropdown and add prefix and suffix to give the second dropdown the proper value.

You can also check this link about AJAX with the FORM API :

# Answer
> 0 votes
I've used a module before called Reference Option Limit. Basically you setup 2 fields as taxonomy term references (each with it's own taxonomy vocabulary), and then on each element of the second dropdown, you select which parent item it should show for. The only issue I ever had with it was it didn't always work for anonymous users if caching was enabled.

---
Tags: nodes, entities
---


title: Job Application

text:
# Question
Title: Job Application
I have a content type called "Job", that has fields for the job and an email field for the job contact. At the bottom of each job node there should be a button "apply now". If you click on the button, there should be a form with textfields, file upload (for the resumee) etc. If you send your application, an email should be sent to the job contact email (which is inside the job node).

What is the best way to achieve this? First I was thinking about using webforms, but I don't know how to get the job contact email form the node as the sendto webform email.

# Answer
> 1 votes
You can create two content types

1. Job
2. Job Application

In `Job Application`, where you have resume upload etc, add a `entity reference` field to `Job` content type.

Then when you list the `Job` and add a link `Apply Now` to create `Job Application`.

Use Entity Refernce Prepopulate module to prepopulate the entity reference in `Job Applciation` based on URL.

Here is good video tutorial expaining `Enity Reference Prepopualte` module.

# Answer
> 0 votes
That's one of the default webform behaviours. Create and save the webform. Then, within the node/%nid/edit page, go to Webform \> Emails and fill in your email there. There's no need to have the email as a separate field on the node.

---
Tags: nodes, forms, webforms
---


# Question
Title: How to add content type as a menu item child without displaying the link in the menu?
I recently found menu block module, which displays my submenu very nicely. Here's the menu hierarchy:

```
Home
About
News & events
-- News
-- Events
Contact

```

So when I go to the News & events page and from there to the News page the submenu displays just fine. But when I open a piece of news in the News page (which is a view displaying content from the News content type) the sub menu disappears. I'd like to show the submenu like the piece of news I just opened would be a child of News menu item. The problem is how to this without actually displaying all the news links in the menu. I know that there's a way to disable menu links but haven't found a way to disable them by default when adding new content.

What would be the best way to implement this kind of hierarchy?

# Answer
If your path aliases are something like, e.g., example.com/news/node\_alias, you could use the menu trail by path module. That way, you don't have to add the nodes to the menu to achieve this: the News item remains active on subpaths of /news/\*.
> 3 votes

---
Tags: uri, blocks, routes
---


# Question
Title: How to add active class to a specific menu only, while ignoring other menus?
I have 2 conflicting menus I need to solve by adding an active class to a targeted menu only, they are a user menu and a profile and account settings menu which have overlapping links.

1. User Menu (in the header section of every page):

* \[username\] (links to Profile2 page)
        + Account Settings (i.e. change password, etc.)
        + Log out
2. Profile and Account Settings menu (appears in the sidebar of the profile2 and account pages):

* View Profile (links to Profile2 page also)
    * Edit Profile
    * Account Settings (same link destination as "Account Settings" of User Menu)
    * Order History

Since I'd like to convey to my users that whenever they are in any page linked by the Profile and Account Settings menu (eg. Edit Profile)I tried using Context to set an .active class for "User Menu\>Profile", which worked.

However, now that "User Menu\>Profile" is active when I'm in "Edit Profile", since "View Profile" shares the same link destination as "User Menu\>Profile", both "View Profile" and "Edit profile" are have an .active class, which is very undesirable.

Hence, I would like to know, if there is a way to use Context or any hooks to set an .active class for the User Menu only when I'm in the "Edit Profile" page?

# Answer
> 2 votes
Try the following modules

1)Menu Position

> Often times site builders want certain types of content to appear in a specific position in the navigational menu. The simplest solution, adding all of that content individually to the menu system, has performance and usability issues. (Imagine hundreds of menu items added to one spot in the menu.)
>
> This module allows for the creation of rules that will dynamically add the current page into the menu system at the requested spots.

I've used Menu Position module for one of my project and it works great!

OR

2) Menu Trail By Path

> Menu Trail By Path sets the active-trail on menu items according to the current url.
>
> For example if you are at yoursite.com/blog/category1/article1 Menu Items with these paths will get the active-trail class on them and expand accordingly.
>
> blog
>
> blog/category1
>
> blog/category1/article1

---
Tags: theming, routes, 7
---


title: nginx rewrite for drupal

text:
# Question
Title: nginx rewrite for drupal
I have installed **Nginx** and I have a Drupal site installed in a sub folder. I also have a directory in `/drupalpath/sites/default/files/books/` that stored some PDF in it. I configure my nginx like this:

```
location /drupalpath {
    rewrite ^/drupalpath/(.*)$ /drupalpath/index.php?q=$1 last;
}

```

and it works nice. But my problem is that the PDFs in `/drupalpath/sites/default/files/books/` affected this rule and when I click to download my books it send 404 Error because this rule. My question is that how to fix it?

# Answer
> 1 votes
```
location ~ \.pdf$ {
  try_files $uri =404;
}

```

---
Tags: 7, uri
---


# Question
Title: How to add section titles to group fields in content type input form used to create content?
Is there a module or setting to provide a title to sections of the content type input form used to create content?

For example - a job application form would have sections:

Section Title: Your Details \- Name \- Address

Section Title: Previous Employment \- Employer etc

Section Title: Qualifications

Happy to consider writing a custom module to output HTML and CSS to do this but wondered if there was a module or setting.

I'm currently using display\_suite to do some layout design of the form in-browser.

(I've done some research and have seen https://drupal.org/project/multistep module but I would prefer all the sections on one page at the moment, that module may be useful for something else, though. Also aware of https://drupal.org/project/field\_group which I expect to use but not sure if it provides titling above the field group).

# Answer
Field Group module is best solution. It will allow you titling above the field group.

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

---
Tags: 7, theming, forms
---


# Question
Title: Custom block won't display in admin - Drupal 7
I am running into an issue where my block won't show up in the admin section of my site. I've added it to `example_block_info()` where the other existing blocks are declared. I've also added content in `example_block_view()`:

```
/*block_info*/

$blocks['example'] = array(
    'info' => 'Example',
    'status' => TRUE,
    'visibility' => BLOCK_VISIBILITY_LISTED,
    'pages' => 'example/1*',
            'cache' => DRUPAL_NO_CACHE
);

/*block_view*/

switch($delta){

...

    case 'example':
        $block['content'] = '
            //content
        ';
        break;

}

```

Am I missing something? All the other blocks show up and work fine. I can modify them as well. This one doesn't work/show up.

# Answer
> 1 votes
Try the next code below, it work for me:

```
/**
 * implements hook_block_info().
 */
function mymodule_block_info() {
  $blocks['hello-message'] = array(
    'info' => t('Message'),
    'status' => TRUE,
    'visibility' => BLOCK_VISIBILITY_LISTED,
    'pages' => 'example/1*',
    'cache' => DRUPAL_NO_CACHE,
  );

  return $blocks;
}

/**
 * implements hook_block_view().
 */
function mymodule_block_view($delta = '') {
  $block = array();

  if ($delta == 'hello-message') {
    $block['subject'] = t('Message');
    $block['content'] = t('Hello World!');
  }

  return $block;
}

```

See https://api.drupal.org/api/examples/block\_example%21block\_example.module/7

---
Tags: 7, blocks
---


title: Custom Validation on Address Field

text:
# Question
Title: Custom Validation on Address Field
In addition to the validation that already takes place using the addressfield module, I'd like to check for (and fix) items like:

* Building to Bldg
* Room to Rm
* Circle to Cir
* Avenue to Ave

Is there a module that would do this? Is this best done with a custom module or using JavaScript?

Any chance that this module might be helpful? https://www.drupal.org/project/field\_validation

# Answer
> 0 votes
Don't use JavaScript validation because some people can disable JavaScript in the browser and you're validation will fall!

If you want custom validation will be better if you will use additional validation for your form (custom code)

---
Tags: entities, javascript
---


title: Body field data disappeared

text:
# Question
Title: Body field data disappeared
EDIT: Looks like I accidentally changed number of values for this field to 1 - it should be Unlimited. It's working now, thanks everyone.

I don't know what I did but I noticed that all (except the first one) body field data in all the nodes disappeared - they're not even available in editor.

All the data is still in DB (in field\_data\_body table) but it's not showing on website.

I have no idea how to fix this, has anyone had the same problem?

# Answer
> 0 votes
See permission for this field.

In the admin section: /admin/people/permissions

# Answer
> 0 votes
Also need to check the input format permissions here -

For Full HTML admin/config/content/formats/full\_html

For Filtered HTML admin/config/content/formats/filtered\_html

For Plain Text admin/config/content/formats/plain\_text

---
Tags: 7, nodes, entities
---


# Question
Title: A view where a user doesn't have a certain content type
I am trying to create a view where a user doest have a certain content type.

Say for instance I have content types A, B and C and I only want to return results to show users who don’t have content type A but could have B or C.

I have created a view for (users) and linked it to the content authored. I have played about a bit but haven’t managed to find the correct filters. Can anyone help??

Many thanks

David

# Answer
> 0 votes
I am pretty sure what you need to do is set in the access permissions of the view to be permission: Publish Content

# Answer
> 0 votes
You could add all content types. If the user doesn't have that content type, they will not see output anyway.

# Answer
> 0 votes
You can do it in one of the following ways.

1. Implement `hook_views_query_alter()` and alter the query to add the where clause.
2. Or, Install `Flag` module
    * Create a user flag called `Reviewer`
    * Create a rule
        + Add a event : Content type `Review` is saved.
        + Condition : User is not flagged
        + Action : Flag the user
    * Now create your view and add relationship with `Flags` and add a filter `User is not flagged`
3. Similar to step 2, but instead of flag assign a new role, reviewer, and in your view add a filter to check user does not have that role.

---
Tags: views
---


# Question
Title: What hook gets called at the formation of a form? (hook_form_alter called for adjusting a form)
what hook gets called at the formation of a form.

I'm trying to add some additional mime types to form with id file\_entity\_add\_upload but my hook\_form\_alter is getting called after these are validated, so attempts to upload them fails.

**Update** \- added screenshot to illustrate the problem

**Update 2** the mime types list in file\_entity\_get\_upload\_validators function in file\_entity.pages.inc dictates what can be uploaded - see this screenshot

Specifically, in, file\_entity\_get\_upload\_validators, the line that populates the valid mime types with hard-coded values is (my screenshot didn't completely show the line): `$validators['file_validate_extensions'] = array(variable_get('file_entity_default_allowed_extensions', 'jpg jpeg gif png txt doc docx xls xlsx pdf ppt pptx pps ppsx odt ods odp'));`

**Update 3**

It would appear that the actual checking of the mime type happens in core module "file", `modules/file/file.js` : `if (!acceptableMatch.test(this.value)) {
 var error = Drupal.t("The selected file %filename cannot be uploaded. Only files with the following extensions are allowed: %extensions.", {` I searched the error message shown in following screenshot in the code and file.js was a result - which looks like where the actual validation is taking place.

New error with Andy's answer - maybe it's me will look into it a little later.

Raised as an issue here: https://www.drupal.org/node/2295671

# Answer
`file_entity_add_upload` is a three step form for uploading files when you have fieldable files.

```
function file_entity_add_upload($form, &$form_state, array $options = array()) {
  $step = (isset($form_state['step']) && in_array($form_state['step'], array(1, 2, 3))) ? $form_state['step'] : 1;
  $form['#step'] = $step;
  switch ($step) {
    case 1:
      return file_entity_add_upload_step_upload($form, $form_state, $options);
    case 2:
      return file_entity_add_upload_step_filetype($form, $form_state, $options);
    case 3:
      return file_entity_add_upload_step_fields($form, $form_state, $options);
  }
}

```
1. Upload the file (validates extensions);
2. Choose the file bundle (based on bundle mimetype associations);
3. Fill out fields attached to that bundle.

As the extensions are validated in step 1, examine `file_entity_add_upload_step_upload()`. Of particular interest is the actual managed file element.

```
$form['upload'] = array(
  '#type' => 'managed_file',
  '#title' => t('Upload a new file'),
  '#upload_location' => file_entity_upload_destination_uri($options),
  '#upload_validators' => file_entity_get_upload_validators($options),
  '#progress_indicator' => 'bar',
  '#required' => TRUE,
  '#pre_render' => array('file_managed_file_pre_render', 'file_entity_upload_validators_pre_render'),
  '#default_value' => isset($form_state['storage']['upload']) ? $form_state['storage']['upload'] : NULL,
);

```

The validators are added using a non-standard property `#upload_validators` to set the file validation callbacks *and their arguments*. In the form alter we can completely overwrite `#upload_validators` or just modify it, and that will affect the file's validation as you'd expect. However if you look in `file_entity_get_upload_validators()`:

```
if (!empty($options['file_extensions'])) {
  $validators['file_validate_extensions'] = array($options['file_extensions']);
}
else {
  $validators['file_validate_extensions'] = array(variable_get('file_entity_default_allowed_extensions', 'jpg jpeg gif png txt doc docx xls xlsx pdf ppt pptx pps ppsx odt ods odp'));
}

```

You can see that the variable `file_entity_default_allowed_extensions` is used to specify which extensions to use by default (unless it's overridden by `$options`).

The `managed_file` element itself passes the extensions to JS for client-side validation in `file_managed_file_process()`:

```
// Add the extension list to the page as JavaScript settings.
if (isset($element['#upload_validators']['file_validate_extensions'][0])) {
  $extension_list = implode(',', array_filter(explode(' ', $element['#upload_validators']['file_validate_extensions'][0])));
  $element['upload']['#attached']['js'] = array(
    array(
      'type' => 'setting',
      'data' => array('file' => array('elements' => array('#' . $element['#id'] . '-upload' => $extension_list))),
    ),
  );
}

```

As you can see from pcambra's neat illustration, processing happens after form alters are called, so any modifications you make will affect both client-side and server-side validation.

So to make a global change modify the variable `file_entity_default_allowed_extensions`: I'd suggest using drush or a `hook_update_N()`.

To modify a subset of forms you can use a form alter. Here's an example:

```
/**
 * Implements hook_form_FORM_ID_alter() for file_entity_add_upload.
 *
 * Modifies the allowed extensions.
 */
function MYMODULE_form_file_entity_add_upload_alter(&$form, &$form_state) {

  // Check this is the file selection step.
  if ($form['#step'] != 1) {
    return;
  }

  $form['upload']['#upload_validators']['file_validate_extensions'][0] = 'png bmp';
}

```
> 2 votes

# Answer
There's this brilliant image on the Form API Internal Workflow in drupal.org, you can see the build process and structure. You've got callbacks such as #process and #after\_build that could be useful for your use case.
> 5 votes

---
Tags: 7, forms
---


title: Hook user register action

text:
# Question
Title: Hook user register action
How to hook user registration page? Basically I want to save some cookies when user comes on the register page through an affiliate link. I used `hook_user_view` but it is working only when user is logged in. Can someone please tell me how to do that?

# Answer
> 4 votes
Implement `hook_form_alter()` and check `$form_id == 'user_register_form'`

---
Tags: 7, hooks
---


# Question
Title: Feeds is not importing images into subfolders
I'm trying to import external nodes from html pages. all working fine but i just cannot make image getting saved in a subfolder.

am mapping a uri value "public://posts/2014/03/4587214.jpg" to "image:uri" and i want the file to be saved in "sites/default/files/posts/2014/03/4587214.jpg" but the file is getting saved in "sites/default/files/posts/4587214.jpg" instead . ("posts" is the value of the subdirectoy in the content type)

any advice on how to make feeds save images in subfolders ? (and create these on fly if do not exist)

i can do it by hacking "feeds/mappers/file.inc" and changing the value of $destination variable as follows:

```
case 'uri':
if ($v) {
try {
/* patch - start */
/* added to allow subfolder destination */
$uri = $v->getValue();
$uri_target = file_uri_target($uri);
$uri_scheme = file_uri_scheme($uri);
$uri_path_info = pathinfo($uri_target);
$destination = file_stream_wrapper_uri_normalize($uri_scheme . "://" . $uri_path_info['dirname']);
/* patch - end */
$file = $v->getFile($destination);

```

but i was wandering if this can be done without hacking feeds source files

# Answer
> 1 votes
My solution to a similar problem was installing FileField module and in the content type design, put the attached files (as images in the example) in a structured folder by tokens.

This way, when feeds grab the image and attach to node, file\_fields module gets the task and put the image into a folder as you mention by design.

It's also helpful when you add single content, not bulk import operations.Everything organized just as you plan.

---
Tags: feeds
---


title: Autopost is not working

text:
# Question
Title: Autopost is not working
I want to autopost the contents in facebook.I installed Drupal for Facebook module and created Apps in facebook.

In this,the user can connect facebook.But the content doesn't get autopost. I got an error like this

"Something went wrong while posting update to your facebook wall. The error has been captured by watchdog".

How to clear this error.

# Answer
> 0 votes
Your error says your application has been deleted. Go to https://developers.facebook.com and check your application under the "Apps" tab. If the app exists, check that your oauth details (on the drupal site) match. If the app doesn't exist, create an app (also under the "Apps" tab) and validate against that in your Drupal site's oauth settings.

---
Tags: social-network
---


# Question
Title: How to duplicate a line item in shopping cart programmatically
At certain point in the checkout process I'd like to seperate line items with quantity more than one into individual line items with quantity 1.

So for example if I have a line item in cart with quantity 5, I'd like to create 4 new line items just like the original one, add them to the cart with quantity 1 individually.

I tried cloning the line item entity into a new variable and use commerce\_line\_item\_save() with it, but it doesn't work.

Does anybody know how to achieve something like this from a module?

Thank you!

# Answer
You can clone a line item and save it without any problems:

```
$cloned_line_item = clone($line_item);

```

But if what you want is to add it back to the order, you'll probably want to call commerce\_cart\_product\_add to add your line item back to your order:

```
commerce_cart_product_add($uid, $line_item, FALSE);

```

Be careful with setting the combine options correctly if you don't want your line items to be aggregated.

```
$line_item->data['context']['add_to_cart_combine']

```

**Update**: Adding more details on the combine part.

**In case you don't want to combine any line items for that product type:**

Be aware that the combine options are at formatter level for the add to cart button, so you need to set them **everywhere** you're using this formatter, in manage display settings for **all your view modes**, in views... the configuration is not shared. This is very important as there might be hidden places you forgot to configure (if I had a penny every time I forget to configure this in "Teaser", i.e....)

**In case you want to combine some times and others not:**

The function `commerce_cart_product_add` above has a combine parameter to make Drupal Commerce try to combine or not and add a new element to the cart or just increase the quantity of an existing one. On top of that, there's something called **comparison properties**, by default these are all the fields that the line item has:

```
foreach (field_info_instances('commerce_line_item', $line_item->type) as $info) {
  if (!empty($info['commerce_cart_settings']['field_access'])) {
    $comparison_properties[] = $info['field_name'];
  }
}

```

So one way you've got to hook into this process is `hook_commerce_cart_product_comparison_properties_alter` to define more comparison properties.
> 4 votes

---
Tags: 7, commerce
---


title: Make a custom view mode default

text:
# Question
Title: Make a custom view mode default
I made a custom view mode in Display Suite and I would like to use it as the default view mode for a given content type. Can anybody enlighten me as to how to do it?

# Answer
This is the way i set the 'fullpage' view\_mode of a node as default:

```
<?php
/**
 * Implements hook_entity_view_mode_alter().
 */
function YOUR_MODULE_entity_view_mode_alter(&$view_mode, $context) {
  // Set default view mode.
  if (isset($context['entity']->nid)) {
    if ($context['entity_type'] == 'node' && $context['entity']->type == 'YOUR_CTYPE' && $view_mode == 'full') {
      $view_mode = 'fullpage';
    }
  }
}

```

It actually sets the view\_mode to 'fullpage' when in full mode (default), but you could ommit that part (&& $view\_mode == 'full').

Remember that 'fullpage' is the machine name of my view\_mode and 'YOUR\_CTYPE' is the machine name of your content type.

Not sure if this will work with Display suite though...
> 1 votes

---
Tags: theming, entities
---


# Question
Title: Change list of values dynamically with a click
I realize my request is a bit complex, I hope someone can answer.

I have a drupal 7 clean installation. I have a node type called `Whole` and another one called `Piece`. A `Whole` contains one to many `Piece`: I used the Entity module (with Entity reference) to link entities. The `Piece` node has a boolean field called `selected`.

When a user views a `Whole` node he can see all the `Piece` elements linked to it.

I need to allow an unlogged user to set the `selected` field of the `piece` node to `true` without leaving the `Whole` node page. I also need to keep track of the selected `Piece` elements (maybe in a session variable?). In the end I need to list all the `Pieces` altered in the session to compose a mail. When the mail is sent the session is cleared.

Is there a module that allows in place edit of node attributes?? I have installed and tried `Editable Views`, but it doesn't work. Maybe there is a conflict with my drupal version (7.14) which unfortunately I can't change.

# Answer
You don't need to let anon visitors edit nodes to achieve this, and I wouldn't recommend it. It presents a security issue, and would store the "selected" status as a property of the node (for all visitors).

Rather, you can store the selected nodes in a session or a cookie, using a standalone drupal form. Create a form, like so:

```
function YOURMODULE_node_store_form($form, &$form_state, $nid) {
  $form_state['nid'] = $nid;
  $dv = (isset($_SESSION['node_store'] && in_array($nid, $_SESSION['node_store']) ? 1 : NULL;
  $form['selected'] = array(
    '#type' => 'checkbox',
    '#title' => 'Include this page in email.',
    '#default_value' => $dv,
  );
  $form['actions']['submit'] = array(
    '#type' => 'submit',
    '#value' => 'Submit',
  );
  return $form;
}

function YOURMODULE_node_store_form_submit($form, $form_state) {
  if($form_state['values']['selected'] && $form_state['nid']) {
    $_SESSION['node_store'][] = $form_state['nid'];
    drupal_set_message('The page will be included in the email.');
  }
}

```

In the template file for the Piece content type, add the form to the teaser display, like so:

```
<?php print render(drupal_get_form(MYMODULE_node_store_form, $node->nid);) ?>

```

To include the stored nodes in the mail, you can retrieve them from the $\_SESSION\['node\_store'\] array. Once the email has been sent, you should probably clear the $\_SESSION\['node\_store'\] array.

If you DO have to store it to the node, use the node\_save function in your submit handler, instead:

```
function YOURMODULE_node_store_form_submit($form, $form_state) {
  if($form_state['values']['selected'] && $node = node_load($form_state['nid'])) {
    $node->field_selected[$node->language][0]['value'] = 1;
    node_save($node);
    $_SESSION['node_store'][] = $node->nid;
    drupal_set_message('The page will be included in the email.');
  }
}

```
> 2 votes

---
Tags: entities, nodes
---


# Question
Title: Let a webform know fropm which page are users coming from
I am developing a Drupal 7 site, with an Omega sub-theme, panels, and views. On every product page, I have a link to a webform. I need the webform to know from which page the customer is coming from.

Is there a specific Drupal way for doing this?

# Answer
You will probably want to use the Prepopulate module, if you are trying to pre-fill the webform with arguments from the URL.

There are probably several ways how to do this, but the first thing which came to my mind was to add a view block which can be shown on your originating content type and that will be used to create the link with the node ID for your webform to process.

>

This is very simple with a view, where you only need to add two fields and then place the block in a theme region. The first field you need is the *Content: Nid* field and exclude it from the display. Then you will add *Global: Custom text* and write the form URL (it must be configured when creating the webform), the field name as key and the *\[nid\]* token as the value in the URL.

*field\_form\_house\_er* is a webform field which has been set to prepopulate from the URL.

A contextual filter must be added to the view to pass the node ID to the block using the *Content ID from URL* option from *Provide default value*.

After saving the view, it can be placed in a theme region. It will create the link every time a node is viewed.
You will probably need different webforms for different content types. With generic settings, this setup will work with any content type if you have set up the webform to allow any content type to be selected.
> 1 votes

# Answer
On you link display something like this :

```
$current_path = current_path();
$current_path_alias = drupal_get_path_alias($current_path);
print url('my-webform', array('query' => array('from' => $current_path_alias )));

```

If you are on content/mynode, the link will display my-webform?from=content/mynode. If you want just the unaliased path skip the use of `dupal_get_path_alias()`

```
$current_path = current_path();
print url('my-webform', array('query' => array('from' => $current_path)));

```

If you are on node/18, the link will display my-webform?from=node/18.
> 1 votes

---
Tags: 7, webforms
---


# Question
Title: How to change title of profile-profile2_machine_name only, but not profile-profile2_machine_name/%user
I'd like to change the title of my profile-profile2\_machine\_name page, but not the page profile-profile2\_machine\_name/%user page.

This is because I have a settings menu for each user in my profile-profile2\_machine\_name page and it's a private profile page, while profile-profile2\_machine\_name/%user is the public profile page.

I've tried many things but when using `arg`, `drupal_get_path_alias()` and `$_GET['q']`, I see that both pages return the same value, which is profile-profile2\_machine\_name/%user

# Answer
> 1 votes
I think this module will do what you need. I have used it on a few projects. It works. And I think it supports wildcards. Also it says it supports tokens.

---
Tags: 7, theming, users
---


# Question
Title: How to make language choice Required for Taxonomy term
Is there any way to make the language choice required for taxonomy term.

I'm pretty sure there is a way to perform this.

Otherwise, how can I at least set a default language choice for my taxonomy. By exemple, I would like to make English as default language. That's mean when the user will create a term the first time, the language choice will be english.

Thanks a lot

# Answer
> 1 votes
Write a custom module and use the following code

```
function MYMODULE_form_alter(&$form, &$form_state, $form_id){
  if($form_id=='taxonomy_form_term'){
     $form['#after_build'][] = 'MYMODULE_after_build';
  }
}

function MYMODULE_after_build($form, &$form_state) {
   if($form['language']['#value']=='und'){
     $form['language']['#default_value']='en';
     $form['language']['#value']='en';
   }
   return $form;

```

}

**NOTE: In your custom\_module.info file use this `dependencies[] = i18n_taxonomy`, so that your module can only be enabled if internationalization is enabled**

---
Tags: taxonomy-terms, i18n-l10n
---


title: display a taxonomy as an image

text:
# Question
Title: display a taxonomy as an image
Hi Im using taxonomies for categorize my products with drupal commerce, Im using "Brand" vocabulary for the products I want to display a thumbnail of the brand instead of the name of the brand in text, for use in views when showing the products in a catalog, or in the main page of the product display when editing the display of the product display...

Any idea. Thanks

# Answer
> 1 votes
You can use the Entity Module which will allow you to add an image field to the taxonomy.

Then instead of displaying the `term->name` you'll be able to display your image.

You can create a field image `field_brand_logo` and get it this way :

```
$term = taxonomy_term_load($tid);
$brand_logo = field_get_items('taxonomy_term', $term, 'field_brand_logo');
if (!empty($brand_logo)) {
   $brand_logo_img = field_view_value('taxonomy_term', $term, 'field_brand_logo', $brand_logo[0], array('type' => 'image'));
}

print render($brand_logo_img);

```

# Answer
> 0 votes
This is probably what you're looking for: https://www.drupal.org/node/1224916

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


# Question
Title: It's true that policy file in drush prevents sql-sync from local to prod?
I know in the policies file in drush there was/is a way to prevent sql-sync'ing from local to prod.

Is this still true? If so how do you go about this?

# Answer
Yes this is still true you can find the relevant snippet in the drush source code:

```
/**
 * Implement of drush_hook_COMMAND_validate().
 *
 * Prevent catastrophic braino. Note that this file has to be local to the machine
 * that intitiates sql-sync command.
 */
function drush_policy_sql_sync_validate($source = NULL, $destination = NULL) {
  if ($destination == '@prod') {
    return drush_set_error(dt('Per examples/policy.drush.inc, you may never overwrite the production database.'));
  }
}

```

You should include the policy.drush.inc in your .drush folder usually located in the users home folder.
> 5 votes

# Answer
The first thing you must decide is where would you like to keep the policy file, and this really depends on your purpose for creating the policy file in the first place. If you are just wanting to prevent yourself from doing something crazy by accident, or if there is special functionality for you, you can add the policy to the .drush directory inside your home directory.

If you are wanting to have a different policy for different sites or Drupal installs, you might think about adding the policy file to the /sites/all/drush directory; this also makes it handy for versioning the file. To have a global policy file that will work for all sites and users on a server, your best bet is to put the policy file in the /usr/share/drush/command directory.

Each of these directories is valid though they aren’t inclusive, meaning that if you have a file in your /sites/all/drush directory, the settings here will overwrite the settings you may have in your ~/.drush directory. Likewise, the policy file in the /usr/share/drush/command directory will overwrite any other policy file, which is what we want, so someone can’t circumvent restrictions by creating their own policy.drush.inc file and adding it to their home directory.

Example of policy.drush.inc file:

```
<?php
/**
 * Implementation of drush_hook_COMMAND_validate().
 */
function drush_policy_sql_sync_validate($source = NULL, $destination = NULL) {
  if ($destination == '@prod') {
    return drush_set_error(dt('Permission denied! You almost overwrote the production database you moron!'));
  }
}

```

See also:
> 3 votes

---
Tags: drush
---


# Question
Title: Views SQL-query slow with big dataset and exposed filters
I have a problem with a Drupal 6 site working with many nodes.

This is the SQL given by Views: https://gist.github.com/ranbogmord/79bfa50e40db1322c9e0

The query takes 5-10s to run through and the specific content-type has 30 fields bound to itself. 21 of those are exposed.

Imagine this as orders in a business system.

Thanks!

# Answer
> 0 votes
Try denormalising the database by storing the relevant node objects in a single caching table. You can model your database schema on that of the core caching tables. That should speed up the query by reducing the amount of joins. Also, put indexes on any columns used in where clauses. If you insert/update rows in your caching table on update/insert of nodes using `hook_nodeapi`, your caching table should remain fresh. You could then either replace the view with a `db_query` in a custom module, or you could expose your table to views.

I haven't tried it, but you may be able to achieve this using the D6 object cache module.

---
Tags: views, 6, database
---


# Question
Title: How to hide a field of a content type except when editing?
I'm using Drupal 7 and have a custom content type that I've given authenticated users the ability to add and edit. Instead of giving them the ability to delete nodes, I've added a Boolean checkbox titled "Delete?" to the content type that they can check when editing the node. This prevents them from deleting a node without any administrative review. Is there anyway to hide this checkbox when they're adding a new node?

# Answer
Implement `hook_form_alter()` and check whether `$form['nid']['#value']` is empty, if empty then it is creation else it is update. If creation then hide the field by setting `#access` property to `FALSE`.

**UPDATE** : Create a custom module and use the following code with needed modification.

Here is an example to hide `tags` field in `article` content type.

```
function MYMODULE_form_alter(&$form, &$form_state, $form_id){
  if($form_id=='article_node_form' && empty($form['nid']['#value'])){
     $form['field_tags']['#access']=FALSE;
  }
}

```

Here is a tutorial on how to create a custom module.
> 3 votes

---
Tags: nodes, users, entities
---


title: Cron won't start

text:
# Question
Title: Cron won't start
I have a smaller Drupal 7 Aquia site and Cron will run successfully if I press the button manually. The issue is that it just won't ever start on its own. The scheduler doesn't seem to be working.

* Cron can finish successfully
* I tried the Elysia Cron module but it doesn't make a difference.
* I've tried visiting the website myself, nothing.
* Visiting the cron page mywebsite.com/cron.php?cron\_key=KEYHERE does make cron run, so that's good and well
* I made sure the cron keys match

In my webhosting panel, I have a Cron Job task set up, it looks like :

```
 /usr/bin/wget -O - -q "http://mywebsite.com/cron.php?cron_key=CRONKEY" > /dev/null 2>&1

```

What's going wrong and how can I fix the problem where cron just isn't automatically triggered?

# Answer
It turns out that my Cron panel had a place for email notifications and like @Free Radical said, some output was critical to debugging.

Basically, some website hosters - like GoDaddy - have inexplicably finicky cron processes. The GoDaddy suggested (hah!) cron task of

```
 /usr/bin/wget -O - -q "http://mywebsite.com/cron.php?cron_key=CRONKEY" > /dev/null 2>&1

```

was never ever going to work. As with many things webhost, we don't know why, just that it's a no-go. So I went digging on the Drupal forums and found one that was compatible. This works :

```
 curl http://mywebsite.com/cron.php?cron_key=CRONKEY

```

So the answer is to give the webhost the finger and use the `curl` unix command, instead.
> 1 votes

---
Tags: cron
---


title: External Server Theming Workflow

text:
# Question
Title: External Server Theming Workflow
Running into a slight workflow problem, and finding out that a lot of us being new to Drupal doesn't help. =) Thank you in advance.

The issue being is that a lot of the front-end developers at my company are used to working locally with every project. But our new Drupal CMS I would like to only have running in one location, not on their local machine or our internal server, but only running on a remote server and installed once. We will have many running for our clients and I need to keep the code maintained properly, and would hate a front-end developer to work on it locally to only find out their version is behind now during the length of their project. Or worse yet, they are working on five projects at once and they have to maintain all of those on their machine.

We figured out a small hack to get CodeKit to work on their machine while still seeing the files on the server refresh, so SASS isn't an issue. But they are so used to working locally, they are having a hard time grasping theming on a remote server. I am very much used to working in larger applications that need several environments or complicated compiles, so using Drupal in one place seems SO easy to me.

How does everyone else work on themes? What does your workflows look like? What advice can you give? Anything will help!

# Answer
> 0 votes
Working locally should be a priority - not working on a remote server, that would cause the most confusion and complications. To work in a team environment for theming, it's best if you use Git for version control and Drush for moving content from the remote server to local. Ideally everyone would compile locally and push up.

```
[remote server] <--- [Bitbucket/Github repo] <---> [local environment]

```

Main code repository would be stored in a central location like Github or Bitbucket. You can go directly to the server, but if you manage multiple projects, it's a lot easier to keep all of them under a team account and manage access to the team.

```
[repository] <---> [local environment]

```

Developers pull down current code from repo. This ensures everyone has the latest updates. Commit often, push semi-often. This makes merges easier if there's a conflict.

```
[remote server] <--- [repository]

```

Have the remote server pull in changes from the repo. If you have Drush aliases set up, this can be as simple as `drush @remote.alias pull`. You should never make changes directly on the server and push them back to the repo as there wouldn't be any really good records of who made that change if you all share the same SSH account.

Also having Drush aliases set up, developers can then use sql-sync or sql-sync-pipe to pull down the databases with ease. Whenever new content is added - just sync. As for files, you can use Stage File Proxy, one of my favorites.

# Answer
> 0 votes
I mount the remote drive locally using 'Transmit' so I can use my local dev stack (sublime, livereload, sass, compass etc...). This does not always play nicely with file permissions and kinda urks some of the devs who are used to working locally then to git and staging servers for testing. I just backup alot and like to fly by the seat of my pants on the live server... although I feel i should be working git in there more!

# Answer
> 0 votes
1. Mount your FTP/WebDAV server as a drive using e.g. NetDrive.
2. Add a new Drupal theme with CSS and JS files.
3. Open you website in Google Chrome/Opera and open DevTools.
4. Make modifications of your CSS/JS files and save them using Ctrl-S in the mounted drive.

Using this workflow you don't have to switch between Chrome/Opera, text editor and FTP/WebDAV client.

---
Tags: workflows, database, theming
---


# Question
Title: How to use Recurring Dates with Views properly?
I am trying to use ***recurring dates*** for one of my content types (*Event*) to limit the amount of *Event* records.

I would like to have one Event record created for all dates of that Event. For example if an Event occurs every week for a year I have 1 record instead of 52.

Still I would like to see 52 separate lines in the related View because I would like to be able to sort/filter the View to see current week's Events only.

How to set up a Events View for that data so that each view line shows one date only ?

I would like a View to return a list like this...

```
 - Event A  12-10-2011
 - Event B  12-11-2011
 - Event A  12-12-2011
 - Event B  12-13-2011
 - Event A  12-14-2011
 - Event B  12-15-2011

```

(Event A and B are recurring every second day )

...instead of a list like this:

```
 - Event A
    - 12-10-2011
    - 12-12-2011
    - 12-14-2011
 - Event B
    - 12-11-2011
    - 12-13-2011
    - 12-15-2011
 - Event A
    - 12-10-2011
    - 12-12-2011
    - 12-14-2011
 - Event B
    - 12-11-2011
    - 12-13-2011
    - 12-15-2011
 - Event A
    - 12-10-2011
    - 12-12-2011
    - 12-14-2011
 - Event B
    - 12-11-2011
    - 12-13-2011
    - 12-15-2011

```

# Answer
> 5 votes
Eventually I found how to set this up an easy way:

1. Go to your **View**
2. Go to **Displays** --\> `<your display name, for example Page>` --\> Edit
3. Select **Format** : **Table**
4. Add a date field:
5. Select a Content: `<your date field name>`
6. You will see Configure field: Content: `<your date field name>`
7. Go to **"Multiple field settings"**
8. Uncheck **"Display all values in the same row"**

> If checked, multiple values for this field will be shown in the same row. If not checked, each value in this field will create a new row. If using group by, please make sure to group by "Entity ID" for this setting to have any effect.

# Answer
> 0 votes
You can also use "unformatted list" and filter your dates with "greater than or equal" now to show current and upcoming events.

# Answer
> 0 votes
If you use Display Suite for displaying the events (Show: Display Suite) you can do something like this in a custom module. Remember to change 'mymodule' and 'field\_date' to correspond your module and date field names.

```
/**
 * Implements hook_ds_views_row_render_entity_alter()
 */
function mymodule_ds_views_row_render_entity_alter(&$content, &$context) {
  //Display only the current date value from repeating dates
  $date_field_name = 'field_date';
  if (isset($content[$date_field_name]) && count($content[$date_field_name]['#items']) > 1) {
    // Modify the view, or the content render array in the context of a view.
    for ($i = 0; $i < count($content[$date_field_name]['#items']); ++$i) {
      if($content[$date_field_name]['#items'][$i]['value'] != $context['row']->field_data_field_date_field_date_value) {
        unset($content[$date_field_name][$i]);
      }
    }
  }
}

```

If you are just using fields as your Show option you can probably do something similar with View's hooks.

---
Tags: 7, views, datetime
---