# Question
Title: How to get list of templates for the active theme?
I am creating UI that will allow users to edit the active theme's template files(something like Wordpress does). For this I need to get the list of all templates from the system and to know which templates are already overridden by the **front-end** theme.

The list of templates can be retrieved via \Drupal::service('theme.registry')-\>get(). The problem is that this will return templates of the **currently used theme** therefore this will not return templates that are overridden by the front-end theme(since this is done on the back-end which has different theme).

The class \Drupal\Core\Theme\Registry has option to specify the theme in it's constructor but there is no option to set this via the service. Calling the class directly would require me to take care of DI and it's not what I'd want to do anyway(not very Drupal-way approach).

In the init() method there is logic that would rebuild the registry if there is no global theme key set or the theme name is different from theme information but I don' want to fiddle with global variables.

So what would be the proper way to do this?

# Answer
> 0 votes
This is a working prototype, although I will be rewritting it a bit later.

```
<?php

/**
 * @file
 * Contains \Drupal\mymodule\Form\ThemeTemplateForm.
 */

namespace Drupal\mymodule\Form;

use Drupal\Core\Form\FormBase;
use Drupal\Core\Theme\Registry;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Drupal\Core\Cache\Cache;
use Drupal\Core\Cache\CacheBackendInterface;
use Drupal\Core\Extension\ModuleHandlerInterface;
use Drupal\Core\Lock\LockBackendInterface;
use Drupal\Component\Utility\String;

/**
 * Form for editing template files for current theme.
 */
class ThemeTemplateForm extends FormBase {

  /**
   * The cache backend to use for the complete theme registry data.
   *
   * @var \Drupal\Core\Cache\CacheBackendInterface
   */
  protected $cache;

  /**
   * The lock backend that should be used.
   *
   * @var \Drupal\Core\Lock\LockBackendInterface
   */
  protected $lock;

  /**
   * The module handler to use to load modules.
   *
   * @var \Drupal\Core\Extension\ModuleHandlerInterface
   */
  protected $moduleHandler;

  /**
   * The theme registry service.
   *
   * @var \Drupal\Core\Theme\Registry
   */
  protected $registry;

  /**
   * The template that is being edited/created.
   *
   * @var string
   */
  protected $template;

  /**
   * The front-end theme that we'll be editing templates for.
   *
   * @var string
   */
  protected $theme;

  /**
   * Creates ThemeTemplateForm object.
   *
   * @param \Drupal\Core\Cache\CacheBackendInterface $cache
   *   The cache backend interface to use for the complete theme registry data.
   * @param \Drupal\Core\Lock\LockBackendInterface $lock
   *   The lock backend.
   * @param \Drupal\Core\Extension\ModuleHandlerInterface $module_handler
   *   The module handler to use to load modules.
   */
  public function __construct(CacheBackendInterface $cache, LockBackendInterface $lock, ModuleHandlerInterface $module_handler) {
    $this->cache = $cache;
    $this->lock = $lock;
    $this->moduleHandler = $module_handler;
    $this->theme = $this->config('system.theme')->get('default');
    $this->registry = new Registry($this->cache, $this->lock, $this->moduleHandler, $this->theme);

    $template = $this->getRequest()->query->get('template');
    if (!empty($template) && $this->templateIsAllowed($template)) {
      // Always use machine name of the template
      $this->template = str_replace('-', '_', $template);
    }
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static(
      $container->get('cache.default'),
      $container->get('lock'),
      $container->get('module_handler')
    );
  }

  /**
   * Returns path to selected theme.
   *
   * @return string
   *   Path relative to Drupal root.
   */
  public function themePath() {
    return drupal_get_path('theme', $this->theme);
  }

  /**
   * Returns the list of template files.
   */
  public function templateList() {
    $list = array_filter($this->registry->get(), function($info) {
      return isset($info['template']);
    });
    // Allow modules to alter the list
    \Drupal::moduleHandler()->alter('editable_template_list', $list);
    ksort($list);
    return $list;
  }

  /**
   * Returns list of overridden templates by the front-end theme.
   */
  public function overriddenTemplateList() {
    $list = array_filter($this->templateList(), function($info) {
      // The system will return templates that have preprocess functions
      // implemented by the theme so we need to remove them from the list
      // since they aren't really overridden.
      $theme_path = $this->themePath();
      return $info['theme path'] == $theme_path && (isset($info['path']) && stripos($info['path'], $theme_path) === 0);
    });
    return $list;
  }

  /**
   * See if provided template is allowed.
   *
   * @param string $template
   *   Template name.
   *
   * @return bool
   *   TRUE if template is allowed, FALSE otherwise.
   */
  public function templateIsAllowed($template) {
    $list = $this->templateList();
    $list[$template] = array();
    \Drupal::moduleHandler()->alter('editable_template_list', $list);
    // If no module removed the template the template is allowed
    return isset($list[$template]);
  }

  /**
   * Returns information if the provided template is overridden by the theme.
   *
   * @param string $template
   *   The template name.
   *
   * @return bool
   *   Returns TRUE if the template is overridden, FALSE otherwise.
   */
  public function templateIsOverridden($template) {
    $overridden = $this->overriddenTemplateList();
    return isset($overridden[$template]);
  }

  /**
   * Returns the template information.
   *
   * @param string $template
   *   The template name.
   *
   * @return array
   *   Returns the template information array. Empty array is returned
   *   when template was not found.
   */
  public function templateInfo($template) {
    $templates = $this->templateList();
    if (isset($templates[$template])) {
      return $templates[$template];
    } else {
      $base_hook = $this->registry->getBaseHook($template);
      return $base_hook ? $template[$base_hook] : array();
    }
  }

  /**
   * Returns the source path of the template file.
   *
   * @param string $template
   *   Template name.
   *
   * @return string
   *   Path to the source template file relative to Drupal root.
   */
  public function getTemplateSourcePath($template) {
    $info = $this->templateInfo($template);
    return $info['template'] . '.html.twig';
  }

  /**
   * Returns the path of the template in the theme.
   * If the template does not exist(is not overridden yet)
   * the 'templates' directory within the theme directory will
   * be used as destination for the new template. Otherwise
   * 'path' will be used since themes don't have to explicitly put
   * their templates into the 'templates'directory.
   *
   * @param string $template
   *   Template name.
   *
   * @return string
   *   The path to the template file within the theme directory
   *   relative to Drupal root.
   */
  public function getTemplateThemePath($template) {
    $info = $this->templateInfo($template);
    if (isset($info['path']) && stripos($info['path'], $this->themePath()) === 0) {
      return $info['path'] . '/' . str_replace('_', '-', $template) . '.html.twig';
    } else{
      return $this->themePath() . '/templates/' . str_replace('_', '-', $template) . '.html.twig';
    }
  }

  /**
   * See if provided path is allowed for writing/overriding
   * a template file.
   *
   * @param string $path
   *   Path to the template relative to Drupal root.
   *
   * @return bool
   *   TRUE if template can be created/overridden, FALSE otherwise.
   */
  public function pathIsAllowed($path) {
    // Access is allowed only to theme's directory AND this
    // always has to be located within the 'sites' directory.
    return stripos($path, $this->themePath()) === 0 && stripos($path, 'sites/') === 0;
  }

  /**
   * Returns content of requested template.
   * If the template is not implemented by the theme
   * the content of the original template will be returned.
   *
   * @param string $template
   *   Template name.
   * @return string|false
   *   Returns the code of the template or FALSE if template could not be loaded.
   */
  public function getTemplateCode($template) {
    $info = $this->templateInfo($template);
    if (empty($info)) {
      return FALSE;
    }
    $path = isset($info['path']) ? $info['path'] . '/' . $template : $info['template'];
    $path .= '.html.twig';
    return @file_get_contents('.' . base_path() . '/' . $path);
  }

  /**
   * {@inheritdoc}
   */
  public function getFormId() {
    return 'theme_template_form';
  }

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, array &$form_state) {
    $templates = $this->templateList();
    $overridden = $this->overriddenTemplateList();

    if ($this->template) {
      $form['#title'] = $this->t('Template: @template', array('@template' => str_replace('_', '-', $this->template)));
    } else {
      $form['#title'] = $this->t('Create new template');
    }

    $form['left'] = array(
      '#type' => 'container',
      '#attributes' => array(
        'id' => 'template-edit-left'
      )
    );

    $form['left']['edit'] = array(
      '#type' => 'textarea',
      '#rows' => 35,
      '#default_value' => $this->template ? $this->getTemplateCode($this->template) : NULL,
      '#required' => TRUE
    );

    $form['left']['name_wrapper'] = array(
      '#type' => 'fieldset',
      '#title' => $this->t('Template name'),
      '#collapsible' => TRUE,
      '#collapsed' => TRUE
    );
    $form['left']['name_wrapper']['name'] = array(
      '#type' => 'textfield',
      '#title' => $this->t('Template name'),
      '#required' => !$this->template,
      '#field_prefix' => $this->template ? String::checkPlain(str_replace('_', '-', $this->template)) . '--' : NULL
    );

    $form['left']['actions'] = array(
      '#type' => 'actions',
      'save' => array(
        '#type' => 'submit',
        '#name' => 'save',
        '#value' => $this->t('Save')
      ),
      'delete' => array(
        '#type' => 'submit',
        '#name' => 'delete',
        '#value' => $this->t('Delete'),
        '#access' => $this->template && $this->templateIsOverridden($this->template)
      )
    );

    $form['right'] = array(
      '#type' => 'container',
      '#attributes' => array(
        'id' => 'template-edit-right'
      ),
      'templates' => array(
        '#theme' => 'item_list',
        '#items' => array()
      )
    );
    foreach ($overridden AS $template => $info) {
      $form['right']['templates']['#items'][$template] = array(
        '#type' => 'link',
        '#title' => str_replace('_', '-', $template),
        '#route_name' => 'mymodule.settings.theme.template',
        '#options' => array(
          'query' => array(
            'template' => str_replace('_', '-', $template)
          )
        ),
        '#attributes' => array(
          'class' => array('overridden')
        )
      );
    }
    foreach ($templates AS $template => $info) {
      if (isset($form['right']['templates']['#items'][$template])) {
        continue;
      }
      $form['right']['templates']['#items'][$template] = array(
        '#type' => 'link',
        '#title' => str_replace('_', '-', $template),
        '#route_name' => 'mymodule.settings.theme.template',
        '#options' => array(
          'query' => array(
            'template' => str_replace('_', '-', $template)
          )
        )
      );
    }

    if ($this->template && isset($form['right']['templates']['#items'][$this->template])) {
      $form['right']['templates']['#items'][$this->template]['#attributes']['class'][] = 'active';
    }

    $form['#attached'] = array(
      'css' => array(
        drupal_get_path('module', 'mymodule') . '/css/mymodule.themetemplateform.css.less'
      ),
      'library' => array(
        'mymodule/codemirror.twig'
      ),
      'js' => array(
        drupal_get_path('module', 'mymodule') . '/js/mymodule.themetemplateform.js'
      )
    );

    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function validateForm(array &$form, array &$form_state) {
    // If there is no template, the 'name' is required so we'll always end up with a value
    // for the name.
    $template = $this->template ? $this->template : '';
    if ((string) $form_state['values']['name'] !== '') {
      $template = (string) $template === '' ? $form_state['values']['name'] : $template . '__' . $form_state['values']['name'];
    }
    $template = str_replace('-', '_', $template);
    if (!$this->templateIsAllowed($template)) {
      $this->setFormError('name', $form_state, $this->t("Template name is not allowed."));
    } elseif (!$this->pathIsAllowed($this->getTemplateThemePath($template))) {
      $this->setFormError('name', $form_state, $this->t("Template cannot be changed."));
    }
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, array &$form_state) {
    // If there is no template, the 'name' is required so we'll always end up with a value
    // for the name.
    $template = $this->template ? $this->template : '';
    if ((string) $form_state['values']['name'] !== '') {
      $template = (string) $template === '' ? $form_state['values']['name'] : $template . '__' . $form_state['values']['name'];
    }
    $template = str_replace('-', '_', $template);

    $tplpath = $this->getTemplateThemePath($template);

    switch ($form_state['triggering_element']['#name']) {
      case 'save':
        $write = @file_put_contents('.' . base_path() . $tplpath, $form_state['values']['edit']);
        if ($write === FALSE) {
          $this->setFormError('edit', $form_state, $this->t("Couldn't write data into file. Please try again or contact help desk."));
        } else {
          $form_state['redirect_route'] = array(
            'route_name' => 'mymodule.settings.theme.template',
            'options' => array(
              'query' => array(
                'template' => str_replace('_', '-', $template)
              )
            )
          );
          mymodule_success_message();
        }
        break;

      case 'delete':
        $delete = @unlink('.' . base_path() . $tplpath);
        if ($delete) {
          $form_state['redirect_route'] = array(
            'route_name' => 'mymodule.settings.theme.template'
          );
          mymodule_success_message();
        } else {
          $this->setFormError('edit', $form_state, $this->t("Couldn't delete template. File does not exist or is not accessible."));
        }
        break;
    }

    // Always rebuild cache
    Cache::invalidateTags(array('theme_registry' => TRUE));
  }

}

```

---
Tags: theming, 8
---


title: Can't upload user picture

text:
# Question
Title: Can't upload user picture
When I want to add my user picture, the picture can't upload and when I inspect it the link is broken and get this error:

> Warning: array\_key\_exists() expects parameter 2 to be array, null given in theme\_image\_formatter() (line 605 of /home/webpenir/public\_html/modules/image/image.field.inc).

However, when I add a picture for another user, it works pretty good.

how can I solve this?

**EDIT**

Only user 1 can't upload but other users can do, which is really strange.

# Answer
It is a known issue you can try this patch and Suppose if that patch not workout for you check the other patches here https://drupal.org/node/920840 and if any of that patches not solved your issue then the best option is you have to submit a bug report.
> 1 votes

# Answer
I think this is your upload location folder permission problem. please ensure that and give your upload location as public:// folder
> 1 votes

---
Tags: users, files
---


# Question
Title: Reference dialog hyperlink configuration
Can anyone please direct me on how to configure References Dialog so that instead of just returning the titles of my node as plain text, they are returned as hyperlinks?

# Answer
AFAIK, References Dialog only add links for add/edit/search.

If it's the display of a referenced node that you want to change, just change the field's format (under Manage Display) to "Title, as link".
> 0 votes

# Answer
This does not answer the question but in case anyone is searching for an alternative of References Dialog module, try Inline Entity Form
> 0 votes

---
Tags: 7, entities, forms
---


# Question
Title: How can I use hook_bootstrap_colorize_text?
I am using Bootstrap subtheme called "pasporty\_bootstrap". I would like to redefine function `bootstrap_colorize_text()` using hook, which can be found at:

http://drupalcode.org/project/bootstrap.git/blob/refs/heads/7.x-3.x:/theme/common.inc#l579

When I added following in my template.php file, nothing happened:

```
function pasporty_bootstrap_bootstrap_colorize_text(&$texts) {
  $texts = array(
    'contains' => array(
      t('Save') => 'primary'
    )
  );
  dpm($texts);
}

```

I tried to clear the cache multiple times but I wasn't successful. Can you tell me what I am doing wrong, please?

# Answer
> 3 votes
This:

```
drupal_alter('bootstrap_colorize_text', $texts);

```

Will invoke a hook by the name of `bootstrap_colorize_text_alter()`...so you just need to update your code to:

```
function pasporty_bootstrap_bootstrap_colorize_text_alter(&$texts) {
  $texts = array(
    'contains' => array(
      t('Save') => 'primary'
    )
  );
  dpm($texts);
}

```

And clear the cache.

---
Tags: theming
---


# Question
Title: Let users review draft copies before publish
Is there a way to set permissions to allow users to *preview an unpublished node* before our a content editor publishes it? Our working group is rather small so Workbench may exceed what we need.

Would setting up a group, giving them permission to view a Content Type but not edit (and therefore publish or un-publish) be an acceptable solution? Would there be any unforeseen drawbacks? Could anyone lend their experience to such an option?

# Answer
> 0 votes
You could accomplish this with a combination of user roles (writer, peer reviewer, editor, for example) and Field Permissions plus maybe a couple of views for users of each role. More details about Field Permissions (from project page):

> The Field Permissions module allows site administrators to set field-level permissions to edit, view and create fields on any entity.
>
> Features:
>
> * Enable field permissions on any entity, not just nodes.
> * Role-based field permissions allowing different viewing patterned based on what access the user has.
> * Author-level permissions allow viewing and editing of fields based on who the entity owner is.
> * Permissions for each field are not enabled by default. Instead, administrators can enable these permissions explicitly for the fields where this feature is needed.
> * Field permissions overview

I would add a select list field to your content type that is editable only by peer reviewers and editors. You might call it publishing status or workflow status with the options of "needs major revision, needs minor revision, ready to publish" (just to give a couple examples). Use the field permissions module to make this field visible to the node author, invisible to anonymous users and authenticated users, and editable by peer reviewers, content editors, and site admins.

You could make it fancier by also using rules so that if someone with a given role (e.g. editor) selects ready to publish, the node is automatically published, and/or promoted to the front page, etc.

Hope this helps.

---
Tags: workflows
---


# Question
Title: How do I select the most recently created entity item in Rules
I have in Drupal Commerce products the price of which needs to calculated based on a value that is updated daily. (For the curious: the prices that are stored are worked into a formula that includes current copper sell prices and a copper price to total price ratio). I have used the Entity Construction Kit to create a small entity type to store copper prices - basically just date and price.

I'm having trouble selecting the most recently added copper price entity though.
Right now I'm looking at action "Fetch entity by property" (out of Entity Rules) and selecting by the current date. This would mean though that each day the customer would need to think to add a new price for tomorrow - which would definitely cause trouble.
Is there a module that offers to sort a list and select the last/first item in Rules?

# Answer
If one 'price entity' is created based on the daily prices per day, you could use the 'after saving new content' action, restricted to your price entity type (provided you entity can be seen as a node.) Then, calculate the values for your products at that time, using the values within the newly created price entity.

Otherwise, you could put a 'last entry' field on you entity and use another rule to set this field to 'true' on a newly created entity and 'false' on all other entities. Then, set a condition on the original rule that filters entities based on this field.
> 0 votes

---
Tags: rules, entities
---


# Question
Title: Using drupal_form_submit for pass-through to external login on click
I need a way for already authenticated users to be able to click a menu link and have a POST submitted to an external site, allowing them to be logged in automatically. This is kind of the opposite from many of the other SSO questions I've seen. I have no control over the other service. Here is where I'm at right now:

* Created a module that registers the desired path as a page callback function
* Added a menu link for that path
* Added a form builder function to generate the necessary fields
* In the page callback, I'm using `drupal_form_submit` to submit the form

I've verified that the form, when rendered, has the correct `action` and `method` parameters, and all the necessary fields, and when submitted manually, it works as expected, but when submitted programmatically using `drupal_form_submit`, nothing happens. I don't really have a way of knowing what the redirect URL should be, as it's controlled by the 3rd party site, so I can't use `drupal_goto`. Is there any way to have `drupal_form_submit` honor redirects from outside the site? I really don't want to have to use `curl` directly, if possible.

# Answer
> 1 votes
> Is there any way to have drupal\_form\_submit honor redirects from outside the site?

Not really - `drupal_form_submit()` is invoked as a result of Drupal *receiving* a form `POST` on the relevant action URL - it doesn't care about how it's been invoked, and doesn't care about the URL itself (the form's already been submitted, so the action is obsolete by that point anyway).

If you need to `POST` form data to an external site, but have the processing done by Drupal, your only option is to use cURL or similar.

---
Tags: 7, forms, routes, authentication-authorization
---


title: Unlimited value fields numbered

text:
# Question
Title: Unlimited value fields numbered
Is it possible to show a numbered output to an unlimited value field (in the input form rather than the display).

Basically I have a field collection and I'd like to show by the side of each one entered a count, so if you write one it looks like

```
1 | field_one
  | field_two
  | field_three

```

Then if you added another it would look like

```
1 | field_one
  | field_two
  | field_three
2 | field_one
  | field_two
  | field_three

```

and so on...

I'm trying to think where you'd go about doing this, I can't see anything that counts out how many values it has when looking at the `$form` array in the page itself, and I wouldn't have thought it'd be something that you can do via a template file.

Can this be done?

# Answer
Wow that was much harder to do than I really thought it would be, for anyone interested in how to do this, you can use the information below, in case anyone is interested I've taken most of the information from this site about how to remove the drag handles, but the principle is the same, added to which, I wanted to remove the drag handles anyway

First you have to create your own module, and use `hook_theme_registry_alter` to change where the default theming is defined for multiple value fields

```
/**
 * Implements hook_theme_registry_alter().
 */
function mymodule_theme_registry_alter(&$theme_registry) {
  if (isset($theme_registry['field_multiple_value_form'])) {
    $theme_registry['field_multiple_value_form']['type'] = 'module';
    $theme_registry['field_multiple_value_form']['theme path'] = drupal_get_path('module', 'mymodule');
    $theme_registry['field_multiple_value_form']['function'] = 'mymodule_theme_field_multiple_value_form';
  }
}

```

Then you can re-define how it's themed by copying the existing theme\_field\_multiple\_value\_form code and writing it into your new function. BUT, be aware that this is going to redefine how ALL unlimited field values work, so really you just want to add in an 'if' clause somewhere, I just put mine at the start

```
function mymodule_theme_field_multiple_value_form($variables) {
  $element = $variables['element'];
  $output = '';

  if (($element['#cardinality'] > 1 || $element['#cardinality'] == FIELD_CARDINALITY_UNLIMITED) && $element['#field_name'] != 'field_myfield') {

  // Input normal code, this is for any unlimited input field you DON'T want altering

  } else if (($element['#cardinality'] > 1 || $element['#cardinality'] == FIELD_CARDINALITY_UNLIMITED) && $element['#field_name'] == 'field_myfield') {

$table_id = drupal_html_id($element['#field_name'] . '_values');
$required = !empty($element['#required']) ? theme('form_required_marker', $variables) : '';

$header = array(
  array(
    'data' => '<label>' . t('!title !required', array('!title' => $element['#title'], '!required' => $required)) . "</label>",
    'colspan' => 2,
    'class' => array('field-label'),
  ),
);
$rows = array();

// Sort items according to '_weight' (needed when the form comes back after
// preview or failed validation)
$items = array();
foreach (element_children($element) as $key) {
  if ($key === 'add_more') {
    $add_more_button = &$element[$key];
  }
  else {
    $items[] = &$element[$key];
  }
}
usort($items, '_field_sort_items_value_helper');

$count = 1;
// Add the items as table rows.
foreach ($items as $key => $item) {
  unset($item['_weight']);
  $cells = array(
    array(
      'data' => $count,
      'class' => array('count'),
    ),
    drupal_render($item),
  );
  $rows[] = array(
    'data' => $cells,
  );

  $count++;
}

$output = '<div class="form-item">';
$output .= theme('table', array('header' => $header, 'rows' => $rows, 'attributes' => array('id' => $table_id, 'class' => array('field-multiple-table'))));
$output .= $element['#description'] ? '<div class="description">' . $element['#description'] . '</div>' : '';
$output .= '<div class="clearfix">' . drupal_render($add_more_button) . '</div>';
$output .= '</div>';

  } else {
      foreach (element_children($element) as $key) {
        $output .= drupal_render($element[$key]);
      }
    }

    return $output;
  }

```

Hope this helps someone in the future
> 0 votes

---
Tags: 7, entities
---


# Question
Title: Drupal Commerce: Theming the Add Products form (Bulk Production Creation)
I am using Drupal Commerce Bulk Product Creation to add products to my site.

I would like to theme the Bulk Add Products form to make it more user-friendly to edit.

I can use page--admin--commerce--products--add-bulk--PRODUCTNAME.tpl.php to override the form. However, I don't know what PHP code to use to print out the product fields.

I found some articles online (, , ) and have tried the following, but none of them work:

```
<?php print render($content['form']['product:field_FIELDNAME']); ?>
<?php print render($content['form']['field_FIELDNAME']); ?>
<?php print drupal_render($field_FIELDNAME) ?>
<?php print render($field_FIELDNAME) ?>
<?php print drupal_render($vars['form']['field_FIELDNAME']);     ?>
<?php print drupal_render_children($form['field_FIELDNAME']); ?>

```

Any pointers would be appreciated.

# Answer
> 3 votes
I have figured this out.

Step 1): Find the ID of your form. To do this, view the source of the form and search for "form" keep on searching until you see a field like this:

```
<form enctype="multipart/form-data" action="SOME_URL_HERE" method="post" id="commerce-bpc-create-bulk-form" accept-charset="UTF-8"><div>

```

The id you want is in the `id=""` string

You need to tell Drupal where to find your tpl.php file. In template.php add the following:

```
function YOURTHEME_theme($existing, $type, $theme, $path) {
    return array(
        'INSERT_ID_HERE' => array(
            'arguments' => array('form' => NULL),
            'template' => 'templates/add/node--add--TEMPLATE_NAME',
            'render element' => 'form',
            ),
    );
}

```

So if you were themeing a Drupal Commerce Bulk Product Creation form, your code would look like this:

```
function YOURTHEME_theme($existing, $type, $theme, $path) {
    return array(
        'commerce_bpc_create_bulk_form' => array(
            'arguments' => array('form' => NULL),
            'template' => 'templates/add/node--add--bpc',
            'render element' => 'form',
            ),
    );
}

```

3) Create a tpl.php template file and save it in the appropriate directory. In our example, the file is called `node--add--bpc.tpl.php` and is saved in `templates/add`

4) In your tpl.php file, insert variables for the fields on the form. Here is a list of the most common fields:

```
<?php print drupal_render($form['product']['sku_fragment']); ?>
<?php print drupal_render($form['product']['title_fragment']); ?>
<?php print drupal_render($form['product']['commerce_price']); ?>
<?php print drupal_render($form['submit']); ?>
<?php print drupal_render($form['static_values']['field_YOUR_CUSTOM_FIELD']); ?>

```

5) At the end of the tpl.php file, put the following code:

```
 <?php print  drupal_render_children($form) ?>

```

It's very important you put this code, or you will get errors when trying to upload images.

6) The code in step 5, might print out fields you do not want. So you to have unset these fields. Here is a list of the most common fields to unset.

```
<?php unset ($form['product']); ?>
<?php unset ($form['combinations']); ?>
<?php unset ($form['title']); ?>
<?php unset ($form['static_values']); ?>
<?php unset ($form['description']); ?>

```

You put all this code on a line before:

```
 <?php print  drupal_render_children($form) ?>

```

7) If you find that any of the steps don't work, be sure to flush your cache. You can do this at: yousite.com/admin/config/development/performance

# Answer
> 0 votes
Thanks. It worked great!

```
function STARTERKIT_theme($existing, $type, $theme, $path) {
    return array(
            'project_node_form' => array(
                    'arguments' => array('form' => NULL),
                    'template' => 'templates/node--add--projects',
                    'render element' => 'form',
            ),
            'idea_or_proposal_node_form' => array(
                    'arguments' => array('form' => NULL),
                    'template' => 'templates/node--add--idea-or-proposal',
                    'render element' => 'form',
            ),
            'quick_announce_node_form' => array(
                    'arguments' => array('form' => NULL),
                    'template' => 'templates/node--add--quick-announce',
                    'render element' => 'form',
            ),
    );
}

```

And next i created all 3 templates files inside my themes templates directory (clear cache).

---
Tags: commerce
---


title: Having trouble rendering a block

text:
# Question
Title: Having trouble rendering a block
I've defined a block that returns a string of HTML as follows:

```
function product_block_view($delta = '')
{
  switch ($delta) {
    case 'groups_images':
      $block['subject'] = t('Category Images in Groups');
      $block['content'] = "<div>Group images html</div>";
      break;

    case 'singles_images':
      $block['subject'] = t('Category Images as Singles');
      $block['content'] = "<div>Single images html</div>";
      break;

    default:
      break;
  }

  return $block;
}

```

This block lives in a custom region named `'myregion'`. I am attempting to render this block's view with `<?php render($page['myregion']) ?>` but nothing comes through. The dump of `$page['myregion']` looks something like this:

```
    array (size=4)
        'product_groups_images' =>
            array (size=5)
              '#markup' => string '<div>Groups images html</div>' (length=29)
              '#contextual_links' =>
                array (size=1)
                  'block' =>
                    array (size=2)
                      0 => string 'admin/structure/block/manage' (length=28)
                      1 =>
                        array (size=2)
                          ...
              '#block' =>
                object(stdClass)[116]
                  public 'bid' => string '77' (length=2)
                  public 'module' => string 'product' (length=7)
                  public 'delta' => string 'groups_images' (length=13)
                  public 'theme' => string 'id' (length=2)
                  public 'status' => string '1' (length=1)
                  public 'weight' => string '0' (length=1)
                  public 'region' => string 'findyourflavor' (length=14)
                  public 'custom' => string '0' (length=1)
                  public 'visibility' => string '1' (length=1)
                  public 'pages' => string '<front>' (length=7)
                  public 'title' => string '' (length=0)
                  public 'cache' => string '1' (length=1)
                  public 'subject' => string 'Category Images in Groups' (length=25)
              '#weight' => int 1
              '#theme_wrappers' =>
                array (size=1)
                  0 => string 'block' (length=5)
        '#sorted' => boolean true
        '#theme_wrappers' =>
            array (size=1)
              0 => string 'region' (length=6)
        '#region' => string 'findyourflavor' (length=14)

```

Any idea what I'm doing wrong that is causing my div to not be rendered by the `render` function?

# Answer
You forgot to print the results. Use:

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

```

---

Explanation:

During a page request, Drupal keeps all the data it loads in PHP arrays for as long as possible. The reason for this is, that as long as the data is in arrays, it can be changed by other elements. This is the power of Drupal's module system.

The array posted in the question is such a data array, it's called a "Render array". Eventually this array must be converted to HTML, this is what render does: it converts a drupal render array to an HTML string. Calling render often happens at end of a page request.

So calling render gives you an HTML string that should be returned to the user, e.g. by *printing* it in a template file.
> 2 votes

---
Tags: blocks, theming
---


title: Mass delete users

text:
# Question
Title: Mass delete users
I need to mass delete about 600k users from a drupal install, I have the UIDS, and built a drush script to do it, however the problem is that this is a live site, so it seems that user\_delete\_multiple acquires a lock for the whole duration ( even split into chunks of 100 it takes too long). so iterating over the array one by one (thus releasing the lock in between and allowing normal operation), and deleting at a rate of 1.5 users per second. 600k --\> going to take about a week.

Plus I cannot parallelize this because of the lock on the table (tried it , it makes it slower). what other options to I have? ( I looked into deleting from database directly but there are lots of modules that implemente user\_delete and entity\_delete so I might forget something...

I'm looking maybe at using the same script but removing the lock on the table... do now know how to to this, but could be an option.

\[EDIT\] just edited the script a but, chunking in size 5 arrays, and using user\_delete\_multiple. this allows me to save 4 calls to module\_invoke\_all which did gain me a bit of speed . I am currently deleting at 5 users in 4, 4.5 s). this also allows me to maintain the lock for less time and also allow site to operate. waitig to see if site is still usable with this fix..

# Answer
I would do a few things.

Slow deletions could be an indication of a poorly tuned MySQL instance (or other database server). I would run MySQLTuner (or whatever is the equivalent in your case) on your server and make sure you have a decent configuration.

Second, I would do this in maintenance mode. Your slowness may the result of the additional traffic on the site, and difficulty acquiring the locks.

If I were in your shoes, I would write a shell script that does something like

```
drush @thesite variable-set -y --always-set maintenance_mode 1
drush @thesite -u 1 scr /path/to/a/drush/script.php
drush @thesite variable-delete -y --exact maintenance_mode

```

and then place this in a nightly crontab. Inside /path/to/a/drush/script.php, you would write your code to delete a batch of users (say 100 or so).

This will then delete your users in small batches while in maintenance mode. This will minimize the downtime on your site.

Monitor progress and remove the crontab entry when you are done.
> 4 votes

---
Tags: users, drush
---


title: Cant make postal code only required

text:
# Question
Title: Cant make postal code only required
I am using the adress field module and like to make only the postal code field required. The rest of the fields i like to hide.

The hiding of the fields are no problem however i am having problems with making only the postalcode field required. I can hide the whole field with:

```
<?php
 function my_form_user_profile_form_alter(&$form, $form_state,  $form_id) {

  if ($form_id == 'user_profile_form') {

  $form['field_adress']['und'][0]['#required'] = TRUE;
      }
    }
      ?>

```

but then this is not working

```
$form['field_adress']['und'][0]['locality_block']['postal_code']['#required'] = TRUE;

```

What am i missing? Without succes i have tried solutions as: In here and here

# Answer
You can make the address field not-required and write a custom validate function to check for the postal code. Like this:

```
<?php
function my_form_user_profile_form_alter(&$form, $form_state,  $form_id) {
  if ($form_id == 'user_profile_form') {
      $form['field_adress']['und'][0]['#required'] = FALSE;
      array_unshift($form['#validate'], '_my_postal_validate');
  }
}

function _my_postal_validate(&$form, &$form_state) {
    if (strlen($form_state['values']['field_adress']['und'][0]['postal_code']) < 2) {
        form_set_error('field_address', t('You must enter a postal code'));
    }
}
?>

```

See form\_set\_error to set better form errors.

If you support non US addresses (without a postal code), make sure the postal\_code is available or you'll get warnings.
> 1 votes

---
Tags: 7, entities
---


# Question
Title: How to change page CSS based on parent menu item?
I'm building a fairly simple site, and I need to alter a background image based on what section the user is in. The main menu only has 2 levels. I'm unsure where I should hook into in order to be able to get the current section (i.e. the root menu item of the current page, see example below) so I can adjust the classes on the page. I was looking at this article as a possible solution, but I only want to alter CSS classes, and that seems like an awful lot of code for such a simple task.

```
Main Manu:
-- Section 1
   --- Page A
   --- Page B
   --- Page C
-- Section 2
   --- Page D
   --- Page E <- Active page, CSS class "section_2"
   --- Page F

```

# Answer
> 0 votes
I solved this by using the Context module. This easily allowed me to add a custom class to the body depending on a selected top-level menu item. Works like a charm.

# Answer
> 0 votes
If it is just additional classes you need, you can add additional and unique classes to menu items using the Menu CSS Names or Menu Attributes modules.

Or, you can effect the element of another DIV on hover using pure CSS like below...

HTML

```
<a id="menu-item" href="#">Menu Item</a>

<div id="container">
    <h1>Change This Background</h1>
</div>

```

CSS

```
#container {
    background:blue;
}

#menu-item:hover + #container {
    background:red;
}

```

See Fiddle here... Affect Another Div on Hover

---
Tags: hooks, theming
---


# Question
Title: Drupal 7 vertical tabs like the ones in Drupal 8
Is there a way to move vertical tabs in node forms to a right side column like in Drupal 8? I know one option is Renderable Elements module but last commit was 1 year ago and it says it is an expiremental module.

EDIT: I want to transform vertical tabs into accordions (like the ones in Drupal 8) because once the vertical tabs are in the right column they look awful.

EDIT 2: I just found an interesting sandbox project that does what I want: Responsive Vertical Tabs. However, it's not stable and breaks my ckeditor fields.

Thank you!

# Answer
Thanks for all your answers. However, I found two better solutions myself which are responsive:

1) (Best option) I've written my own module to responsify vertical tabs on admin pages: Vertical Tabs Responsive

2) "Responsive Vertical Tabs" could be useful if you don't use "Fieldsets" and "Horizontal tab groups" in your forms. More information in my issue on drupal.org.
> 0 votes

# Answer
You can use a combination of the Node form columns module and the Renderable elements modules.

> Node Form cols separates the node forms into two columns and a footer.
>
> This module alleviates some of the problems with the mile-long node forms in Drupal. Other than that it gives you the possibility to use different weights and collapsed states for your forms than for your presentation.

Renderable elements is more complicated to use but lets you split out the parts of the vertical tabs part of the node edit form. For example, after enabling these two modules, do the following for the article content type:

1. Visit node/add/article to add a new article content type
2. Click the new link at the top of the form which says "Manage Form Display"
3. Tick all the items you want to break out of the vertical tabs. As an example choose "Publishing options", "Published", "Promoted to front page" and "Stick at top of lists"
4. Click save
5. Goto Structure -\> Content types -\> Article -\> Manage form
6. Set the "Publishing options (Field group)" and "Save" to be in the right region and press save. nb. I had to use the drop downs here, it didn't seem to rememebr my region choices if I used drag and drop.
7. Visit node/add/article and see the collapsing publishing options block on the right.
> 0 votes

# Answer
To transform vertical tabs into accordions, you could download Easy Responsive Tabs to Accordion, a JQuery plugin which supports vertical tabs. Add this lightweight script to your theme and call the `easyResponsiveTabs()` function on your HTML tabs markup.

If you use it out of the box, it will gracefully **switch from tabs to accordion** according to the screen width. In order to display only accordions, just edit the width breakpoint of the script and set it to a high value.

If you use Panels, have a look at Panels responsive tabs to accordion, a sandbox project which provides a Responsive Tabs to Accordion Panel style.
> 0 votes

---
Tags: 7, forms
---


# Question
Title: Field collection item not visible to anonymous user
I have a field collection, 'related content', that displays inside the 'page' content type tpl. It is a 'field' in the page content type. It works perfectly fine while logged in as admin, but cannot be seen by the anonymous users.

UPDATE: I've actually determined that this has something to do with Organic Groups. The 'page' that the field collection belongs to is a member of a group...the anonymous user can see this page, can see the body, title and other fields...however, I still cannot get the field collection to show up on the page even though the variables are available and can be dumped to the page...rendering the content using `render()` results in nothing, but works fine if logged in as admin.

If I simply do `var_dump($content['field_related_content'])` I can see that all of the information is there...however `print render($content['field_related_content'])` displays nothing for anonymous users.

# Answer
> 0 votes
The permissions for the individual groups also have to be set for each added field...it was kind of buried and hard to find. The path would be like `/group/node/13/admin/permissions`

---
Tags: organic-groups
---


# Question
Title: How do you populate an image field in a field collection programmatically?
I'm trying to do a large import that's more complex than feeds can play nicely with, so I'm in the process of writing a custom import script. Everything works except loading images that are associated through a field collection. I have a field collection that contains node and taxonomy references just fine, but I've had no luck on the image field.

I have a field on the node called field\_signature\_media which references a field collection that can be a variety of media types. In the field collection I have field\_signature\_image for handling the images.

Attempt One: using entity\_metadata\_wrapper:

```
    // Image file created in earlier part of the process and loaded into $file
    // The node that's being worked on has been created in $node
    // Create the field collection
    $fc_item = entity_create('field_collection_item', array('field_name' => 'field_signature_media'));
    $fc_item->setHostEntity('node', $node);
    $fc_wrapper = entity_metadata_wrapper('field_collection_item', $fc_item);

    $field = array('alt' => '',
          'title' => '',
          'fid' => $file->fid,
          'display' => 1,
          'width' => $file->image_dimensions['width'],
          'height' => $file->image_dimensions['height'],
          'image_field_caption' => array
              (
                  'value' => '',
                  'format' => 'full_html',
              ),
    );

    $fc_wrapper->field_signature_image->set($field);
    $fc_wrapper->save(true);  // <-- at this point it enters infinite recursion.
    field_attach_update('node', $node);

```

Attempt Two without the wrapper:

```
    $fc_item = entity_create('field_collection_item', array('field_name' => 'field_signature_media'));
    $fc_item->field_signature_image[LANGUAGE_NONE][] =
                        array('alt' => '',
                              'title' => '',
                              'fid' => $file->fid,
                              'display' => 1,
                              'width' => $file->image_dimensions['width'],
                              'height' => $file->image_dimensions['height'],
                              'image_field_caption' => array
                                  (
                                      'value' => '',
                                      'format' => 'full_html',
                                  ),
                        );
    $fc_item->setHostEntity('node', $node);
    $fc_item->save(TRUE);
    field_attach_update('node', $node); // <-- At this point field_collection cannot find an array it was expecting.

```

Attempt Three with wrapper and not creating field data by hand:

```
    $fc_item = entity_create('field_collection_item', array('field_name' => 'field_signature_media'));
    $fc_item->setHostEntity('node', $node);
    $fc_wrapper = entity_metadata_wrapper('field_collection_item', $fc_item);
    $fc_wrapper->field_signature_image->set($file->fid);
    $fc_wrapper->save(true);  // <-- at this point it enters infinite recursion.
    field_attach_update('node', $node);

```

# Answer
> 2 votes
There should be no difference between setting the field on a node versus a field collection item.

This should work

```
$fc_wrapper->field_signature_image->file->set($file);

```

This should also work

```
$fc_wrapper->field_signature_image = (array) $file;

```

assuming `$file` is a valid file object. When I have trouble with adding files, it is usually because I have a property missing. In that case, I will make a node and field collection item via the UI, and then `dpm()` to see what us missing. Half the time, it is `$file->display`, and the rest is usually `$file->description`. My guess is that `$file->description` is your problem.

What I don't recall is whether using File Entity changes this. Both line above are based on import scripts I have where this module is disabled.

---
Tags: 7, media, entities
---


# Question
Title: Title field input not appearing when creating content type by module
I have this problem, I'm creating a content type by creating a module, using the example 'node\_example' of examples project as a code template. The thing is that I get it work, I create the content type successfully but when I create a new node of that content type, all fields appear but the title. I'm a little lost. I put by myself the propperty 'has\_title' to true on hook\_node\_info() but it stays the same. Cleared drupal caches several times, removed previous nodes, nothing. Any idea? Thanks.

(Maybe I don't follow all the standards, I'm quite a begginer and I try to follow them as possible) Module name: ct\_conversacion. Content type: conversacion.

**-------------edit:**

Ok, it was tough but I found the solution. The function 'ct\_conversacion\_form' that I wrote below should be 'conversacion\_form' (the content type name preceding).

My code:

```
  /**
   * Implements hook_node_info().
   */

      function ct_conversacion_node_info() {

        return array(
          'conversacion' => array(
        'name' => t('Conversacion'),
        'base' => 'conversacion',
        'description' => t('Es una conversacion.'),
        'has_title' => TRUE,
        'title_label' => t('Title'),
        'locked' => TRUE,
      ),
    );
  }

  /**
   * Implement hook_form().
   */
  function ct_conversacion_form($node, $form_state) {
    return node_content_form($node, $form_state);
  }

  /**
   * Implements hook_node_type_insert().
   */

  function ct_conversacion_node_type_insert($content_type) {
    if ($content_type->type == 'conversacion') {

      $body_instance = node_add_body_field($content_type, t('Mi descripcion'));

      field_update_instance($body_instance);

      foreach (_conversacion_installed_fields() as $field) {
        field_create_field($field);
      }

      foreach (_conversacion_installed_instances() as $instance) {
        $instance['entity_type'] = 'node';
        $instance['bundle'] = 'conversacion';
        field_create_instance($instance);
      }
    }
  }

  /**
   * Define the fields for our content type.
   *
   */
  function _conversacion_installed_fields() { // Cambiar *****
    return array(
      'conversacion_field2' => array(
        'field_name' => 'conversacion_field2',
        'cardinality' => 3,
        'type'        => 'text',
        'settings'    => array(
          'max_length' => 60,
        ),
      ),
    );
  }

  /**
   * Define the field instances for our content type.
   */

  function _conversacion_installed_instances() {
    return array(
      'conversacion_field2' => array(
        'field_name' => 'conversacion_field2',
        'label'       => t('Field 2 de Conversacion.'),
        'widget'      => array(
          'type'    => 'text_textfield',
        ),
      ),
    );
  }

```

# Answer
the error is obviously because you use a wrong base

change it to 'ct\_conversacion'

see https://api.drupal.org/api/drupal/modules%21node%21node.module/function/node\_type\_save/7

base: A string that indicates the base string for hook functions. For example, 'node\_content' is the value used by the UI when creating a new node type.
> 1 votes

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


# Question
Title: Batch process stuck repeating first operation over and over
It's my first time working with the Batch API. I have a batch operation that I have *almost* working, but it gets stuck on the first item and I'm out of ideas on how to fix it.

What the batch thing does is iterate over a bunch of nodes and transform the fake-locations scattered over a dozen text fields into real Location CCK fields. When the batch process runs, it continually fixes the first node over and over again. My logs fill up with the Location module deleting orphaned locations, and if I `dpm($node)`, it shows the first node over and over again.

I've checked my `$batch` variable, and the `operations` array *does* have all different nids.

Here's the code:

```
function rlh_tweaks_menu() {
    $items['location-fix'] = array(
        'title' => 'Location fixer',
        'page callback' => 'rlh_tweaks_location_fix',
        'access callback' => '_rlh_tweaks_user_one_only',
    );

    return $items;
}

function rlh_tweaks_location_fix() {
    $batch = array(
        'finished' => '_rlh_tweaks_batch_finished',
    );

    $query = new EntityFieldQuery();
    $query->entityCondition('entity_type', 'node')
        ->entityCondition('bundle', 'business');
    $result = $query->execute();

    foreach($result['node'] as $nid => $data) {
        $batch['operations'][] = array('_rlh_tweaks_batch_update_location', array($nid));
    }

    batch_set($batch);
    batch_process('node');
}

function _rlh_tweaks_batch_update_location($nid, &$context) {
    if (!isset($context['sandbox']['progress'])) {
            $context['sandbox']['progress'] = 0;
            $context['sandbox']['max'] = db_query('SELECT COUNT(DISTINCT nid) FROM {node} WHERE type = \'business\'')->fetchField();
        }

            // Here we actually perform our processing on the current node.

            $node = node_load($nid);
        $location = _rlh_tweaks_update_node_location($node);

        $lid = location_save($location);

        if(!empty($lid)) {
            $node->field_location[LANGUAGE_NONE]['0'] = location_load_location($lid);
        }

        node_save($node);

            // Store some result for post-processing in the finished callback.
            $context['results'][] = check_plain($node->title);
            // Update our progress information.
            $context['sandbox']['progress']++;
            $context['sandbox']['current_node'] = $node->nid;
            $context['message'] = t('Now processing %node', array('%node' => $node->title));
        // Inform the batch engine that we are not finished,
        // and provide an estimation of the completion level we reached.
        if ($context['sandbox']['progress'] != $context['sandbox']['max']) {
            $context['finished'] = $context['sandbox']['progress'] / $context['sandbox']['max'];
        }
}

function _rlh_tweaks_update_node_location($node) {
    $street_part_keys = array('street_no', 'pre_dir', 'street_name', 'post_dir', 'street_type');

    $all_parts = array('street_no', 'pre_dir', 'street_name', 'post_dir', 'street_type', 'suite_no', 'city', 'po_box', 'state', 'zip');

    $parts = array();

    foreach($all_parts as $key) {
        $parts[$key] = _rlh_tweaks_get_text_field_value($node, $key);
    }

    $street_parts = array();

    foreach($street_part_keys as $key) {
        if(!empty($parts[$key])) {
            $street_parts[] = $parts[$key];
        }
    }

    $street = implode(' ', $street_parts);

    if(empty($street)) {
        if(empty($parts['po_box'])) {
            continue;
        } else {
            $street = $parts['po_box'];
        }
    }

    $location = array(
        'street' => $street,
        'additional' => $parts['suite_no'],
        'city' => $parts['city'],
        'province' => $parts['state'],
        'postal_code' => $parts['zip'],
        'country' => 'us'
    );

    return $location;
/*
    if(!empty($lid)) {
        $node->field_location[LANGUAGE_NONE]['0'] = location_load_location($lid);
    }

    return $node); */
}

function _rlh_tweaks_batch_finished($success, $results, $operations) {
    if ($success) {
        // Here we do something meaningful with the results.
        $message = t("!count items were processed.", array(
            '!count' => count($results),
        ));
        $message .= theme('item_list', array('items' => $results));
        drupal_set_message($message);
    }
    else {
        // An error occurred.
        // $operations contains the operations that remained unprocessed.
        $error_operation = reset($operations);
        $message = t('An error occurred while processing %error_operation with arguments: @arguments', array(
            '%error_operation' => $error_operation[0],
            '@arguments' => print_r($error_operation[1], TRUE),
        ));
        drupal_set_message($message, 'error');
    }
}

function _rlh_tweaks_get_text_field_value($node, $field_name) {
    $item = field_get_items('node', $node, 'field_' . $field_name);
    return $item[0]['safe_value'];
}

function _rlh_tweaks_user_one_only() {
    global $user;

    if($user->uid == '1') {
        return TRUE;
    }

    return FALSE;
}

```

Why is this not moving on to the rest of the batch operations?

# Answer
> 3 votes
Your approach is slightly incorrect.

You should add a single batch operation and within that operation callback query the relevant node ids (once and only if not already set in sandbox) then add them to `$context['sandbox']` for processing. Set and check the current node id in the sandbox to process the next set on each batch run.

At the moment, it can never reach the "`max`" count and finish as only a single `$nid` is passed at a time.

---
Tags: 7, batch-operations
---


# Question
Title: How do I pre-configure a block's settings in my module in Drupal 7?
I'm building up a custom module which contains a few blocks. These blocks will always only appear either on the front page or on every other page, mutually exclusive.

I'd like to be able to pre-configure these blocks on install, but I'm not sure how to go about it. The documentation for `hook_block_configure` mentions an `'#options'` key, but has no details on the format of that info.

Can anyone get me pointed in the right direction here?

# Answer
If you want to set the standard block options, you can do that in `hook_block_info`

e.g:

```
/**
 * Implements hook_block_info
 */
function MODULE_block_info() {

  $blocks = array();

  // Assign block to front page, sidebar_first region by default
  $blocks['my_front_page_block'] = array(
    'info' => t('Front page block'),
    'status' => 1,
    'region' => 'sidebar_first',
    'visibility' => BLOCK_VISIBILITY_LISTED,
    'pages' => '<front>'
  );

  return $blocks;

}

```
> 0 votes

---
Tags: 7, blocks, installation
---


# Question
Title: Add class to template based on boolean field
I want to add a class to my custom Display Suite template if a boolean field is checked on the form. I have the following code:

```
if (isset($node->field_boolean_field[LANGUAGE_NONE][0]['value']) == 1 ) :
    $class = 'this-is-the-class';
endif;

```

And then in the appropriate place:

```
<a href="#" class="<?php print $class ?>">link</a>

```

This always returns the class regardless of whether the boolean field is checked or not though.

```
<a href="#" class="this-is-the-class">link</a>

```

Any thoughts on what I could be doing wrong here?

Many thanks

# Answer
You have written wrong logic in if statement. Correct way is following:

```
 $class = NULL;
 if (isset($node->field_boolean_field[LANGUAGE_NONE][0]['value']) && $node->field_boolean_field[LANGUAGE_NONE][0]['value'] == 1 ) :
        $class = 'this-is-the-class';
 endif;

```
> 1 votes

---
Tags: 7, theming, display-suite
---


# Question
Title: Can't use node_page_edit in ajax callback function
I have an ajax callback function:

```
function mymodule_callback($form, &$form_state) {
    $nid = $form_state['build_info']['args'][0]->nid;
    $node = node_load($nid);

    module_load_include('inc', 'node', 'node.pages');
    $form = node_page_edit($node);
    return print_r($form, true);
}

```

(Please note that I'm returning from print\_r as I'm trying to debug the problem).

This callback is being run from a form submit:

```
function mymodule_form_{my_form_id}_alter(&$form, &$form_state, $form_id) {
    $form['actions']['submit'] = array(
        '#type' => 'submit',
        '#value' => 'save',
        '#ajax' => array(
            'wrapper' => 'my-form-id',
            'method' => 'replace',
            'callback' => 'mymodule_callback',
            'effect' => 'fade'
        ),
        '#submit' => array('node_form_submit'),
    );
}

```

When I submit the form I get an AJAX error which says 'cannot unset string offsets' in field.default.inc. I know that the node\_page\_edit function is causing it because when I remove it the error doesn't happen.

Interestingly, if I press the submit button again straight after getting this error, it works - and the full structure of the form is loaded in to my div.

Why doesn't it work the first time and how do I fix it?

# Answer
> 0 votes
My solution:

```
/* Drupal caches all ids of form elements and when ajax request happen, this
 * results in the new form have id's appended with --2 --3 etc, so css breaks.
 * Unsetting this makes the ids always the same. Maybe hook_init is not the best
 * place for this, but for now it works.
 */
function mymodule_init() {
    if(isset($_POST['ajax_html_ids'])) {
        unset($_POST['ajax_html_ids']);
    }
}

function mymodule_form_{my_form_id}_alter(&$form, &$form_state, $form_id) {
    //only do the do if this is and ajax request
    if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
        $form['actions']['submit'] = array(
            '#type' => 'submit',
            '#value' => 'Save',
            '#ajax' => array(
                'wrapper' => 'my_form_id',
                'method' => 'replace',
                'callback' => 'mymodule_callback',
                'effect' => 'fade'
            ),
            '#submit' => array('node_form_submit'),
        );

        /* For some reason this _has_ to be in form_alter. Putting it in a submit
         * callback doesn't work. What this is doing is setting the changed time
         * of the form to be in the future, if we don't do this, when the form is
         * reloaded after a submit, it's not possible to submit the reloaded form
         * because Drupal thinks someone else has edited it (I think it checks
         * the last update time of the node VS this value). This adds a 5min window
         * where changes can still happen. It's not the best solution but I think
         * it will work.
         */
        $form['changed']['#default_value'] = time() + 300;
    }
}

function mymodule_callback(&$form, &$form_state) {
    $new_form = drupal_rebuild_form('my_form_id', $form_state, $form);
    $form_html = drupal_render($new_form);

    return $form_html;
}

```

---
Tags: 7, forms, ajax
---


# Question
Title: Form returned from AJAX callback missing JS and CSS
I have a form set up like this:

```
function mymodule_form_{my_form_id}_alter(&$form, &$form_state, $form_id) {
    $form['actions']['submit'] = array(
        '#type' => 'submit',
        '#value' => 'Save',
        '#ajax' => array(
            'wrapper' => 'ajax-node',
            'method' => 'replace',
            'callback' => 'mymodule_callback',
            'effect' => 'fade'
        ),
        '#submit' => array('node_form_submit'),
    );
}

```

And then the callback:

```
function ajax_complaint_save_callback($form, &$form_state) {
    $nid = $form_state['build_info']['args'][0]->nid;
    $node = node_load($nid);

    return drupal_render(node_view($node));
}

```

Now this does work *sort of*, but the node is not rendered correctly. I have some more AJAX stuff on the same page which uses the ajax links api and that produces the node forms correctly. Here are some pictures to demonstrate.

In this picture, one of the links in the table was clicked and the stuff circled with blue was loaded using the links api - this is how it should look.

But if go to the edit tab on the loaded node (which is also loaded up through the ajax links api) then press the save button, I get this:

There's more to this picture, but this is loaded in the same div as the other stuff was - but it seems like it is missing style information, and also the view/edit tabs are missing.

How do I make it load up the node form properly?

# Answer
> 0 votes
I ended up loading the form with tabs in to my ajax-node div using the links api, but then within the form I made the submit button replace the form container.

My full solution:

```
/* Drupal caches all ids of form elements and when ajax request happen, this
 * results in the new form have id's appended with --2 --3 etc, so css breaks.
 * Unsetting this makes the ids always the same. Maybe hook_init is not the best
 * place for this, but for now it works.
 */
function mymodule_init() {
    if(isset($_POST['ajax_html_ids'])) {
        unset($_POST['ajax_html_ids']);
    }
}

function mymodule_form_{my_form_id}_alter(&$form, &$form_state, $form_id) {
    //only do the do if this is and ajax request
    if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
        $form['actions']['submit'] = array(
            '#type' => 'submit',
            '#value' => 'Save',
            '#ajax' => array(
                'wrapper' => 'my_form_id',
                'method' => 'replace',
                'callback' => 'mymodule_callback',
                'effect' => 'fade'
            ),
            '#submit' => array('node_form_submit'),
        );

        /* For some reason this _has_ to be in form_alter. Putting it in a submit
         * callback doesn't work. What this is doing is setting the changed time
         * of the form to be in the future, if we don't do this, when the form is
         * reloaded after a submit, it's not possible to submit the reloaded form
         * because Drupal thinks someone else has edited it (I think it checks
         * the last update time of the node VS this value). This adds a 5min window
         * where changes can still happen. It's not the best solution but I think
         * it will work.
         */
        $form['changed']['#default_value'] = time() + 300;
    }
}

function mymodule_callback(&$form, &$form_state) {
    $new_form = drupal_rebuild_form('my_form_id', $form_state, $form);
    $form_html = drupal_render($new_form);

    return $form_html;
}

```

---
Tags: 7, forms, ajax
---


# Question
Title: How can I see what variables are available on the loaded page via the devel PHP Execute block?
How can I see what variables are available to me on the page i am viewing via the PHP Execute block? I'm trying to do a dsm($node) but that doesnt seem to work. Neither does dsm($page).

# Answer
Drupal doesn't define a global `$node` or `$page` object, those are created within the context of various functions during the page build.

To get the node object on a full node page, you can use `menu_get_object()`:

```
$node = menu_get_object();

```

For the page array, you'll need to implement `hook_page_alter()`:

```
function MYMODULE_page_alter(&$page) {
  dpm($page);
}

```

As a general rule PHP's own `get_defined_vars()` function will get you all the variables available in the current context. But it won't be useful to find those two particular vars as they won't be available in the context of a devel PHP form execution.
> 2 votes

# Answer
Drupal loads all variables into `$variables`.

So in the PHP block just load: `<?php dsm($variables); ?>`.

For dsm to work you need the Devel module installed.
> 3 votes

---
Tags: 7, debugging
---


title: Replace main menu block with nice menus

text:
# Question
Title: Replace main menu block with nice menus
I am using Bootstrap theme, attempting to build a basic skeleton site that will use Nice Menus dropdown. Cannot get it to work: if putting in a block it displays alongside main menu, if disabling block and enabling Nice Menu 1 in Structure -\> Blocks it does not behave correctly, no dropdown on hover

# Answer
> 0 votes
Nice menu works in same way as you required. Did you configured this module correctly?

First you need to look into configuration of this module(Nice menus).

After that you need to configure your nice module correctly in block list as in attached image. If still error persists then look for JS error.

---
Tags: navigation
---


title: Can I rename index.php?

text:
# Question
Title: Can I rename index.php?
I am going to replace the front page of a Drupal 6 site with a new `index.php`. How can I rename the Drupal 6 `index.php` (say, to `drupal.php`) and keep the Drupal site functions working? For example, I'd like to have all the `URL aliases` work as before.

Is changing:

```
RewriteRule ^(.*)$ index.php?q=$1 [L,QSA]

```

to:

```
RewriteRule ^(.*)$ drupal.php?q=$1 [L,QSA]

```

in `.htaccess` all what I need?

I need Drupal to co-exist with another site (which should be load by default) in the same http doc directory, and to keep existing Drupal functions (a few webforms).

# Answer
Others have advised you not to do this. I too remain in that idea, but to answer your question:

**Can Drupal even run without index.php? Can it be a different file name?**

Technically it's possible for Drupal to run on any different directory index file name. But you need to configure your web server for that first. Unfortunately you will need to hack core as well, which is considered without-doubt a bad idea.

**.htaccess changes**

Assuming you are using Apache, and because it can automatically detect http://example.com?q=node and http://example.com/drupal.php?q=node if the `DirectoryIndex drupal.php`, you will only need to change the .htaccess file.

if your web server is not Apache and if you can't configure it to above URL patterns, you have to modify line 1518 in common.inc as well (Drupal 6.31). Things will get much complex in Drupal 7.x. You will have to make several hacks which you will find difficult to maintain patches for.

In your .htaccess, change these (using "drupal.php" as the new file name).

* `ErrorDocument 404 /index.php` to `ErrorDocument 404 /drupal.php`
* `DirectoryIndex index.php` to `DirectoryIndex drupal.php`
* `RewriteRule ^(.*)$ index.php?q=$1 [L,QSA]` to `RewriteRule ^(.*)$ drupal.php?q=$1 [L,QSA]`

You will probably need to modify your unit tests and shell scripts as well.
> 2 votes

---
Tags: 6, .htaccess
---


# Question
Title: what variable can i use to identify a specific pages
i need to load a diff stylesheet depending upon which page the user is on.

when using: themename\_preprocess\_page(){kpr(&$variables;)}

i thought i'd see a pageId or pageTitle in which i could use for a conditional statement but i'm not seeing those variables. am i overlooking something? what can i use to uniquely identify a page so i can the use drupal\_add\_css()?

i guess i could do at the node level? but the stylesheet i need to load is really a page level thing.

can someone advise on the best way to do? big thanks in advance

# Answer
> 1 votes
You may have trouble adding CSS with drupal\_add\_css in `hook_preprocess_page` because the `$styles` variable has already been built.

Better to add CSS in `hook_preprocess_html` or `hook_page_build`

Note, you should be able to target specific pages in CSS by using body classes.

e.g:

```
body.page-node-type-article #content{
  background-color:pink;
}

```

But yes, to check the path, you can use

```
$arg = arg($index); // system path component
$path = current_path(); // full base system path ($_GET['q']);
$alias = $_SERVER['REQUEST_URI']; // full alias only

```

# Answer
> 0 votes
You can use arg to identify specific page.

It returns a component of the current Drupal path.

When viewing a page at the path "**admin/structure/types**", for example, arg(0) returns "admin", arg(1) returns "structure", and arg(2) returns "types".

For more info go through the documentation.

# Answer
> 0 votes
I'm using:

```
if ( preg_match('(^comment/reply/[0-9]*)', current_path())  === 1 ) {}
if ( preg_match('(^node/[0-9]*$)', current_path())  === 1 ) {}
if ( current_path() == 'search' ) {}

```

Using themename\_preprocess\_html, I think works fine. But I'm not sure if you need this exactly. However, is an alternative.

# Answer
> 0 votes
hook\_init() is best function to make changes at page level. You can use arg() function to get arguments of current page. Even you can also use menu\_get\_object() to get all possible values on rendered page.

---
Tags: theming
---


# Question
Title: Make certain pages available to logged-in users only
I need some help and here is the issue:

I am building a site using Drupal 7.

I need to make certain pages only visible to logged-in users (each having their own username/password), other users should be simply redirected or shown an error message. Is this functionality maybe included in Drupal 7 itself or is there a module that does this (something simpler than Organic Groups)?

# Answer
You need to use Content Access module for fine grained node view permissions.

> This module allows you to manage permissions for content types by role and author. It allows you to specifiy custom view, edit and delete permissions for each content type. **Optionally you can enable per content access settings, so you can customize the access for each content node.**
> 7 votes

# Answer
If you're looking to do it programmatically within a module or node (w/ PHP Input Filter), you could use user\_is\_logged\_in() for something like this:

```
<?php
if (!user_is_logged_in()) drupal_not_found();
?>

```
> 1 votes

# Answer
Although the Content Access module solves the problem well, it's an extra module and it's not stable yet on D7.

An alternative using only commonly used modules is:

1. Create the nodes but set them as unpublished
2. Create a node view, e.g. "role-restricted content". Show the full node's content to replicate the standard node/% display.
3. Restrict the view to your desired roles (e.g. "Role | Authenticated user")
4. Set the view path to something like:

```
restricted-content/%

```
5. Set a contextual filter by Nid.
6. Remove the default "content is published" filter.

Now you will have a view that works just like node/%, except it also handles unpublished content and restricts by role.
> 0 votes

# Answer
There is pretty simple programatic solution, you can read user role (and also if it is anonymous or registered) like this:

```
$roles=$GLOBALS['user']->roles;

```

you will get an array with roles of current user in $roles.

You can redirect that user depending on role with some logic using

```
drupal_goto ('url-of-the/page');

```
> -1 votes

---
Tags: 7
---


title: Views data relationships?

text:
# Question
Title: Views data relationships?
I am trying to figure out how add a relationship in a view\_data...

I have a hook\_views\_data which sets up the base table and a group called List. It has two tables

1. Main List
2. List Contents

And they are related via a list\_id. I have a table -\> join to join the table with the list contents and all that fun stuff and that all seems to be working. But when I add a relationship for List Contents it won't show any List Contents fields.

So I can get List Name and List ID no problem, I add a relationship to List and a contextual filter for List ID but after I add a relationship I still cannot access any of the `$data['list']` array members (so product id or nid or what not).

Any idea what I am missing?

```
  $data['lists']['table']['group']  = t('Lists');

  $data['lists']['table']['base'] = array(
    'field' => 'list_id',
    'title' => t('Lists'),
    'help' => t('TODO:'),
    'entity type' => 'commerce_product',
    'access query tag' => 'commerce_product_access',
  );

  $data['lists']['table']['join'] = array(
    'commerce_List' => array(
      'left_field' => 'list_id',
      'field' => 'list_id'
    )
  );

  // Expose the List id.
  $data['lists']['list_id'] = array(
    'title' => t('List ID'),
    'help' => t("The List ID."),
    'field' => array(
      'handler' => 'views_handler_field_numeric',
      'click sortable' => TRUE,
    ),
    'filter' => array(
      'handler' => 'views_handler_filter_numeric',
    ),
    'sort' => array(
      'handler' => 'views_handler_sort',
    ),
    'argument' => array(
      'handler' => 'views_handler_argument_string',
    ),
    'relationship' => array(
      'title' => t('List'),
      'help' => t("Relate this List to its contents"),
      'handler' => 'views_handler_relationship',
      'base' => 'commerce_List',
      'base field' => 'list_id',
      'field' => 'list_id',
      'label' => t('List contents'),
    ),
  );

  // Expose the List name.
  $data['lists']['name'] = array(
    'title' => t('List Name'),
    'help' => t('List name'),
    'field' => array(
      'handler' => 'views_handler_field',
      'click sortable' => TRUE,
    ),
    'sort' => array(
      'handler' => 'views_handler_sort',
    ),
    'filter' => array(
      'handler' => 'views_handler_filter_string',
    ),
    'argument' => array(
      'handler' => 'views_handler_argument_string',
    )
  );

  // Expose the product ID.
  $data['list']['product_id'] = array(
    'title' => t('Product ID'),
    'help' => t('The unique internal identifier of the product.'),
    'field' => array(
      'handler' => 'commerce_product_handler_field_product',
      'click sortable' => TRUE,
    ),
    'filter' => array(
      'handler' => 'views_handler_filter_numeric',
    ),
    'sort' => array(
      'handler' => 'views_handler_sort',
    ),
    'relationship' => array(
      'title' => t('Product'),
      'help' => t("Relate this List to its owner's user account"),
      'handler' => 'views_handler_relationship',
      'base' => 'commerce_product',
      'base field' => 'product_id',
      'field' => 'product_id',
      'label' => t('List product display'),
    ),
  );

  // Expose the product type.
  $data['list']['nid'] = array(
    'title' => t('Nid'),
    'help' => t('The human-readable name of the type of the product.'),
    'sort' => array(
      'handler' => 'views_handler_sort',
    ),
    'relationship' => array(
      'title' => t('Product display (node)'),
      'help' => t("Relate this List to its owner's user account"),
      'handler' => 'views_handler_relationship',
      'base' => 'node',
      'base field' => 'nid',
      'field' => 'nid',
      'label' => t('List product display'),
    ),
  );

  // Expose the creator uid.
  $data['lists']['uid'] = array(
    'title' => t('Uid'),
    'help' => t("The owner's user ID."),
    'field' => array(
      'handler' => 'views_handler_field_user',
      'click sortable' => TRUE,
    ),
    'argument' => array(
      'handler' => 'views_handler_argument_user_uid',
      'name field' => 'name', // display this field in the summary
    ),
    'filter' => array(
      'title' => t('Owner'),
      'handler' => 'views_handler_filter_user_name',
    ),
    'sort' => array(
      'handler' => 'views_handler_sort',
    ),
    'relationship' => array(
      'title' => t('Owner'),
      'help' => t("Relate this List to its owner's user account"),
      'handler' => 'views_handler_relationship',
      'base' => 'users',
      'base field' => 'uid',
      'field' => 'uid',
      'label' => t('List owner'),
    ),
  );

  // Expose links to operate on the product.
  $data['list']['delete_List'] = array(
    'field' => array(
      'title' => t('Delete'),
      'help' => t('Provide a simple link to delete the product from the List.'),
      'handler' => 'commerce_List_handler_field_product_link_delete',
    ),
  );

```

# Answer
The problem was I was missing some parts for my second table. Any table used in this views data hook needs to have a group. Adding

```
  $data['list']['table']['group']  = t('List');

  $data['list']['table']['join'] = array(
    'lists' => array(
      'left_field' => 'list_id',
      'field' => 'list_id'
    )
  );

```

Fixed it.
> 0 votes

---
Tags: 7, views
---


# Question
Title: Drupal Crumbs can't get first "level" to show breadcrumb?
I seem to be having a problem with Crumbs and I can't seem to figure it out. I have it setup to show

```
crumbs.home_title
path
menu.hierarchy.main-menu
*

```

But it doesn't seem to show anything for the very first level, anything under that shows fine. I can't seem to figure out what is going on. At least it should show the Home title?

# Answer
> 0 votes
As Clive said, this ended up being a configuration issue on my part.

Shortest visible breadcrumb under /admin/structure/crumbs/display was set to 3 levels.

---
Tags: 7, breadcrumbs
---


# Question
Title: How to increase delta value of a multiple valued field +1?
I would like to output the delta value of a multiple image field as a affix for the image title in a view, but increased with 1. So, it should start with 1 not with 0. How can I do this?

Why do I need this? I need to reference to the images from articles using the scheme *Fig. 1*, *Fig. 2* etc. There for the view output should look like:

```
+----------------+
|                |
|    an image    |
|    delta 0     |
|                |
+----------------+
Fig. 1: Image Title

+----------------+
|                |
|    an image    |
|    delta 1     |
|                |
+----------------+
Fig. 2: Image Title

+----------------+
|                |
|    an image    |
|    delta 2     |
|                |
+----------------+
Fig. 3: Image Title

```

The first thing I tried is, to sort the view by delta and than output "Global: View result counter", but this does not work if a filter is applied to the view. If a filter is in action, the numeration would not be concordant with the delta anymore.

Do I have to write an custom formatter? And when, where do I start, I don't have an idea.

# Answer
> 2 votes
It depends upon what you're planning to do with that delta. Here's a possible solution for you:

Use Aggregation on the view and use "max" for the delta. Hide the field and then do a math operation to add +1 to the value of the delta.

If you could expound on the "why" it would help.

---
Tags: views
---


# Question
Title: Is there a way to prevent content from being selected for copying or being printable for Drupal sites?
I would like the to display some content to users that would be viewable, but not easily duplicated by users without permission. Do major browsers provide a setting option, or is there a way that Drupal can mange this action?

# Answer
I am unaware of any way to do this out of the box, and the problem isn't really related to Drupal. The problem is just a user selecting text in the browser and doing a Crtl-C.

While not foolproof, you can use CSS and/or jQuery shenanigans to place a `<div>` over your content with a transparent background PNG. This should make the text beneath it unselectable. It will also make any links unclickable. You could add some permission logic to only do this for certain user roles.

This does not prevent anyone doing a view-source, wget, or any other method for getting at the markup. If it's on the web, someone will figure out a method for getting it.
> 4 votes

# Answer
As MPD already mentioned, it is not really a Drupal problem but rather more general. Something that might help in your case is Cufon, a method to replace text with images. It's somewhat obsolete now with @font-face being widely supported, but it could be a solution for you.
> 2 votes

# Answer
You could use something like phpThumb to create an image from your text.

Check out this demo: http://phpthumb.sourceforge.net/demo/demo/phpThumb.demo.demo.php#x51
> 1 votes

# Answer
We can achieve that by Copy Prevention module.

From module page:

> This module includes several different technical ways/methods to make copying/stealing information/images from your site harder than it usually is:
>
> * Disable text selection
> * Disable copy to clipboard
> * Disable right-click context menu on all site content
> * Disable right-click context menu only on images ( tag)
> * Place transparent image above all your images - this will protect your real images from being saved using context menu or drag-and-drop to desktop
> * Protect/hide your images from search engine indexes so that your images don't show up in image searches - add "noimageindex" robots tag and disallow image files indexing in robots.txt

I've tested all the features of this module and works great!
> 0 votes

---
Tags: 7, users
---


title: How do I sub-sort a view?

text:
# Question
Title: How do I sub-sort a view?
We have a view containing two fields that we would like to sort - specifically issue # and Title. We would like to sort the view first by the Issue # field and then secondly by Title, so that nodes from the same issue are clustered and sorted again by title.

How can we sub-sort a view so that one field is the primary sort and another is the secondary sort (similar to sorting in a spreadsheet)?

# Answer
> 1 votes
Just add two entries in the "Sort criteria" section, left column, bottom. The more important sorting criteria should be on top.

Add button can be used as a drop-down, to show Rearrange button, if needed.

---
Tags: views
---


title: Get order value on completed checkout

text:
# Question
Title: Get order value on completed checkout
I'm using drupal 6 and ubercart 6.x-2.9

I've created my own template for the checkout complete page, this is so I can install conversion tracking code from adwords.

I'd like to pull the order value and insert it into the adwords snippet.

Does anyone know how to call this value? Is there already a variable with the correct value that I can just echo/print into my template?

# Answer
I was able to pull the order value using the following code

```
$order = uc_order_load(intval($_SESSION['cart_order']));

if ($order)
{
   $amt = round($order->order_total,2);
}

```
> 0 votes

---
Tags: 6, ubercart
---


title: FAPI text_format field doesn't render

text:
# Question
Title: FAPI text_format field doesn't render
In D7 I'm creating a form for a custom module. I would like one of the form fields to provide a wysiwyg editor (these work and render properly elsewhere around the site). In my custom form though, the text\_format field doesn't render. If I change the type to 'textarea' it shows up, but as text\_format, it's just non-existent in the rendered output.

My code is like this:

```
function mymodule_menu() {
  $items = array();
  $items['admin/mymodule'] = array(
    'title' => 'My Module Form',
    'page callback' => 'mymodule_form',
    'access callback' => TRUE,
    'type' => MENU_CALLBACK,
  );
  return $items;
}

function mymodule_form($form_state) {
  $form = array(
    'field1' => array(
        '#type' => 'textfield',
        '#title' => t('Field 1'),
        '$required' => true,
    ),
    'field2' => array(
        '#type' => 'text_format',
        '#title' => 'Filed 2',
        '#default_value' => "",
        '#format' => 'filtered_html',
    ),
  );
  return $form;
}

```

Can anyone spot a problem with this? What else should I be looking for to understand why the field doesn't render when the type is 'text\_format'?

# Answer
Well I finally figured this one out. Hopefully this helps someone else out there:

```
function mymodule_menu() {
  $items = array();
  $items['admin/mymodule'] = array(
    'title' => 'My Module Form',
    'page callback' => 'mymodule_callback',
    'access callback' => TRUE,
    'type' => MENU_CALLBACK,
  );
  return $items;
}

function mymodule_callback() {
  $form = drupal_get_form('mymodule_form');
  return $form;
}

function mymodule_form($form_state) {
  $form = array(
    'field1' => array(
      '#type' => 'textfield',
      '#title' => t('Field 1'),
      '#required' => true,
    ),
    'field2' => array(
      '#type' => 'text_format',
      '#title' => 'Filed 2',
      '#default_value' => "",
      '#format' => 'filtered_html',
    ),
  );
  return $form;
}

```

For whatever reason, having the menu callback not point directly to the form builder function, but instead at an intermediary function that calls drupal\_get\_form() caused the text\_format type to work properly.
> 0 votes

---
Tags: forms, wysiwyg
---


title: Where is the view menu?

text:
# Question
Title: Where is the view menu?
When I want to see the wishlist of user 1, for example I go to `http://localhost/drupal/user/1/wishlist`. And I successfully get a well organized page.

But I don't see any items in the `hook_menu()` that describes this. How does it work?

Though there is `hook_views_api()`, I am not sure whether it is the place for view.

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

  $items['user/%user/wishlist/delete/%'] = array(
    'page callback' => 'commerce_wishlist_delete',
    'page arguments' => array(1, 4),
    'access callback' => 'commerce_wishlist_access',
    'access arguments' => array(1, 4),
    'type' => MENU_CALLBACK,
  );
  $items['admin/commerce/config/wishlist'] = array(
    'title' => 'Wishlist configuration',
    'description' => 'Configure wishlist',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('commerce_wishlist_admin_form'),
    'access arguments' => array('administer wishlists'),
    'file' => 'commerce_wishlist.admin.inc',
  );
  $items['wishlist-actions'] = array(
    'page callback' => 'commerce_wishlist_operations',
    'access arguments' => array('view own wishlist'),
    'type' => MENU_CALLBACK,
  );

  return $items;
}

```

# Answer
> 1 votes
Some pages are generated entirely through views, bypassing the code. You can set the menu link and path in the view's settings. The navigation to that page would then be completely independent of the code.

If the page was created when you installed someone else's module, I would guess that the view is embedded into the site through code, and the path can be set that way as well. In that case, the path would be set in an array with something like this:

```
$handler->display->display_options['path'] = 'user/%/wishlist';

```

Contained in a function utilizing `hook_views_default_views`.

You can tell where the view is generated on the admin/structure/views page, where under each view title it tells you either: "In database", "In code", or "Database overriding code." I'm assuming that the wishlist page is a view. So, if your page doesn't appear on the views admin page, then it's a different problem.

---
Tags: views
---


title: Print array element syntax

text:
# Question
Title: Print array element syntax
I am using devel and `<?php dpm($items); ?>` in my field template file so the node looks like the following.

I can print the #theme element (which is a string) with the following code.

```
<?php print $items[0]['#theme']; ?>

```

What is the syntax to print elements in an array such as URLs, labels, titles?

# Answer
> 2 votes
You'll have to follow the trail in the DPM structure. The **url** field is under the **#element** element. The **#element** element is under the **0** element. This means you can access the value of **url** with:

```
$items[0]['#element']['url'];

```

You can reach the **title** element in a similar way.

The value of **#theme** is directly under the **0** element, that is why you could access it with:

```
$items[0]['#theme']

```

# Answer
> 1 votes
where did you output the `dpm`? double click on any of the attributes then it shows you the trail array which displays that content. like this

then use this array key at the beginning of the variable passed in your hook preprocess function. for example:

```
function hook_preprocess_node(&$variables){
    $variables['value'] = $variables['revision_timestamp']
}

```

---
Tags: theming
---


# Question
Title: Converting a timestamp to PHP date format for a field in a node template
I have an imagefield, 'event\_image' and printing all possible variables for the field tells me I have timestamp as a possible variable of the image to render. I use:

```
print '<pre>';
var_dump(get_defined_vars());
print '</pre>

// renders:
["timestamp"]=>
string(10) "1348629688"

```

... in `node--mycustom.tpl.php` to get the variables.

Now I can render the timestamp as such:

```
<?php print $node->field_event_image['und'][0]['timestamp'] ?>

```

... and it prints a UNIX formatted timestamp as:

```
1348629688

```

I'd like to convert this to a PHP date format. So I am guessing I would need to convert the UNIX timestamp somehow using the PHP `gmdate` function. Typically I would use something like this for raw php:

```
  $mytimestamp=1348629688;
  print gmdate("m-d-Y", $mytimestamp);

```

Which would take my timestamp and output:

```
09-26-2012

```

... but I just don't know how to do within the context of my drupal 7 field and the node template.

**UPDATE:**

Base on clive's comment below, it turns out a preprocess function is the way to go: So in my theme's template.php file I now have:

```
function MYTHEME_preprocess_node(&$vars, $hook) {

$node = $vars['node'];
$field_items = field_get_items('node', $node, 'field_event_image');
$vars['upload_date'] = format_date($field_items[0]['timestamp'], 'mdy');

}

```

... and then in my custom node template, I have:

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

```

Note, `'mdy'` is a custom format I set in the Drupal UI. That's better than using `gmdate` I suppose.

# Answer
> 6 votes
As already pointed out by Mohammed Shameem:

```
<?php print gmdate("m-d-Y", $node->field_event_image['und'][0]['timestamp']) ?>

```

However, the Drupal way would be:

```
<?php print format_date($node->field_event_image['und'][0]['timestamp'], 'short'); ?>

```

The latter construct will render the date in the standard short date format set up for the site. The former will use the format *you* pick. The Drupal way ensures that the date format is standardized throughout the site.

# Answer
> 0 votes
Another example based on field in user object:

```
  global $user;
  $curr_user = user_load($user->uid);
  $field_items = field_get_items('user', $curr_user, 'field_some_date_end');

  $datetime = $field_items[0]['value']; // Unix time
  $formatted = format_date($datetime, 'short'); // Date in short format

```

---
Tags: 7, entities, nodes, theming, datetime
---


title: hook_init for node redirect

text:
# Question
Title: hook_init for node redirect
I need to check if the http\_referrer var is a specific page in Drupal and redirect otherwise.

I was trying the Rules module but I need something flexible enough to add PHP code.

Can I use hook\_init() in my template.php function to check for the referrer and the destination node and redirect if certain conditions are in place?

# Answer
You can implement `hook_init` in a custom module.

```
function my_module_init() {
  // Since this file should only be loaded on the front page, it cannot be
  // declared in the info file.
  if (drupal_is_front_page()) {
    drupal_add_css(drupal_get_path('module', 'foo') . '/foo.css');
  }
}

```

But note that this WILL NOT work if the page is cached or if you are using a revers proxy cache. If you need to do this on cached pages look into using `hook_boot`

That being said, there is often better ways to accomplish a redirect based on certain conditions. Update your question with more details and perhaps we can find more suitable solutions.
> 0 votes

---
Tags: rules, redirection
---


title: Drupal Services node filtering

text:
# Question
Title: Drupal Services node filtering
Is there a way to filter the nodes that come from a SERVICES node Endpoint, by a field or status?

# Answer
`http://test/api/node?parameters[nid]=1&parameters[status]=1&fields=status,bid,title`

As always you can look at the tests.

Below you can see whats possible.
> 19 votes

# Answer
At least when the resource is provided by Drupal Commerce Services, this appears to be slightly different. I had to go read the source, but the equivalent to the parameter query string parameter for commerce services is filter.
> 0 votes

---
Tags: 7, nodes, services
---


title: CKEDITOR is not defined?

text:
# Question
Title: CKEDITOR is not defined?
I've installed Wysiwyg with CKEditor and set up a profile for the editor. However, the CKEditor toolbar isn't showing up. When I add new content Firebug shows the following script error:

```
CKEDITOR is not defined

```

It highlights line 144 of /sites/all/modules/wysiwyg/wysiwyg.js:

```
CKEDITOR.config.customConfig = '';

```

I'm really not sure how to solve this problem. Do I need to manually define CKEDITOR.config.customConfig? If so, what should its value be?

I should add that this is a fresh Drupal install (version 7.27) and that I'm using Wysiwyg 7.x-2.2-dev with CKEditor 4.4.0 (standard version). The reason for using the development version of Wysiwyg is that the stable version is unable to detect CKEditor.

# Answer
> 0 votes
Yeah, I can confirm Molots statement.

Try to use **CKEditor 3.5.3** with the newest Wysiwyg. Even with patches I could not solve the problems between CKE 4 and wysiwyg.

regards, SuperEngineer 64

EDIT: Also possible is to install the Develpoment-Version of Wysiwyg. I use it mit CKE4 now.

---
Tags: wysiwyg
---


# Question
Title: Trying to get a "Is between" date filter to work... it is returning an offset by + 1 days.
Please see my website to see what i'm talking about: http://apollo.tbc.iit.edu/~spaceweather/sw\_test/?q=download-cases-data#

Ive found some examples and posts on how to do this but even after following them i'm still having issues.

I'm trying to filter the results shown in a table. I want the dates in between the two specified dates a user might put in.

When I select 05/24/2013-05/26/2013 I get an offset of 05/25/2013-05/27/2013 for the results. Can anyone help with this? I'm storing the date as a Unix time stamp.

Thank you for your help!

(\*Note my website has been updated according to the suggestion below by @adem .)

# Answer
I figured out my own issue, which as with most quirky issues like this end up being buried in the details that other users wont know right away.

When I put these dates into my database I used an offset timezone for "America/Chicago". In the on the Drupal side it was displaying the time in UTC which happens to be forward 5 hours from CST time.

I went to edit the field I created for these dates and changed the timezone from UTC to "America/Chicago" and it fixed the issue. Everything filters nicely now.

Here is a screen shot of where i found this option to change things. I hope this helps others who might see an unexpected offset in their days. Always make sure your timezones are correct to what youre expecting!
> 1 votes

# Answer
The filter type must be "single filter", operator must be "is between", as demonstrated in this screenshot:
> 1 votes

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