title: Publish press release at a precise time

text:
# Question
Title: Publish press release at a precise time
My department is planning to move its website to a new platform in the next year. We are evaluating several options including Drupal and Liferay.

One of the critical requirements is that we need to publish press releases at 11:00 each day. This time has to be very precise; how precise was not specified, the specification just said at 11:00 exactly but I would interpret this as meaning within 5 seconds or less after 11:00. This precision is needed because some of the statistics we publish are "market-sensitive" and we don't want some people to get them sooner than others (the media receive them ahead of time under embargo, other people get to see them at 11:00 via other channels).

We were told that Drupal would be able to do this, but in the initial test rounds it did not work. Now we are told that Drupal does not have the capacity to do this, or at least not with the specific architecture which the central IT service has set up with the assistance of Acquia. To quote:

> As it stands now, the proposed solutions by Acquia and the central IT department, which are based on existing modules, will not be able to publish 'by design' a press release at 11:00 'sharp'.
>
> 'By design' means that content in Drupal which is 'published' is identified with a simple 'flag' which is set by a 'cron job' that checks at regular intervals if the publish date for an item has passed.
>
> This means that in Drupal content can only be published (better: flagged as published) after the publish date/time and not on the publish date/time.

It is said that this might result in press releases appearing 5-60 seconds after 11:00.

Does this information make sense? I would have assumed that quite a few organisations have this requirement and that it would not pose a problem for Drupal? I would like to think that a clean solution can be found, as Drupal meets all our other requirements.

**Notes**:

* Our present website uses Oracle Portal version 10.1.4. According to our website team, this platform has built-in timed publishing which works fine. That is, pages and portal items (files) are set up with a specific time to become visible, which is quite precise. We have had some cache-related issues, but none with the actual timing of the publishing.
* We normally publish only 1 press release per day, occasionally 2. The press releases themselves are PDF files (ca 150 kbytes) with a 1-line title published on the front page of the website. Therefore the operations which have to happen between 11:00:00 and 11:00:05 are something like (a) do something to make the PDF file accessible (b) write new version of front page (c) manipulate cache(s) so that users actually get the new version of the front page.

# Answer
> 0 votes
I'm not aware of *any* architecture that can guarantee publishing of N number of items exactly at some atomic time -- as the number of items N increases; you will always have more processing time given linear execution.

* It sounds like they used hook\_cron and an interval check for publishing unpublished items.

**Option 1 (get rid of interval cron and provide 1 specific cron task @ time)**

They could easily change the architecture to use a specific cron task to check at a specific time via Cron and publish all unpublished items via a Drush task -- removing timeout errors.

This requires new, relatively easy code.

**Option 2 (parrallelize option 1)**

call option 1 with like ultimate\_cron module and background task, with N tasks to publish approximately N content items; parallelize the publishing process to limit how long it takes.

This is new harder code, and harder to debug.

**Option 3 (crazyiness here)**

create an unreachable directory which can be scraped. Scrape the result of viewing the Drupal pages final result to static files; remove restricting .htaccess file or rule at 11pm based on a simple cron task. Eg, make all your dynamic content -- into static pages prior to release and make they public instantly. Your page content may not allow this approach -- but everything would be made public in an instant.

This is crazy and pretty much a rewrite of any approach and removes Drupal and largely the DB almost (but for a reason).

**Whose fault is the problem**

Well, no 1 party is at fault ... the requirements were vague on how many items (at most) would be published at X time and also how long a lag in publishing is allowed.

---
Tags: nodes
---


title: AJAX form duplicates fields

text:
# Question
Title: AJAX form duplicates fields
I am following the ajax\_example.module in the example module closely. Essentially, I have a fieldset with several fields inside. The user fills out these fields, clicks 'add more', and then another fieldset loads beneath it via AJAX.

My form works fine for up to three entries. But, after a third entry is added, it begins duplicating fieldsets.

The logic that generates the form is a simple for loop; it should work the same for 1 or 100 values, and I'm not really sure why the duplicates are being generated. What's even more perplexing is that if I examine $form in a debugger, the form elements are all where they should be, and there are no duplicates.

Code overview: I have a page that calls this form. The form has a button with the 'ajax' property, and when clicked, it adds 1 to $form\_state\['item\_quantity'\]. Then, it regenerates the form, and a for loop creates one fieldset per item\_quantity. There is a conditional to check if this is the last item, which will add a special CSS class if true.

```
function manual_import_form($form, &$form_state) {
  //set up options for select list
  $task_options = get_task_options();
  $location_options = get_location_options();
  $model_options = get_model_options();

  $form['#attached'] = array(
    'css' => array(
      'type' => 'file',
      'data' => drupal_get_path('module','manual_import') . '/manual_import.css',
    ),
  );
  $form['#tree'] = TRUE;
  $form['scenario'] = array(
    '#type' => 'select',
    '#title' => t('Import Scenario'),
    '#options' => array(
      'shipment' => t('Shipment'),
      'location' => t('Location'),
      'manual' => t('Manual'),

      ),
    '#default_value' => 'shipment',
  );
  $form['scenario_shipment'] = array(
    '#type' => 'fieldset',
    '#title' => t('Associate Group To Shipment'),
    '#description' => t('Associate a group of items to a shipment, and auto-generate tasks'),
    '#states' => array(
      'visible' => array(
        ':input[name="scenario"]' => array('value' => 'shipment'),
      ),
    ),
    '#collapsible' => TRUE,
    '#collasped' => FALSE,
  );
  $form['scenario_shipment']['shipping_list_number'] = array(
    '#type' => 'textfield',
    '#title' => t('Shipping List Number'),
    '#prefix' => '<div class="manual-import-shipping-list">',
    '#suffix' => '</div>',
  );
  $form['scenario_shipment']['shipping_from'] = array(
    '#type' => 'select',
    '#title' => t('Shipping From'),
    '#options' => $location_options,
    '#default_value' => 283,
  );
  $form['scenario_shipment']['shipping_to'] = array(
    '#type' => 'select',
    '#title' => t('Shipping To'),
    '#options' => $location_options,
    '#default_value' => 283,
  );

  $form['scenario_location'] = array(
    '#type' => 'fieldset',
    '#title' => t('Associate Group To Location'),
    '#description' => t('Associate a group of items to a location, and auto-generate tasks'),
    '#states' => array(
      'visible' => array(
        ':input[name="scenario"]' => array('value' => 'location'),
      ),
    ),
    '#collapsible' => TRUE,
    '#collasped' => FALSE,
  );
  $form['scenario_location']['location'] = array(
    '#type' => 'select',
    '#title' => t('Location'),
    '#options' => $location_options,
    '#default_value' => 283,
  );
  $form['scenario_manual'] = array(
    '#type' => 'fieldset',
    '#title' => t('Manually Create Tasks'),
    '#description' => t('Manually select the tasks to be created for the items in the group.'),
    '#states' => array(
      'visible' => array(
        ':input[name="scenario"]' => array('value' => 'manual'),
      ),
    ),
    '#collapsible' => TRUE,
    '#collasped' => FALSE,
  );
  $form['scenario_manual']['task'] = array(
    '#type' => 'select',
    '#title' => t('Task Type'),
    '#options' => $task_options,
  );
  $form['import_items'] = array(
    '#type' => 'container',
    '#prefix' => '<div id="import_items">',
    '#suffix' => '</div>',
  );
  if (empty($form_state['import_item_quantity'])) {
      $form_state['import_item_quantity'] = 1;
  }
  for ($i = 1; $i <= $form_state['import_item_quantity']; $i++) {
    $form['import_items'][$i] = array(
      '#type' => 'fieldset',
      '#title' => t('Import Item @item', array('@item' => $i)),
      '#collapsible' => TRUE,
      '#collapsed' => FALSE,
    );
    $form['import_items'][$i]['ticket_number'] = array(
      '#type' => 'textfield',
      '#maxlength' => 32,
      '#title' => t('Ticket Number'),
      '#class' => 'manual-import-item-field',
      '#prefix' => '<div class="manual-import-item-field manual-import-item-ticket">',
      '#suffix' => '</div>',
    );
    $form['import_items'][$i]['device_id'] = array(
      '#type' => 'textfield',
      '#maxlength' => 32,
      '#title' => t('Device ID'),
      '#prefix' => '<div class="manual-import-item-field manual-import-item-device-id">',
      '#suffix' => '</div>',
    );
    $form['import_items'][$i]['device_model'] = array(
      '#type' => 'select',
      '#title' => t('Make/Model'),
      '#options' => $model_options,
      '#prefix' => '<div class="manual-import-item-field manual-import-item-device>',
      '#suffix' => '</div>',
    );
    if ($i == $form_state['import_item_quantity']) {
      $form['import_items'][$i]['device_model']['#prefix'] =
        '<div class="manual-import-item-field manual-import-item-device manual-import-item-last">';
    }
  }
  $form['import_items']['item_add'] = array(
    '#type' => 'submit',
    '#value' => 'Add another!',
    '#ajax' => array(
      'callback' => 'manual_import_item_ajax_callback',
      'wrapper' => 'import_items',
    ),
    '#submit' => array('manual_import_item_add'),
  );
  xdebug_break();
  return $form;
}

function manual_import_item_ajax_callback($form, $form_state) {
  return $form['import_items'];
}

function manual_import_item_add($form, &$form_state) {
  $form_state['import_item_quantity']++;
  $form_state['rebuild'] = TRUE;
}

```

# Answer
It's in your CSS.

```
$form['import_items'][$i]['device_model']

```

Is missing a double quote on the #prefix. Change To:

```
 '#prefix' => '<div class="manual-import-item-field manual-import-item-device">',

```
> 0 votes

---
Tags: forms, ajax
---


title: can't delete the preview button

text:
# Question
Title: can't delete the preview button
I have used the following code to delete the preview button which is on one of my create content type pages, but its not doing anything, what am I doing wrong?

```
function example_module_form_alter(&$form, $form_state, $form_id) {
// Check for a particular content type's node form.
if ($form_id == 'example_content_type_node_form') {
drupal_set_message("entering formId");

unset ($form['preview']);
}
}

```

the drupal\_set\_message does go off, so I know that I am entering the if statement. I have put this code in a custom module (example\_module).

# Answer
> 1 votes
You don't need to write the code your self, there are already modules out there for exactly that!

**1. Jammer Module** (*Recommended*)

> > Hide or remove items from displaying including the **node and comment preview buttons**, node delete button, revision log textarea, workflow form on the workflow tab, and feed icon

**2. Preview module** (*Less Recommended*)

* This module hasn't officially been released yet on Drupal 6 or 7, and it hasn't been updated in quite a while, so you may not want to use it on your live site

---

***However if your using drupal 7, it's already a built in feature:***

> For Jamming the Preview button for content types in Drupal 7, the functionality is built into core. Visit admin/build/node-type/blog (example for blogs), or by navigation path, Administer - Site building - Content types - edit - Submission form settings fieldset

---

**Edit:** Since your using drupal 6, my recommendation is just to go with the Jammer Module.

# Answer
> 3 votes
You don't need to use custom code to delete the preview button. On the Content Type administration page at admin/structure/types/manage/your\_content\_type, you can selection `Disabled` for `Preview before submitting` under `Submission form settings`. This will remove the preview button for that content type.

# Answer
> 0 votes
I needed to do it programmatically; here's the code solution in case anybody else needs to do it this way.

**Disables comment preview for ALL node types**

```
/**
 * Disables comment preview button for ALL node types.
 */
function my_module_update_7001() {
  $node_types = array_keys(node_type_get_types());
  foreach ($node_types as $node_type) {
    variable_set('comment_preview_' . $node_type, DRUPAL_DISABLED);
  }
}

```

If you want to remove the subject/title field from all node types (as I did) add this line below the other `variable_set...`

```
variable_set('comment_subject_field_' . $node_type, DRUPAL_DISABLED);

```

---
Tags: forms, 6
---


# Question
Title: How to add an html element (BODY) class based on taxonomy from logged in user?
I'm building a website on Drupal 7 which will be accessible only to registered users. A taxonomy term is referenced to the user account. I need to add a body class based on that taxonomy term so I can personalize the theme's look depending on the logged in user.

# Answer
> 1 votes
In your custom module implement hook\_preprocess\_field().In the given code I am adding a taxonomy term field with uid as class,you can change to your requirement.

```
function mymodulename_preprocess_field(&$variables) {
  global $user
  if($variables['element']['#field_name'] == 'your_taxonomy_term_name') {
    dpm($variables);
    dpm($variables['classes_array']);
    $variables['classes_array'][] = $user->uid;
  }
}

```

# Answer
> 0 votes
Here is how I did it.

```
function mytheme_preprocess_html(&$variables) {
  global $user;
  $user = user_load($user->uid); // Load user
  $variables['classes_array'][] = $user->field_myfield['und'][0]['tid'];
}

```

It will output the tid not the term name that is being referenced in the user account.

---
Tags: 7, taxonomy-terms, users, theming
---


# Question
Title: How can I display the price field twice?
I am using commerce kickstart 2. Here's a screen shot of my product display

I've set a VAT tax rate in Drupal Commerce, so the price in that screenshot is the price of the product, plus the 20% VAT tax.

How can I display the price excluding VAT?

# Answer
You should use Commerce Extra Price Formatters module.

**Extra Price Formatters Implemented So Far**

* **RRP / Your Price**

Allows you to display the *Retail Price* and the *User Price* for a product and optionally the amount the customer will save.

Allows you to switch the display back to a single price if there is no discount available on a particular product.
* **Formatted Price with Prefix and Suffix**

Allows you to present a price in the style **just £9.99 ex VAT** or **only £9.99 for a limited time only.**
* **Formatted Price with no decimal places**

When you are selling items with whole unit prices, you don't necessarily want to see £10.00. This formatter lets you change the display to show £10. (use this with care!)

There's a video demo here: http://www.youtube.com/watch?v=-WR3mKjou8M

Then you should add two *price fields* in your product content type. In your manage display tab you would be having a settings option to calculate your price excluding or including tax and other parameters and thus you can add two price fields.
> -1 votes

---
Tags: entities, commerce
---


# Question
Title: Page title set from the title callback doesn't change
I created a simple download module to redirect a user when they click the download button to another page. Now I need to change the the page title every time a new download is triggered.

This is my code.

```
function custom_download_menu() {
  $items['download-code'] = array(
    'title callback' => 'custom_download_page_title',
    'page callback' => 'custom_download_view',
    'access arguments' => array('access content'),
    'access callback' => TRUE,
  );

  return $items;
}

function custom_download_page_title() {
  if (isset($_POST['title'])) {
    $title = "Downloading " . $_POST['title'] . " Code";
  }
  else {
    $title = "Download Code";
  }

  return $title;
}

```

But most of the time, the title does not change. It seems that it is using the title that is cached before.

I already added the following code so the page will not be cached:

```
drupal_add_http_header("Last-Modified", gmdate("D, d M Y H:i:s") . " GMT");
drupal_add_http_header("Cache-Control", "no-store, no-cache, must-revalidate"); // HTTP/1.1
drupal_add_http_header("Cache-Control", "post-check=0, pre-check=0", false);
drupal_add_http_header("Pragma", "no-cache"); // HTTP/1.0
drupal_add_http_header("Expires", "Sat, 26 Jul 1997 05:00:00 GMT"); // Date in the past

```

Am I missing something?

Update:

```
<form id="form1" name="form1" method="post" action="/download-code">
    <input type="hidden" name="title" id="title" value="[node:title]" />
    <input type="hidden" name="download_code" id="download_code" value="[node:field_code_file]" />
    <input type="hidden" name="uri" id="uri" value="[node:url:relative]" />
    <input type="submit" class="downloadButton" value="Download Code">
</form>

```

# Answer
You're missing the `title arguments` key in `hook_menu`

e.g:

```
/**
 * Implements hook_menu
 */
function custom_download_menu() {
  $items = array();

  $items['download-code/%'] = array(
    'title callback' => 'custom_download_page_title',
    'title arguments' => array(1),
    'page callback' => 'custom_download_view',
    'access callback' => TRUE,
  );

  return $items;
}

/**
 * hook_menu title callback
 */
function custom_download_page_title($file) {
  if (isset($file) {
    $title = "Downloading " . $file . " Code";
  }
  else {
    $title = "Download Code";
  }
  return $title;
}

```

If the download link is

> download-code/my-file.txt

The page title should then reflect that.
> 3 votes

# Answer
Instead of a title callback, in the page callback for the download-code page, put the check and set title using, drupal\_set\_title.

Put this code at the top of the callback function:

```
if (isset($_POST['title']))
        $title = "Downloading " . $_POST['title'] . " Code";
    else
        $title = "Download Code";
drupal_set_title($title);

```

Please make sure you clear menu cache and check to see if this works
> 0 votes

---
Tags: 7, routes
---


title: jQuery in external file not working

text:
# Question
Title: jQuery in external file not working
I have an external file being loaded via template.php using the following code:

```
function digital_dots_preprocess_views_view(&$vars) {
  $view = $vars['view'];
  if($view->name == 'work') {
    drupal_add_js(drupal_get_path('theme', 'digital_dots') . '/assets/scripts/fx.js');
  }
}

```

The JS file is being loaded with the following code:

```
(function ($) {
    $(".image-overlay").hide();
    //alert('It works!');
})( jQuery );

```

Un-commenting the alert will trigger the alert however the hide effect doesn't?

Very confused!

# Answer
> 2 votes
If you are getting `alert` from the JS file than it means your JS file is loading properly, and the problem of hide seems to be causing because hide to be called in the document.ready as following:

```
// Jquery wrapper for drupal to avoid conflicts between libraries.
(function ($) {
  // Jquery onload function.
  $(document).ready(function() {
    $(".image-overlay").hide();
  });
})(jQuery);

```

---
Tags: 7, javascript
---


title: jquery.js from CDN sources

text:
# Question
Title: jquery.js from CDN sources
I hope use a CDN source as default, which doesn't load the local jquery.js while the CDN is OK. If the CDN doesn't reply, load the local jquery.js.

I have writted this in my template.php.

```
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>!window.jQuery && document.write('<script src="<?php echo base_path().path_to_theme(); ?>/js/jquery.min.js"><\/script>');</script>

```

It worked well until I used the Flag module, which loads the flag.js file. I think this file just work with the version of jQuery that comes with Drupa, as it doesn't work with the jQuery library from Google CDN.

Did Drupal developers rewrite the whole jquery.js? I cant believe that.

What should I do to solve this problem? Can I fix it by rewriting flag.js? If it's possible I really don't want use other module such as the jQuery Update module; it is too huge.

# Answer
No, Drupal devs didn't rewrite jQuery, a standard version is included (1.3.2). I can vouch for flag.js working fine with that version of jQuery.

It's *not* compatible with the version of jQuery that you're including though. You're probably also introducing a conflict between the two versions of the library that are included in the page.

jquery\_update isn't a huge module at all, and it gives you several versions of jQuery plus the CDN option out of the box. It was written specifically to solve the problem you're trying to get round.

There's no good reason not to install it; if you don't, you'll just be reproducing functionality it already provides, which is time you could spend doing something productive.
> 3 votes

---
Tags: javascript, cdn
---


# Question
Title: Need to ignore empty variable values for Computed Field when multiplying
In my entityform, different fields appear based on choices (dependencies). Two appear at once. I'm multiplying the values using a Computed field. All works if the variables have a value. I have 8 fields I want to multiply, but ignore the empty values. Can't set field defaults to 0 (wrecks multiplication) or 1 (messes with totals).

The following warning appears for each empty field; here it's "line 1" for the 1st variable/field. No warning for those that have a value.

> Warning: array\_pop() expects parameter 1 to be array, null given in eval() (line 1 of /home/content/67/10793667/html/sites/all/modules/computed\_field/computed\_field.module(466) : eval()'d code).

How can I instruct the computed field to ignore the empty fields?

Here is my Computed Code (PHP).

```
$howmany = array_pop(array_pop(field_get_items($entity_type, $entity, 'field_how_many')));
$price1 = array_pop(array_pop(field_get_items($entity_type, $entity, 'field_reg_price1')));
$price2 = array_pop(array_pop(field_get_items($entity_type, $entity, 'field_sale_price2')));
$entity_field[0]['value'] = $howmany*$price1*$price2;

```

I tried adding this after the `$price2` line, but it didn't work.

```
if ($price2 == null) {
    $price2 = 1;
}

```

I tried this too, and it didn't work.

```
if (!empty($price2)) {
  $price2 = 1;
}
else {
  $price2 = array_pop(array_pop(field_get_items($entity_type, $entity, 'field_sale_price2')));
}

```

# Answer
Both @Neo's answer and @danielesus's question shows PHP code that will throw errors. @Neo, `empty()` only works with variables before PHP 5.5. Both: `array_pop` requires a variable or something returned by a reference-returning-function which `field_get_items` is not.

Now let's consider what `field_get_items($entity_type, $entity, 'field_how_many')` returns: it returns an array indexed by delta where the values are `field_column => value`. You can do

```
if ($all_items = field_get_items($entity_type, $entity, 'field_how_many')) {
  $item = reset($all_items);
  $value = reset($item);
}

```

as there's no need to actually modify the array with `array_pop` but also you can use your knowledge about Field API and know the actual column name which I suspect will be `value` here (would be `tid` for a taxonomy reference field for example) and that `$delta` is, if you have a field with cardinality 1 is actually 0:

```
$value = NULL;
if ($all_items = field_get_items($entity_type, $entity, 'field_how_many')) {
  $value = $all_items[0]['value'];
}

```

Fast and simple.
> 1 votes

# Answer
```
$howmany = !empty(field_get_items($entity_type, $entity, 'field_how_many')) ? array_pop(array_pop(field_get_items($entity_type, $entity, 'field_how_many'))) : 1;

$price1 = !empty(field_get_items($entity_type, $entity, 'field_reg_price1')) ? array_pop(array_pop(field_get_items($entity_type, $entity, 'field_reg_price1'))) : 1;

$price2 = !empty(field_get_items($entity_type, $entity, 'field_sale_price2')) ? array_pop(array_pop(field_get_items($entity_type, $entity, 'field_sale_price2'))) : 1;

$entity_field[0]['value'] = $howmany*$price1*$price2;

```

If this still does not work, Please try to inspect the structure of the stuff returned by field\_get\_items(). I am pretty sure the issue lies in returning a null from the fist array\_pop.

In order to inspect the structure, add these lines to your compute code after enabling and installing devel module:

dpm(field\_get\_items($entity\_type, $entity, 'field\_how\_many')); dpm(field\_get\_items($entity\_type, $entity, 'field\_reg\_price1')); dpm(field\_get\_items($entity\_type, $entity, 'field\_sale\_price2')));
> 0 votes

---
Tags: entities
---


# Question
Title: Have the ability to present multi-part, segmented content
With a Drupal 7 website I have the following requirements. It shall have the ability to present multi-part, segmented content which includes: a table of contents, links to navigate forward and backwards through the child content items, and a link to navigate up to the table of contents.

What is a good way to implement the above requirements?

# Answer
> 0 votes
Provided "contents" means "nodes" (and it usually does in the Drupal universe) this looks like the sort of application that the core book module is supposed to handle.

If you require functionality *beyond* what is provided by the book module, you need to expand the question.

Note than in Drupal 7, the hierarchical relationship management, navigation links and generated table of contents may be extended to *any* node entity, just by including the node in a "book" (i.e. you no longer need to use the *book* content type to have the functionality of the book module).

---
Tags: nodes
---


# Question
Title: Attaching comments to blog post promoted to front page
I have 'blog posts' that are promoted to the front page. We would like to have the ability to have users posts comments on these posts through the front page without having to click through to get to the posts page.

# Answer
> 1 votes
The reason you do not see comment form on content promoted to front page is because by default comment form shows on full node view.So following code may help you.

```
function mymodulename_node_view($node, $view_mode, $langcode) {
  if(drupal_is_front_page() && $node->type == "your_content_type") {
      $node->content['comments'] = comment_node_page_additions($node);
  }
}

```

---
Tags: 7, comments
---


# Question
Title: How can I get my WYSIWYG editor to stop *#@&%^ing up my HTML?
I've tried every combination of "CLEANUP AND OUTPUT" settings that might conceivably prevent munging my HTML, but nothing works. No matter, what, my HTML gets flattened or in some way rewritten, mainly with whitespace being trimmed off that I want to leave in.

I would suspect CKEditor (version 3.6.4.7575) except that when I tell WYSIWYG to "Apply source formatting", CKEditor doesn't prevent that, so it seems that logically this problem is in the WYSIWYG module. "Apply source formatting" simply causes the HTML to be screwed up differently. Some linebreaks are left in place, but spaces at the beginning of the line are left in place.

How can I prevent this, and still use a WYSIWYG editor?

# Answer
> 3 votes
I had just run into this problem of wysiwyg editors reformatting the html source into a minimized blob of contiguous html.

The solution I found was to use TinyMCE editor with WYSIWYG and to add an additional module called wysiwyg-codemagic. With this module, you place the codemagic plugin for TinyMCE in the TinyMCE library's plugins (Follow the instructions in module's Read.Me).

Now, when the author of the node content drops into the html source, as occasionally needed, the source is very readable and presented correctly.

This was an old post, but I thought this new info would help for the others of us that still run into this problem

# Answer
> 2 votes
Have you looked at the Text Formats section in the administration pages, such as admin/config/content/formats/filtered\_html? Especially note the "convert line breaks into HTML" setting, and the "Limit Allowed HTML Tags" tab, as these settings will affect your HTML output even after the WYSIWYG editor is done with it.

# Answer
> 1 votes
This may not solve all of your problems, but I can recommend the WYSIWYG Filter module. It provides a new filter you can add to your input format(s), giving you more control over the HTML code that the input format should allow.

# Answer
> 0 votes
One solution is to make rich text editors NOT the default. This is really a work-around, but it allows me to have some pages use well-formatted and non-mangled HTML without fearing that everytime I edit the page it'll make a round-trip through whatever is munging it (either the editor, or the WYSIWYG module, or the text format settings). As long as I don't open the rich text editor on that node (or panel page) I'm okay.

Another similar work-around is to define a text format (e.g. "Pure HTML") which doesn't allow a rich text editor. Then select that text format for pages where you want to edit the HTML manually.

Neither of these are complete solutions, unfortunately, because for any given node you can *either* have a rich text editor *or* complete control over your HTML and its formatting.

---
Tags: wysiwyg
---


# Question
Title: Validate form: at least one of the fields is required
Users need to fill link fields wrapped in a field group to their various social profiles like fb, twitter, pinterest. I need them to give any one of the fields as required since I use it to verify their profile.

I've tried conditional fields and field validation. Field validation require one of various fields gives me like seven "one of the fields is required" messages for all seven fields.

I tried different configurations with conditional fields without results.

Is there a workaround with any other modules?

# Answer
> 3 votes
Where are these fields attached to? User registration page or content type?

Anywhere it might be, there must be a form, and what you need to do is add a form level validation function, not a field level validation. Field level validation works well, when logic is associated with that particular field but for your case you need to add form level validation handler:

Here is an example:

```
/**
 *  Implementation of hook_form_alter().
 */
function yourmodulename_form_alter(&$form, $form_state, $form_id) {
  switch ($form_id) {
    case 'user_register': // or whatever is the form id in which you want to apply validation
      // this line adds a new validation function
      $form['#validate'][] = 'custom_data_validate'; //or whatever validation function name
      break;
    }
}

/**
 *  Custom validation function.
 */
function custom_data_validate(&$form, &$form_state) {
  $values = $form_state['values'];  //all submitted values will be in this array, keyed by the name, grab any value you want.

  if (empty($values['facebook']) && empty($values['twitter'])) {
    form_set_error('facebook', t("you need to fill up either of the two fields"));
  }
}

```

I did not take care of the logic and the code provided is just an example but the basic workflow is:

1. Alter the form and add a custom validation function.
2. All the submitted values will be available in $form\_state in the validation function.
3. Check the logic and trigger a form\_set\_error() to set the error.

---
Tags: 7, forms
---


# Question
Title: Pros and cons of exposed filters versus contextual filters
I need to do some complicated filtering on my View and it seems that contextual filters lack the operators (e.g. between, greater than) available within the exposed filter configuration. However, I don't want to user to be able to see or amend any filter widgets.

I can achieve this by setting the exposed filters to appear as a block and NOT assigning the block to the page. I can then invoke the View by constructing a path with whatever querystring I wish and the filters are applied appropriately (e.g. www.mywebsite.com/myview?field\_range=10&field\_color=red).

Is there anything inherently wrong with this approach to using views, or any disadvantages?

# Answer
> 1 votes
Nothing wrong with your approach. i have used it myself a couple of times and seemed to have worked pretty well.

regarding the situation you faced, contextual filters are more sort of an argument rather than a filter so the miss the comparison operators.

The tool in view to use external input to filter is the exposed filter. that is what it is designed for and I think you can go ahead with this approach.

---
Tags: views
---


# Question
Title: How to display view with context filters as a block in sidebar?
I'm trying to display a view in a block, the content of which is based on value of one of field of currently displayed node. I found out that I must use `Views content panes` and `Mini panels` modules. I created appropriate view in format "content pane" and I'm stuck. I can't find how to proceed any further. I tried to create new mini panel but I don't see how to associate one with another.

---

## Clarification

I choose `Panels` after quick research because I want to display view in a block, which takes arguments **from it's context**: field value of current node. Nodes are displayed using standard template and `Display Suite`.

## Clarification 2

What I exactly want to do: take field value from currently displayed node and in a block in sidebar display list of nodes that also have same value in that field.

# Answer
> 2 votes
I got it!

1. Create views block type display that requires context filters.
2. Create block with PHP filter content type.
3. Put into it code:

```
<?php
  $node = menu_get_object();
  $field = field_get_items('node', $node, 'field_NAME');
  echo views_embed_view('VIEW_NAME', 'block_1', $field[0]['value']);
?>

```

(this eventually can be moved into custom module to avoid using PHP filter)

# Answer
> 1 votes
Do you really want to add mini-panels? based on your question, you want to display a view in a block. You can just create a block display of a view. this can be added to a normal panels page (as you want to have this view display contents based on the field value of the node) I am guessing that you have overridden the node template by panels and now you can embed the block display of the view directly in the panels and pass in the context of the present node.

I am not sure you even require mini panels. Answer can be pin pointed if you make your question more clear to give out what is that you are exactly looking to do.

UPDATE:

Ok, yes panels can very easily come to your rescue here. So that part is good, you can pass in field value as context.

So how to add a content to a panel (or mini panel) is same as what ankit explained in his answer. the trick is that when you try to add a views block to a panel, it will give you an option to pass context for panels to views per "contextual filter" you have defined in a view.

So here are the steps:

1. Create a views block type display.
2. obviously you will be adding some contextual filters which accepts arguments from panels. (remember this contextual filters are what will accept arguments from panels)
3. While adding this view to panels through steps mentioned by Ankit in his answer, pass in the required argument per contextual filter you have added.

In order for me to help you to configure the view, you heet to let me know what exact stuffs you are looking to add in a view and how are you planning to construct it functionally. Hope this helps.

Update 2:

Mini-panels are not listed in blocks page. Mini Panels are listed in mini panels page. Also mini Panels do not have a dedicated page. They are meant to be embedded into a parent panels page. I don't think you need mini panels at all. As per my Understanding, here a couple of pointers.

1. I think you are trying to add a view to a mini panel and have it available as block and place it in a region in a page. this will not work out as mini panels are never available as blocks.
2. I am not sure about display suite, but now if you want to use this mini panel, you need to override the node template with panels.

You need to understand that Panels/mini panels and display suites are two different approaches to do the same thins. Here is a very good resource to know more.

UPDATE 3:

Just found an awesome module that might just do the trick for you through a views only approach. This module provides a views display that gets directly attached to the node and gets tokens from node field that you can use as view's contextual filters directly.

Here is the link to the module.

# Answer
> 0 votes
To make mini panel acts like a block try the following:

* Select the mini panel for editing and select the "content" editing display.
* Next pick the `gear` (present in the upper right corner of the desired region in the mini panel) and select 'add content', the pop-up will give you the selection of available content that can be placed in the panel.
* Once you have the mini panel configured, you place it in a theme region just as we do for block: select the mini panel from the `admin/structure/blocks` page for your theme (It can be found in the list of disabled blocks at the bottom of the layout page form).

Also you can have look at the tutorials that may be helpful for you:
http://drupalize.me/videos/basics-views-content-panes
https://drupal.org/node/1704274

---
Tags: blocks, panels, views
---


# Question
Title: What does "Entity API" add to the Drupal API, and why would a module depend on it?
The Entity API module extends the entity API defined in Drupal. In which cases should a module use the API provided from that module? Are modules that implement new entities easier to be written if they depend on the *Entity API* module?

By "easier to be written" I mean that modules using *Entity API* would require less code to be written compared to a module that doesn't use *Entity API*.

I read the project page, but I still don't completely understand the reason to prefer creating a module that depends on the *Entity API* module, rather than a module depending only from Drupal core code. I understand that a module extending rules and implementing an entity should use the *Entity API* module; in the first case, the reason is also that the *Rules* module depends on the *Entity API* module.

# Answer
> 15 votes
Not complete, but here are some advantages that I know of:

* Drupal core only provides an EntityController for loading entities. For save, update and delete, you either need to write it yourself or use Entity API.
* You you can expose the base properties of your entities wit hook\_entity\_property\_info(), see privatemsg\_entity\_property\_info() for an example. The advantage of this is that rules.module knows your entity properties and you read and write them with rules. And you also get token integration for free.
* It can also automatically provide you with an administrative UI for your entities

# Answer
> 7 votes
Automatic Views integration, admin UI, exportable entities (all of this is optional). Plus a lot of syntax sugar things that didn't make it into D7 and you need them (generic entity\_save(), entity\_create(), putting your custom logic in "entity classes"...)

Plus, modules (efq\_views, rules) do really cool things with properties.

# Answer
> -1 votes
i do believe, the entity api (module) was basically removed from drupal 7 core prior to release because it was considered incomplete.. Only the basic entity api CRUD functions where left in drupal core for its GM release .

---
Tags: entities
---


title: Showing blocks basing on content type

text:
# Question
Title: Showing blocks basing on content type
Can anyone provide a snippet code that is applicable for Drupal 6?

# Answer
> 1 votes
If used from inside the Drupal 6 Block UI Admin Page use php area:

```
$whereami=menu_get_object();
if (isset($whereami->type) && $whereami->type=='TYPEYOUARELOOKINGFOR') {
  return TRUE;
} else {
  return FALSE;
}

```

# Answer
> 0 votes
With the following code snippet, your block will be visible, if you add, edit or view a node of a specific content type:

```
<?php

    $type = 'my-content-type';

    if (arg(0) == 'node' && is_numeric(arg(1))) {
      $node = node_load(arg(1));
        if ($node->type == $type) {
            return TRUE;
        }
    }

    if (arg(2) == $type) {
        return TRUE;
    }

    return FALSE;

?>

```

---
Tags: blocks, nodes
---


# Question
Title: Having trouble printing my theme from a custom module
I created a custom tpl.php page with some basic HTML:

```
<div id='test'>TEST</div>

```

And a module file that defines the theme:

```
function my_module_test_theme($existing, $type, $theme, $path) {
    $items = array();

    //Test
    $items['test_test'] = array(
        'template' => 'test-test',
        'path' => drupal_get_path('module', 'my_module') . '/templates',
    );

    return $items;
}

```

But when I try to print it out in my theme it doesn't work:

```
<?php $output = theme('test_test'); ?>

```

Am I printing out the theme in my site's theme's page.tpl.php incorrectly?

# Answer
> 1 votes
I forgot to echo $output.........

---
Tags: 7, theming
---


# Question
Title: How can I assign an icon to users depending on their gender?
I'd like comments on my website to look like this:

Every comment has to be preceded by an image, depending on the gender of the user who wrote the comment. Users can choose Male/Female as their gender when they register, so the icon can't be changed: it's only related to the gender. How can I achieve this?

# Answer
Create a vocab as gender and add two taxonomies to it as male and female. To the gender vocab add image field and while creating the male and female taxonomy term add the respective images.

Now add the term reference file to user entity and keep it as stele list.

In your custom module hook\_user\_presave and get the value for the taxonomy field.when you know the selected taxonomy you can load the taxonomy to get the image field fid associated with it assign the fid to $user-\>picture.

Now everywhere image will load as per the gender selected.
> 1 votes

---
Tags: 7, media, comments
---


title: Remove an uploaded file

text:
# Question
Title: Remove an uploaded file
I am working with files in a Drupal module. I added this form:

```
$form['Background_image'] = [
  '#type'               => 'managed_file',
  '#title'              => t('Image'),
  '#progress_message'   => t('Please wait...'),
  '#progress_indicator' => 'bar',
  '#description'        => t('Click "Browse..." to select an image to upload.'),
  '#required'           => TRUE,
  '#upload_validators'  => ['file_validate_extensions' => ['jpeg jpg png gif']],
  '#upload_location'    => 'public://backgroundimage/',
  '#default_value'      => $this->options['Background_image'],
];

```

The file is added properly. Once the file is uploaded a remove button appears allowing to remove the file and upload a new one. The problem is that this button is not working. How can I remove an uploaded file?

# Answer
Once you have uploaded a file you must be having file object so use file\_delete(stdClass $file, $force = FALSE) to delete the file.
> 0 votes

---
Tags: 7, forms, files
---


# Question
Title: Add multilingual support to Drupal 8 Hello World module
Today we already can upgrade contrib projects to Drupal 8 (#D8CX) and there are more and more “Hello World” code examples for Drupal 8. Some of them:

1. Drupal 8: Writing a Hello World Module
2. Drupal 8: Hello OOP, Hello world!
3. Drupal 8: Hello, Configuration Management
4. Drupal 8 module development #3 - adding a settings page - revision
5. Drupal 8 isn't Scary, Pt. 1: Introduction & Creating a Hello World Module

Can we add multilingual support to such simple modules?

# Answer
Drupal 8 has many improvements for interface, configuration and content translation. There are great series of articles from Gábor Hojtsy: Multilingual Drupal 8.

Let's make Hello World module settings from this article translatable. Full module code is avalible here: https://github.com/kalabro/drupal-examples/tree/master/hello
This code was tested with core 8.x dev branch (`ed8dfae` 2014-05-19).

## 1. Preparing Drupal 8 installation

* Enable “Language”, “Interface Translation” and “Configuration Translation” modules.
* Configure multiple languages.
* Place “Language switcher” block.
* Check how “Configuration Translation” with *Site information* form.

## 2. “Hello World” module

* Use Drupal 8: Hello, Configuration Management article as base for “Hello World” module.
This module provides static `/hello` page with hardcoded “'Hello, World!'” message in it. The message can be outputted in normal or upper case. There is a setting for message case:
* Play with the code until it becomes yours.
**hello.info.yml:**

```
name: Hello
description: '"Hello World" module with config translation support.'
core: 8.x
type: module
configure: hello.settings_form

```

## 3. More complex settings

* Let's make message on `/hello` page configurable (dynamic).
For this purpose we should update form and controller.

+ Add `'hello_message'` textfield in `'buildForm'` method:

    ```
    $form['hello_message'] = array(
      '#type' => 'textfield',
      '#title' => t('Your "Hello World!" message'),
      '#default_value' => $config->get('hello_message'),
      '#required' => TRUE,
    );

    ```
    + Update `HelloController` to take hello message from setting instead of hardcoding it:

    ```
    $hello_message = $config->get('hello_message');

    ```
* Check full code in repository: HelloConfigForm.php, HelloController.php and etc. Feel free to ask any questions.

## 4. Make settings translatable

Our setting 'Your "Hello World!" message' should be translatable.

* First of all we have to add config schema. It is recommended to add schema for any modules with configuration.
**hello.schema.yml:**

```
hello.settings:
  type: mapping
  label: 'Hello World settings'
  mapping:
    case:
      type: integer
      label: 'Letter case of your "Hello World!" message'
      # translatable: true
    hello_message:
      type: text # translatable by default.
      label: 'Your "Hello World!" message'

```

Now Drupal knows what kind of data is stored in module config. Some of config data types are translatable by default (text, label, mail). You can also add `translatable: true` to settings manually (try to do it for “case” setting).

* Add *Configuration Translation* support.
**hello.config\_translation.yml:**

```
  hello:
    title: 'Hello World settings'
    base_route_name: hello.settings_form
    names:
      - 'hello.settings'

```

Just small YAML file and **that's all**.

To see *“Translate settings”* tab you need existing default local task (See hello.local\_tasks.yml for an example. *Note: because of a change in Drupal core, this file name is no longer correct. It should be `hello.links.task.yml` now.*).

Only translatable settings are appeared.

**P.S.:** In Drupal 7 i18n\_variable API is used for this task.
> 9 votes

---
Tags: i18n-l10n, 8
---


title: journal website

text:
# Question
Title: journal website
I need to create a journal management website that will have

```
authors - who can submit journals to be published,
reviewers  - who review submitted journals of the author,
subscribers - who can subscribe to journals that are published,

```

The site will have search for journals that will be listed with thumbnails, recent published journals

is this a job for drupal, what is the best and fast way to go?

the people that will be using this are non technical so using the admin of drupal is not good

# Answer
> 4 votes
First let me remind you, the scope for the question is very vast. What I will try to do is list out pros and cons of using Drupal and provide you a general direction to start,

Firstly, yes Drupal is perfectly capable of handling sites of these type with efficiency and a large number of such sites and created using Drupal. But please do remember, Drupal is an open source CMS and dont expect to get everything ready and out of the box. Be prepared to get your hands dirty and try out a few stuffs.

But what Drupal will provide you is with an awesome API to ease your work and a set of very powerful contrib modules. in a nutshell, I think Drupal will be a great choice in your case.

Now a general direction and a few contrib modules you can start looking at:

1. Workbench Moderation \- this awesome module will help you to create all sorts of workflow for document creation, approval, and publishing.
2. Subscriptions

Now a word for your concern regarding Drupal backend, i agree with you it is a bit too much for non technical guys but with a pro that it is functionally solid. So what i usually tend to do is redesign the forms and create a dashboard like stuff for the non admins/content editors. So with a few sets of permissions, form layout change and css you can make that really usable for non technical guys.

Hope I could provide you with details you needed.

# Answer
> 2 votes
Q1. Is this a job for drupal- Definitely yes

Q2. what is the best and fast way to go? - Depends on kind of resources you have to develop it and its always hard to say the best ;)

Q3. The people that will be using this are non technical so using the admin of drupal is not good? - Once it is developed, role of people will not be much more than creating a node/content.

Now come to, how drupal can be helpful,I agree to @new suggestions - Modules that can be helpful for the development

For your content workflow

For Subscriptions

* Subscriptions, Notifications, Simple Subscrption, SimpleNews
* which subscription module should be used, again depends on requirement and what module provides so preferably a module which has functionality close to requirement should be best option so you do not have a overkill module or module along which you have to custom code everything.

As a glance what you will get out of box for workflow of your content.

# Answer
> 1 votes
You might also look into the Open Publish Distribution, which can give you a headstart on some issues that can be tough to figure out like multiple authors on an article, for example.

https://drupal.org/project/openpublish

http://openpublishapp.com/

Try a demo (20 min limit) at http://simplytest.me by entering openpublish in the box and selecting the 7.x version

# Answer
> 1 votes
While you *can* do this with Drupal, you may want to look at Open Journal Systems as well. This is a free and open source "out-of-the-box" WCMS dedicated to the task of publishing multiple (peer-)reviewed journals on a single web-site.

> Open Journal Systems (OJS) is a journal management and publishing system that has been developed by the Public Knowledge Project through its federally funded efforts to expand and improve access to research.
>
> OJS Features:
>
> 1. OJS is installed locally and locally controlled.
> 2. Editors configure requirements, sections, review process, etc.
> 3. Online submission and management of all content.
> 4. Subscription module with delayed open access options.
> 5. Comprehensive indexing of content part of global system.
> 6. Reading Tools for content, based on field and editors’ choice.
> 7. Email notification and commenting ability for readers.
> 8. Complete context-sensitive online Help support.

You can do all of the above with Drupal, but you will have to do a lot of customization that you get by default with OJS.

I am a Drupal developer, but I also run a peer-reviewed journal. I have choosen OJS rather than Drupal for that *specific task*.

---
Tags: nodes, files
---


title: Can I create a link to a taxonomy page?

text:
# Question
Title: Can I create a link to a taxonomy page?
I have a page that has a single category applied to it, for this example, "Self Help Books".

I want to put a place on content type that display a "view all \[insert category here\]" that links to that category listing page. I was hoping I could do something like `<a href=%taxonomyLink:books--self-help-books%>view all %taxonomy:books%</a>` which would pull in the category for anything using that content type. I'm using the Panels module, so I had planned on placing this in a panel the content type was using.

Is it possible?

I thought about creating a block and placing that in a panel.

# Answer
There's a default path that links to `taxonomy/term/term_id`. For instance if the `term_id` for the term `Self help books` is 42, the following path will list all self help books.

```
taxonomy/term/42

```

Now, to replace this with the appropriate string, navigate to:

```
Home » Administration » Configuration » Search and metadata » URL aliases

```

and specify that `Self help books` should be an alias for `taxonomy/term/42`.

First, make sure all nodes that you want listed as self help books is tagged with the tag `Self help books`.

Then, to create a link to the nodes tagged with a specific term based upon vocabulary, you need to install and enable the Token module and the Token Filter module (unless you've already done so).

Next navigate to:

```
Home » Administration » Configuration » Content authoring » Text formats

```

and click `Configure` on the text format (or formats) you plan to use. Under `Enabled filters`. make sure the filter named `Replace tokens` is activated.

You can now see the what tokes that exist by going to:

```
Home » Administration » Help » Token

```

and expand the *Nodes* item. Let us say that your book category field is named `node:field_book_category`.

Then, if you put an HTML link like this somewhere on a page tagged with `Self help books`:

```
<a href="/[node:field_book_category]">View more [node:field_book_category]</a>

```

you will get a link back to a page listing all nodes tagged with `Self help books`.

This will of course work with any other taxonomy term (e.g. `sport books`, `cooking books`, etc.) as well. However, the node can only be tagged with a *single* term from a particular vocabulary for this method to work.

**Note:** For this to work, the node must actually be tagged with exactly one taxonomy term from the relevant vocabulary. You can easily check that the node is tagged this way: When you view the content of the node, the taxonomy term or terms it is tagged with is automatically inserted by Drupal with link to a list of all nodes tagged with the term. If this link does not appear, then the node is untagged. If multiple links appear, then there are multiple taxonomy terms. If the node is untagged, there will be no token replacement and the token will appear as plain text. If the node is tagged with multiple terms, then the token will expand into a list of taxonomy categories, and can no longer be inserted in a single link.

PS: As an alternative solution you can override the template for the node (`node.tpl.php`), you can replace the simple link mentioned in the previous paragraph with the string "View more" followed by the link. This also work if there are more than one tag from the vocabulary on the page.
> 0 votes

# Answer
Create a taxonomy term reference field in the content type where you want to place the link. Select *Books* as the vocabulary so that this field can reference the terms of the *Books* vocabulary. Let the field machine name be *field\_book\_reference*.

Use the following code.

```
$node = menu_get_object();
if(is_object($node)) {
  $title = $node->title;
  $book_tid = $node->field_book_reference['und'][0]['tid'];
  echo '<a class="vocab-link" href="/taxonomy/term/"' . $book_tid . '>View all ' . $title . '</a>';
}

```

You may place that code anywhere PHP code is accepted. Better, create a PHP block and place it in a panel.
> 0 votes

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


# Question
Title: How can I make teasers refresh when they are flagged?
I have several flags like "Sold" "Withdraw" etc which appear in Contextual links. Flagged nodes are checked through node--type.tpl.php and this allows me to add text strings like "Sold" or "Withdrawn", which I theme with CSS to show as large labels.

The problem is that when the end-user flags an item with a Flag toggle, it's not very clear what this flag does. I need that teaser to auto-refresh, so that my labels ("Sold" or "Withdrawn") become visible immediately without the end-user having to reload that page.

I have found this js code , but what it does is slide the node teaser up, which is okey for the "Withdrawn" flag in some views), but is not the correct behaviour for the "Sold" flag. For the "Sold" I need that teaser to refresh itself.

```
$(document).bind('flagGlobalAfterLinkUpdate', function(event, data) {
      $('#'+data.contentId).hide('');
       // $.growl('Flag', 'The article '+data.contentId + ' has been flagged and hidden.');
    });

Drupal.behaviors.moduleName = function()
{
  $(".flag-action").each(function()
  {
    $(this).click(function()
    {
      $(this).parents(".node").slideUp();
    });
  });
};

```

# Answer
> 0 votes
Step 1 (PHP part):

You need to implement, hook\_flag\_javascript\_info\_alter() function, and pass in the refreshed teaset html, so that you can use this in js file.

```
function yourmodulename_flag_javascript_info_alter(&$info) {
  $content_id = $info['contentId'];
  $node = node_load($content_id);
  $view = node_view($node, 'teaser');
  $rendered = drupal_render($view);
  $info['rendered_node'] = $rendered;
}

```

Step 2 (JS) Part:

Now upon flagging, you will have the refreshed node html as data.rendered\_node. So employing your js code you wrote above:

```
$(document).bind('flagGlobalAfterLinkUpdate', function(event, data) {
  var node_id = data.contentId;
  var rendered_teaser = data.rendered_node;
  //here you have to check the logic, find the selector that is to be
  //replaced, and then replace that with the 'rendered_node' variable we declared above.

});

```

Please note that my intention here was to give you a direction and the general logic and not the exact code, so most probably you have to modify the above code to make it work.

UPDATE:

In the step 2 code, you see I got a variable node\_id. That is the nid of the content that was flagged. In the html, you must be having some class using that nid, may be "node-765"..where this 765 is the id. look for such a class. Once you have the class name, and say that class is of the form "node-nid-765". So we will check for that like this:

```
$('node-nid'+node_id).replace(rendered_teaser);

```

Again please note the class names are not exact and have been provided to give you an example.

---
Tags: 7, flags, javascript
---


# Question
Title: Workbench: Allow users to publish revisions without moderation
I want to be able to moderate authors who create new nodes, but allow authors to update their existing nodes without moderation. It's not immediately obvious to me how to do this in Workbench.

It seems like I should be able to set up a Rule that will basically have

Event: After updating existing content

Condition: Content's current moderation state is published

Reaction: Set moderation state during save: Published

Something like that. I've tried a lot of combinations, but I can't get it to work.

Also, every time an author saves, it saves as a Draft, which I almost never want. Even though the Default State is set to Needs Review that only applies to new nodes. Revisions of existing nodes are always saved as drafts.

So ideally what I'm trying achieve is this

* new nodes default to Needs Review
* revisions of existing nodes default to Publised

# Answer
This is sort of bizarre and I'd love to hear other answers, but after much trial and error with Rules, it turns out this seems to work with the following setup:

Event: After updating existing content \[so it's not a new node\]

Condition: Content is published \[so admin has approved it at least once\]

Reaction: 1. Publish Content 2. Set moderation state during save: Published

I would have thought that *either* #1 or #2 would have been sufficient, but strangely if they are not combined, it always reverts to draft. Also strange, the order doesn't seem to matter. I've had it working #1 then #2 and #2 then #1.
> 1 votes

---
Tags: workflows, workbench
---


title: Password Strength

text:
# Question
Title: Password Strength
How to remove password strength in Drupal registration form?

# Answer
Use Password Strength Disabler Drupal Module.

Enabling this module will disable the password strength checker upon new user registration.
> 2 votes

# Answer
If you just want to disable it for the user registration form, without using third-party modules, you can use the following code in one of your custom modules.

```
function mymodule_form_user_register_form_alter(&$form, &$form_state) {
  $form['#attached']['js'][] = drupal_get_path('module', 'mymodule') . '/user.js';
}

```

The content of the user.js file would be the following.

```
Drupal.behaviors.password.attach = function (context, settings) {};

```

Differently from the approach followed by the Password Strength Disabler module, the code I suggest just removes the password strength part from the user registration form, not from every form using the password confirmation form element. The generic code to remove it in more than one form is the following one.

```
function mymodule_form_alter(&$form, &$form_state, $form_id) {
  if (in_array($form_id, $alter_forms)) {
    $form['#attached']['js'][] = drupal_get_path('module', 'mymodule') . '/user.js';
  }
}

```

`$alter_forms` is an array containing all the form IDs for the forms where you don't want the password strength to be visible.
> 2 votes

# Answer
If you do not want to install any module at all, Just copy this function from the Disable password strength module into your theme's template.php file, it works great for me on my sites. "yourtheme" in the function should be changed to your theme name. That's all.

```
/**
 * Implements hook_element_info_alter().
 */
function yourtheme_element_info_alter(&$types) {
if (isset($types['password_confirm']['#process']) && (($position = array_search('user_form_process_password_confirm', $types['password_confirm']['#process'])) !== FALSE))
 {
   unset($types['password_confirm']['#process'][$position]);
  }
}

```

Note: Though this code came from the Disable password strength module, you do NOT need to install the module, just copy the above code provided into your theme's template.php file and thats it.
> 1 votes

---
Tags: 7, javascript
---


title: Static html page import

text:
# Question
Title: Static html page import
I want to import static html reports generated for source code by code analysis tools like doxygen, understand. Is there any module that can import the html reports generated by these tools directly into drupal? I tried import html without any success. Any tried and tested procedure to achieve this feature ?

# Answer
You can do it with the built-in text filter named "PHP Code". To get access to this, you need to first enable the core **PHP Filter** module (in core, but disabled by default). Then navigate to *Home » Administration » Configuration » Content authoring » Text formats* and allow the Administrator to use the filter named "PHP code".

Now the Administrator can create nodes that use the PHP include statement to embed static HTML pages in Drupal nodes. For example, to import a static HTML page located in the Drupal root named `static.html`, create a Basic page node with this contents:

```
<?php include $_SERVER['DOCUMENT_ROOT'] . '/static.html'; ?>

```

and set its text format to "PHP Filter".

Note that the "PHP code" text filter allows arbitary PHP to be embedded into nodes, so make sure that only highly trusted users have access to this filter.
> 2 votes

---
Tags: 7, importing-exporting
---


title: How is a TypedData value validated?

text:
# Question
Title: How is a TypedData value validated?
I do not understand how the Boolean (just for example) is validated. This is my code:

```
$tdm = \Drupal::typedData();
$data = $tdm->create(array('type' => 'boolean'), 1000);
drush_print_r($data->validate());

```

The `$data->validate()` returns a list of ConstraintViolations, but where is the logic of these constraints, per `Drupal\Core\TypedData\Plugin\DataType\Boolean` does not implements `getConstraints` method.

Thanks

# Answer
Primitive types are special case.

By default, they get the PrimitiveType validation constraint in TypedDataManager::getConstraints().

```
<?php
// Auto-generate a constraint for data types implementing a primitive
// interface.
if (is_subclass_of($type_definition['class'], '\Drupal\Core\TypedData\PrimitiveInterface')) {
  $constraints[] = $validation_manager->create('PrimitiveType', array());
}
?>

```

Validation constraints are usually provided in one of the following places:

* The plugin annotation (see e.g. EntityReferenceItem)
* base field/property definitions (see e.g. Node::baseFieldDefinitions(), title field)
* By overriding the getConstraints() method on a typed data class.
> 1 votes

---
Tags: 8
---


# Question
Title: Display content type through custom template
I have been losing quite a lot of time with something that seemed straightforward initially.

I am trying to use a template file(tpl.php) to print a content type with custom html layout.

In template.php I added.

```
function responsive_bartik_preprocess_node(&$variables) {
  if ($variables['type'] == 'dagens_billet') {
    $variables['theme_hook_suggestions'][] = 'templates/dagens_billet--template';
   }
}

```

I added a templates/dagens\_billet--template.tpl.php but nothing is being printed. I've added the following test code in there:

```
<?php print render('Giannisssssssssssssss'); ?>

```

Any suggestions to make it work?

# Answer
> 1 votes
this is my method for doing such thing and it always works.

create a view of your content type (`ct`), say `ct__view`. create a page and rename it to
`page--path_of_view.tpl.php` and embed that view inside it at any where you want with this instruction `<?php print views_embed_view('ct__view','page');?>`. now you can customize its fields output with `views-view-fields--ct__view--page.tpl.php`

# Answer
> 0 votes
The solution I found is quite simple. Just creating a sites/all/themes/{mytheme}/templates/node-{content\_type\_machine\_name}.tpl.php

This is explained nicely at http://www.slideshare.net/aimeemaree/a-look-at-drupal-7-theming

---
Tags: theming, hooks, nodes
---


title: Can't we sort a "Node module element"?

text:
# Question
Title: Can't we sort a "Node module element"?
I'm creating a new content type named "Portfolio".

**Image 1:** I put a name to the "Title field label": *Project Name*

**Image 2:** That thing works as a 'Node module element' in Fields

**Image 3:** I can't get the Field to sort it below the Project Image

I even can't get this 'Node module element' from Views (using Views module). The sorting problem is specific to "Teasers" in the portfolio page:

I just want the Project Title to sort a bit so that I can place the title just after the Project Image. I'm familiar with WordPress, but a newbie in Drupal.

# Answer
> 1 votes
There are three ways to go about.

1) Use views. In views the Field to add is Content : Title. (Even if you change the name of the title field it is still title. It is just changing the label on the form.)

2) You can install Display Suite Module. Once you install this module you would get additional fields once you select a layout in the layouts section.

> 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.

3) The third method is to work with the node.tpl.php you have a node object. Since you are using teaser the title would be available in a field. All the other fields can be accessed from the node object.

# Answer
> 1 votes
In image 3, there is another separate tab for editing the order and display of teasers for your content types.

If your content isn't displaying properly in views as a teaser, you can change the format options in your view to show:Fields instead of show:Content , this will then allow you to add specific fields from your content type, and add custom CSS classes to all of your fields for extra formatting in CSS.

---
Tags: entities, nodes
---


# Question
Title: VIews Proximity Search Fields as Separate Block?
Just a quick question, or if someone can point me in the right direction...

I have a website that needs to have a search field where customers can enter a service (e.g. photography) in one field, and a post code/zip code in the other so search for services near them.

To do this, I have a content type for each service with addressfield, geofield and geocoder modules installed, and I have a view set up with an exposed filter criteria to filter the results.

This all works perfectly.

What I would like to do is have the filter criteria search in an external block at the top of every page (like the default drupal search block) that will show a list of results on a NEW page whenever a customer submits the form. Using my current method, I first have to direct customers to the page with the view on before they can search.

I experimented with the Search Configuration module (https://drupal.org/project/search\_config) which lets you use the existing drupal search block, but can limit the results to only show one content type, which is perfect, but doesnt include the location post code field, and doesnt have the configuration of displayed results like views fields would do.

If anyone could offer up a bit of advice of where to go next I'd really appreciate the help.

# Answer
> 1 votes
If you are using drupal 7 You have an option to expose the filter as a block. and you can display the block in any region as you do all the other blocks. You would find this option under the advanced section in the views.

Please check the screenshot below

---
Tags: views, search, location
---


# Question
Title: return all content types name containing text files
I want to get the content type name instead of the file name: I have this function that access to the files folder: site/all/default/files and get all the file with a text extension and put the text files in an array, is there a possibilty to retun all content types names that contain text files instead of the text files names?

```
function get_projects(){

$directory= variable_get('file_directory_path', 'sites/default/files');
$filenames = array();
$extension =".txt";

$iterator = new DirectoryIterator($directory);
foreach ($iterator as $fileinfo) {
if ($fileinfo->isFile()) {
    //check the extension ".txt"
    if (strpos($fileinfo->getFilename(),'.txt') !== false)
    {
        //Delete the extension ".txt"
        $filenames[$fileinfo->getMTime()] =substr($fileinfo->getFilename(), 0, -4);
        //$filenames[$fileinfo->getMTime()] =$fileinfo->getFilename();
        //$fileinfo->getFilename().get
     }
 }
}
 return $filenames;

}

```

# Answer
> 2 votes
```
  function get_content_type_by_filename($filenames = array()) {
    $sql = "SELECT nt.name, fm.fid
    FROM file_managed AS fm
    LEFT OUTER JOIN file_usage AS fu ON (fm.fid = fu.fid)
    LEFT OUTER JOIN node AS n ON (fu.id = n.nid)
    LEFT OUTER JOIN node_type AS nt ON (n.type = nt.type)
    WHERE fu.type = 'node' AND n.nid IS NOT NULL AND fm.filename IN (:filename)";
    $results = db_query($sql, array(':filename' => $filenames));
    $results = $results->fetchAll();
    return $results;
  }

```

This function accepts an array of file names you want to find content types for and returns an array of matched objects with properties fid and content type.

Update:

Please take a note that I am not trying to give you the exact code rather point you in the right direction.

To achieve what you want, call the function you mentioned in the question (i assume it does what you say, that it returns an array of file names)

so :

```
function get_content_type_by_filename($filenames = array()) {
    $sql = "SELECT nt.name, fm.fid
    FROM file_managed AS fm
    LEFT OUTER JOIN file_usage AS fu ON (fm.fid = fu.fid)
    LEFT OUTER JOIN node AS n ON (fu.id = n.nid)
    LEFT OUTER JOIN node_type AS nt ON (n.type = nt.type)
    WHERE fu.type = 'node' AND n.nid IS NOT NULL AND fm.filename IN (:filename)";
    $results = db_query($sql, array(':filename' => $filenames));
    $results = $results->fetchAll();
    $types_array = array();
    foreach($results as $obj) {
      $types_array[] = $obj->name;
    }
    return $types_array;
  }
$files_array = get_projects();
$content_types_array = get_content_type_by_filename($files_array);

```

The $content\_types\_array will contain the array of content type names. Hope this helps.If this does not give please debug by installing devel module and passing the variables and arrays through dpm() function to see contents of the array.

---
Tags: nodes, files
---


title: file field properties drupal7

text:
# Question
Title: file field properties drupal7
I'm building a library and it is possible to add books to website. I need to get uploaded file urls and display them in 'a' tag inside views page (not node). how can I do that?

unfortunately I can't use kpr() to find file properties I guess because it has lot's of outputs and it prevents the page from loading (var\_dump does the same thing)

I also tested this function to print the file size but it failed

```
function MYT-HEME_file_link(&$variables) {
$file = $variables['file'];
print $file->getsize();
}

```

# Answer
You can follow the below steps

1. Create a Relationship of the type "File Usage: File"
2. This will bring up additional Fields. You can add the filed called File: Path (Path) and select the above relationship.
3. Check "Display download path instead of file storage URI" This would give you the entire path. You can use the same any where in the view.

Once you add the relationship you would get additional fields related to the file. For example if you want to print the size of the file you can use the field "File: Size" etc.
> 0 votes

---
Tags: files
---


# Question
Title: Empty view is rendered even though there is no result
I have created a view in order to create a block for slide show in drupal 7. In my view I used a conditional field. This field gets the id of node from URL so I set "When the filter value is NOT available" to "Provide default value" and in TYPE drop down menu I set "Content ID From URL"

This view works with no problem. However, when the view is empty (there is no rows for fetched parameter value from URL) I see some rendered codes.

```
<div id="block-views-coupon-slides-block" class="block block-views clearfix">
  <div class="content">
    <div class="view view-coupon-slides view-id-coupon_slides view-display-id-block view-dom-id-90e27feb6919634c2f506f189c503c01">
      <div class="view-content">
        <div class="skin-default">
          <div class="views-slideshow-controls-top clearfix">
            <div id="widget_pager_top_coupon_slides-block" class="views-slideshow-pager-fields widget_pager widget_pager_top views_slideshow_pager_field views-slideshow-pager-field-processed">
            </div>
          </div>
          <div id="views_slideshow_cycle_main_coupon_slides-block" class="views_slideshow_cycle_main views_slideshow_main viewsSlideshowCycle-processed">
            <div id="views_slideshow_cycle_teaser_section_coupon_slides-block" class="views-slideshow-cycle-main-frame views_slideshow_cycle_teaser_section">
              <div id="views_slideshow_cycle_div_coupon_slides-block_0" class="views-slideshow-cycle-main-frame-row views_slideshow_cycle_slide views_slideshow_slide views-row-1 views-row-odd">
                <div class="views-slideshow-cycle-main-frame-row-item views-row views-row-0 views-row-first views-row-odd">
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</div>

```

What is your solution for this problem? As far as I know when a view returns no row, it must not be rendered in source code. In above codes, you see there is no result but the codes of block are printed !!!

Thanks a lot for your guidance.

# Answer
> 10 votes
You should add a filter criteria for any one of the fields. For example if you have a field called company then you could add a filter criteria for this field and then choose "Is Not Empty (NOT NULL)" from the Drop down. This would make sure that the view is rendered only if the required field is present.

In normal case when you are passing a Contextual filter the view is rendered even though the result is null. but if we provide a filter as I mentioned above it does not display at all.

---
Tags: views
---


# Question
Title: How can I clear all check boxes on failed validation?
I have form with check boxes. The user checks the boxes and hits the submit button. If validation fails an error message is displayed. I also want all of the user's checks to be cleared so they can try again. Here's my code, but it does not clear the checks? Thanks.

```
/**
 * Defines a form.
 */
function my_form($form, &$form_state) {

    $form['alerts'] = array(
        '#type' => 'checkboxes',
        '#options' => $options,
    );

    // the rest of my form

    if (isset($form_state['clear_checkboxes'])) {
        $form_state['values']['alerts'] = array_fill(0, count($form_state['values']['alerts']), 0);
    }
    return $form;

}

/**
 * Form validator.
 */
function my_form_validate($form, &$form_state) {

    // if validation fails set error message

    $form_state['rebuild'] = TRUE;
    $form_state['clear_checkboxes'] = TRUE;

}

```

# Answer
You can unset your field in the form .Check for the array which has field array.

```
unset($form_state['field_checkbox']['und'][0]['value']);

```
> 0 votes

---
Tags: forms
---


# Question
Title: Difference between field form hooks for settings
I created a field for my module and now I want to create settings for this field.

Now I found four hooks:

* hook\_field\_settings\_form
* hook\_field\_instance\_settings\_form
* hook\_field\_widget\_settings\_form
* hook\_field\_formatter\_settings\_form

What is the difference between these hooks?

I think "formatter\_settings" is for settings to change the later display of the output on the entity. Right? And the other hooks?

# Answer
> 3 votes
Let me explain to you briefly what each of them does. Basically a field has two prime components, one is widget and the other is formatter. The widget is the input part( like checkbox, select list, textfield). This helps field to grab data from the user. The other one is formatter. Formatters are responsible for how output is rendered by that field.

Now regarding the hooks you mentioned:

I will try and help you visualise these by comparing to the steps which you encounter while creating a field.

1. hook\_field\_settings\_form - this is the global settings form, the first page which you encounter when you create a field.
2. hook\_field\_instance\_settings\_form - this the instance level field settings form, usually same options as global settings form but applicable to each instance.
3. hook\_field\_widget\_settings\_form - This is the settings form for the widget, which i have already described above.
4. hook\_field\_formatter\_settings\_form - This is the settings form for the formatter. This exposes options that will be used to render the value of the field.

Observe closely the forms and steps that come up while you create a field through UI in Drupal and you will gain more insights on these components. hope that helps.

---
Tags: hooks, entities
---


title: error with ownership

text:
# Question
Title: error with ownership
"The specified file temporary://filelo2Fkx could not be copied, because the destination directory is not properly configured. This may be caused by a problem with file or directory permissions. More information is available in the system log."

ANYWAY what I am getting is everything minus theme and all images but strangely my multi site folders in root drupal sites folder are all working fine.

In the end I solved it by putting the root subfolder in sites along with other multi-sites. No amount of changing permissions or ownership or clean install or dropping and recreating database worked until then...which is very odd because it used to before I took the site down.

# Answer
You can try and change the permission of the folder 'sites/all/files' to give it 777 permission in your drupal installation and see if this works.
> 0 votes

# Answer
you have a problem with temporary directory (/tmp is the default).

Read this: https://stackoverflow.com/questions/5040718/file-system-permission-error-while-installing-drupal-modules

M.
> 0 votes

---
Tags: users
---


# Question
Title: Create a Views Block to show all Node 'Attached Files' as a File list.
In creating the CMS structure, I've been trying to do this today, but seem to be getting no where.

I simply want to show all the files as link (PDF, Doc, Docx etc) that have been uploaded by a user to a node type listing which has a Field already created in the Content type structure (by me, the Admin/web) using Views. I've got as far as creating the View with the relevant fields and set it in the Panel Page as a block, but in testing nothing seems to show.

All I require is any relevant 'attached' files related to that Node Content (ie XYZ rock Band, attached mp3 files at bottom of page) so that future readers can click to download to local.

Can someone refresh my memory as how to do it so I can compare where I may be going wrong? I have set the author ID in Relationship, but still the files I have set do not show. Maybe I'm missing something here.

# Answer
> 1 votes
Based on the discussion above, create a new view, and configure and filter it however you need. the main part is to have the file display as link for download. For this, when you add the relevant field to views, in the settings form, there will be a drop down option for "Link this field to". Choose "File" from there and the field value will be linked to it. Clicking on it will allow the user to download the file. Hope this helps.

---
Tags: views, files
---


# Question
Title: Fatal error: Call to undefined function context_get()
I got an error after trying to update two modules:

> `Fatal error: Call to undefined function context_get() in
>  sites/all/modules/context/context_ui/context_ui.module on line 422`

Also:

```
An AJAX HTTP error occurred. HTTP Result Code: 200 Debugging information follows. Path: http://redneckrampage.ee/authorize.php?batch=1&render=overlay&id=78&op=do StatusText: OK ResponseText: Fatal error: Call to undefined function context_get() in sites/all/modules/context/context_ui/context_ui.module on line 422

```

Any ideas on how to fix this without deleting/renaming the module folder on the server?

Drupal version 7.22

# Answer
> 0 votes
Try installing Context module and if this does not solve, also also try installing the spaces module.

---
Tags: 7
---


# Question
Title: How to add rel="author" attribute to Drupal 7?
In the brave new world of Google, great integration with Google+ is mandatory for all webmasters who want to get as much traffic as possible. If adding the `rel="publisher"` attribute to a website is done with the Meta Tags module, it seems that there's no official way for supporting the rel="author" attribute. For those of you who don't know about I am talking about, read this article from Google: Author information in search results

Apparently support will be included in Drupal 8. I've seen some discussions about adding this to the Drupal 8 core.

But how to implement this in Drupal 7?

I am asking this as a noob in customizing the insides of Drupal. So, if you have some good ideas, please keep this in mind.

Appreciate your ideas.

# Answer
The rel=author property is now supported by the Drupal 7 Metatags module dev version.

After installing the metatags module (http://drupal.org/project/metatag), go to admin/config/search/metatags, and edit the front-page or one of the node pages. Under 'Advanced' you will see the author and publisher fields where you can input your google+ page URL. On the following screenshot, I've marked the places you need to change the configuration in pink.

**Metatags frontpage configuration page:**
> 8 votes

# Answer
Using ideas from the `rdf_preprocess_node()` function that Dave Hall linked you could implement it this way (code goes into your theme's template.php file):

```
function mytheme_preprocess_node(&$variables) {
  if ($variables['page']) {
    $account = user_load($variables['uid']);
    $title = $account->name;

    $author_info = array(
      '#tag' => 'link',
      '#attributes' => array(
        'rel' => 'author',
        'href' => 'http://localhost',
        'title' => $title,
      ),
    );

    drupal_add_html_head($author_info, 'author');
  }
}

```

This adds the necessary link into the head section of full node pages. I used the node author's id to get the necessary user data. You'd probably want to add a website field for users that you could use here to get a complete solution.
> 5 votes

# Answer
Implementing hook\_preprocess\_node() in a module or your theme should do it. Check out the rdf module's implementation for some inspiration. http://api.drupal.org/api/drupal/modules--rdf--rdf.module/function/rdf\_preprocess\_node/7
> 4 votes

# Answer
I know I'm late to the party, but I'm answering this for people who land on this page in search of a solution.

There is now a Google Authorship module.
> 1 votes

# Answer
```
function themename_preprocess_username(&$vars) {
  // Username is linked, use the link_attributes to inject the rel attribute
  if (isset($vars['link_path'])) {
    $vars['link_attributes']['rel'][] = 'author';
  }
  // Username is NOT linked, use the attributes_array to inject the rel attribute
  else {
    $vars['attributes_array']['rel'][] = 'author';
  }
}

```
> 0 votes

---
Tags: 7
---


# Question
Title: How can I filter specific user on Views list?
Using Views 3.

I have User view and here, list all user by post count. It's working. But I want, ignore admin user post count in this view. How can I filter my views to not show admin in the view list?

# Answer
1. Add a filter criteria of type `User: Roles`,
2. Select the operator `Is none of:`
3. Select `Administrator` from the listbox.
4. Save the settings

This will block the display of all the users with role as administrators. If you only want to limit a certain user you can select the filter criteria of `User: Name`, or `User: The User ID`, whatever suits you.
> 4 votes

# Answer
1. Add a filter "user id: uid"
2. In the filter settings, select "not equal to" and put in 1 as value. Similarly if you want any other user excluded, please add the corresponding uids.

I am not having a set up with me right now, so the labels might not be exact, but please keep looking for similar options as i had mentioned in the filter settings.
> 3 votes

# Answer
Create a filter in the in views as following:

1. Select the filter: `User: The user ID`
2. Select the operator: `Is not equal to`
3. Enter the Value: `1` ("Enter the user of the admin i.e 1, or the user id of any user whose post you want to hide")
4. Save the view

**Note:** If you want to hide the post of particular role instead of particular user than instead of selecting the filter as `User: The user ID` select the filter as `User: Roles` and select operator as `Is none of` and than select the all the roles of user whose post you want to hide.
> 2 votes

---
Tags: 7, users, views
---


# Question
Title: Trying to use Panelizer for a node content type with a panels layout
I've got a zen theme, with a sub theme, with a plugins folder enabled in which I have a custom layout. I've got panelizer enabled on a content type and I am trying to make that content type use my custom layout, however, when I select the layout for that content type it doesn't seem to use it. Usually devel\_themer it looks like the page is still using node.tpl.php, I want to override the whole page with my custom layout. Are their any things I should bear in mind using panelizer - stuff I need to disable /enable.

# Answer
> 1 votes
Panelizer 7.3.1 Panelized content shows in preview, but when I view the live page, it looked like a regular, un-panelized node.

Turned on and off everything I could think of...

Finally, I looked at the Display tab of my content type, and clicked open the Custom Display Settings. I turned OFF "use custom display settings for view modes: Full Content and Teaser". Suddenly my nodes were panelized. Click back on "Full Content", and panels disappear.

---
Tags: panels
---


# Question
Title: Is this the correct way to complete aliases.drushrc.php in order to avoid messing with other accounts?
I´ve read many questions about drush in a multisite configuration. This case isn't a multisite, but several different installations in a single VPS. Something like a reseller account. They are all my sites, but I don't want to mess them up. I need drush commands to be applied to a single site each time.

I´ve installed drush using my root access, under home/root/drush. So when I try to access ssh using one of my site´s credentials (not the root user, but one of the site´s admin), it doesn´t recognize drush commands.

Should I install drush in every single account, right outside /public\_html, or should I edit the .bashrc file in any way? And in that case, how may I prevent the commands to affect other sites when I try to do something with a single specific installation?

I'm using Drupal 7 and Drush 5.x because of my php version (5.2.17).

I understand that I should have (inside the drush folder?) a file called **aliases.drushrc.php**, with something like this.

```
$aliases['site1'] = array(
    'uri' => 'mysite1.com',
    'root' => '/home/site1username/public_html',
    'remote-user' => 'site1username',
  );
$aliases['site2'] = array(
    'uri' => 'mysite2.com',
    'root' => '/home/site2username/public_html',
    'remote-user' => 'site2username',
  );

```

Is this correct? And how may I access drush only to a specific site?

# Answer
> "when I try to access ssh using one of my site´s credentials (not the root user, but one of the site´s admin), it doesn´t recognize drush commands."

The only requirements for using Drush from another user (than the one that installed it) is a) the drush directory should be readable, and b) drush should be in your PATH.

It is okay to install Drush once per user. I use a custom move-in script to accomplish this, but in my case it's rare for me to have more than one Drush-using user on one system. Setting the PATH in your bashrc to include the Drush directory of the root user is also fine. \[Aside: it is best to avoid calling Drush using the root user, for security's sake. Any Drupal module can define code that runs during the execution of any Drush command.\]

You aliases file looks okay, except that you only need to define remote-user for remote aliases. The aliases you are defining are local, so remote-user will be ignored. The alias file should go in the ~/.drush directory (inside the home directory of the user that is calling Drush).

You can download the Drush chapter of DGD7 for free; it is one of the book's sample chapters. It does a pretty good job at describing alias files and configuration. Although it was written for Drush 4, most of what it describes is unchanged in Drush 6 and Drush 7. Be sure to also read all of the Drush README.

**Update:** Forgot to mention: to use your aliases, type `drush @site1 status`. If your settings.php file is in a folder called default, then you may also access your site via `cd /home/site1username/public_html && drush status`.
> 2 votes

---
Tags: drush
---


# Question
Title: Extract field from content type in View and have it appear as a block next to appropriate node
I need to pull a field from a content type and have it appear as a view in the sidebar next to the node it belongs to. I can't figure out what parameter to use in Views to indicate that my view block should appear by the node it was extracted from. Maybe something to do with relationships?

# Answer
> 4 votes
This can be done with contextual filters.

1. Set up the view to display whatever information you need; put the view in a block that only displays on the page for that content type
2. Add a contextual filter, selecting a field that contains the NID. For example, this could be content: nid
3. For "when filter is not available" select "provide default value", then "content ID from URL"

After doing this, the view will only display the single result, where the NID field matches the NID of the node currently being viewed.

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


# Question
Title: Alternatives to Messaging and Notifications
I maintain a Drupal 6 site for a team of scuba-divers.
Given the discontinued support for Drupal 6, I am looking at upgrading the site to Drupal 7.

We primarily communicate by e-mail, so we have set up a Messaging+Notifications thing, where users can subscribe to new nodes of a given node-type, with one primary purpose: When a boat-commander arranges a new diving trip (node-type) all interested divers receive a notification mail, so they can sign-in to the trip.
The same functionality goes for clubhouse events and articles in general (secondary).

Mails are formatted so, that they contain a link to the node on the site (obviously), and they also contain a link to unsubscribe to further mails of same kind.

It seems Messaging+Notifications are not (actively) maintained on D7, so I am looking for an alternative.

I have tried a Commons distro, but I just cannot get the grasp of the Messages (log?) and Flags concept. It seems to me that it is build to click-to-follow existing posts, but I want to have the option to always follow posts of a certain kind.

Am I misunderstanding the Messages module, or am I looking at a wrong module?

# Answer
> 2 votes
A project that is similar in scope to Notifications and is actively supported for Drupal 7 is Subscriptions.

You may also want to look at some of the more lightweight notification modules. The project Notify is designed to send out notifications whenever new content of a certain content type appear (Disclosure: I am the maintainer of Notify).

There is a Notifications via e-mail comparison at Groups.Drupal.org. This gives you a good idea of what is available for Drupal 7.

---
Tags: 7, notifications
---


# Question
Title: Get the value from $node inside two objects
I have an array output like this from drupal, how do I access the value of \[name\] from field\_episode\_tags, I have this so far

```
print $node->field_episode_tags['und']['0']['taxonomy_term']->['name']

```

When I get up to 'taxonomy term' there is another object i tried using another -\> poitner but that did not work.

```
stdClass Object
    (
        [vid] => 25
        [uid] => 1
        [title] => Is there any cosmos theory?
        [log] =>
        [status] => 1
        [comment] => 1
        [promote] => 0
        [sticky] => 0
        [nid] => 25
        [type] => tv_episode
        [language] => en
        [created] => 1380610491
        [changed] => 1381115053
        [tnid] => 0
        [translate] => 0
        [revision_timestamp] => 1381115053
        [revision_uid] => 1
        [body] => Array
            (
                [und] => Array
                    (
                        [0] => Array
                            (
                                [value] => summary text summary text summary text summary text summary text summary text summary text summary text summary text summary text summary text summary text summary text summary text summary text summary text summary text summary text summary text summary text summary text summary text summary text summary text summary text summary text summary text summary text summary text summary text summary text summary text summary text summary text summary text summary text summary text summary text summary text
                                [summary] =>
                                [format] => filtered_html
                                [safe_value] => <p>summary text summary text summary text summary text summary text summary text summary text summary text summary text summary text summary text summary text summary text summary text summary text summary text summary text summary text summary text summary text summary text summary text summary text summary text summary text summary text summary text summary text summary text summary text summary text summary text summary text summary text summary text summary text summary text summary text summary text</p>

                                [safe_summary] =>
                            )

                    )

            )

        [field_video_category] => Array
            (
                [und] => Array
                    (
                        [0] => Array
                            (
                                [tid] => 25
                            )

                    )

            )

        [field_featured] => Array
            (
            )

        [field_kaltura_video] => Array
            (
            ) und 0 taxonomy term->name

        [field_episode_tags] => Array
            (
                [und] => Array
                    (
                        [0] => Array
                            (
                                [tid] => 95
                                [taxonomy_term] => stdClass Object
                                    (
                                        [tid] => 95
                                        [vid] => 1
                                        [name] => zen
                                        [description] =>
                                        [format] =>
                                        [weight] => 0
                                        [vocabulary_machine_name] => tags

                       [rdf_mapping] => Array

```

# Answer
The correct way would be

```
print $node->field_episode_tags['und']['0']['taxonomy_term']->name

```

without the square brackets and quotes. Elements with in objects are accessed with

```
->objectname

```

and elements with in arrays are accessed by `['object']`
> 1 votes

---
Tags: 7
---