# Question
Title: Split node edit tab in several tabs with panels (or programmatically)
I have a content type with many fields, so that loading `node/%node/edit` is a pain ! In order to split node edit form **in smaller forms** (menu tabs), I used Page Manager.

## What I did so far

1. Enable the *Node add/edit form* coming with Page Manager, with selection rule *node being edited is from foo\_type*
2. Add three new custom panels pages in `admin/structure/pages`, with paths `/node/%node/photos`, `/node/%node/prices`, `/node/%node/fd` ; with selection rule *node being edited is from foo\_type*
3. Define its menu as local menu tab.
4. Share *foo\_type* fields between these forms, and add a submit node form to each.

**This renders correctly three node edit forms accessible in new local task menu tabs :**

## The buggy part

If I edit the node from any of these forms :

* the fields present in it are saved
* the data from other fields saved before is still in the database, and also readable in the form fields if I show up the other forms (except for pictures), but it **is not displayed anymore in the node.**

As per @Letharion comments : " *\[...\] while Panels happens to let you output only half the form as well, that is not supported by form api. One way or another, every field must be present. If not, form api will interpret it as "the user deleted the content of those fields" \[...\]*

# The question

I'm searching a way to patch the current solution, or a fully programmatic way to split node edit into tabs. Thanks for your contribution!

# Edit:

Most of the issue is solved thanks to flexiform, except for inline entity commerce products. So I'm trying with MrD answer for this specific field, as exposed below.

The commerce product is saved (corresponding DB tables `commerce_product`, `field_data_commerce_price` and so on have a new record), but not attached to its product display (and no record in `field_data_field_product`). No error is returned.

**How to correctly save that commerce product so that it is attached to its node display ?**

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

  $items['node/%node/prices'] = array(
    'title' => 'Prix et dates',
    'page callback' => 'node_page_prices',
    'page arguments' => array(1),
    'access callback' => 'node_access',
    'access arguments' => array('update', 1),
    'weight' => 4,
    'type' => MENU_LOCAL_TASK,
    'context' => MENU_CONTEXT_PAGE | MENU_CONTEXT_INLINE,
  );

  return $items;
}

function node_page_prices($node) {
  $form = drupal_get_form('vts_nodedit_form', $node, 'field_product');
  return $form;
}

function vts_nodedit_form($form, &$form_state, $node, $field_name) {
  $form = array();
  field_attach_form('node', $node, $form, $form_state, NULL, array('field_name' => $field_name));
  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Save')
  );
  return $form;
}

function vts_nodedit_form_submit($form, &$form_state) {
  $node = $form_state['build_info']['args'][0];

  //retrieve commerce product to be saved... NON DRUPAL way... :(
  $item = key($form_state['inline_entity_form']);
  $entities = end($form_state['inline_entity_form'][$item]['entities']);
  $product =$entities['entity'];//this is the correct product entity
  //SAVE THE COMMERCE PRODUCT
  commerce_product_save($product);
  //MrD solution
  field_attach_submit('node', $node, $form, $form_state);
}

```

# Answer
I think the best way to do this is to use `field_attach_form`

You can see my example below

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

  $items['node/%node/settings'] = array(
    'title' => t('Settings'),
    'page callback' => 'node_page_settings',
    'page arguments' => array(1),
    'access callback' => 'node_access',
    'access arguments' => array('update', 1),
    'weight' => 0,
    'type' => MENU_LOCAL_TASK,
    'context' => MENU_CONTEXT_PAGE | MENU_CONTEXT_INLINE,
  );

  return $items;
}
//You can replace body with your field name
function node_page_settings($node) {
  $form = drupal_get_form('foo_form', $node, 'body');
  return $form;
}

/**
 * Implements hook_form();
 */
// Have default value if node exit data
function foo_form($form, &$form_state, $node, $field_name) {
  $form = array();
  field_attach_form('node', $node, $form, $form_state, NULL, array('field_name' => $field_name));
  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Save')
  );
  return $form;
}
/**
 * Implements hook_form_submit();
 */
function foo_form_submit($form, &$form_state) {
  $node = $form_state['build_info']['args'][0];
  //common fields case
  field_attach_submit('node', $node, $form, $form_state);
  //add this for inline entity multi-values fields case (eg commerce products)
  $item = key($form_state['inline_entity_form']);
  $entities = $form_state['inline_entity_form'][$item]['entities'];
  $product = array();
  foreach ($entities as $key => $entity) {
    $product[$key] = array(
      'product_id' => $entity['entity']->product_id
    );
  }
  $node->field_product_store['und'] = $product;
  node_save($node);
}

```
> 1 votes

# Answer
It sounds like you have done a lot of work already, and this continues to be a learning experience. Since the form is now managed how you want it and it is only the data management in the save process that is causing you trouble, I would suggest a few code additions. Using hook\_form\_ID\_alter there are two methods you can try.

**Method 1** Add a custom validation callback to the form.

```
$form['#validate'][] = 'MYMODULE_node_data_validate';

```

Then in your new validation function I suggest loading the node ($node = node\_load(nid);) and propagating the data into the form\_state. I am not sure this will work, but I have it listed as method 1 because it is the less disruptive path of the two that I have in mind at the moment.

**Method 2** Replace the submit handler with your own. Similar to the validate function mentioned above, the idea here is to load the node to get the data that was not present on the form that you edited. However, this time you are going to invoke node\_save yourself. Also you will need to end with a drupal\_goto or some other method of sending the user someplace. Yes you could add an additional handler to the #submit array in the form variable, but either it will be too late to prevent the change the form is doing or it would just be a different name for method 1.

```
function hook_form_ID_alter(&$form, &$form_state, $form_id) {
    $form['#submit'] = array( 'hook_something_submit');
}
/**
 * Implements hook_form_FORM_ID_alter();
 */
function vts_nodedit_form_accompagn__node_form_alter(&$form, &$form_state, $form_id) {
    $form['#submit'] = array( 'vts_nodedit_data_submit');
}

function vts_nodedit_data_submit($form, &$form_state) {
  // possible cause of missing data is that the form build populates
  $original = node_load( $form_state['node']->nid );

  // this drupal core function does the work of a full node edit save
  // but we have to have the node to hand it
  // and I do not trust all of $form['node'] in your instance
  field_attach_submit('node', $original, $form, $form_state);

  drupal_set_message(t('The changes have been saved.'));

  if( isset( $form_state['redirect']) ){
    drupal_goto( $form_state['redirect'] );
  } else {
    drupal_goto( '/home' );
  }
}

```

**EDIT**
The difference between form\_state\['input'\] and form\_state\['values'\] is that input is the raw $\_POST from the user. I think it would be a security concern to use that directly. The other validators that are running (why we use $form\['#validate'\]\[\] and append instead of replace) are taking the new data from input, cleaning it, and putting it in values. Then if there are blank spots, they fill values with #default\_value of the node. Default is typically the existing value. Therefore, a submit handler can ignore form\_state\[input\] and have the benefits of drupal in just the form\_state\[values\] array.
Input vs Values
> 1 votes

# Answer
This issue can be solved using Panels and Node Form Panes modules, also we need to enable "Page manager" module from Ctools.

1. Open "Page manager" administration page(admin/structure/pages) and click on "Add custom page" link
2. Insert basic settings for new page
3. Set Context argument
4. Add access settings
5. Add menu settings
6. Choose node type
7. Choose needed layout
8. Add needed fields
9. Add "Save button" The result should be like this
> 1 votes

# Answer
Almost the Graal for that feature, Flexiform project has an Edit Panels Pane display:

> Edit an entity using a form embedded in a panel where the base entity is loaded from the panel context.

Just follow these steps :

1. Add new custom pages in `admin/structure/pages`, with paths `/node/%node/foo`, `/node/%node/bar` and so on
2. With selection rule *node ID is from foo\_type*
3. Define its menu as local menu tab
4. Create some **flexiforms**, with the fields you wish to
5. Instead of adding separate fields, add your flexiforms as pane contents

This saves correctly the nodes now, even with a few fields in each form. Only some complex fields such as *Inline entity form/Multiple values* are buggy...
> 1 votes

# Answer
Instead of doing it in code, you should consider using MSNF module

> For each step you can define which fields should be included in this step. "Fields" includes core-fields like "Title", "Body" or "Authoring information" as well as fields defined by other modules

You can also consider using Field Group Module if you need simplicity.

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

---
Tags: commerce, panels, routes, chaos-tool-suite
---


title: How to add a span before a tabs item?

text:
# Question
Title: How to add a span before a tabs item?
I would like to add a little icon before the tab item 'Edit'. Firebug shows that the default code looks like this:

```
<ul class="tabs-primary tabs primary">
  <li class="tabs-primary__tab">
    <a href="/MY_SITE/node/%/edit" class="tabs-primary__tab-link">Edit</a>
  </li>
</ul>

```

My idea is to add a `span` before the `<a>...</a>`:

```
<ul class="tabs-primary tabs primary">
  <li class="tabs-primary__tab">
    <span class="edit"></span>
    <a href="/MY_SITE/node/%/edit" class="tabs-primary__tab-link">Edit</a>
  </li>
</ul>

```

where the edit class has the underneath CSS.

```
.edit {
    background-image: url("MY_IMAGE.png");
    background-repeat: no-repeat;
    display: inline-block;
    height: 16px;
    padding-right: 2px;
    vertical-align: middle;
    width: 16px;
}

```

Adding the `<span>` directly with Firebug gives the wanted result, but I don't know how to do this in a template or with a function. What is the correct way to achieve this?

# Answer
> 2 votes
Instead of adding a `<span>` element, you could also use the ::before CSS selector. If a combination with :first-child or :nth-child() is not helpful, most likely you have to implement `hook_menu_local_tasks_alter()` and add a specific class to the desired link(s) (you can add them through attributes in `localized_options` of the `#link` property, see https://api.drupal.org/comment/25393#comment-25393) and then you could use the ::before selector. Or you could implement/overwrite `theme_menu_local_task()` (probably in combination with a theme preprocess or the earlier mentioned alter function) to add your `<span>` element.

# Answer
> 2 votes
You can paste code below in your theme file template.php and clear cache

```
function [yourtheme]_menu_local_task($variables) {
  $link = $variables ['element']['#link'];
  $link_text = $link ['title'];

  if (!empty($variables ['element']['#active'])) {
    // Add text to indicate active tab for non-visual users.
    $active = '<span class="element-invisible">' . t('(active tab)') . '</span>';

    // If the link does not contain HTML already, check_plain() it now.
    // After we set 'html'=TRUE the link will not be sanitized by l().
    if (empty($link ['localized_options']['html'])) {
      $link ['title'] = check_plain($link ['title']);
    }
    $link ['localized_options']['html'] = TRUE;
    $link_text = t('!local-task-title!active', array('!local-task-title' => $link ['title'], '!active' => $active));
  }

  return '<li' . (!empty($variables ['element']['#active']) ? ' class="active"' : '') . '><span class="edit"></span>' . l($link_text, $link ['href'], $link ['localized_options']) . "</li>\n";
}

```

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


# Question
Title: how to create rules to send email notification for node reference content?
I have two content types: job posting and job application.
The *job application* content type has a node reference field for *job posting*. Whenever users create a *job posting* node, other users can send a *job application* to that *job posting* by filling the fields.

How can I send a notification to the user who had posted the *job application* node when the node has been created?

# Answer
> 8 votes
Sure, with the Rules module create a new rule with this configuration:

1. At `admin/rules/trigger/add` choose a name for your rule
2. In the **Event** dropdown choose *After saving new content* and click 'Save changes'
3. Add a condition of: *Content has type* under the **Node** heading in the conditions dropdown
4. Add an action of: *Load a referenced node* under the **CCK** dropdown heading and choose the node reference field you want to use (the one in the job app content type) and click 'Save'
5. Add another action: *Load a user account* under the **User** dropdown heading. In the **User id** field, add `<?php print $referenced_node->uid; ?>` and click 'Save'
6. Add a third action: *Send a mail to a user* under the **System** dropdown heading, changed the **Recipient** dropdown to *Loaded user* and configure the Sender, Subject, and Body of the email and click save.

Now when a user creates a job application an email will be sent to the user who created the referenced job posting (assuming there is a value in the node reference field, it should be required).

# Answer
> 1 votes
For D7

you can try something like this

Conditions:

Entity has field \>\>\>\> select your entityreference field

Actions: Fetch entity by id \>\>\>\> node:your-reference-field:nid (this should pull data from the node that is referenced via your entity reference field)

Now, if the email field is on your referenced node that should become available when you drill down

eg: node:your-reference-field:field-email

---
Tags: nodes, rules
---


# Question
Title: Undefined index errors when running cron.php
I am getting a slew of errors when I attempt to run a cron job following my hosting company's instructions. From researching the errors, I suspect the instructions are wrong. But their support is telling me this is a development issue and they can't help me. So I hope someone here can tell me the correct way to run cron in this environment.

The site is running without error. Cron runs successfully by using "admin/reports/status/run-cron" or by using the URL provided for running cron from outside the site.

The instructions say to use the following command: `cd /home/username/public_html && php /home/username/public_html/cron.php >/dev/null 2>&1`

This fails silently, meaning that nothing happens that I can see, but the status report does not indicate that cron has run. So I removed the "\>/dev/null ..." part in order to allow the system to send me a result e-mail. Thus the command I'm using now is: `cd /home/username/public_html && php /home/username/public_html/cron.php`

When this command executes, I get an e-mail with hundreds of errors, mostly like: `Notice: Undefined index: argc in /home/username/public_html/includes/bootstrap.inc on line 3407
Notice: Undefined index: SCRIPT_NAME in /home/username/public_html/includes/bootstrap.inc on line 1622`

I found a forum post about the same kind of problem, and the offered solution was to "Use a URL to cron.php with wget or curl." Unfortunately, my Unix is rusty and I don't know how to do that.

Can someone suggest how to modify the command in the host instructions so that cron will run correctly?

Thanks for your help.

# Answer
You shouldn't run cron.php throught php cli. basically you should have a line like this in your crontab file:

0 * * * * wget -O - -q -t 1 http://www.example.com/cron.php

but you also need to append security token to the url.

by reading Configuring cron jobs using the cron command page you will get a better idea of how it works.
> 1 votes

---
Tags: cron
---


# Question
Title: How to define positive AND negative depth on taxonomy filter in views' module?
I am looking for a way to have an exposed filter in a view, based on the option "has taxonomy terms with depth", that can look for a term in a positive and a negative depth.

An example : I want that when "EUROPE" is selected, all contents that have "WORLD" or "SPAIN" "ENGLAND" Show-up in the results.

Does anyone has an idea ?

Thank you in advance.

# Answer
> 0 votes
I think i found a way to do it. One should create both type of filters (with positive and negative depth), and then implements a hook\_form\_alter this way :

```
function example_form_alter(&$form, &$form_state, $form_id){

//forbid the direct access to the filter you want to hide
$form['term_node_tid_depth_negative']['#access'] = FALSE;
//put the value of one filter in the other.
$form['term_node_tid_depth_negative']['#value'] = $form_state['input']['term_node_tid_depth_positive'];
 }

```

And that's it !

# Answer
> 0 votes
I've done stuff like this (eg, World and nesting of regions in the world with heirarchical taxonomies).

Take a look at Taxonomy Edge. It provides view integrations to provide search filters for `"Taxonomy edge: Parent term ID"` and I believe `"Taxonomy edge: Parent term has child term"`. I mean it adds some useful parent and child Views search filters (I dont believe it adds a single positive or negative search as you've described).

---
Tags: views
---


# Question
Title: SearchAPI + FacetAPI: How to add a facet programmatically
Using SearchAPI and FacetAPi with Solr I have a facet block filled by one Solr indexed field i.e. "region".

Example:

> * Region A
> * Region B
> * Region C

I need to programmatically combine two of the active facets to show the accumulated results, while keeping the original facets untouched.

How to achieve this?

> * Region A
> * Region AB \<= new facet which accumulates Region A + Region B
> * Region B
> * Region C

There is a similar use case described in How can I merge or combine facets?

The difference in my use case is that I need the "combined facet" as an additional item, not replacing an existing facet item.

Any idea or hint is highly appreciated. Thank you.

# Answer
> 2 votes
The above use case may be an exotic one but I post my solution in case anybody else has a similar one and maybe it's a motivation for a more elegant solution.

Versions used:
\- Drupal 7.38
\- facetapi 7.x-1.5+1-dev
\- facetapi\_bonus 7.x-1.1+7-dev
\- search\_api 7.x-1.15
\- search\_api\_solr 7.x-1.8

Steps in short

1. Add a new facetapi plugin to filter active facet items, using hook\_facetapi\_filters() \[1\]
2. Plugin method execute(): Add the additional facet items to the $build array of the active facet items
3. Alter the Solr query for the newly added facet items to combine the two with operator OR, using hook\_search\_api\_solr\_query\_alter() \[2\]
4. Activate the new plugin in the index facet configuration

Steps in detail

1. Add a new facetapi plugin with hook\_facetapi\_filters()

Documentation see facetapi.api.php and class FacetapiFilter \[3\]. Note the programmers comments in the docbloc of FacetapiFilter where another solution is suggested by adding an "alter callback". Unfortunately I couldn't get the alter callback to do what I like to do.

```
/**
 * Implements hook_facetapi_filters().
 * Define the plugin class to add additional facet items to an active facet.
 */
function mymodule_facetapi_filters() {
 return array(
   'add_items' => array(
     'handler' => array(
       'label' => t('Add facet items to facet "region"'),
       'class' => 'MyModuleFacetapiFilterAddItems',
       'query types' => array('term'),
     ),
   ),
 );
}

```
2. Plugin method execute(): Add the additional facet item to the $build array of the active facets

Sample plugin code.

```
/**
 * Plugin that adds additional facet item(s) to an active facet.
 */
class MyModuleFacetapiFilterAddItems extends FacetapiFilter {

  // Execute active facets.
  public function execute(array $build) {
    // Taxonomy term ids of the facet items to combine into a new facet item.
    $tid1 = 1;
    $tid2 = 2;
    // Create the additional facet item. Check that the original facet items are
    // available.
    if (isset($build[$tid1])  && isset($build[$tid2])) {
      $add = array();
      $add['#markup'] = 'Region AB';  // the label of the new facet item
      $add['#path'] = 'search';  // your base search path
      $add['#html'] = FALSE;
      $add['#indexed_value'] = $tid1;  // @see comments below
      $add['#count'] = $build[$tid1]]['#count'] + $build[$tid2]['#count'];  // accumulate the #count of the two combined facet items
      $add['#active'] = 0;
      $add['#item_parents'] = array();
      $add['#item_children'] = array_merge($build[$tid1]['#item_children'], $build[$tid2]['#item_children']);  // merge the item children
      $add['#query'] = array(
        'f' => array(
          0 => 'field_region:' . $tid1,  // add both term ids in the #query f parameter
          1 => 'field_region:' . $tid2,  // leads to URL parameters like this: f[0]=field_region:1&f[1]=field_region:2
        ),
      );
      $build[] = $add;
    }
    return $build;
  }

  // Adds settings to the filter form, here only used for users' documentation. Inspired by facetapi_bonus.
  public function settingsForm(&$form, &$form_state) {
    $form['add_items'] = array(
      '#title' => t('Add a facet item for facet "region"'),
      '#type' => 'checkbox',
      '#default_value' => TRUE,
      '#suffix' => t('
        By enabling this filter, an additional facet item is added to facet "region".
        <br/>
        At the moment this list is hard coded and consists of
        <br/>
        - Region AB (combines Region A + Region B, with operator OR)
      '),
    );

    // TODO
    // - add UI settings to avoid hard coding stuff in code
    // - would be nice to be able to specify the operator (conjuntion) OR or AND in the $form array to pass it to the Solr query
  }
}

```

So far is achieved that the new facet item in facet "region" shows up. But it has zero results.

> Region A (10)
> Region AB (0)
> Region B (15)

As the operator (conjunction) for the facet "region" in my case is configured with "AND", the result of the newly added facet item "Region AB" is zero. So I need to combine the two filters with OR in the Solr query.

3. Alter the Solr query for the newly added facet items to combine the two with operator OR.

Sample hook\_search\_api\_solr\_query\_alter() code.

```
/**
 * Implementation of hook_search_api_solr_query_alter()
 */
function mymodule_search_api_solr_query_alter(array &$call_args, SearchApiQueryInterface $query) {
  // Only alter queries on the node index.
  if ($query->getIndex()->machine_name != 'node_index') {
    return;
  }

  // Facet query params array.
  $fq = $call_args['params']['fq'];

  // Get the key of the query that we need to alter. Depending on the active facets and if the
  // visitor is logged in or not, the fq array contains more or less queries in our environment.
  // The code below assures we modify the correct query.
  //
  // In this demonstration we use taxonomy term ids: tid1 = 1, tid2 = 2 for Region AB.
  // If both facet queries are present in the fq array, combine them to one query with operator OR.
  // Afterwards unset the second query.
  if ( (false !== $key1 = array_search('{!tag=facet:field_region_ref}im_field_region_ref:"1"', $fq))
  && (false !== $key2 = array_search('{!tag=facet:field_region_ref}im_field_region_ref:"2"', $fq))
  ) {
    $call_args['params']['fq'][$key1] = '{!tag=facet:field_region_ref}im_field_region_ref:"1" OR im_field_region_ref:"2"';
    unset($call_args['params']['fq'][$key2]);
    return;
  }
}

```

Now the counter of the newly added facet item shows up correctly.

> Region A (10)
> Region AB (25)
> Region B (15)

That's it about the coding. Of course "mymodule" has to be changed to the name of your module.

Remains just the last step to active the new plugin.

4. Activate the new facetapi plugin in the index facet configuration

In the Drupal administration UI visit "Configuration" \> "Search and metadata" \> Search API
\- edit the Solr node index, visit tab "Facets"
\- find facet "region" and select the "configure filters"
\- active the new plugin "Add facet items .."
\- store the changed settings

Note some drawbacks with this solution

1) Hard coded facet item properties
2) Facet item property: #indexed\_value: can only specify one value. Don't know if this has implications on the counters when dependent facets are clicked. So far everything seems to be fine in my implementation.
3) Kind of complicated code to alter the query of the newly added combined facet items. It would be much more elegant if I could specify the operator as a parameter of the #query property when creating a new facet item. Or even easier: specify the fq query right in the wanted way like this: fq\[0\]=tid:(1 OR 2) -- only possible right now in module "ApacheSolr".

Links

\[1\] http://www.drupalcontrib.org/api/drupal/contributions!facetapi!facetapi.api.php/function/hook\_facetapi\_filters/7
\[2\] http://www.drupalcontrib.org/api/drupal/contributions!search\_api\_solr!search\_api\_solr.api.php/function/hook\_search\_api\_solr\_query\_alter/7
\[3\] http://www.drupalcontrib.org/api/drupal/contributions!facetapi!plugins!facetapi!filter.inc/class/FacetapiFilter/7

---
Tags: search
---


title: Problem while updating modules

text:
# Question
Title: Problem while updating modules
I'm running a Drupal website for a while but suddenly and for an unknown reason the website become unable to update modules via the back office. The download of the modules goes good but when I click to the button to update the database I got an error page and when I see the recent reports logs I have that:

```
UpdaterException: Unable to determine the type of the source directory. in Updater::factory() (line 99 of ../www/includes/updater.inc).

```

Is there any solution for that problem?
**Notice**: I'm using Zeus server instead of Apache.

# Answer
It looks like the directory it's expecting the source to come from doesn't exist. Here's the snippet of code which causes the exception to be thrown.

```
if (is_dir($source)) {
  $updater = self::getUpdaterFromDirectory($source);
}
else {
  throw new UpdaterException(t('Unable to determine the type of the source directory.'));
}

```

When updating this is the default directory: `$directory = 'temporary://update-extraction-' . _update_manager_unique_identifier();`

Make sure your defined temporary folder in the file system can be written to by Drupal.

If all else fails, manually update your modules via file transfer.
> 2 votes

---
Tags: updating
---


# Question
Title: Unable to display images after Drupal Update
I recently updated my site to Drupal 7.34 using these instructions -

https://www.youtube.com/watch?v=\_uDTyzE47pQ

After update, I am not able to see the images in the site. All I see is the placeholder for image, but not the image itself. I checked and its not a path issue.

This is how it looked before -

And this is how it looks after -

Also notice that the theme has changed. I was using bartik before. Can somebody tell me if I did anything wrong or how to get the images to display? Could this be an issue with image styles?

# Answer
After some digging around, I finally found a solution as per SA-CORE-2013-003 - Drupal core - Multiple vulnerabilities.

I changed the content of the .htaccess file in the sites/default/files folder to this.

```
#SetHandler Drupal_Security_Do_Not_Remove_See_SA_2006_006
#Options None

Options None
Options +FollowSymLinks

SetHandler Drupal_Security_Do_Not_Remove_See_SA_2006_006

<Files *>
  SetHandler Drupal_Security_Do_Not_Remove_See_SA_2013_003
</Files>

<IfModule mod_php5.c>
 php_flag engine off
</IfModule>

```

I was able to see the images again.
> 1 votes

# Answer
My guess is you didn't correctly copy sites/all and sites/default/ over during the update or the permissions on the files in those directories aren't correct so Drupal can only "see" core modules and themes. The data in the database is still working, but any field, content type, or url that requires a module from sites/all probably doesn't work either.
> 1 votes

---
Tags: updating, media
---


# Question
Title: How to avoid "header already sent" warning when loading a pdf
In drupal 7, when I load a pdf page in a new tab, and after reloading the initial page, I have this warning:

```
Warning : Cannot modify header information - headers already sent in invoices_callback() (line 1093 in C:\xampp\htdocs\drupal\sites\all\modules\custom_profile\custom_profile.module).
Warning : Cannot modify header information - headers already sent in drupal_send_headers() (line 1221 in C:\xampp\htdocs\drupal\includes\bootstrap.inc).

```

Actually, I have a link in my initial page (named 'my-account/invoices') which redirects to a PDF page named 'my-account/invoices/%invoice\_number'. This last one is loaded by a 'page callback' function :

```
function invoices_callback($var){
require_once('sites/all/libraries/dompdf/dompdf_config.inc.php');

$filename = 'Invoice n°' . $var . '.pdf';
$dompdf = new DOMPDF();
    $dompdf->load_html('<div>Test n° : ' . $var . '</div>');
    $dompdf->render();
    $dompdf->stream($filename, array('Attachment'=>0));
    header('Content-type: application/pdf');

}

```

As you see, I didn't use a pdf module, like printer, which is too heavy. I use a custom module which implement a page callback function, and inside I use dompdf library.
The pdf is displayed normally, but when I come back to initial page I have these warnings.

I have tried several things:

* I removed the header function. Effect: the first warning is gone but I still have the second. It seems like the stream method of DOMPDF class wants to sent a header...
* I have added a charset utf-8 to the header function
* I used `ob_start()` and `ob_end_flush()` functions at the beginning and at the end of the code. Surprisingly doesn't work.
* I lastly use drupal\_add\_http\_header function. Doesn't remove warnings.

What i can do is to call a script in an external link, because my test work when i call a php script located elsewhere. But for the UX, i try to have all my scripts managed by drupal, and i want the invoices to be called by a simple alias url (my-account/invoices/%invoice\_number).

So my question is simple: How to avoid these warnings without moving my script to an external location?

# Answer
> 2 votes
So, this question is very specific. The problem of 'headers already sent' warning is common, and each situation is specific, but here...

I don't need to send header-content-pdf, it is redundant, because the stream method of dompdf object sent it. So I had to erase this line.

Secondly, the most important thing is that: My code is in a page callback function, which is executed by drupal at a moment of the page generation process. After a page callback function is executed, the http headers are not sent yet, it is the job of the delivery callback function which is by default drupal\_deliver\_html\_page. We can override this default behavior by adding in the hook\_menu item the delivery callback property:

> "delivery callback": The function to call to package the result of the page callback function and send it to the browser. Defaults to drupal\_deliver\_html\_page() unless a value is inherited from a parent menu item. Note that this function is called even if the access checks fail, so any custom delivery callback function should take that into account. See drupal\_deliver\_html\_page() for an example.

Implementing our custom delivery callback function should work... But I didn't try it... Because, in my research, i found this function: drupal\_exit()

> Performs end-of-request tasks. In some cases page requests need to end without calling drupal\_page\_footer(). In these cases, call drupal\_exit() instead. There should rarely be a reason to call exit instead of drupal\_exit();

But here, for me there is a reason to end the request roughly: The stream method of the dompdf object render the page as i want, ie a pdf page. So to be clear, here is my new code:

```
function invoices_callback($var){
require_once('sites/all/libraries/dompdf/dompdf_config.inc.php');

$filename = 'Invoice n°' . $var . '.pdf';
$dompdf = new DOMPDF();
$dompdf->load_html('<div>Test n° : ' . $var . '</div>');
$dompdf->render();
$dompdf->stream($filename, array('Attachment'=>0));
drupal_exit();

```

}

The stream method sends the http header and renders the page, we don't need anything else, so we exit. It takes me a lot of time, i know how drupal generates a page now. Hope this helps.

# Answer
> 0 votes
You can disable all messages , execute the instructions prone to failure and reactivate the messages to restore stability to the system.

```
    // Desactivamos los posibles warning para que no se envien los headers
    error_reporting(0);

$dompdf = new DOMPDF();
$dompdf->load_html($html);
$dompdf->render();

    // Save file
    $output = $dompdf->output();
    $dest = "/your-directory/final_file.pdf";
    $result = file_put_contents($dest, $output);

    // Reactivamos los warning
    error_reporting(E_ALL ^ E_NOTICE);

    if( $result ) {
        // Send file
        $dompdf->stream($dest);
    }
    else{
         echo "<p> An unexpected error has occurred. Please try again later or contact support. </p>";
    }

```

---
Tags: 7, files
---


# Question
Title: How to declare @font-your-face local fonts in CSS?
Pretty simple question, why does my CSS not render my fonts when I declare it programmatically (in my CSS) vs when I use the @font-your-face UI?

For a number of reasons I'd like to be able to control this from my styles. I'm declaring the CSS font-family declaration correctly and the text is being changed but it's going to some sort of Sans-Serif or Helvetica default.

If it matters I'm using, or trying to use omega 4. thanks in advance.

Here's my css for the relevant selector, I know it's trying to work because the text changes but not to this font.

```
.l-page{width:960px;
    margin:0 auto;
    border:2px solid black;
    border-radius:15px;
    padding:2px;
    font-family: 'Cassannet - simple';
    font-weight: normal;
    font-style: normal;}

```

# Answer
There is an option to apply the CSS in the theme in the drop down of the @font-your-face UI.
> 1 votes

---
Tags: theming
---


title: How to set Time Limit on Comment Edit

text:
# Question
Title: How to set Time Limit on Comment Edit
I need to set time limit to edit comment, like Stack Overflow strategy that sets 5 minutes time limit. The Time Limit on Comment Edit asked the same question and the Edit Limit was proposed.

In `admin/people/permissions` I allow authenticated users to *Edit own comments* and also Installed Edit Limit module. This is the configuration

Despite of letting the contents to be editable in 3 minutes, Users are still unable to edit their own comment right after sending their comments. What is the problem? Is there any other solution?

# Answer
On my site, all I have to do to make this work is to enable the permission "Edit own comments" for the role, and set the time limit. If you've done this, it should work. This is how it looks like when working:

The only thing I can suggest is that you go over your settings again.
> 1 votes

---
Tags: 7, nodes, comments
---


# Question
Title: Operations between the same field of a content type
I feel like this is a very basic question, but after a couple of years it is the first time I need something like this and I cannot wrap my mind around the structure and get an idea of how to acomplish it.

Lets say I have a content type called "Fruit" where I store data in the fields "Name" (text), "Description" (text), "Price" (integer), "Date" (date). In a view I'd like to select the fruit with names "Pear" and "Apple" with their respective prices for the dates inserted, but also make mathematical operations on the prices of the fruit (Like, "The price of apples was the 3/4 of the price of pears"). I cannot think of a way to do this since it is actually the same field, only grouped by some other field.

Any suggestions?

# Answer
> 0 votes
Install views\_php module. This module adds a field to the view and it also provides a few tokens. You can use the current row values. Note that you have to insert the main fields before the *PHP* field and exclude the *Price* field from display, Then the `$results,$data,$row` objects will give you the value of the row, Do the mathematical calculations and output the result.

# Answer
> -1 votes
If you want to perform mathematical operations, then you have to create view in normal way and in the view query alter functions, you have to append your condition, then you will get your expected output.

---
Tags: 7, views
---


title: Field shows nulls as zeros

text:
# Question
Title: Field shows nulls as zeros
I defined the hook\_views\_data in order to display some data from a custom table in the database. One field is a nullable decimal(5,1). The value of this field is displayed correctly in the view but shows nulls as 0.0. "No results behavior" seems to have no effect on it in any way. The field is defined as follows:

```
$data['customview']['value'] = array(
        'title' => t('value'),
        'help' => t('the requested value'),
        'field' => array(
            'handler' => 'views_handler_field_numeric',
        ),
        'sort' => array(
            'handler' => 'views_handler_sort',
        ),
        'filter' => array(
            'handler' => 'views_handler_filter_numeric',
        ),
    );

```

Using PHPMyAdmin, I can verify that the values are null. Any custom properties I should add to the definition of the field in order to allow nulls (Display them as empty or dash)?

# Answer
There are some issues in the views queue that can help out with fixing these issues. This issue is very similar to the issue you are having (Empty rounded numeric fields not hidden properly). It has a patch that should fix the issue that has been reviewed and tested by the community but has not made it into dev yet. You could either patch views or write your own numeric views handler to fix this issue.
> 1 votes

---
Tags: entities, views
---


# Question
Title: Entity metadata wrapper - how to get field value, NOT key
I hhave `field_something` which is a select field with multiple options:

```
key1|Value 1
key2|Value 2

```

I'm trying to get the value of this field using the Entity metadata wrapper.

`$wrapper->field_something->value();`

This will return the key, not the value as defined in the node's fields.

Any ideas?

# Answer
You may use `$wrapper->field_something->label()`.
> 13 votes

# Answer
You can try code below:

```
$wrapper = entity_metadata_wrapper('node', $node);
$list = $wrapper->field_machine_name->optionsList();

```

I hope it helps you!
> 1 votes

---
Tags: 7, entities
---


# Question
Title: Is there an existing way to make blogs for nodes (not users)?
I want to be able to set up blogs (or blog-like things, anyway) on arbitrary nodes -- imagine that you have a content type representing an organization, and that organization's owner can create blog entries about the organzation, its activities, etc. This would not be a lot of code to write, but I'd sure prefer to use an existing solution than hack a new one together.

Is there anything out there like that? Any experiences to report about adapting/hijacking the existing blog module for this purpose? Thanks!

# Answer
> 1 votes
It is a little bit of a learning curve at first but you could use OG Groups for something like this. Make your organization node be a group and add an audience field to blog content type.

# Answer
> 1 votes
A possible approach to "*... adapting/hijacking the existing blog module ...*", is to consider the Enterprise Blog module. From its project page:

> Enterprise Blog is a complete blog solution that borrows many features from Wordpress. It is designed to be a **replacement for the core blog module** and provide much greater features and customizations.
>
> Check out OpenEnterprise for a great distribution to install Enterprise Blog.

Should you want to consider using the Blog module instead, you may want to review the existing Community documentation about it.

---
Tags: 7, nodes
---


# Question
Title: How do I create an AND filter for the same field
I am having a problem with a view filter. I have one field called Category. The field contains a comma separated list of id numbers that represent different categories. I want to create a filter that will filter out all records that contain one id number, but not another. So my filter is Category=5601 AND Cateogry\<\>5612. Whenever I create this filter, the result ends up as OR instead of AND.

# Answer
> 1 votes
By default, drupal filters with AND. Maybe you clicked the rearrange and/or option by mistake intsead of just adding a new filter. Try removing both and creating again by clicking add.

---
Tags: input-formats
---


# Question
Title: Module to create nodes that are lists of other nodes?
I'm looking for a way to allow users on my site create a piece of content that is a list of current content. For example a user can create a "favorite articles list" content piece and then select his favorite existing articles that will populate this new content type. Is there an exisiing module that does this or something similar?

# Answer
> 1 votes
You could probably try the Flag module. It doesn't create nodes, but the idea is pretty much what you're lining out.

> Flag is a flexible flagging system that is completely customizable by the administrator. Using this module, the site administrator can provide any number of flags for nodes, comments, users, and any other type of entity. Some possibilities include bookmarks, marking important, friends, or flag as offensive. With extensive views integration, you can create custom lists of popular content or keep tabs on important content.
>
> Flags may be per-user, meaning that each user can mark an item individually, or global, meaning that the item is either marked or it is not marked, and any user who changes that changes it for everyone.

# Answer
> 0 votes
It sounds like you are look for the Views Module:

> You need Views if
>
> You like the default front page view, but you find you want to sort it differently. You like the default taxonomy/term view, but you find you want to sort it differently; for example, alphabetically. You use /tracker, but you want to restrict it to posts of a certain type. You like the idea of the 'article' module, but it doesn't display articles the way you like. You want a way to display a block with the 5 most recent posts of some particular type. You want to provide 'unread forum posts'. You want a monthly archive similar to the typical Movable Type/Wordpress archives that displays a link to the in the form of "Month, YYYY (X)" where X is the number of posts that month, and displays them in a block. The links lead to a simple list of posts for that month. Views can do a lot more than that, but those are some of the obvious uses of Views.

Despite that terrible description from the module page, Views is a sql query manager that arranges data however you like. It allows you to very specifically create lists of all types of entities (users, nodes, taxonomy, etc) and customise the layout and information presented to users. The front page here on Drupal Answers for example can easily be duplicated using Views.

# Answer
> 0 votes
The Relation Add Module was the solution. It allowed me to add me to set a list of related nodes to another node via a custom field.

---
Tags: 7, entities
---


# Question
Title: Background CSS images won't be changed after reuploading & Cache flushing
If I Download a css background image of my site, changing it with GIMP (or MS paint for that matter) and re upload it, nothing will happen. Moreover, even after I delete the file from the server, the image stays online... clicking "Flush all caches" nothing happens... I also note that the image basically stays the same --- Same filename and file extension, so it's extremely wired. What would you suggest of checking?

## What I already tried and didn't help:

* Turning off server external caching tool (for both static and dynamic cache).
* Turning off AdvAgg from config/development/performance/advagg (Unchecked "Enable...")
* Turning off Drupal's internal cache system.

Update: Working answer found... See below for the answer with green checkmark.

# Answer
> 0 votes
The problem is apparently CDN based. I use the free version of the Cloudflare CDN service, and after purging it's cache, the deleted image no longer appeared on-line at site... I've tried to repeat the procedure to vindicate that indeed it was the CDN service so I reuploaded the image with some color changes and another file name, and again, after I deleted it, it kept appearing on-line at the site, but disappeared only after purging the CDN cache (but not any other type of cache) via the Cpanel based Cloudflare managing area.

So, Better try to purge it if you come across this problem, or purge and turn off the CDN for a while (especially if it won't damage your loading times and on-page optimization scores). Maybe dev mode is an alternative for turning it off completely - didn't try that option. Ben.

# Answer
> 1 votes
Since all caching aren't able to fix, let's try narrowing down the issue.

First, try to delete the image from your theme. Flush all caches and see if the background image is still there. If it is, open your browser development tool and check the background image URL and try opening it in a new tab, check the URL of the image and follow it in your server's directory if it really still exists.

Second, try restarting the server or any related running services you have in your server.

Hope this can at least give an idea on where to find what's causing the issue.

# Answer
> 0 votes
Go to your theme's settings page and save it. The color module can cause issues like you're describing. AdvAgg tries really hard to detect this but it can't catch every use case. This is an issue with core that AdvAgg fixes 95% of the time.

# Answer
> 0 votes
This is a caching issue, and there are different places this could happen depending on your set up:

* Proxy (like Varnish)
* Webserver (like apache or nginx)
* browser

Webservers usually don't cache resources, I've seen some short lived caches on nginx - like 5-10 secs.

Most likely the caching is going on in a proxy or your browser. You would probably know about the proxy issue if you did use a proxy, so my best guess, is that your browser is caching the image.

To test if the issue is a caching issue, you can try to view the image from the url used in the CSS and you should see the same image as on the webpage. You can then try to alter the URL by adding a GET param.

If the url to the image is: http://example.com/image.png, you can change the url to http://example.com/image.png?test=1

Since the url is now completely different, the browser (and proxy) wouldn't have stored a cache for this, and you should see the image that you just uploaded. If that is the case, it proves you need to clear caches.

When doing development, it can be an advantedge to turn off browser cache completely to avoid issues like this. There are many extensions for all browsers that can help you with this, if it's not built in the browser.

# Answer
> 0 votes
I get this randomly and also the same thing with favicons. I wasn't running a CDN and never solved it, instead I just started incrementing the file names one by one to avoid the issue completely.

It's not a clever solution, but if you're in a rush it should work.

---
Tags: theming
---


# Question
Title: Drupal commerce display VAT exclusive unit price & subtotal for line item in cart and order
I has a VAT tax for my products. It's a B2B site so we only show Tax exclusive price to customers. Even in cart and order. The VAT only show in the cart & order bottom just as the Drupal commerce original one.

My problem is I can not find a way to show the VAT exclusive price in the cart views. There is no option for that. The line item unit price field 'formatted amount' is showing VAT included price. 'formatted amount with components' is showing a price table like this:

```
Subtotal    $16.50 AUD
GST $1.65 AUD
Unit price  $18.15 AUD

```

That's not what I want. How can I only show the the price exclude the VAT tax?

# Answer
Finally I find this module: Commerce price by components

This is perfect for my requirement.

> Extension to Drupal commerce that provides a price formatter to enable/disable price components such as discounts or taxes when displaying prices. This gives the admin absolute control over which components should be displayed and which shouldn't. It also provides two Views handlers to display/hide price components in cart totals and order totals. Additionally it has basic rules support that gives to the commerce administrators the ability to do conditions using price components such as discounts or taxes and react accordingly.
>
> Example use case
>
> If you want to customize your cart or checkout views, you may want to display prices with taxes and without discounts (or viceversa) in your line items but the total amount should be displayed. Then you enable this module and choose at formatter level (both display fields and views) which components you want to hide or display.
> 3 votes

---
Tags: commerce
---


# Question
Title: How to show a block on user profile edit page ?
I am trying to display a block on an user edit page (example: user/123/edit/custom\_url, but for some reason, I can't seem to get it working. Any help is appreciated.

I tried this, but this isn't working:

```
<?php
global $user;
if (arg(0) == 'user' && $user->uid == arg(1) && arg(2) == 'edit' && arg(3) == 'custom_url' ){
  return TRUE;
}
else {
  return FALSE;
}
?>

```

# Answer
Using the `block ui`, you can select the visibility of block using `user/*/edit/custom_url`. The star is a wild card and will give you the ability to place blocks on pages that have a variable in the path.
> 1 votes

# Answer
I think it is better to write:

```
if (arg(0) == 'user' && arg(1) == $user->uid  && arg(2) == 'edit' && arg(3) == * ){
  return TRUE;
}
else {
  return FALSE;
}
?>

```

or do it by the use of template system.
> 0 votes

---
Tags: 7, blocks, users
---


# Question
Title: How to use the gallery formatter settings in a display suite code field?
I am using the gallery formatter module to format photo galleries.

To satisfy a requirement I need to create a `Display Suite code field` that displays the list of pictures attached to a related node (attached through the Entity reference module).

The get the `field_gallery` containing images of the related page I use the following in the code field:

```
<?php
    $relatedNode = node_load($entity->field_related_page['und']['0']['target_id']);
    $field = field_view_field('node', $relatedNode, 'field_gallery', array( 'label'=>'hidden'));
    echo drupal_render($field) ;
?>

```

However this only displays a raw list of images. **I need this list of images to be fomatted by the gallery formatter**.

The formatter should be passed to field\_view\_field() as an array (instead of `array( 'label'=>'hidden')`) but **how can I get the list of key-\>values that fill the array?**

# Answer
> 0 votes
May I suggest field slideshow if you havent tried that already. Field Slideshow

> Provides a Slideshow formatter for Image fields, using JQuery Cycle plugin.
>
> Compared to Views slideshows, building the slideshow from multiple nodes, this module builds it from a single node, with a multi-valued Image/Media/Field Collection field.

# Answer
> 0 votes
You can try code below:

```
<?php
    $display = array(
      'label' => 'hidden',
      'type' => 'galleryformatter_default'
    );
    $relatedNode = node_load($entity->field_related_page['und']['0']['target_id']);
    $field = field_view_field('node', $relatedNode, 'field_gallery', $display);
    print drupal_render($field);
?>

```

---
Tags: media, display-suite
---


# Question
Title: Total count of two different content types in one View?
Use case: How many Demonstrations and Deliverables are from each State?

I'm using a View with Aggregate but don't see a way add multiple content type counts.

Refer to screen capture of the page and view settings please.

# Answer
The table in the screen capture is similar to this one:

The Views Calc module can be used to transform that table so that the calculations in the last rows (with **Count**, **Sum** and **Max**) get added to it.

By replacing the columns like '# Fish' and 'Weight' with 'Total Demonstrations' and 'Total deliverable ...' (as in the question), and by asking for only the 'sum' to be added, it should answer the question.

To ask for the 'sum', just select it from the selection list, similar to what is shown in this screenshot:

For more details (step-by-step instructions), refer to the community documentation about the Views Calc module.

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

---
Tags: views
---


# Question
Title: Getting path alias on the base of term id
Foolowing is the code to display breadcrumb, it will display the results like this `Parent1/Parent2/Parent3/..`

```
$var1=taxonomy_get_parents_all("term_id");
for($j=sizeof(intval($var1)) ; $j>=0 ;$j--)
{
  print $var1[$j]->name."/";
}

```

Here I want to compute the path alias for each parent, any suggestions?

# Answer
> 0 votes
To get the alias of a term : `drupal_get_path_alias('taxonomy/term/[tid]')`.

**Just a suggestion :** To print the `breadcrumbs` you should try Custom Breadcrumbs module.

---
Tags: 7, path-aliases
---


# Question
Title: How to format the raw date formats when using Google Analytic Reports?
I am using Google Chart Tools, Views, and Google Analytic Reports to create charts for an admin dashboard.

However the date format (Time Dimensions: ga:date) outputs the date in the YYYYMMDD format.

How can I change that to something like Oct 31?

**Note**: I have been asking around and apparently NO ONE knows how to do this. Here are some relevant URLs about it:

# Answer
Feature request #1900994 (from early 2013), with title "**Date Format in Views**", seems to have been delivered (fixed) near the end of 2014 via issue #2368159, with title "**Add support for datapoints types**". Refer to description of the issue for more details about it (the problem description, and the actual solution that got implemented).

Issue #2368159 also resolved the issue about Format time duration, a typical variation of the question here.
> 0 votes

---
Tags: views, google-analytics, charts
---


# Question
Title: How to redirect the checkout complete page?
In my Drupal Commerce site, I redirect to a local payment API with a custom module after the user selected the local payment gateway in the review order page. The users enter username and password in the local payment website; if the user is authenticated successfully, the payment gateway server redirects back to my localhost at http://localhost/commerce/sites/all/modules/paymentgateway/CheckoutComplete.php.

In that page, the pay button exists; the user has to click the pay button to finish the payment transaction. After finishing payment, I want the server to redirect to Drupal Commerce's checkout complete page, e.g. http://localhost/commerce/checkout/93/complete.

How do I redirect to this link? Do I have to implement a hook?

# Answer
In this payment structure with local payment gateway, I have to pass product item lists, return url and cancel url to local payment gateway through drupal commerce’s Local Payment Module. If detail information of this payment is returned, in that page I redirect to the this link http://localhost/checkoutComplete/completeCheckout .

Checkout\_complete.admin.inc

```
function checkout_complete_loadAllrecord()
{
    //current orderId
    $paraorder = variable_get("order", "");
    $order = commerce_order_status_update($paraorder, 'checkout_complete');

    //assign order status to checkout_complete
    $order->status = "checkout_complete";

   //calling this method order status will be changed to "Checkout_complete", this method will fire commerce_checkout_rule()
   //In commerce_checkout_rule(), we can send email to client to notify checkout is complete.
    commerce_checkout_complete($order);

    //redirect to order completed page
    drupal_goto(commerce_checkout_order_uri($order));

}

```

Thanks
> 0 votes

---
Tags: commerce
---


# Question
Title: Add a link into a drupal header and table
I am currently in the process of creating a free sports betting site, and I would be able to manage the matches. For this, I create a table with the data from my table, but I would add a column to manage the matches, to remove them or modify them. Outside, I do not like to add a link in the header, for exemple:

```
 l(t('Modify'), 'link/modi');

```

Here is my actual code:

```
    function get_rencontre_all(){

    $header = array(
    array('data' => 'journee', 'field' => 'journee' ),
    array('data' => 'eq1', 'field' => 'eq1'),
    array('data' => 'eq2', 'field' => 'eq2'),
    array('data' => 'stade', 'field' => 'stade'),
    array('data' => 'date', 'field' => 'date'),
    array('data'=>'Opérations', 'colspan' => 1),
    );

    db_set_active('sport_db');
    $query = db_select('rencontre', 'r')->fields('r');

    $sorter = $query->extend('TableSort') //création de l'objet TableSort
    ->orderByHeader($header); //détermination du trier
    $result = $sorter->execute(); //exécution du TableSort
    db_set_active();
    return $result->fetchAll(PDO::FETCH_ASSOC); //revoie d'un tableau de lignes

}

function modulesport_page_rencontre_manage(){
    $rows = get_rencontre_all();
    //header qui définit les colonnes et les champs associés
    $header = array(
    array('data' => 'Journée', 'field' => 'journee' ),
    array('data' => 'Equipe domicile', 'field' => 'eq1'),
    array('data' => 'Equipe exterieur', 'field' => 'eq2'),
    array('data' => 'Stade', 'field' => 'stade'),
    array('data' => 'Date', 'field' => 'date'),
    array('data'=>'Opérations', 'colspan' => 1),

    );

    $page_array = array(
    'titre' => array(
    '#prefix' => '<h1>',
    '#suffix' => '</h1>',
    '#markup' => 'Liste des rencontres',
    ),
    'tableau' => array(
    '#theme' => 'table',
    '#header' => $header,
    '#rows'=> $rows,
    ),
    );
    return $page_array;

}

```

# Answer
> 2 votes
Instead of returning **returning** `$result->fetchAll(PDO::FETCH_ASSOC)`, You need to loop the result and add a link to the array like :

```
$rows = array();

foreach ($result->fetchAll(PDO::FETCH_ASSOC) as $row) {
  $rows[] = $row + array('link' => l('MyLinkText', 'mylinkhere'));
}

return $rows;

```

---
Tags: 7
---


# Question
Title: How do I display an image using the Dynamic Background module?
I have been struggling to get the Dynamic Background module working for users' profiles. The profiles are displayed in a panel.

I enabled the Panel and User sub-module and after hours of trial and error I found a CSS combination that seems to work: #page #main-wrapper.

So the image displays as a background. But if I go to `/user/[uid]/backgrounds` to enable a background image for that user, it works but the image displays for ALL users, even when the other users have not enabled a background image.

I am at a loss because I thought that everything after `user/[uid]` only affected that user.

Any idea what I am doing wrong?

# Answer
> 0 votes
Make sure you also completed the required **configuration** steps as described in the Readme.txt of this module. I.e.:

> Enable the modules/extensions that you want to use and go to the administration interface at /admin/config/user-interface/backgrounds/settings. Start by filling out the form and remember to fill out the CSS behaviour section. Then go into the configuration tab for each module/extension that you have enabled and as a minimum filling out the CSS behaviour fields.
>
> Go to /admin/config/user-interface/backgrounds and select some images to upload after pressing "Save configuration" the form will change and allow you to select a default image. If you have enabled some of the extensions go to their location and select one of the uploaded images. See the extension descriptions above for information on where to select images for each extension.

---
Tags: 7, panels
---


title: _cron_queue_info

text:
# Question
Title: _cron_queue_info
worker callback dosen't run in \_cron\_queue\_info

```
function samadiet_cron_queue_info() {
    drupal_set_message("pre run ittttt".date_iso8601(variable_get('samadiet_readsite_queue', time())));

    $queues['samadiet_readsite_queue'] = array(
        'worker callback' => 'samadiet_cron_worker',
        'time' => 1,
    );
    return $queues;

}
function samadiet_cron_worker($item)
{
    drupal_set_message("xxxxx run ittttt".$item);
}

```

no message was show?

# Answer
> 0 votes
This way you just have declared the queue. You need to invoke `queue` using `DrupalQueue::get('samadiet_readsite_queue')`.

Example to implement :

```
function samadiet_cron(){
  $queue = DrupalQueue::get('samadiet_readsite_queue');
  $queue->createItem($item); // $item argument form samadiet_cron_worker callback
}

```

---
Tags: cron
---


# Question
Title: How to add content programmatically to a field collection that it's in an entity (build with eck)
I'm trying to save information into an entity build with eck, this entity has a field\_collection with more fields.

I have take a look around internet, and I only find examples that works with node entity and user entity, but when I try to use the same code with my entity, it doesn't works.

This is my code:

```
<?php
$idform = 1;
$entity = entity_load('formulario',array($idform));
//dpm($entity);

$newfield_collection = entity_create('field_collection_item', array('field_name' => 'field_form_field'));
$newfield_collection->setHostEntity('formulario',$entity);
$newfield_collection->field_name[LANGUAGE_NONE][0]='name3';
$newfield_collection->field_form_id[LANGUAGE_NONE]['0']['value']=3;
$newfield_collection->field_sff_name[LANGUAGE_NONE]['0']['value'] = 'value name 3';
$newfield_collection->field_field_id[LANGUAGE_NONE]['0']['value'] = '13434';
$newfield_collection->field_field_type[LANGUAGE_NONE]['0']['value'] = 'value type 3';
$newfield_collection->save(FALSE);

?>

```

And this is my error message:

> EntityMalformedException: Missing bundle property on entity of type formulario. in entity\_extract\_ids() (line 7633 of /home/oscar/webapps/www/drupal/drupal7/includes/common.inc).

I have debuging the code and seems that the problem is with `setHostEntity` But I don't know if it's because I build the entity with eck module.

Thanks

Oskar

# Answer
> 0 votes
The problem here is that entity\_load returns an array, not the single entity. So you should do something like this :

```
$entities = entity_load('formulario',array($id));
$entity = end($entities);

```

and then the rest of your code ...

# Answer
> 0 votes
Use entity\_load\_single instead of entity\_load to load single value instead of array.

This will solve the error.

---
Tags: 7, entities
---


# Question
Title: Google chart not displayed through ajax call
I am trying to use Gooogle Chart Tools for showing some statistics. Below is the example code I'm using:

```
$settings['chart']['chartOne'] = array(
    'header' => array('Apple', 'Banana', 'Mango'),
    'rows' => array(array(12, 6, 8)),
    'columns' => array('Fruit count'),
    'chartType' => 'PieChart',
    'containerId' =>  'content',
    'options' => array(
      'forceIFrame' => FALSE,
      'title' => 'Fruit count',
      'width' => 800,
      'height' => 400
    )
  );
  //Draw it.
  $ret = draw_chart($settings);
  $stats = '<div class="response_stat"><b>'.$ret.'</b></div>';

```

I am then trying to push $stats to page by ajax.

But all I see in display is 'array'.

I feel I need to render the `$ret` array , or maybe there is some other problem. Any idea where the problem is and how to correct it?

# Answer
This question seems similar to what is described in the issue about Ajax load of chart (current status = needs review).

You may want to try the patch attached to either comment #3 or #11 of that issue.
> -1 votes

---
Tags: ajax, charts
---


# Question
Title: How to create a Pie chart using views google chart tools
I am using the Google Chart Tools module to create a pie chart of cricketers runs wagon wheel.

I am facing a problem with the creation of a pie chart for creation of wagon wheel. I have cricketer content type which has these fields:

* Name
* Mid-On-Score
* Point score
* Mid-off-score
* Gully Score

Now I want to create a pie chart (i.e wagon wheel of scored runs by each individual cricketer). So that it shows me a pie chart which will have areawise score.

I have created a view for this and used Google Chart Tools trying to create a piechart for this. But it is not showing the pie chart correctly.

I have done correct configuration but the pie chart shows only first field in whole circle and other fields are not shown.

Here is an image with a Column chart:

And here is a similar image with a pie chart:

In the above pie chart, it should show me colored regions (slices) but it's not showing.

What am I doing wrong or does pie chart not have such functionality?

Note: it is showing other charts correctly.

# Answer
> 1 votes
I had the issue - though not in drupal, but a native php application. While I've read that large differences in values can trigger the "other" slice, this was not the case in my application.

The datatable rendered perfectly as ColumnChart, but failed to show slices as PieChart and only came back with 100% "other". What resolved the issue for me was casting the values in php to integer with `intval()`. Apparently the CulumnChart visualization is forgiving, while the PieChart is not when it comes to values other than intergers. Hope that helps clarify.

# Answer
> 0 votes
This is a known (active) issue for the Google Chart Tools module, as described in issue #2077751.

In case it's an option to consider changing to an alternative module, then you may want to look at the Charts module as a possible alternative. For the Charts module, there is a similar issue (also because Charts is using the same Google Charts library as its renderer). However, comment #4 in it contains a patch that might be a good fit as a (temporary?) alternative. That issue also has some "child" issues that may help also.

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

---
Tags: views, charts
---


# Question
Title: How to display more than 1 chart on the same page when using Google Chart Tools?
I have created a simple page (in Views) listing a series of nodes. Each node has an (EVA) field showing a pie chart.

When I use the Google Chart Tools module as a Views field format, the page shows only 1 chart (to the most recent node).

It seems that I need to do something so that multiple charts can show in the same page. **But what am I missing here?**

Any help would be much appreciated.

# Answer
> 1 votes
I finally managed to achieve this using the dev version of the Views Dataviz module. Of course there are other solutions but these require coding so i guess this is the easiest way of showing multiple charts in the same page.

# Answer
> 0 votes
I've been trying to place multiple charts on the same page at some point, through code. Just by mixing html code with the returned code from the charts worked for me. In case this is of any help, which might not be the case here since you use views.

You can just create your custom module and on one of the functions have something like the example found in the Google Charts tools module, where you can get a chart with `draw_chart($settings)`.

```
chart_a = draw_chart($settings_a);
$chart_b = draw_chart($settings_b);
return '<div id="chart-a">'.$chart_a.'</div>'.'<div id="chart-b">'.$chart_b.'</div>';

```

# Answer
> 0 votes
To answer the question about "But what am I missing here?": it seems that what might be the answer is what is described in the issue about Can't display more than 1 chart at the same page. More specifically, this is what is included in comment #2 in it:

> **Turn on Aggregation** in Views, (Advance section of views). Then there will be a setting on the field called "**Aggregation Settings**". And then in the field "Aggregation Type" select "**Group Results Together**". Watch your overrides.

Give it a try and see what happens ...

---
Tags: 7, views, charts
---


title: Context aware plugins

text:
# Question
Title: Context aware plugins
I am working on porting a module from Drupal 7 to Drupal 8.
In the process I have to port a ctools content type plugin to the new context aware plugin.
The legacy plugin had "node" as a required context because it had to appear only on the node pages. I am finding it hard to implement it in the new plugin system.
Here is how I define the new plugin

```
/**
 * Provides a 'Custom' block for the current node.
 *
 * @Block(
 *   id = "machine_name_of_block",
 *   admin_label = @Translation("Admin label for the block"),
 *   context = {
 *     "node" = @ContextDefinition("entity:node", required = FALSE)
 *   }
 * )
 */
class ModuleBlock extends BlockBase {
  /**
   * {@inheritdoc}
   */
  protected function blockAccess(AccountInterface $account) {
    /** @var $user \Drupal\user\UserInterface */
    // $user = $this->getContextValue('user');
    $node = $this->getContextValue("node");
    if (!is_null($node)) {
      return AccessResult::allowed();
    }
    else {
      return AccessResult::forbidden();
    }
  }

  /**
   * {@inheritdoc}
   */
  public function build() {
    // Sample output which will be changed later.
    return array('#markup' => '<span>' . $this->t('Powered by <a href="@poweredby">Drupal</a>', array('@poweredby' => 'https://www.drupal.org')) . '</span>');
  }

}

```

I have a problem in accessing the context value in this plugin using `$this->getContextValue('node');`. It seems to return null even if I am on a node page.
Am I missing something?

# Answer
> 3 votes
Why don't you just use the existing node type condition plugin?

That won't solve your problem if you also need the node to actually display something, but core currently just doesn't really do this for blocks, there is no UI to configure the mapping, so it only works if the context has the exact same name.

You will likely have to fall back to getting the parameter yourself out of the route match service, for now.

---
Tags: 8
---


# Question
Title: Is there a module which allows users to edit text together?
I am building a site which allows users to upload handwritten images and transcribe them. Ideally, I would like if there were a text box type of module which updated the default value of the box each time it was written to.

Example:

1. Text box is created: "Default text"
2. Alice updates text box: "Alice was here!"
3. Text box now reads "Alice was here!" to all users.
4. Bob updates text box to "Alice was here! And bob!"

Is it possible to do something like this using modules? If so - which?

The page layout will look something like this:

```
[ Slide show ]
[ Transcription box ]
[ Comments ]

```

Ideally it would have the following functionality:

* The image must appear on the page alongside the text editor (I had a WYSIWYG in mind but haven't been able to crack it yet)
* Version control for text
* Load 'default text'
* Saving would overwrite the 'default text'

Is it possible to embed the transcription box in to the page? It is important that the user is able to view the image while editing the text box.

Thanks

# Answer
> 0 votes
Maybe you want to consider using the Paragraphs module for this. Here are some quotes about it (from its project page):

> Paragraphs is the new way of content creation! It allows you — Site Builders — to make things cleaner so that you can give more editing power to your end-users.
>
> Instead of putting all their content in one WYSIWYG body field including images and videos, end-users can now choose on-the-fly between pre-defined Paragraph Types independent from one another. Paragraph Types can be anything you want from a simple text block or image to a complex and configurable slideshow.
>
> Paragraphs module comes with a new "paragraphs" field type that works like Entity Reference's. Simply add a new paragraphs field on any Content Type you want and choose which Paragraph Types should be available to end-users. They can then add as many Paragraph items as you allowed them to and reorder them at will.

Some other questions on Drupal.SE where the Paragraphs module has also been suggested as a possible answer (which may help for more inspiration about what kind of things you can do with this podule):

---
Tags: 7, entities
---


title: Hook Function to Footer

text:
# Question
Title: Hook Function to Footer
I would like to know how to hook a function in the footer area right before the `</body>` tag. The function would produce html.

```
function html_footer(){
    does stuff
}
places_in_footer('html_footer()');

```

I've done some research on the subject but it seems like there are a lot of different methods but all of them are deprecated. So I'm not sure what the right method would be.

For example in wordpress it would be:

```
function your_function() {
    echo '<p>This is inserted at the bottom</p>';
}
add_action( 'wp_footer', 'your_function' );

```

# Answer
You can create one block and add the html content and place this block in the footer region. This content will place inside the tag and after the main content. Thats mean you will get your content before the closing tag.
> 1 votes

---
Tags: hooks
---


# Question
Title: Extra space at beginning of downloaded image
I'm using custom code to download images, as I need to check permissions and keep a trace of each download (inter alia).

Here's how I decided to go:

* Simple link, triggering an AJAX call of my download page
* As it's an AJAX called page, `html--ajax.tpl.php` is used
* Same for `page--ajax.tpl.php`
* My final file force the image download

...and the content of the 3 related files:

**html--ajax.tpl.php**:

```
<?php print $page; ?>

```

**page--ajax.tpl.php**:

```
<?php print render($page['content']); ?>

```

**download.ajax.php**:

```
<?php

// ...extra code to populate $path and $filename

header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename='.$filename);
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($path));
readfile($path);
exit;

```

> **My problem is that I've an extra space in my downloaded image bytes**

The downloaded image is corrupted, so I decided to compare its bytes with the original image with `xxd`, and here's the result where you can see an extra `20` byte at the very beginning:

```
00000000: 20ff d8ff e000 104a 4649 4600 0101 0000   ......JFIF.....
00000010: 0100 0100 00ff fe00 3b43 5245 4154 4f52  ........;CREATOR
00000020: 3a20 6764 2d6a 7065 6720 7631 2e30 2028  : gd-jpeg v1.0 (
00000030: 7573 696e 6720 494a 4720 4a50 4547 2076  using IJG JPEG v
00000040: 3632 292c 2071 7561 6c69 7479 203d 2037  62), quality = 7
00000050: 300a ffdb 0043 000a 0707 0807 060a 0808  0....C..........
00000060: 080b 0a0a 0b0e 1810 0e0d 0d0e 1d15 1611  ................
00000070: 1823 1f25 2422 1f22 2126 2b37 2f26 2934  .#.%$"."!&+7/&)4
00000080: 2921 2230 4131 3439 3b3e 3e3e 252e 4449  )!"0A149;>>>%.DI
00000090: 433c 4837 3d3e 3bff db00 4301 0a0b 0b0e  C<H7=>;...C.....

```

I used the same approach as the one described in this post to find the origin the the space. The better I could have is to determine that the space appears in `page--ajax.tpl.php` :

```
00000000: 5020 44ff d8ff e000 104a 4649 4600 0101  P D......JFIF...

```

**P** is printed before the `render()`, in `page--ajax.tpl.php`, and **D** before my `readfile()`.

Any ideas to helps me to find the origin of this space?

Thanks

# Answer
> 1 votes
Vinodkumar's answer didn't solved my issue, but it pointed me in the right direction.

I still haven't found the extra space, but as Drupal already used `ob_start()` in `bootstrap.inc`, I can now call `ob_clean()` to ensure no extra characters are shown:

```
<?php

// ...extra code to populate $path and $filename

ob_clean();
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename='.$filename);
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($path));
readfile($path);
exit;

```

# Answer
> 0 votes
Remove extra space in the file download.ajax.php at the top. If that didn't work then try to call ob\_start() function at the start of the file and check it. It will work.

---
Tags: media
---


title: How to read the field collection data

text:
# Question
Title: How to read the field collection data
I have a field collection with name as 'TELEPHONE NUMBERS AND DETAILS' and the machine key as 'field\_telephone\_numbers'.

When I use `node_load` getting the output as

```
[field_orgs_number_details] => Array

(

[und] => Array

(
    [0] => Array

    (
        [value] => Number 2
        [format] =>
        [safe_value] => Number 2
    )

)

)

[field_orgs_telephone_number] => Array

(

[und] => Array

(
    [0] => Array
    (
        [value] => 123456
        [format] =>
        [safe_value] => 123456
    )

)

)

```

How to read the data 'Number 2' and '123456' into a array.

Updated:

```
 [1] => Array

   (

   [entity] => Array

      (

        [field_collection_item] => Array

            (
            [15994] => Array
                (
                [field_orgs_number_details] => Array
                    (
                    [#object] => FieldCollectionItemEntity Object
                       (
                         [field_orgs_number_details] => Array
                             (
                                [und] => Array
                                    (
                                        [0] => Array
                                            (
                                            [value] => Number 3
                                            [format] =>
                                            [safe_value] => Number 3
                                            )
                                    )
                            )

                        [field_orgs_telephone_number] => Array
                            (
                            [und] => Array
                                (
                                [0] => Array
                                  (
                                [value] => 333333333333
                                [format] =>
                                [safe_value] => 333333333333
                                )
                            )
                        )

                    [rdf_mapping] => Array
                        (
                        )

                [entity_view_prepared] => 1
                    )
                )
            )
        )
    )
)

 When i use

 $data = render($content['field_telephone_numbers']);

 Getting output as

  Telephone
  123456  - Number 2

```

# Answer
> 0 votes
consider you have called like this $content = node\_load(1);

then you can get the values like below

```
$content['field_orgs_number_details']['und'][0]['value']

```

Similarly you can do the same for getting the telephone numbers

# Answer
> 0 votes
**place the following hook in your template.php**

```
function rows_from_field_collection(&$vars, $field_name, $field_array)    {
    $vars['rows'] = array();
    foreach($vars['element']['#items'] as $key => $item) {
        $entity_id = $item['value'];
        $entity = field_collection_item_load($entity_id);
        $wrapper = entity_metadata_wrapper('field_collection_item', $entity);
        $row = array();
        foreach($field_array as $field){
          //$row[$field] = $wrapper->$field;
          $row[$field] = $wrapper->$field->value();
          //$row[$field] = $entity->$field->value();
         }
        $row['field_collection_id'] = $item['value'];
        $vars['rows'][] = $row;
    }
}

```

and use

```
<?php print render($content['node_field_name']); ?>

```

---
Tags: entities, database
---


# Question
Title: Why is the "My account" link shown even if it is disabled?
In "Administration \> Structure \> Menu," I disabled the "My account" link, but the theme is still showing it.

I took the screenshot after disabling the link, closing the overlay, and clicking the "reload" button of the browser; still the link is show, even if it is disabled.
Why is it happening?

If I disable the "Log out" link that doesn't appear anymore.

Why is the "My account" link so special? More importantly, how can I disable it?

# Answer
> 1 votes
I could disable it by clicking "edit" and then unchecking the "enable" box.

# Answer
> 3 votes
This is a known bug and is already discussed a lot:

http://drupal.org/node/1092866

http://drupal.org/node/1197622

Quick fix would be to create a new menu and add that in your template.

# Answer
> 0 votes
In my case the menu item of the user profile was always marked as disabled in the settings. As administrator I could always see the menu item on the front end, other users could never see it. In this answer I found a workaround with the module menu\_token and setting the path to `user/[current-user:uid]`.

---
Tags: navigation
---


title: Drupal Fields Ajax not working

text:
# Question
Title: Drupal Fields Ajax not working
I have added fields to my entity via Field UI and trying to fire an ajax callback but it is not working.

This works

```
$form['customField'] = array(
        '#type' => 'textfield',
);

$form['customField']['#ajax'] = array(
      'callback' => 'just_test',
      'wrapper' => 'membership_suggestions',
);

```

But this does not ('field\_member\_first\_name' is added to the entity via Field UI and is a text field)

```
$form['field_member_first_name']['#ajax'] = array(
    'event' => 'blur',
    'callback' => 'just_test',
    'wrapper' => 'membership_suggestions',
);

```

Thanks a lot.

# Answer
> 1 votes
Since the fields were attached via Field API, I have to do this way

```
$form['field_member_last_name'][LANGUAGE_NONE][0]['value']['#ajax'] = array(
    'event' => 'blur',
    'callback' => 'get_suggestion_by_name',
    'wrapper' => 'suggestions_by_name',
    'method' => 'html',
);

```

---
Tags: entities, ajax
---


title: How to add field to ALL webforms?

text:
# Question
Title: How to add field to ALL webforms?
How do I add a field to all webforms? I have a website where I'm using webform for surveys and I want that on each survey there will be a field that is the same in all of the nodes/webforms. Thank you.

# Answer
> 0 votes
You have 2 options:

* Go to `/admin/structure/types/manage/webform/fields` and add a field. Then all your new webforms will use the new field.
* Install the Webform Share module, create a webform as usual, create your field, click the `Export` tab, go to `/admin/structure/types/manage/webform` and paste your configuration in the `Publishing options > Webform default components` box.

If all you need is one simple field, I recommend the former option.

# Answer
> 0 votes
1. Go to /admin/structure/types and find your webform content type.
2. Go to manage fields of your webform content type
3. Add your new field like any other content type
4. After setting your desired field, go to manage display of your content type and decide the order of your fields
5. In my case I have a full node

---
Tags: forms, webforms
---


# Question
Title: How may I curtail or minimize the text below CKEditor (while keeping it available for screen readers)?
In the add/edit form of a node, is there a way to reduce, hide, or minimize the **Text Format** block information contained inside of `<div class="form-item form-type-textarea form-item-body-und-0-value">`?

Would it be best to do an accessible hide as mentioned in Drupal 7, two new system classes to improve accessibility by using the classes `.element-invisible` and `.element-invisible.element-focusable`? Or should I edit a template file?

I'm using the Autoform Block module and placing this block inside the main page of an Organic Group. The rich text editor is managed by using the CKEditor module.

# Answer
> 1 votes
if you want something interactive, you can do this - this example assumes a field called `body` working on a node of type `article`, adjust as necessary:

* in css, for `.page-node-add-article .field-name-body .filter-wrapper .fieldset-wrapper { display:none; }` \- this will initially hide the text format
* add this JS either in a custom module or in html.tpl.php before `</body>`, so long as it runs after ckeditor, or the classes won't exist and throw an error:

```
<script>
    Drupal.behaviors.ckeditor_fix = {
        attach: function (context, settings)
        {
            jQuery('.page-node-add-article .field-name-body .filter-wrapper').once(function()
            {
                jQuery(this).append('<div id="filter_show" style="width:100%; background:#ccc; text-align:center; cursor:pointer;">show/hide format information</div>');

                jQuery('#filter_show').click(function()
                {
                    jQuery('.page-node-add-article .field-name-body .filter-wrapper .fieldset-wrapper').slideToggle();
                });
            });
        }
    };
</script>

```

# Answer
> 0 votes
I'm happy to tick the correct marker for any better answer, but for the meantime I'm using Code Per Node and the following

```
.block-afb fieldset {
positi/on: absolute !important;
clip: rect(1px 1px 1px 1px); /* IE6, IE7 */
clip: rect(1px, 1px, 1px, 1px);
}

.block-afb {
border: 1px solid blue;
background-color: #79A9D4;
margin: 5px;
padding: 5px;
width: 90%;
}

```

---
Tags: wysiwyg
---


# Question
Title: How to add title attribute to views trimmed title field?
The title field of a view is trimmed to 40 characters, and the Title field is linked to it's content. Since the Title field text is trimmed I need to add `title` attribute to the `<a>` tag of the Title field and the content of the `title` attribute must be the non-trimmed version of the Title field. So on mouseover event it should show the non-trimmed Title field text. How do I can do this?

I tried this

```
 function THEME_preprocess_link(&$vars) {
    // If title set and not empty dont do anything
    if (isset($vars['options']['attributes']['title']) && !empty($vars['options']['attributes']['title'])) {
        return;
    }

    // Use the link text as the title
    $vars['options']['attributes']['title'] = strip_tags($vars['text']);
 }

```

But it shows the trimmed version as the `title` attribute.

# Answer
you can accomplish this by overriding the field tpl file for the field and view:

* assuming a View called 'title\_test', and a field named 'title'
* under Advanced, Theme, it gives the following option for the field tpl file: views-view-field--title-test--title.tpl.php
* copy the modules/views/theme/views-view-field.tpl.php to your themes template folder, and rename it to views-view-field--title-test--title.tpl.php
* replace the existing $output code with:

```
<?php
    $field_output = l($field->last_render_text, $field->options['alter']['path'], array('attributes' => array('title' => $field->original_value)));
    print $field_output;
?>

```
* clear the cache

BE AWARE that this is overriding the default output by manually creating the link, so any special classes, or formatting included in the View must be added to this or you get unexpected behaviour (like missing classes, or field styling, etc). All of the information is available in the $field variable, you just need to extract it, for which Devel and `dpm($field);` will prove invaluable:

> Devel Helper functions for Drupal developers and inquisitive admins. This module can print a summary of all database queries for each page request at the bottom of each page. The summary includes how many times each query was executed on a page (shouldn't run same query multiple times), and how long each query took (short is good - use cache for complex queries). Also a dprint\_r($array) function is provided, which pretty prints arrays. Useful during development. Similarly, a ddebug\_backtrace() is offerred.
> 1 votes

---
Tags: navigation, views
---


title: node preview button not working

text:
# Question
Title: node preview button not working
The issue I am having is that when I try to preview the content of a node I have created by clicking the 'Preview' button the page just refreshes and the preview.

What I have tried

* Looking into permissions to do with viewing unpublished content.

# Answer
> 1 votes
1. Your site local or not? Can you give a link?
    2. You use standart theme or custom?

Try to edit node type configuration → http://somesite.ltd/admin/structure/types/manage/content\_type\_machine\_name. Before open link you must change somesite.ltd & content\_type\_machine\_neme

---
Tags: 7, nodes
---


title: Create interactive search filter

text:
# Question
Title: Create interactive search filter
I need to develop a search form with two differents taxonomy (taxo1,taxo2).

When a user selects in taxo1 la term, the second list has to be shown with inside only corresponding taxonomy terms.

Here is a example: if the user selects term *departement* in the first taxonomy taxo1 (using a select list), then a second select list (with terms from taxo2) should appear with only *towns* from the *department* previuously selected.

I can't do that with Views because filters can not interact.

Can anybody give me a way to do this?

# Answer
> 1 votes
What you are looking for is **hierarchical list** and can be accomplished by using these well-maintained modules below. The difference is *Simple Hierarchical Select* module provides a simpler implementation for dependent taxonomies \[might work for your situation better\].

> \- Hierarchical select -- This module defines the "hierarchical\_select" form element, which is a greatly enhanced way for letting the user select items in a hierarchy. Hierarchical Select has the ability to save the entire lineage of a selection or only the "deepest" selection. You can configure it to force the user to make a selection as deep as possible in the tree, or allow the user to select an item anywhere in the tree. Levels can be labeled, you can configure limit the number of items that can be selected, configure a title for the dropbox, choose a site-wide animation delay, and so on. You can even create new items and levels through Hierarchical Select!
>
> Simple hierarchical select Simple hierarchical select defines a new form widget for taxonomy fields to select a term by "browsing" through the vocabularies hierarchy. The widget is available in node forms and as Views exposed filter.This module has been inspired by Hierarchical select but is much simpler (hence the name ;) ).Unlike Hierarchical select this module provides a simple widget for taxonomy terms only. As an addition Simple hierachical select works as Views exposed filter.

---
Tags: forms, search
---


# Question
Title: Change output of a field with PHP field?
I'm constructing a view in Drupal 7 with a field called "Content: Fruit". If the value of that field is "lemon", I want to change the output to "citrus". How can I accomplish this?

Here's what I tried:

First, I excluded the "Content: Fruit" field from the display. Then I added a "Global: PHP" field after it where, in the "Value code" section, I added:

`return $row->field_fruit;`

Then in the "Output code" section I added:

```
<?php
    if ($value == 'lemon') {
        print 'citrus';
    }
?>

```

This doesn't work. The value of `$value` seems to be the node ID ("nid").

Thought this would be straightforward... what am I doing wrong here? Is there a better way to accomplish this?

# Answer
it looks like you have the logic a little backwards:

Value Code:

`if($row->field_fruit == 'lemon') return 'citrus';`

Output Code:

`<?php print $value; ?>`
> 0 votes

# Answer
use devel's dpm() to find the field you need in the view. drill down through the variables and once you found the value you are looking for double click it to give you the code suggestion for that field. The php module is funky as hell and needs to be updated.

`$row->field_fruit` SHOULD give you the NID, that's normal functionality (too bad it doesn't reflect in the view php docs hey? lol)

try:

```
$data->field_field_fruit[0]['raw']['value'];

```

so

```
<?php
  if($data->field_field_fruit[0]['raw']['value'] == 'lemon' ){
    print 'citrus';
  }
?>

```

tada
> 0 votes

---
Tags: views
---


title: Delete Drupal login capability

text:
# Question
Title: Delete Drupal login capability
In our environment, we make changes to a drupal site that are then replicated to an outside webserver. We do not want people to be able to log into the drupal site from the outside. I want to remove whatever file /user and /admin resolves to but I can't find any information on this. In wordpress, you delete the wp-admin folder. Is there anything like this with Drupal? Turning off the "Allow login" setting will not work for us.

Note- We cannot make any changes that are saved in the database. Changing Drupal settings will not work. There's got to be a login file on the server we can delete.

# Answer
> 1 votes
Just have an htaccess entry that redirects /user and /admin to the front page.

# Answer
> 0 votes
Well you could do a couple of things but you would need to have full access to the admin in the backend and I'm not really sure that if you are saying that the access in the backend is just changing the same database or the content is being pushed by a services type deploy module.

The first thing is hiding the login blocks, which you probably already have done this but here is a link: https://www.drupal.org/node/13777

Next, depending on your setup you will want to either forward the /user (or /user/login if you have user profiles that are on that path) to the home screen. That will make it impossible for a user to login. You could do this with an htaccess rule which is a little out of scope for Drupal Answers or do a redirect using either the redirect module or the rules module. Depending on your setup the rules could match the URL (say if the URL is admin.example.com for the admin install) and forward only the main site /user page to the home page so your users on the admin install can still access the site.

There are probably some more ways to do this, I will add more as I think of them.

# Answer
> 0 votes
you can remove the login functionality technically, but if you do it, then your administrator could never log onto the site.

you can remove the registration functionality, you simply need to browse to admin/user/settings (for Drupal 6) or admin/config/people/accounts (for Drupal 7) and select the the "Only site administrators can create new user accounts" option.

### Reference

# Answer
> 0 votes
There's an alternative:

https://www.drupal.org/project/login\_disable

This module requires a "secret" token to access the user login page:

Example: http://example.com/user/?hell0darling-XD

# Answer
> 0 votes
The best way is not to fiddle with the core, or you may end up breaking your site (when applying updates, patches etc). Better way is to implement IP based login (with .htaccess) or use one of the available modules that restricts admin path to selected IP.

---
Tags: users
---


# Question
Title: How to render a taxonomy field in a Views' PHP code field?
In Views PHP code, I could render a field by :-

```
<?php
  print drupal_render($data->field_field_my_text);
?>

```

But this only seems to work field with type Text. I have a field which is Taxonomy (Term Reference) and I am trying to output that through the above code but it's not working.

This is what I wrote:-

```
<?php
      print drupal_render($data->field_field_my_category);
    ?>

```

Unfortunately, this is not working. Any idea what I should do here?

Thanks.

# Answer
> 1 votes
I can't comment because of rep.. Use devel module and use the dpm() function in your php for some debugging, drill down and find the value you are looking for then double click the value in the debug widget and it should tell you your field value.

here's my guess:

`$data->field_field_my_category[0]['raw']['value'];`

Might be slightly different if it's a tax term but devel is your best friend and you should use it quite frequently. Stop guessing and start debuging (best advice i've ever gotten).

---
Tags: views
---