# Question
Title: Make commerce billing information readonly
I want to prepopulate commerce billing address in checkout process and make all fields in the address field readonly.

I've tried the next code:

```
$form['customer_profile_billing']['#disabled'] = TRUE;

```

But disabling didn't help me because values are not submited when field is disabled. And I get the notice:

> Notice: Undefined index: customer\_profile\_billing in commerce\_customer\_profile\_copy\_validate() (line 1372 of ...

I also've tried the next code but it doesn't solve anything:

```
  $form['customer_profile_billing']['#attributes']['readonly'] = 'readonly';
  $form['customer_profile_billing']['commerce_customer_address'][LANGUAGE_NONE][0]['#attributes']['readonly'] = 'readonly';
  $form['customer_profile_billing']['commerce_customer_address'][LANGUAGE_NONE][0]['#attributes']['#address']['readonly'] = 'readonly';

```

Using of `'#type' => 'value'` or `'#markup'` didn't help me too.

Here is result of `dpr($form['customer_profile_billing']['commerce_customer_address']);`:

```
Array
(
    [#type] => container
    [#attributes] => Array
        (
            [class] => Array
                (
                    [0] => field-type-addressfield
                    [1] => field-name-commerce-customer-address
                    [2] => field-widget-addressfield-standard
                )

        )

    [#weight] => -10
    [#tree] => 1
    [#language] => und
    [und] => Array
        (
            [0] => Array
                (
                    [#entity_type] => commerce_customer_profile
                    [#entity] => stdClass Object
                        (
                            [revision_id] => 196674
                            [revision_uid] => 1
                            [status] => 1
                            [log] =>
                            [revision_timestamp] => 1380789191
                            [data] =>
                            [profile_id] => 196674
                            [type] => billing
                            [uid] => 193074
                            [created] => 1372337831
                            [changed] => 1380789191
                            [commerce_customer_address] => Array
                                (
                                    [und] => Array
                                        (
                                            [0] => Array
                                                (
                                                    [country] => DE
                                                    [administrative_area] =>
                                                    [sub_administrative_area] =>
                                                    [locality] => Ahaus
                                                    [dependent_locality] =>
                                                    [postal_code] => 48683
                                                    [thoroughfare] => Am Aabach 6
                                                    [premise] =>
                                                    [sub_premise] =>
                                                    [organisation_name] =>
                                                    [name_line] => Aabachschule
                                                    [first_name] =>
                                                    [last_name] =>
                                                    [data] =>
                                                )

                                        )

                                )

                            [rdf_mapping] => Array
                                (
                                )

                            [entity_context] => Array
                                (
                                    [entity_type] => commerce_order
                                    [entity_id] => 46
                                )

                        )

                    [#bundle] => billing
                    [#field_name] => commerce_customer_address
                    [#language] => und
                    [#field_parents] => Array
                        (
                            [0] => customer_profile_billing
                        )

                    [#columns] => Array
                        (
                            [0] => country
                            [1] => administrative_area
                            [2] => sub_administrative_area
                            [3] => locality
                            [4] => dependent_locality
                            [5] => postal_code
                            [6] => thoroughfare
                            [7] => premise
                            [8] => sub_premise
                            [9] => organisation_name
                            [10] => name_line
                            [11] => first_name
                            [12] => last_name
                            [13] => data
                        )

                    [#title] => Address
                    [#description] =>
                    [#required] => 1
                    [#delta] => 0
                    [#weight] => 0
                    [element_key] => Array
                        (
                            [#type] => value
                            [#value] => commerce_customer_profile|billing|commerce_customer_address|und|0
                        )

                    [#type] => container
                    [#handlers] => Array
                        (
                            [0] => address
                            [1] => name-oneline
                        )

                    [street_block] => Array
                        (
                            [#type] => addressfield_container
                            [#attributes] => Array
                                (
                                    [class] => Array
                                        (
                                            [0] => street-block
                                        )

                                )

                            [#weight] => 0
                            [thoroughfare] => Array
                                (
                                    [#title] => Address 1
                                    [#tag] => div
                                    [#attributes] => Array
                                        (
                                            [class] => Array
                                                (
                                                    [0] => thoroughfare
                                                )

                                        )

                                    [#size] => 30
                                    [#required] => 1
                                )

                            [premise] => Array
                                (
                                    [#title] => Address 2
                                    [#tag] => div
                                    [#attributes] => Array
                                        (
                                            [class] => Array
                                                (
                                                    [0] => premise
                                                )

                                        )

                                    [#size] => 30
                                )

                        )

                    [locality_block] => Array
                        (
                            [#type] => addressfield_container
                            [#attributes] => Array
                                (
                                    [class] => Array
                                        (
                                            [0] => addressfield-container-inline
                                            [1] => locality-block
                                            [2] => country-DE
                                        )

                                )

                            [#weight] => 50
                            [#attached] => Array
                                (
                                    [css] => Array
                                        (
                                            [0] => sites/all/modules/contrib/addressfield/addressfield.css
                                        )

                                )

                            [postal_code] => Array
                                (
                                    [#title] => Postal code
                                    [#size] => 10
                                    [#required] => 1
                                    [#attributes] => Array
                                        (
                                            [class] => Array
                                                (
                                                    [0] => postal-code
                                                )

                                        )

                                )

                            [locality] => Array
                                (
                                    [#title] => City
                                    [#size] => 30
                                    [#required] => 1
                                    [#prefix] =>
                                    [#attributes] => Array
                                        (
                                            [class] => Array
                                                (
                                                    [0] => locality
                                                )

                                        )

                                )

                        )

                    [country] => Array
                        (
                            [#title] => Country
                            [#options] => Array
                                (
                                    [AF] => Afghanistan
                                    [AX] => Aland Islands
                                    ...<<< COUNTRIES GO HERE >>>....
                                    [ZM] => Zambia
                                    [ZW] => Zimbabwe
                                )

                            [#render_option_value] => 1
                            [#required] => 1
                            [#attributes] => Array
                                (
                                    [class] => Array
                                        (
                                            [0] => country
                                        )

                                )

                            [#weight] => -10
                            [#ajax] => Array
                                (
                                    [callback] => addressfield_standard_widget_refresh
                                    [wrapper] => addressfield-wrapper
                                )

                            [#element_validate] => Array
                                (
                                    [0] => addressfield_standard_country_validate
                                )

                            [#limit_validation_errors] => Array
                                (
                                )

                        )

                    [#wrapper_id] => addressfield-wrapper
                    [#prefix] => <div id="addressfield-wrapper">
                    [#suffix] => </div>
                    [name_block] => Array
                        (
                            [#type] => addressfield_container
                            [#attributes] => Array
                                (
                                    [class] => Array
                                        (
                                            [0] => addressfield-container-inline
                                            [1] => name-block
                                        )

                                )

                            [#weight] => -100
                            [name_line] => Array
                                (
                                    [#title] => Full name
                                    [#tag] => div
                                    [#attributes] => Array
                                        (
                                            [class] => Array
                                                (
                                                    [0] => name-block
                                                )

                                        )

                                    [#size] => 30
                                    [#required] => 1
                                )

                        )

                    [#address] => Array
                        (
                            [country] => DE
                            [administrative_area] =>
                            [sub_administrative_area] =>
                            [locality] => Ahaus
                            [dependent_locality] =>
                            [postal_code] => 48683
                            [thoroughfare] => Am Aabach 6
                            [premise] =>
                            [sub_premise] =>
                            [organisation_name] =>
                            [name_line] => Aabachschule
                            [first_name] =>
                            [last_name] =>
                            [data] =>
                        )

                    [#addressfield] => 1
                    [#process] => Array
                        (
                            [0] => addressfield_process_format_form
                        )

                )

            [#theme] => field_multiple_value_form
            [#field_name] => commerce_customer_address
            [#cardinality] => 1
            [#title] => Address
            [#required] => 1
            [#description] =>
            [#prefix] => <div id="customer-profile-billing-commerce-customer-address-add-more-wrapper">
            [#suffix] => </div>
            [#max_delta] => 0
            [#after_build] => Array
                (
                    [0] => field_form_element_after_build
                )

            [#language] => und
            [#field_parents] => Array
                (
                    [0] => customer_profile_billing
                )

        )

    [#access] => 1
)

```

P.S. I added `...<<< COUNTRIES GO HERE >>>....` instead of countries list

# Answer
> 1 votes
Here is one working solution.

We can disable address field. To submit data of the addressfield we can add address value into `$form_state['input']` manualy in validation callback.

In `hook_form_alter` disable `customer_profile_shipping` field.

```
$form['customer_profile_billing']['#disabled'] = TRUE;

```

Add custom validation and submit handler before others:

```
array_unshift($form['customer_profile_shipping']['commerce_customer_profile_copy']['#element_validate'], '_my_custom_address_validation');
array_unshift($form['#submit'], '_my_custom_address_validation');

```

Magic implementation of adding address values into `$form_state` input:

```
/**
 * Helper function for address field validaton and submit.
 * Implementats adding address values into $form_state input.
 */
function _my_custom_address_validation(&$form, &$form_state) {

  if (!empty($form_state['values']['customer_profile_billing'])) {
    $form_state['input']['customer_profile_billing'] = $form_state['values']['customer_profile_billing'];
  }
}

```

---
Tags: 7, entities, commerce
---


# Question
Title: How can I use the Commerce Paypal module module without the Commerce module?
I have a form, which has an amount and item detail values to pass to PayPal.

I have installed the Commerce Paypal module, but I don't find any clue on how to integrate it so that when the form is submitted, it should go to PayPal for transaction. On success, it should redirect to the success URL; likewise, it should happen on failure, where the users are redirected to the failure URL. I haven't installed the Drupal Commerce module as there is no use of pages like catalogs and checkout in this system.

How can I use the Commerce Paypal module?

# Answer
Commerce Paypal has the following dependencies:

* commerce
* commerce\_ui
* commerce\_payment
* commerce\_order

Installing/using Commerce Paypal *without* Drupal Commerce isn't possible; it's a supplemental payment module, and requires Commerce's API to work.

You may instead be interested in something like Webform Paypal

> The Webform Paypal module sends the user to Paypal to complete a payment whenever they submit a webform containing the component on your site.
> 6 votes

---
Tags: 7, commerce, payment-gateways
---


title: How to access nid in views

text:
# Question
Title: How to access nid in views
I'm trying to build a simple module that renders facebook like boxes for each article. To do that, I need to know full absolute path to article.

I have my views set up to show all published posts as content (teaser). But I would like to insert a custom markup after each item. For that I need to know nid, so I can build a link that leads to article. How can I do that?

Here is how my views is set up: https://i.stack.imgur.com/soP2R.jpg

# Answer
> 2 votes
If you're using the rendered entity style I don't think you can do it through the UI - Views passes off the display to `node_view()` in that case, and doesn't get involved with the markup for the row.

The easiest way to do what you want is to implement `hook_preprocess_node()`, look for a View in the current context, and if the node is being rendered as part of that display, you can make some alterations.

For example

```
function MYMODULE_preprocess_node(&$vars) {
  if (!empty($vars['view']) && $vars['view']->view_name == 'foo') {
    $nid = $vars['node']->nid;
    $vars['extra_link'] = l('Some text', "node/$nid");
  }
}

```

Then in your node.tpl.php file you'll have access to `$extra_link`.

# Answer
> 0 votes
One possible for getting the node ids for each item from UI:

* Change the **Format** of view to show **fields** instead of the **content**
* Add the required **fields**, for example: `nid`, `title`, `body` (for body content, you can specify the maximum length of this field, to show it as a teaser), and other needed fields.
* Rewrite the output of any of the added fields (may be `nid`) to have it as markup.

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


# Question
Title: How to use content type tokens File path in file and image field?
I want to have one field for header images, but sort them by type of content. Sadly, when I try to do that, I get:

> The File directory is using the following invalid tokens: \[content-type:machine-name\].

there is no "avaliable tokens" link under *File path* box, but when I click generic one, I get:

* Current date - Tokens related to the current date and time.
* Current page - Tokens related to the current page request.
* Current user - Tokens related to the currently logged in user.
* Random - Tokens related to random data.
* Site information - Tokens for site-wide settings and other global information.
* Variables - Tokens for variable values.

Now, I can add Node to the list with File (Field) Paths, but that's overkill. I want more basic thing - content type or more generic **bundle tokens**. And they are not provided. Is there something I'm missing?

# Answer
> 1 votes
One way to do it, is to use File (Field) Paths, as node provides content type "subtokens" like:

```
[node:content-type:machine-name]

```

Problem with any other implementation will be caused by the fact that fields can be attached to things that does not have content types.

This answer is limited to nodes, so it's only a partial one, but it will do the trick in many cases.

---
Tags: 7, tokens, media, files
---


# Question
Title: Cant make profile2 fields visible to other users
How can you make a profile (from the profile2 module) visible to all visitors?

I've given all users permission to "View user profiles". When viewing a user's page the fields from core are visible (username and picture). However the fields I've added with the profile2 module are not visible.

The profile2 fields are only visible when a user looks at their own profile, or when the administrator views users profiles. This seems like a permissions issue but I cant see what permission to change.

# Answer
Profile2 module separates core drupal user profile by adding a separate profile entity to it.The permission "view user profile" you are adding is related to drupal core user management not with profile 2 module.

Here is a screenshot for working permission set for a profile created using profile2 mdoule. The profile name is common

The roles in the screen shot are anonymous, authenticated administrator cutom\_role.

As a tutorial this video can help.
> 1 votes

---
Tags: users
---


# Question
Title: How to render an entire page from external php page?
I'm creating a custom .php page that is outside my drupal installation and it should render a custom page of the installation. The "entire" page, also with theme and everything else.

I'm using this code, works but is not loading the theme:

```
    <?php

    /**
     * Root directory of Drupal installation.
     */
    define('DRUPAL_ROOT', '/home/quickstart/websites/custom.dev');

    include_once DRUPAL_ROOT . '/includes/bootstrap.inc';
    drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);

    drupal_deliver_html_page('user');
    ?>

```

Where am I wrong?

# Answer
> 1 votes
`drupal_deliver_html_page()` is never called directly; you should eventually call `drupal_deliver_page()`. It also seem you are calling the function with the wrong argument, since `drupal_deliver_html_page()` doesn't get a path as argument, but the result obtained by a page callback.

The correct code would be the following one.

```
define('DRUPAL_ROOT', '/home/quickstart/websites/custom.dev');

require_once DRUPAL_ROOT . '/includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);
menu_execute_active_handler('user');

```

Since that is just the index.php code just slightly modified, I don't see any reason not to use http://example.com/user directly. A custom PHP file like that should be used to perform specific tasks, like in the case of cron.php.

```
define('DRUPAL_ROOT', getcwd());

include_once DRUPAL_ROOT . '/includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);

if (!isset($_GET['cron_key']) || variable_get('cron_key', 'drupal') != $_GET['cron_key']) {
  watchdog('cron', 'Cron could not run because an invalid key was used.', array(), WATCHDOG_NOTICE);
  drupal_access_denied();
}
elseif (variable_get('maintenance_mode', 0)) {
  watchdog('cron', 'Cron could not run because the site is in maintenance mode.', array(), WATCHDOG_NOTICE);
  drupal_access_denied();
}
else {
  drupal_cron_run();
}

```

Normally, you don't need to use a similar file, and you should handle it through a normal menu callback; this even more true when you need to just shown a specific page as you are doing.

Keep in mind that Drupal 8 doesn't use anymore the cron.php file; cron tasks are handled through a menu callback too.

---
Tags: 7
---


title: Update query is not working

text:
# Question
Title: Update query is not working
In a Drupal 7 custom module, I am updating a record in the database using a form, and I am using the following code to update, but for some reason it is not updating. Can anyone tell me why? I tried like 3 hours to change every possible thing but no luck.

```
function edit_job_form_submit($form, &$form_state){
  $id = $form_state['values']['id'];
  $job_title = $form_state['values']['job_title'];
  $description = $form_state['values']['description'];
  $cat_id = $form_state['values']['cat_id'];
  $job_type = $form_state['values']['job_type'];
  $company_id = $form_state['values']['company_id'];
  $description = $form_state['values']['description'];
  $location = $form_state['values']['location'];
  $Salary = $form_state['values']['Salary'];
  $benifits = $form_state['values']['benifits'];
  $Nationality = $form_state['values']['Nationality'];
  $Age = $form_state['values']['Age'];
  $join_date = $form_state['values']['join_date'];
  $date_added = date("y-m-d", time());

  $join_date_mod = gmdate('Y-m-d',strtotime($join_date));

  $num_updated = db_update('echelon_jobs')->fields(
    array(
      'job_title' => $job_title,
      'cat_id' => $cat_id,
      'job_type' => $job_type,
      'company_id' => $company_id,
      'location' => $location,
      'Salary' => $Salary,
      'benifits' => $benifits,
      'Nationality' => $Nationality,
      'Age' => $Age,
      'join_date' => $join_date_mod,
      'date_added' => $date_added,
    )
  )
  ->condition('id', $id)
  ->execute();

  //dpq($num_updated, $name);
  drupal_set_message(t('Vacancy Updated Successfully..  '));
}

```

# Answer
> 1 votes
As a matter of debugging, if you have the Devel module installed, try executing the query at devel/php with hard-coded data. That will help understanding if there is an issue with the `db_update()`. Also, when you run the query and an error occurs, the error log at admin/reports/dblog on your site should show you any error message about that query.

In case you need to update or insert values on a table, `db_merge()` should be used instead of `db_update()`. `db_update()` doesn't insert new rows, but updates the existing ones; `db_merge()` updates the existing ones, or creates new rows.

Once you are ready with a working query, debug the `$form_state` values; there might a mismatch between database table column type and the data you are trying to put there.

---
Tags: 7, database
---


# Question
Title: Duplicate the value of the price of the products to field in node
I have node (Product display) and inside this node is field link to product. The usual option for commerce.

In commerce product is the field - commerce\_price.

In node is field field\_node\_price.

How can synchronize value from commerce\_price to field\_node\_price?

# Answer
> 0 votes
You need to use Computed Field here.

> Computed Field is a very powerful field module that lets you add a custom "computed fields" to your content types. These computed fields are populated with values that you define via PHP code. You may draw on anything available to Drupal, including other fields, the current user, database tables, you name it. (Feeling the power yet? :) ) You can also choose whether to store your computed field values in the database with other content fields, or have them "calculated" on the fly during node views. (Although you should note that Views use requires database stored values.) This field is literally the Swiss Army knife of fields. So start cooking up your PHP based values!

Now, substitute plain link with Entity reference \- that way you will be able to access referenced product's fields in code and use them, especially price, in node's computed field

---
Tags: commerce
---


title: Disable AJAX in a form

text:
# Question
Title: Disable AJAX in a form
I need to disable AJAX proccessing for a multiple value field in forms.

Can somebody tell me how to disable it?

# Answer
> 3 votes
Ajax behavior is attached to form elements when there is a record in `Drupal.settings.ajax` for the HTML-id of the form element. Therefore in order to disable Ajax for a given form-element, you need to remove the appropriate ajax settings record. You can achieve that by implementing `hook_js_alter`:

```
function hook_js_alter(&$javascript) {
  foreach ($javascript['settings']['data'] as $index => $item) {
    foreach ($item as $key => $settings) {
      if ($key == 'ajax') {
        // The prefix id for a field_collection with the name fc:
        $field_id_prefix = 'edit-field-fc-und';

        // Remove ajax settings for the "Add another item" button
        unset($javascript['settings']['data'][$index][$key][$field_id_prefix . '-add-more']);

        // If you also need to de-ajaxify the "Delete" buttons:
        foreach (array_keys($settings) as $element_id) {
          if (preg_match('/' . $field_id_prefix . '-[0-9]+' . '-remove-button/', $element_id)) {
            unset($javascript['settings']['data'][$index][$key][$element_id]);
          }
        }
      }
    }
  }
}

```

---
Tags: forms
---


title: Form post tag missing

text:
# Question
Title: Form post tag missing
I am writing a module which uses a template to output results from a database; these results can be edited. I use a form with a fieldset of submit buttons. Each result has an edit button. I get the buttons rendered but there is no `<form>` tag so nothing happens when the buttons are hit. Below is my code. I believe I am missing something fundamental, or there is a better way to do it.

```
  function eventhistory_menu() {
    $items['personal-history'] = array(
      'title' => 'Event history',
      'page callback' => 'historypage_rendered',
      'access callback' => TRUE,
    );

    return $items;
  }

  function eventhistory_theme() {
    return array(
      'eventhistory_template' => array(
        'variables' => array('output' => NULL, 'hist_form' => NULL),
        'template' => 'eventhistory_template',
      ),
    );
  }

  function historypage_rendered() {
    $output = array(
      '#theme' => 'eventhistory_template',
      '#type' => 'markup',
      '#hist_form' => drupal_get_form('historyEdit_form'),
      '#output' => getHistory(),
    );

    return $output;
  }

 function historyEdit_form($form, &$form_state) {
   $form['#tree'] = TRUE;
   $num_hist = 0;

   $form['history']  = array(
     '#type' => 'fieldset',
   );

   if ($form_state['hist_num']) {
     for ($i = 1; $i <= $form_state['hist_num']; $i++) {
       $form['history']['num' . $i] = array(
         '#value' => 'Edit',
         '#type' => 'submit',
       );
     }
   }

   return $form;
 }

```

In the template I have `print drupal_render($hist_form['history']['num' . $count]);`. The buttons show, but they are not surrounded by any `<form>` tag.

What am I doing wrong?

# Answer
Your way of implementation is partially wrong. Please try it like that:

```
function eventhistory_menu() {
  $items['personal-history'] = array(
    'title' => 'Event history',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('eventhistory_edit_form'),
    'theme callback' => 'eventhistory_template',
    'access callback' => TRUE,
  );

  return $items;
}

function eventhistory_theme($existing, $type, $theme, $path) {
  return array(
    'eventhistory_template' => array(
      'variables' => array('output' => NULL, 'hist_form' => NULL),
      'template' => 'eventhistory_template',
    ),
  );
}

function eventhistory_edit_form($form, &$form_state) {
 $form['#tree'] = TRUE;
 $num_hist = 0;

 $form['history']  = array(
   '#type' => 'fieldset',
 );

 if ($form_state['hist_num']) {
   for ($i = 1; $i <= $form_state['hist_num']; $i++) {
     $form['history']['num' . $i] = array(
       '#value' => 'Edit',
       '#type' => 'submit',
     );
   }
 }

 return $form;
}

```

I've discarded the `historypage_rendered` function from your code and called the form directly in `hook_menu` implementation. I also added the `theme callback` to `hook_menu`, and also renamed your form function to follow Drupal coding standards.
> 1 votes

---
Tags: 7, forms
---


# Question
Title: How to show a views count for nodes that ar not available to anonymous users
I made a view which displays a count for nodes in a nodetype. But anonymous users don't have access to nodes in that type. Those users should be able to view the count. Is there a way to achieve this?

# Answer
Go to edit screen of your view. In right column, *Advanced* section, click *Query settings*. Check *Disable Query Rewritting*. Now Drupal permissions will not affect views results.
> 3 votes

---
Tags: views, users
---


title: Checkbox for Views Filter

text:
# Question
Title: Checkbox for Views Filter
I have a view and used Better Exposed Filter module to show this Checkbox to filter the content in the view. The picture may explain the situation properly

In above filter by criteria, those values are Taxonomy Terms, which will increase later.

However my problem is, I want to have a Checkbox only for **Development** Taxonomy. So, instead of **Filter by** and list of Taxonomies, it would only be **Filter by Development** with a checkbox near to it. When the checkbox is checked it'd show the view which is **Listed Under** only **Development**

I tried something like CSS or jQuery show only this taxonomy class and hide other taxonomy terms, but that's last resort.

Any Drupal way I can accomplish this without writing codes?

# Answer
> 3 votes
In your filter settings there is an option "Limit to the selected items". Check that and select "Development" from the select field of options and it should do what you are trying to achieve.

Then change the label of your filter as required.

See the attached image:

The view itself looks like (note I changed the filter to be cat, not car as in the previous image, because I already had content tagged with cat):

---
Tags: 7, views
---


# Question
Title: Create Famous button in article type with value stored in database
I have two user roles: **editor** and **publisher**.

I want to add a **Button** in article which says **Make This Famous**. This button is only visible to **Publisher** and when the **Publisher** clicks it, it'll ask for confirmation and if confirmed, the article will be *Famous*.

Once the article is famous the *Button* would be disabled for **Publisher** and the text/label would change to *Already Famous*. But for **Admin** The same *Button* would still be active with text/label *Make This Infamous*.

I want the process to be like:

* *Editor* can create articles and publish it
* Only *Publisher* can make the article famous by clicking the *Button* displayed in article.
* Once article is made famous only *Admin* can make it infamous.
* Once the article is famous, it'd display in article saying *This content is Made Famous by **Username*** of the *Publisher* On the **Date** made famous. This is just like **Submitted by** in Drupal.
* For Anonymous users, If the article is not *Famous*, it'd not display anything about famous, it'll just display the article as it is.

I have been looking for this for few days, used Workflow and Workbench Module, but those are big and complex solutions. I am not looking for content revisions and those things, just a simple **Button** which can make the content famous and store the time in database, so, it'd display nicely in articles.

Is there any simpler module or easy way I can accomplish this?

# Answer
> 3 votes
Sounds like you might want the flag module.

You can create a "Famous" flag, where certain roles can flag items and administrators can remove the flag.

It allows you to set the text for flagging and unflagging, so you can have "Make This Famous" or whatever you like.

The only part I'm not sure about off the top of my head is showing who flagged the content as famous. I'm not sure if there is a setting for that, however there is views integration so you could create a view that shows who has flagged the current node and put it as a block on the page.
Since only one person can make something famous in your system there will only ever be 1 result so you will get what you require.

# Answer
> 1 votes
You could use the Flags module and create a flag called "Make This Famous". Grant Publishers the permission to only flag content, Editors the permission to only unflag content and make it unavailable for Anonymous users. You can display a message by creating a Rule that's activated after **A node has been flagged, under "Make This Famous"**.

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


# Question
Title: How to alias pages generated by panels (node edit or view pages)
I have a panel page that is in the form:

"/productsByMfg/%nid" where nid is the node id of the a manufacturer. This is not a node edit or view page since I already have that.

I have about 100 of these pages /productsByMFg/1, /productsByMfg/2 etc... How do I create aliases so I can use something like /productsByMfg/IBM, /productsByMfg/Microsoft?

# Answer
Sub-pathauto (Sub-path URL Aliases) works for me. It takes care of situation like yours. Here is a quote about it (from the module's project page):

> The Drupal Path module matches only full URLs when creating SEO-friendly aliases. This module extends that behavior by also matching known sub-paths and replacing them with their respective alias.
>
> For example, if user/1 is aliased to users/admin, this module rewrites the link to the user contact page user/1/contact to use the aliased URL users/admin/contact instead. This also includes Views URLs taking a node as argument (e.g. node/%/yourview), in short, every URL that is based on, or extends, an existing alias. In combination with the Pathauto module it is possible to get rid of all remaining exposed internal non-administrative URLs.
> 2 votes

# Answer
Page Manager Pauthauto module should take care of this.
> 2 votes

# Answer
There's no easy way to do this currently.

It's among the oldest still open feature requests for Page manager. Ideally, someone would sponsor having the work done.

Currently, you'd have to write a custom module that figures out what all the possibilities are, and creates the aliases.
> 0 votes

---
Tags: panels, path-aliases
---


title: Modify VBO checkbox value

text:
# Question
Title: Modify VBO checkbox value
I would like to modify the value of my VBO checkboxes but can't figure where to hook in.

```
<input name="objects[selection][1]" id="edit-objects-selection-1" value="1" class="form-checkbox select" type="checkbox">

```

becomes

```
<input name="objects[selection][1]" id="edit-objects-selection-1" value="1-XXX" class="form-checkbox select" type="checkbox">

```

# Answer
> 1 votes
I guess it should be form, so you can try the following on VBO page, if it workds.

```
   function  mymodule_form_alter(&$form, &$form_state,$form_id) {
      dpm($form_id);
    }

```

# Answer
> 0 votes
The value I needed was in the $context variable in the action :|

*EDIT*
I didn't need to change the checkbox value because the value I wanted was in the actions $context variable.

---
Tags: 6, forms, views
---


# Question
Title: Add custom link when using field_get_field
I have an image field on a taxonomy term. I am retrieving it via field\_view\_field and render it afterwards to display it. But I would like to give it a custom link. How to do this? Do I need to make a new image formatter, with a link as configuration property? Or is there another solution to add the link before the render?

Thanks!

# Answer
> 1 votes
Problem with that module is that you have to define a token or fixed link. I am writing code that create a link on the fly, that can change in time.

For example: displaying the image of a taxonomy term, with a link to the last added node having this term.

The easiest solution: $image = render(field\_view\_field(……)); $output = l($image, $link, array('html' =\> TRUE));I

When I tried this earlier it wasn't working, because by default the HTML option is set to false, displaying HTML code instead of rendered HTML code.

# Answer
> 0 votes
Check if Image Link Formatter module works for you.

> allows an image field to be displayed with a link to a custom URL:

Please check the project page as it has similar module suggestions as well.

---
Tags: navigation, media, entities
---


# Question
Title: How do I allow users to remove their pictures from their user profile?
Users on my recruitment website are able to upload profile pictures and CVs to their user profile. However, they aren't able to remove uploaded pictures and CVs or replace them with new files. What do I do to allow users to change their existing profile pictures as well as CVs?

# Answer
> 2 votes
If you use Field Permisions module, you should check the permission settings for that field. There are 5 permissions for each field: "Create own, edit own, edit anyone's, view own, view anyone's". It seems that you didn't give the 'edit own value' permission to users.

---
Tags: 7, users
---


# Question
Title: How to provide a custom option for an exposed filter in Views?
I have a site in which members can upload pictures of themselves (imagine a personals site). Users can upload up to five pictures, and each time they upload a picture, a rule increases the value of a custom field, **Number of pictures**.

Members can search for other members using a view. This view has a number of exposed filters.

What I would like to do is add another option, **Show members with pictures only**. Ideally, this would be a checkbox. However, I have no idea how to add such a thing to a view. I could add the **Number of pictures** field as an exposed filter, but since this is an integer, users would have to type "1", which is ugly and unintuitive. How might I start to go about this?

# Answer
if you are not able to achieve what you need with views default options. You can create your custom views handler. In this case, it would be a filter handler.

https://api.drupal.org/api/views/handlers!views\_handler\_filter.inc/group/views\_filter\_handlers/7

https://drupal.org/node/1239866

Extending views functionallity to provide an approach to your problem
> 1 votes

# Answer
You are looking for Sexy Exposed module. I think you can do it with this module, It makes any views exposed filter's select list as checkbox list.

> This module makes any views exposed filter's select list sexy using the jQuery Dropdown Check List plugin.
>
> After installing this module, you will get a new checkbox on your view's exposed filter settings form called 'Make it sexy'. By ticking it your exposed filter will be pimped up by some hot javascript magic thanks to jQuery Dropdown Check List.
> -1 votes

---
Tags: views
---


# Question
Title: Problem with creating page for the path of page display of a view
I created a *library* content type. Its view is *library\__view*; this view has a page display whose path is *library*, which has a contextual filter on the subject of the books(e.g. math, physics).

I created a page in my theme folder, and renamed it *page--library.tpl.php*. I also embedded library\__view using this line.

```
views_embed_view('library__view','page');

```

The problem is that *library/math* does not show math books (while it works right in the view administrative menu).

What is wrong with this? What is the filename of a view whose path is specified to be in a certain URL (e.g. page--library.tpl.php, library.tpl.php)?

# Answer
I infer: you have created the view for listing the contents of **library** content type, now you are embedding that view in the page template file for theming the contents listed on the page created by view. If this is the case than you are doing the things in incorrect way.

Possible cases for creating the template file for views page:
**1.** Theme the contents rendered by **views** on `http://www.yourdomain.com/library` page: For this you need to create template file as per the views template suggestion, also its best to create the template for view from the suggestion generated by view at **Theme: Information** as below:

The suggestions for creating the template in the below image is based upon the "test-contact" page I have created in views:

**2.** Theming the content created for **library** content type: If you want to theme the contents that is rendered while creating a nodes of `library` type than you need to create the `node--library.tpl.php`. This template will be just for theming the contents of `library` content type created originally (not for the content listed on `library` page created from views) and it wont have any impact on your views page.

> Now coming to your issue of page at \`library/math' does not show math books:

* Check if the result in your created view displayed correctly (to confirm that the contextual filter is working fine) on passing `math` as argument to "Preview with contextual filters" (present at bottom of view).
* Make sure that the path of page that you are creating from view is `/library`, and for testing purpose you can try changing the path temporarily to `/library123` (If changing the path, than test the result at `yourdomain.com/library123/math` page)
* Remove the template you have created for embedding the view (as it doesn't seems to be needed, at least as of now)
* Clear the cache and check again (not needed logically but no problem for testing purpose)
> 1 votes

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


title: Update time zone when user travels

text:
# Question
Title: Update time zone when user travels
I am creating a site that increments a "day" session at midnight. Is there a way to update the timezone set for that user when they travel between time zones?

Would using javascript to pull the value from the calendar on their computer be an option? Right now we are storing timezone values in the DB so this would be a major code change, but would it work? Is there any Drupal module that could help with this?

# Answer
> 1 votes
You can use javascript to get the browser timezone. Assuming their computer timezone is updated, their browser timezone will change.

```
var offset = new Date().getTimezoneOffset();

```

Or if you want the name you'll have to do something like https://stackoverflow.com/questions/2853474/can-i-get-the-browser-time-zone-in-asp-net-or-do-i-have-to-rely-on-js-operations

Sadly there is no way to do this without Javascript.

---
Tags: 6
---


# Question
Title: Allow all OG members to view/edit all content
I'm pretty new to OG and I'm testing a collaborative intranet site at this moment with Drupal7 and Organic Groups 7.x-2.3.

It is a simple app for a small group where all the members know each other and can be trusted. We're working on a Degrowth Workshop (link to the workshop announcement, in Spanish).

I've used OG to set the organizers in the different work areas (catering, activities, kids, lodging,...), have lists grouped by... groups (of course), and create a customized homepage for the members of the different groups. Everything ok until this point.

Now what I want is that **everyone (all registered users - there's NO access to anonymous) have access, can read, write, edit, comment, etc to any node, whether it be of their group or not**.

I'm fighting with the Field Settings, Permissions and roles but can't get to achieve it and there's always some hidden content to members of different groups. I've read quite a few solutions to similar issues but can't get a clue.

# Answer
> 2 votes
Organic groups controls (`Organic Groups Global Permissions`) are different from your site permission, roles etc. To allow authenticated users the required permission, configure the organic groups global permission:

Navigate to: Configuration -\> Organic Groups Global Permissions (`drupal/admin/config/group/permissions`), here you will find the controls over who can view and edit nodes and fields on your group pages.

Few reference for the organic groups permission:
http://vimeo.com/32398425
http://vimeo.com/32398425
https://drupal.org/node/2014929
https://drupal.org/node/2014793

---
Tags: organic-groups
---


title: Facebook profile details

text:
# Question
Title: Facebook profile details
I have a webform (survey) on my site, some of the fields are personal details (age, name, DOB, etc). I want to actually force the user to login with facebook and pro grammatically obtain those few details from facebook.

Which module(s) would I be most interested in, in achieving?

# Answer
> 0 votes
There is no module that can do this for you. You would need to make your own according to what fields you want. You would need to use the Facebook SDK and PHP (or Javascript) to query the `graph` and fill in the details you need.

See https://developers.facebook.com/docs/reference/api/user/ for details on how to get the data.

# Answer
> 0 votes
Find the drupal facebook module listing on this link

So far I find fb module will be worth starting with.

> This set of modules turns Drupal into a platform for developing Facebook Applications. This allows you to embed your content and features within facebook, or allow facebook users onto your site via Facebook Connect.

A quick glance for module description is here.

---
Tags: social-network
---


title: Uploading local photos to blog

text:
# Question
Title: Uploading local photos to blog
I notice here that I can upload a photo from my computer, like this one:

On my drupal site, I can do so as well, as an admininstrator. But for a regular authenticated user, I can't. Here's what regular users gets when they click on the upload media icon. Only access to gallery, not local files. Why?

# Answer
Go to permissions settings page `admin/people/permissions` and search for the permission '**Import media files from the local filesystem**'. Give this permission to all user roles that should be able to upload files from their local computer.
> 1 votes

---
Tags: files, media
---


# Question
Title: References lost when a content type is renamed
Actually I work in a project developed using drupal 7. Drupal is totally new for me and sometimes something happens that leaves me stunned… Today I have discovered something terrifying: when a content type is renamed (and his machine name change), you have to turn the whole project in the parts where the content type was used (in my specific case rules link) because when the machine name change it is possible that the references are lost!!!

You can help me to understand this comportament?

# Answer
why not name it back, and then only changing the displayname, not the machinename would maybe sufficent for you ?

else do an export and import - as suggestes via features module.
> 1 votes

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


title: Formatting a date field in Drupal rules

text:
# Question
Title: Formatting a date field in Drupal rules
Is there a way to format a date in Drupal rules? I've got a date timestamp, but obviously that's less than ideal for a client-facing situation.

How do you change a field to a different sort of formatting while in the rules UI?

# Answer
Can't you use `[node:field_calendar_date:custom:l, Fd, gia]`? Custom being whatever date format you set up. (like the presets: short, medium, long)

Make sense?
> 1 votes

---
Tags: rules
---


# Question
Title: How to display the abstract with javascript
I have a page that is a list of items, where I show the article title, author and abstract, but I want to show the abstract with javascript, a link that says show abstract and when I click out the absract od this article.

Then when clicking on the same link that hide the abstract.

Any idea to do this. PS: I am using the latest version of Drupal 7.

# Answer
> 0 votes
Along with Field group module , ctools\_collapsible theme function can also be used. As a sample code if it can help

```
print theme(
  'ctools_collapsible',
  array(
    'handle' => 'Abstract',
    'content' => $collapsed_content,
    'collapsed' => TRUE
  )
);

```

# Answer
> 0 votes
One way you can do it is with the field group module.

You can go to the display settings of your content type and add a group, set it as a div or fieldset, depending on what you want it to look like, and set it as collapsed.

That is probably the easiest way.

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


# Question
Title: How can i redirect the path from the product save button?
In my drupal commerce installation are two roles and one of them havn\`t the permission for the admin/commerce/products path. They get an "access denied". Thats not so nice. How can i overwrite the path from the submit button in the product form to another site (maybe to a views page)?

I\`m little bit confused, is it not possible to show only the products from the current logged in user on the admin/commerce/products path? I be really convinced that i give all the right permission.

Thx! Bruno

# Answer
> 2 votes
As with most listings in the commerce module suite, the admin/commerce/products listing is already a view. It is a default view provided by the module.

If you go to the listing of views on your site, you can override the "Products" (commerce\_products) view and make any changes you want.

For example, you can change the permission required to view the page, then you can change the view to only show products created by the current user.

You could then also create a second view that shows all products if you still needed that.

Really you can do anything to it that views will allow.

# Answer
> 3 votes
Easy to do with Rules, no coding required.

You can import this rule export, but will need to adjust the role ID and redirect path to match

**Redirect on product save using Rules**

```
{ "rules_redirect_on_product_save" : {
    "LABEL" : "Redirect on product save",
    "PLUGIN" : "reaction rule",
    "REQUIRES" : [ "rules", "entity" ],
    "ON" : [ "commerce_product_update" ],
    "IF" : [
      { "user_has_role" : {
          "account" : [ "site:current-user" ],
          "roles" : { "value" : { "3" : "3" } }
        }
      }
    ],
    "DO" : [ { "redirect" : { "url" : "somepath" } } ]
  }
}

```

---
Tags: forms, commerce
---


# Question
Title: How to set percent discount by old and new price
I have commerce-product, add new field **old price** and **percent discount**

Then i create new rule

# Answer
> 1 votes
There isn't really enough information here to diagnose your issue, but the likely problem is a mismatch between the data type required by your custom field and the data type of your calculated value. Since you didn't specify the type of field you used to create your custom field, I can't say for certain, but Rules will only allow you to set it to a valid value for the field type.

At the very least, it doesn't appear to be anything to do with Commerce or Rules themselves.

---
Tags: commerce, rules
---


# Question
Title: One-to-many and many-to-many relation between nodes of different content types
I am using Relation module for creating relationship. But i didn't find the option how to create one to many, many to many relation. Can anybody tell me regarding that Thanks

# Answer
The Relation module itself provides a block that can be used to create relations, you can create a simple relations by configuring relations and entity collector or can use the Rules module to create relations.

If your want to set up a relationship between entities than you may use the relation\_add module: It provides a block that allows the user to add an appropriate relation from an entity page to any other appropriate entities, with a generic autocomplete for each endpoint, and relation fields. Tutorial for relation add module.

Tutorials for creating a relation type (`administration toolbar > Structure > Relation types`):
https://drupal.org/node/1276284
http://nodeone.se/en/creating-a-first-relation-type-the-entity-collector
http://nodeone.se/en/directional-relations-and-fields-on-relations

Few Tutorials that may be useful for you: http://vimeo.com/28178686
http://nodeone.se/en/learn-the-relation-module
https://drupal.org/node/1276298
https://drupal.org/node/1276380
> 0 votes

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


# Question
Title: Add contextual link to panels "custom content" pane?
I am wondering if there is a way to add a contextual link to a "custom content" pane? For example my "block" panes have the block contextual link that allow for easy edit. But is there a way to do this for regular panes?

I am trying to find a way to make Panel's more accessible to the "non technical user". Having to click Panel Content, then find the gear, then edit that. Is a little too much work that can easily get lost.

# Answer
Try FAPE, Field API Pane Editor. It is a separate module from ctools.

It does make it much easier for non-technical users to edit a field or a single pane of a page.
> -1 votes

---
Tags: 7, panels
---


# Question
Title: jQuery not functioning in Chrome regardless of core/custom code
For whatever reason jQuery is refusing to function in Chrome for us. It works in all other browsers. This is the case regardless of the theme, page (aka: core admin pages like blocks have no jquery like drag), custom jquery, or core jquery.

In the firebug console $ correctly returns function() and the javascript is present in the html. Its basically like Chrome is just ignoring it. There have been no changes to core files and thus you would imagine at least the core admin pages would be functioning properly.

Scratching my head on this one here, any suggestions are appreciated.

# Answer
This is an issue with CloudFlare and Chrome:

https://support.cloudflare.com/hc/en-us/articles/200169456-Why-is-JavaScript-or-jQuery-not-working-on-my-site-
> 0 votes

---
Tags: javascript, debugging
---


# Question
Title: Homepage accessible to non-members though title of the page says : "Access Denied"
Since i upgraded to 7.8 i noticed that the homepage of my site now displays a title of "Access denied" as it used to be "Welcome to my site". Though it remains perfectly accessible to non-members.

I'don t recall modifying any permission so far so i doubt this is because of my code. Have anyone experienced that ? How could it be fixed ? Do i need to override menu title for that page ?

# Answer
> 1 votes
I have no idea what caused that though i solve it by creating a custom menu item with HOOK\_menu giving it full permissions, then i added that new menu item in the homepage field in site configuration .

# Answer
> 0 votes
The site's default front page, under Admin \> Configuration \> Site Information, was set to content/home-page, once I removed this path and saved configuration, the 'Access Denied' message disappeared from the browser tab.

---
Tags: 7, users
---


# Question
Title: How to remove an option from an exposed filter with a drop-down list?
This is this drop-down list for the field `field_gender` on the view whose name is `members`:

* M|Male
* F|Female

I know the following callback is executed (tested with var\_dump...), but it doesn't do what I think it should do: **Provide only the option which value is "M" for "Male"** (this choice is decided programmatically, Views UI won't work).

Here is the callback:

```
/**
* Implementation of hook_views_pre_...().
*/
// function mymodule_views_pre_render(&$view){
// function mymodule_views_pre_build(&$view){
function mymodule_views_pre_execute(&$view){
    if ($view->name == 'members') {

        // get our filters
        $filters = $view->display_handler->get_option('filters');

        // Force
        $filters['field_gender_value']['value'] = array('M' => 'M');

        // apply changes
        $view->display_handler->override_option('filters', $filters);
    }
}

```

# Answer
You use hook\_form\_alter:

```
/**
 * Implementation of hook_form_alter().
 */
  function mymodule_form_alter(&$form, &$form_state, $form_id) {
  switch ($form_id) {
  case 'views_exposed_form':
    // Force
    $form['field_gender_value']['#options'] = array('M' => 'M');
    break;
  }
}

```
> 3 votes

# Answer
If it is a select field, the time you will be adding it as expose filter you will get option to narrow down your options. Check the screenshot
> 1 votes

# Answer
Although I prefer using Views API I went with hook\_form\_alter. This is how I did it.

```
/**
 * Implementation of hook_form_alter()
 */
function mymodule_form_alter(&$form,$form_state,$form_id) {

    switch ($form_id) {
        /*
            ...
        */
        case 'views_exposed_form':
            if($form['#id'] === 'views-exposed-form-members-page'){

                // Get the user gender
                global $user;
                $user = user_load($user->uid);
                $user_gender = $user->field_gender[LANGUAGE_NONE][0]['value'];

                // Get available exposed options
                $exposed_options = $form['field_gender_value']['#options'];

                // Override options by whitelisting only the user gender
                $form['field_gender_value']['#options'] = array_intersect_key($exposed_options, array_flip(array ($user_gender)));

            }
    }
}

```
> 0 votes

---
Tags: views
---


# Question
Title: Why are there "updates" to dev versions of modules that do not include any changes to the code?
When I used drush to check for updates to my site, which has about 100 modules installed, I was informed that the dev versions of several versions of the modules had updates.

However, when I updated the new version, the only thing that was changed was the packaging information and datestamp.

For example, this is the git diff for the Prepopulate module dev version:

```
-; Information added by drupal.org packaging script on 2013-05-25
+; Information added by drupal.org packaging script on 2013-10-01
 version = "7.x-2.x-dev"
 core = "7.x"
 project = "prepopulate"
-datestamp = "1369450574"
+datestamp = "1380623732"

```

That's it-- no actual changes to the code. If this was just one module, I wouldn't think much of it. However, I had several modules like this-- the Role Expire module, Views PHP module, PHP Mailer module, i18nviews, and there may be more.

It's pretty frustrating for me to download each of these updates and do a diff, only to see that nothing has changed. I feel that I am really wasting my time. Are the maintainers doing this? Does this have anything to do with Drupalcon?

# Answer
> 6 votes
Strange, I selected some modules at random and I see dev versions consistently packed 2013-Oct-01. **I can't find any one with another date now**.

Examples I've tested:

and many more.

**Edit:** Some of them, closer to the beginning of alphabet, was packaged one day earlier:

but operation big as this surely needed to take considerable time and it still looks like one long rebuild queue.

With so many unrelated projects repackaged at the same day, and without any correlation to their GIT log, it must be something on the Drupal.org side that triggered mass repackaging.

It's simply impossible that all maintainers decided to rebuild at the same day, plus as far as I remember only way to trigger for them rebuild is via GIT anyway.

**GOT IT**

https://drupal.org/node/2101175#comment-7919049

> -dev releases are currently being rebuilt ... working alphabetically, and there are a lot of packages, so it will take a while. :)

So it was a manual rebuild triggered to fix an issue with infrastructure, not something planned as regular action.

---
Tags: 7, community-official-site
---


# Question
Title: How to generate content to Drupal 7 with a PHP-script?
I have been given the task to generate a couple of thousand of pages in drupal that should contain text generated by a php-script. After that is done, I'm supposed to perform searches on the generated words and play with the settings in Drupal to make the searching as fast as possible.

I have the php-script that generates the text but what I am asking for is the php-script that generates the pages and for each one calls my php-script to put a mass of generated text on the page.

I know that there is a file in Drupal that I can use since I read this page https://api.drupal.org/api/drupal/scripts!generate-d7-content.sh/7, but that one generates text that I can't perform my searches on. I think I need to modify it to call for my own text generator but I'm not sure of how?

Is there someone out there that maybe could help me? It would be most appreciated!

# Answer
> 1 votes
You can use contrib module for that purpose

Devel

> Generate content
>
> Accelerate development of your site or module by quickly generating nodes, comments, terms, users, and more.

Dummy content

> DC allow your custom module to provide demo nodes as soon as the module is installed - this helps with populating blocks, views, and generally showcasing your module's functionality. This is very useful when showcasing a module's functionality to a client. For example, rather than installing the Forum module and having to manually create forum nodes, the DC API can be used to pre-populate the site with forum-type nodes as soon as the Forum module is enabled. Additionally, rather than having purely Lorem Ipsum-type content, you can define relevant pieces of text and images, giving the content a more complete & realistic look & feel.

**Note:** Both modules will create random content.

# Answer
> 0 votes
I would go the other way around. You can easily modify your script to generate XML of texts. With that, you could import your XML with Feeds module. It maps XML fields to content fields pretty OK now, so it should be easy enough for simple content type.

---
Tags: 7, nodes, external-scripts
---


# Question
Title: How to gather user opinions via a survey based on tagging?
I'm completely new to Drupal, and am hoping it can help me with this job without me having to do too much tweaking.

I'm looking to gather user opinions on different subjects, but would rather not do it with a regular questionnaire type survey. I'm looking for something which would allow users to select topics and simply tag them with whichever words they find appropriate.

Does anyone know of a feature like this?

# Answer
You can easily do this with taxonomy free tagging

Step 1 : Create a vocab, going at admin/structure/taxonomy/add check the screen shot after adding a vocabulary named as survey.

Step 2: Create custom content type,going at admin/structure/types/add

Step 3: Add taxonomy term reference field to it.Check the settings in screen shot

once you click on save it will take you to next config page,where you will be choosing the vocab you created in step 1

Clicking field settings will take you now to last configuration page as in screen shot
> 0 votes

# Answer
I haven't tried to combine the module Webform with terms, but you could try. (There is also a module that adds a pre-built option lists of vocabulary terms to be used in Webform 3.x - Webform Term Options.)

It is easy to set up different surveys with the webform module. Here is an example on youtube: http://www.youtube.com/watch?v=8qIydHdxNx0&t=28m31s
> 0 votes

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


# Question
Title: How do I get Captcha to reappear in my registration form if an error was detected after submission?
I'm using Drupal 7 and have added an image Captcha as part of the registration process. The Captcha works just fine but if the form is submitted with an error, it no longer appears with the rest of the form when the registration page reloads. How do I make sure it always reappears? Thanks.

# Answer
> 0 votes
It's in module settings. Under Persistence , you can set CAPTCHA to appear:

* always,
* once per form,
* once per session.

It used to default to always, but as far as I remember there was an issue to change default. Probably now it defaults to once per form or once per session. It should be enough to manually change it to always.

---
Tags: 7, captcha
---


# Question
Title: Can Ckeditor use relative paths for images?
I am building a drupal 7 site on my localhost with ckeditor (7.x-1.13), HTML Purifier (7.x-1.0).

I realized that when my ip changes on the network, the links to the images I upload from ckeditor are broken. As I checked the html source, I saw that they are absolute urls and are using the previous ip as a part of them. Now that the ip is different, they are broken.

I need to develop the site and enter most of the content on localhost and if I cannot solve this problem, things will get complicated when I move the site to the server.

After reading a related question (D7 - Losing images when moving site location; placeholders point to old absolute path rather than relative path) I tried installing pathologic (7.x-2.11) module, checking the settings for text formats, clearing the cache with no result.

Is there a way to make ckeditor to use relative paths for images? Would it have any disadvantages?

# Answer
You should always use relative paths in your content to avoid the problem you now have.

If it was me I would fix the links in the database so they are all relative. You can do so with sql queries like this:

```
UPDATE field_body_data
SET body_value = REPLACE(body_value, 'http://example.com/', '/')
WHERE body_value LIKE '%http://example.com/%';

```

Followed by:

```
UPDATE field_body_data
SET body_value = REPLACE(body_value, 'http://example.com', '/')
WHERE body_value LIKE '%http://example.com%';

```

There are two to catch the case you might have a path to the home page without a trailing slash.

You would have to do this for any text area field that might contain a hyperlink.

The Pathologic module will also help you around this issue. You add the pathologic input filter for your relevant formats, then configure it with your old domain name. Also add the domain name / This will make it change relative paths to use their alias, like /node/10 to be /node-path-alias

That last feature with the aliases is very useful.

See https://drupal.org/node/257026 for more info on configuring pathologic.
> 2 votes

---
Tags: 7, wysiwyg, input-formats
---


# Question
Title: Why cache form table gets new entries by anon page views?
I am seeing new entries in my cache\_form table when anonymous user view a page that had a comment form. The page cache is enabled and set to 30 min. Does this mean that cache page is being bypassed? Or does drupal cahe forms for every anonymous user using a hashed key?

Also I should mention that this happening for forms called and renderd in the theme layer (someone's mistake and I'm trying to correct this) .

# Answer
> 1 votes
Comment form is a form. All forms generate entries in form cache. Form engine uses cache as it's temporary data storage, not as the cache in usual definition of the word.

One thing it always store is a list of fields it actually displayed to a client, so it can compare it with a list of values that come back and prevent hijacking and other abuse - hence one entry per user session per form.

---
Tags: forms, caching
---


# Question
Title: Is there a simple way to add user access on a page level?
I'm still getting used to the way Drupal works, most of what I have read on adding User Level Security on a Drupal site seems to be either View based or by using a Module like Panels. I am creating a site that is rather simple in structure, with some high level pages that differentiate out the content to different areas. I am using Superfish to generate a drop down menu system at the high level, and underneath I have some content areas that will either contain only a few pages or one specific area that will have many. I am also using shortened URLs to make site structure easier to manage, although in general it comes across as flat. I may be wrong in thinking in terms of pages, and if I need to reconsider that for the site that's ok, I have only been using Drupal for the past 6 months but its a good fit as a CMS for the site I am working on.

The requirement is only for three types of Users - Admin, Group Leaders, and Members. I'd like to give Group Leaders some access to pages for editing permissions, although mostly only at a second level or specific pages. Members will have some editing rights but only on a few pages. Group Leaders and Members will have access to content in one specific area, where I will have many pages, no one else should be able to get in. Content pages on Member activities will be accessible by only those who have a login, those not logged in should ideally not see the links or not be able to access the pages.

With Drupal 7, and using the Bartik theme and some modules (Chaos Tools, Display Suite and Superfish for now) what is the best mechanism to be able to grant permissions to view and access content on only specific pages in the structure I have? The site is still new, so if I have to make changes I'd like to do so now before it gets too complex.

**Update**: Just to note in addition what happened. I was looking for some sort of access that was simple to add in and allow me control on an individual node. Content Access module gave me this in a way I can teach my Users to utilize. Sorry if it seems a duplicate, I was looking for more of a description on what the modules did than I had seen before.

# Answer
> 1 votes
You can try the organic groups module, it provides all the functionalities that you are looking for:

* Organic Groups (OG) enables users with permissions to create and manage their own groups.
* Content of the "Group Content Type" has the unique ability to belong to multiple Groups at once. This reduces duplication and increases content accessibility.
* Utilizing users to adopt content allows users to create their own libraries of content without having to create duplication.
* Content is thus associated with the user and can be maintained by the user, and group maintainers can then manage content in ways that help their audience.

Few references for the organic groups:
Module docs: https://drupal.org/node/1114858 , https://drupal.org/node/1603460

http://vimeo.com/32398425
http://vimeo.com/32398425
https://drupal.org/node/2014929
https://drupal.org/node/2014793

---

However if you are looking for some simpler method than you can try the following modules:

1. Content access module: It allows you to manage permissions for content types by role and author. It allows you to specifiy custom view, edit and delete permissions for each content type. Optionally you can enable per content access settings, so you can customize the access for each content node.
2. Node access module:It is a Drupal access control module which provides view, edit and delete access to nodes. Users with the 'grant node permissions' permission will have a grant tab on node pages which allows them to grant access to that node by user or role. Administrators can set default access controls per content type, and also define which roles are available to grant permissions to on the node grants tab.

# Answer
> 2 votes
Well when you say page in drupal, it comes down to a lot of options. it might be a views page, a panels page, a page created directly with hook\_menu().

So options:

1. If its a panels/views page, you already have permissions options there through UI in those cases.
2. Node and taxonomy term pages, have contrib modules that does this..Ankit's answer above lists out some.
3. If the page is a custom page defined bu hook\_menu, you can employ '#access\_callback' parameter to add a permissions function where you can return TRUE of FALSE based on check.

After restricting access to each page based on roles, these will be respected already when you add their links to the superfish menu.

# Answer
> 0 votes
It looks like choice is between organic groups use or not.

In order to get clear what exactly @MichaelF needs: \- Do you have something on mind like subsites not exactly subsites though \- Consider with this simple example. A "Sport" site where you need different groups as soccer, cricket and each sport will have related content we can say as events and also related users to it.So with a obvious reason we do not want a user from group cricket to see/edit/create events(will be content in terms of drupal) in soccer group, and also we need permission on granularity of groups let say we only want specific user roles in group cricket to create cricket events but not all users can.May be we need to have specific groups menus as well that means when a user belongs to soccer group logs in to the site user has different navigation menus and when user from group cricket logs in he/she has different. \- If you have something on mind as as example mentioned above, with no doubt OG is what you are asking for.

Few modules after og module itself that can be helpful for building something mentioned in example are https://drupal.org/node/206712

but yes if you have different thing in mind as per me using OG will turn out to be overkill in every aspect with no use and @neo has well said about the other side.

---
Tags: users, nodes
---


# Question
Title: How can i move a secondary level Tab to the parent Tabs
I use the Profile2 module and i get in the user edit view the secondary tabs with the extra profile information. How can i move it to the parent tabs and hide the child tabs: "Edit | Info".

# Answer
> 1 votes
Well, for each page, the type of tab is decided my a parameter 'type'. So you can do a hook\_menu\_alter() on the specific page to change that. Please have a look at the "Rendering Menu Items As Tabs" section of the documentation for hook\_menu() to gain idea of what options do what.

---
Tags: routes
---


# Question
Title: Show a block within node content (field template) based on context/taxonomy?
I've created a block using Views that I want to display only on nodes that have a specified value for a taxonomy field (no taxonomy info in the URL). The catch is that I want to display it *within* the main content (between certain fields), not above or below the main content. I've tried doing this in various ways, but none of my attempts have quite gotten what I needed.

Using one method, I managed to use pre-processing functions and the specific field template for the field (field--body--story.tpl.php) to get the block to show up in right place, but it showed for all the nodes of that content type. I tried evaluating for other fields' values within *mytheme*\_preprocess\_field, but those field values don't seem to be available within that function? (They don't show at all using dsm($vars) on the page, I think because the display of that field is hidden.)

Using another method, I used the Context module to get the block to show up only on the nodes of that content type that had that field set to the desired value, but then I could only get it to show above or below the main content, not between specified fields within the main content.

I'm new to Drupal (but am otherwise an experienced web developer), so I'm probably over-complicating this and/or not understanding some major concept. I'm sure there is an elegant way to do this, but I just can't get it (at all, much less elegantly). What am I missing?

# Answer
> 0 votes
you can do what i did before :

-1 install computed field module and enable it.

-2 you have to call the specific views that you want in computed field like this way

```
<?php
$view = views_get_view('your_views_name');
$view->set_exposed_input();
$display_id = 'default';
$view->set_display($display_id);
$view->render();
$entity_field[0]['value'] = ($view->preview());
?>

```

# Answer
> 0 votes
computed field module really great (if you are ok with PHP in the DB). Just wanted to help refine / simplify the example code, and cover a likely use case.

In the computed field to embed a views block just use this in **Display Code (PHP)**

```
$display_output = views_embed_view('view_name', 'display_id');

```

Or to add a common use case, say I have a Field who's value is what I want to pass as an context argument to the view. The inline instructions for **Computed Code (PHP)** cover how to pull that field value into the computed field. And to pass that to the view use.

```
$display_output = views_embed_view('view_name', 'block',$entity_field_item['value']);

```

# Answer
> -1 votes
Did you tried Entity View Attachment (EVA) and adding a PHP Condition (that returns true only on your desired case) to the view? Then you add that whenever the condition is NOT satisfied the view doesn't display anything.

Maybe it would be the way to go.

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


# Question
Title: How can I speed up drupal's node_save() function?
I am having a lot of trouble with the inefficiency of node\_save(). But is node save my problem? That's ultimately what I am trying to find out.

I created a loop with 100,000 iterations. I created the bare minimum for the node object to be valid and save correctly. Here is the node save code:

```
$node = new stdClass();
        $node->type = "test_page";

        node_object_prepare($node);

        $node->uid = 1;
        $node->title = $node_title;
        $node->status = 1;
        $node->language = LANGUAGE_NONE;
        if($node = node_submit($node)){
            node_save($node);
}

```

Here are the results:

100,000 nodes were saved, each using node\_save(). It took 5196.22 seconds to complete. That is ONLY 19 saves a second.

To say the least, that is not acceptable, especially when this person is getting around 1200 individual insert queries per second, and this person is getting 25,000 inserts per second.

So, what's going on here? Where is the bottleneck? Is it the with the node\_save() function and how it's designed?

Could it be my hardware? My hardware is a development server, no one on it except for me - Intel dual core, 3Ghz, Ubuntu 12.04 with 16 gigs of ram.

While the loop runs my resource usage is: MySQL 27% CPU, 6M RAM; PHP 22% CPU 2M RAM.

My mysql configuration was done by the percona wizard.

Mysql says that if my CPU usage is under 70% my problem is disk bound. Granted, I have only a run of the mill WD Caviar 7200 RPM, but I should be getting more than 19 inserts a sec with it I hope!

Not too long ago I wrote about saving 30,000 nodes in a day. However, to be clear, this node has nothing to do with any external forces. It's purely a benchmark to learn about how to increase the speed of calls to node\_save().

Realistically, I need to get 30,000 items into the database every minute using node\_save. If node save is not an option, I wonder if I can write my own drupal api function "node\_batch\_save()" or something that takes advantage of mysql's ability to to do bulk inserts with the INSERT query. Thoughts on how to approach this?

# Answer
You will never get 30 000 inserts a minute using node\_save. No way.

An INSERT is fast because that's all it does. Node save does multiple inserts (main table, revision table, a table for each field), clears any entity caches, and fires hooks. The hooks are the tricky part. If you have many contrib modules (or even one that misbehaves) that can really kill performance, especially if the author didn't account for the "I am saving a ton of nodes at once" use case. For instance, I had to add this to my Migrate class:

```
  public function processImport(array $options = array()) {
    parent::processImport($options = array());
    // Do not force menu rebuilding. Otherwise pathauto will try to rebuild
    // in each node_save() invocation.
    variable_set('menu_rebuild_needed', FALSE);
  }

```

On the other hand, if you write a custom save function that invokes no hooks, you are in clear danger of getting inconsistent data, in a state that is unexpected by the system. I would never recommend doing that. Fire up xhprof and see what's happening.
> 10 votes

# Answer
First of all, install XCache/APC (for PHP \< 5.5) and configure memcached for Drupal.

Then you can optimize your MySQL configuration for heavy queries by using mysqltuner script available at: http://mysqltuner.pl

E.g.

```
# performance tweaks (adjusted based on mysqltuner.pl)
query_cache_size = 32M
query_cache_limit = 256M
join_buffer_size = 32M
key_buffer = 8M
max_allowed_packet = 32M
table_cache = 512
sort_buffer_size = 1M
net_buffer_length = 8K
read_buffer_size = 256K
read_rnd_buffer_size = 1M
myisam_sort_buffer_size = 8M

# When making adjustments, make tmp_table_size/max_heap_table_size equal
tmp_table_size = 16M
max_heap_table_size = 16M

thread_cache_size = 4

```

Other suggestions:

* disable modules which you don't need (e.g. Devel, core Database Logging module, etc.),
* upgrade your PHP to the latest or higher branch,
* recompile your PHP for 64-bit or higher architecture depending on your CPU,
* use the faster storage device for your db files or whole LAMP environment (e.g. SSD or memory-based filesystem),
* use PHP debugger or profiler to find out any performance bottleneck (e.g. XDebug Profiler, DTrace or NuSphere PhpED PHP Profiler),
* run some time-consuming drush command under gprof profiling tool, so you can find some performance bottleneck as well
> 4 votes

# Answer
Use Mongodb module to store fields https://drupal.org/project/mongodb Results here: as per http://cyrve.com/mongodb
> 1 votes

---
Tags: 7, performance, nodes
---


# Question
Title: How do I put a taxonomy term on a panel page?
I'd like to put several hand-picked taxonomy terms on a panels page, each term as a panels pane, showing their descriptions, with a *more* link to the term's view page, and maybe some of the fields that I have added. Is there any module to do this?

Right now for each term I have to create a page, panelize it, add a view pane of the term to it, and then add the page to the panels I want them to show up. Seems to be working nicely enough but still too troublesome for ordinary editors to do it themselves.

# Answer
> 1 votes
1. Create a `Page`
2. Give it a `%term` argument and map it to a `taxonomy term`
3. Create a view pane that takes a `taxonomy term` as argument.
4. Create a mini panel that requires a `taxonomy term` argument.
5. Add the View to the mini panel. Configure it to use the `taxonomy term`.
6. Add the mini panel to the `Page`.

# Answer
> -1 votes
Are you confortable with custom coading?..If so here is an approach that might be friendly:

1. Create a Select field with simple yes/no option, to taxonomy term vocab (whose terms you want to be displayed in panels pane). lets call this "field\_check". For each terms you want to be placed in panels, you will select yes, others will default to no.
2. In a custom module implement hook\_block, to generate a block for all terms, which have the above field checked.

for example:

```
/**
 * Implements hook_block_info().
 */
function mymodule_block_info() {
  $blocks = array();
  $vocab = taxonomy_vocabulary_machine_name_load('vocab_name');
  $vid = $vocab->vid;
  //get the taxonomy terms by vocab id
  $terms_array = taxonomy_get_tree($vid);
  foreach ($terms_array as $key => $voc) {
    if($voc->field_check['und'][0][value] == 'yes') {
      $blocks['term:' . $voc->tid]['info'] = $voc->name;
    }
  }
}

```

Also implement a corresponding hook\_block\_view().

1. This will create a separate block for each term you have chosen to be exposable to be added to panels. Now your content editor can just go in and add the blocks to the panels as panes.
2. Please remember the output will depend on the implementation of hook\_block\_view corresponding to each term you have exposed.

Hope this helps.

---
Tags: taxonomy-terms, panels
---


# Question
Title: Views block: select one item from each content type
I am using a flexslider views block for the homepage of a site. There are content types such as news, articles, announcements... In that views block I would like to display the latest item of each content type.

I played around with the filter and sorting settings in the views admin panel but could not manage to list the items that way. I can either list the latest item -no matter what content type, or list the latest items of a certain content type -only one type. I tried to group the results in someway and that also was not what I need.

I found a related question but there seems to be no useful solution on that page.

Any ideas how I can manage this?

# Answer
> 0 votes
That is easy. Simply create the most recent item for each content type on a different attachment display, and combine them all into the views block display. That is only way you will be able to achieve that

---
Tags: 7, views
---


# Question
Title: Trying to get a field from a fetched entity in rules
I'm trying to use PHP evaluation in rules, and I'm having some trouble getting the data.

This is the beginning of the variable $entity\_fetched:

```
Test 103
stdClass Object
(
[vid] => 611
[uid] => 1
[title] => Test 103
[log] =>
[status] => 1
[comment] => 1
[promote] => 1
[sticky] => 0
[nid] => 611
[type] => calendar_event
[language] => und
[created] => 1380898459
[changed] => 1380898459
[tnid] => 0
[translate] => 0
[revision_timestamp] => 1380898459
[revision_uid] => 1
[body] => Array
(
)
[field_date_time] => Array
(
[und] => Array
(
[0] => Array
(
[value] => 1380898800
[value2] => 1380898800
[timezone] => America/Detroit
[timezone_db] => UTC
[date_type] => datestamp

```

I'm trying to get the value under field\_date\_time, but trying to get it as an array gives me an error that I am trying to get arrays from a stdClass object.

```
<?php print_r($entity_fetched['field_date_time']['und']['0']['value']); ?>

```

So then I try to do this:

```
<?php print_r($entity_fetched->field_date_time->und->0->value); ?>

```

and it gives me an error:

```
Parse error: syntax error, unexpected T_LNUMBER, expecting T_STRING or T_VARIABLE

```

What am I doing wrong here? How do I get this information?

# Answer
> 0 votes
Correct way to get the value is:

```
<?php print_r($entity_fetched->field_date_time['und']['0']['value']); ?>

```

The `$entity_fetched` is returning an object so to access it values you would need to use `->` operator, and than you have array contents which you can access using the array subscript operator `[]`.

**Note:** You **cannot** access object members via the array subscript operator `[]`.
For accessing the object members you need to use the `->` operator.
And to access the array contents we use the `[]` operator.

---
Tags: rules
---


title: custom page template not showing up

text:
# Question
Title: custom page template not showing up
I have created a new page template page--membership.tpl.php and placed it in the /templates folder inside of my theme (the same folder as my regular page.tpl.php file). I flushed the cache, but my page sitename.com/membership is not picking up the changes. (I even tried deleting all of the content of the tpl file to see if it would mess up the page, but nothing.) Any ideas?

# Answer
Reason of `page--membership.tpl.php` not working for `sitename.com/membership` may be:
Drupal used templates as `page--[front|internal/path].tpl.php` based on the internal path of the current page. Do not confuse the internal path to path aliases (Pathauto module uses path aliases) which are not accounted for.

To create the template for `page--membership.tpl.php` one may try one of the following methods:

1. Create template as `page--node--[NODE_ID].tpl.php`, here replace the `[NODE_ID]` with the node id of `membership` page.
2. To get recognize the aliased paths, you have to add the aliased path as part of the theme suggestions: https://groups.drupal.org/node/130944#comment-425189
> 1 votes

---
Tags: theming
---


# Question
Title: Show a maintenance page while moving the site
I am going to move the finished drupal site from the sub-directory to root, because the files are quite large, it takes a while to do so, I want to put a html file there to show 'site maintenance in process, be back soon'.

How can I do this while I move everything?

# Answer
First put your site into the maintenance mode than ("Administer \> Site configuration \> Site maintenance"), and than do the following:

Create the template file for maintenance page as `maintenance-page.tpl.php`.

Tutorial for creating a template file for maintenance page: https://drupal.org/node/195435
> 3 votes

---
Tags: maintenance-mode
---


# Question
Title: Moving drupal site to the root of the server
I have finished my drupal site and about to launch it in the end. Now everything is in a subdirectory called www.mysite.com/drupal\_test, to do that, I had to change one line in the .htaccess file:

```
uncomment #RewriteBase /drupal

```

and change to

```
RewriteBase /drupal_test

```

I realised that .htaccess and some of other files in drupal are hidden files. I just blindly uploaded it and can't really see it in the ftp.

Now, I am ready to move everything to the root. I suppose I have to change that line back. But will I lose all the hidden files if I move? I can re-upload .htaccess, but there so many other hidden file that I don't know, will I lose them?

Is there anything else I should do when I move the directory or is there a better/proper way to do so rather than dragging and dropping all the files to the root?

Sorry if the question is stupid, I only have one day left to do this and I am terrified by moving drupal sites.

# Answer
> 1 votes
I guess you can upload the new .htaccess file and change back the line `#RewriteBase` if you have modified only one line of the .htaccess file, there won't be any problem and even if the file exists there it will give you a option to replace.

Few things that you have remember while moving your site to root folder are:

* Put the site into maintenance mode so that user's posts, comments etc. doesn't gets lost.
* The `#RewriteBase` is uncommented when we use the drupal from the subdirectory. So if you are moving it to the root folder than I guess no need to modify this line. (Anyways you try you way also).
* If you have modified/using the $base\_url in setting.php than don't forget it to update as well.log
* Clear the complete cache, and check the watchdog table data (dblog) at "/admin/reports/dblog" to make no page or anything is having issue.

---
Tags: .htaccess
---


# Question
Title: passing argument from one view to another view
I have created two views , View1 has a list of city names (drop down select box) and View2 displays all the pharma shops across multiple cities. What i am trying to do is , when a city is choosen from view1 i need to display only the pharma shops in that city using view2. I am using drupal 7 and have no knowledge on php. Is there a way to achieve this without doing any coding? Any help would be highly appreciated.

# Answer
> 0 votes
You do not need two separate views for that.

Step 1: Install Address Field Module

Step 2: "Create a content type let say "Pharma Shops" , add adress field to this content type.

Step 3: Add some nodes to this content type, so you can see the results filtering with your views.

Step 4: Create view of type content for "Pharma Shops", add fields you want to show for the nodes in the display and search to find views setting for exposed filters,where again you will be exposing address field to all users to filter down the results.

As a Note: Consider view as ui to make database queries.

---
Tags: views
---


# Question
Title: Why are some place holders '@' and others '%'?
For example:

```
watchdog('alerts', 'Message for %user was sent.', array('%user' => $user));

```

and

```
drupal_set_message(t('options: @options', array('@options' => $form_state['values'])));

```

Is there any difference?

# Answer
Have a look into the function definition of the format\_string() function which is used by the t() function:

Each type of placeholder has a way in which this function intrepretes it:

```
@variable: Escaped to HTML using check_plain(). Use this as the default choice for anything displayed on a page on the site.
%variable: Escaped to HTML and formatted using drupal_placeholder(), which makes it display as <em>emphasized</em> text.
!variable: Inserted as is, with no sanitization or formatting. Only use this for text that has already been prepared for HTML display (for example, user-supplied text that has already been run through check_plain() previously, or is expected to contain some limited HTML tags and has already been run through filter_xss() previously).

```
> 10 votes

---
Tags: tokens
---


# Question
Title: Categorize the contents of content type without creating a different template file for each
I want to apply similar style to the nodes of same content type (style may vary or may be same between content types, but will definitely be same for the nodes of same content types) without creating a template file for each of the content type.

I know one way is to create a template file as `node-TYPE.tpl.php` but I am looking if there is some other way.

# Answer
> -2 votes
If am not wrong than you want to add different class for each content type nodes (this is what the drupal already provides), but if you want to add class to body in your own way or may be adding same class to two different content types than you can try the following.

You can use hook\_template\_preprocess\_node() for adding class to the contents following:

```
function MyTheme_preprocess_node(&$variables) {
  // If you want to same class to two different content types.
  if (('YOUR_CONTENT_TYPE' == $variables['type']) || ('ANOTHER_CONTENT_TYPE' == $variables['type'])) {
    $variables['classes_array'][] = 'CLASS-NAME';
  }
}

```

# Answer
> 1 votes
You can use

Panels Module

It gives you UI to override node templates,providing appropriate selection criteria you can have different layout as per content types.

Display Suite

Display Suite allows you to take full control over how your content is displayed using a drag and drop interface. Arrange your nodes, views, comments, user data etc. the way you want without having to work your way through dozens of template files. A predefined list of layouts (D7 only) is available for even more drag and drop fun!

---
Tags: 6, theming, nodes
---


title: How to change logo dynamically?

text:
# Question
Title: How to change logo dynamically?
How can i change the logo on a site, dynamically, with a URL field which doesn't point to an actual image but to a rendering of an image. Is this possible? I've tried this:

```
$thisimage = $logo_img_url. "&file=" . $_SESSION[ 'logo_img' ] . "&width=300&height=80";
variable_set( 'logo', $thisimage );

```

but it's not working.

Any help would be appreciated. Thanks

# Answer
> 0 votes
This should echo the path to the theme logo, which you could wrap in an tag:

```
<?php echo theme_get_setting('logo_path'); ?>

```

If you want to re-size, crop, or modify the image you should do that in an image style. Once you have made an image style in Configuration \> Media \> Image Styles, you can echo the logo with that style like so:

```
<?php echo image_style_url('my_style_name', theme_get_setting('logo_path')); ?>

```

---
Tags: files
---