title: Should I learn Symfony 2?

text:
# Question
Title: Should I learn Symfony 2?
I saw this, How much of Drupal 8 will rely on or be compatible with Symfony? but I don't understand if it applies to my question. Should I learn Symfony 2 to develop with Drupal?

# Answer
Symfony 2, as in the full stack Symfony 2 has no bearing on Drupal 8 -- we do not use its bundles, we do not use the same routing as Symfony does (we use a botched up work on top called Symfony CMF which is made less dog slow by bastardizing my menu work on top of it but it's ~~still undocumented~~, incomprehensible, does not yield to static code analysis tools and altogether is broken and slow). We do not use the same ORM (Doctrine). We are using *some* Symfony 2 components however there is very little visible of it to the "end" developer. For example, confusingly enough, *sometimes* you need to use events (what was hook\_boot/hook\_init in D7 is replaced by Symfony HTTP kernel events) whereas most often Drupal still uses its hooks. Confusing is the name of the game where Symfony 2 interacts with Drupal. It's an extremely poor fit and the (non)amount of the documentation of how this fit (does not) happen makes it even harder.

Edit: we do use the service container http://symfony.com/doc/current/book/service\_container.html at least the static parts of it -- *however* dynamic service additions and alterations are done via Drupal specific means (service providers which attaches to the system via a special magic way which is neither events nor hooks. Welcome to Drupal 8.)

So: if you know Symfony 2 inside and out then a little of that will be usable in Drupal 8. If you don't then don't bother with Symfony 2 books or tutorials.
> 24 votes

# Answer
I "grew up" on Drupal so I was always procedural guy(Drupal is my main/only tool for making websites which is my job). At first I was very confused when I started to use Drupal 8. The OOP wasn't that hard since I knew OOP, but the new architecture was hard to get my head around. But after two weeks I started to feel like home again. This website and #drupal-contribute helped me a lot. I've read some information from Symfony documentation to understand controllers basically and no I'm working with D8 for 4 months and I feel like home again.

Things have changed but you'll learn the new ways very fast. You really don' have to learn Symfony AT ALL. I didn't.

One thing that made things MUCH easier for me was switching my IDE from NetBeans to PHPStorm because NetBeans didn't supported browsing inherited methods. After few months I cannot understand how was I able to use NB :) (though working with Git in NB is for me much better)

So to answer your question: you absolutely don't have to learn Symfony. To meake your life easier look at \*.services.yml files in modules(that implements them) and also route callbacks in any modules \*.routing.yml file to understand page callbacks(from hook\_menu in D7).
> 6 votes

---
Tags: 8
---


# Question
Title: How do I remove text format information from the bottom of my text areas
I have a content type which all of my users can create instances of. The last text area has a section listing the particulars of the text format. I would like to disable this area so that the test format does not explain itself, and all the user sees is a text area.

# Answer
You can use the Simplify module for this.

It describes itself as follows:

*Simplify allows particular fields to be hidden from the user interface. This helps to de-clutter forms and present a more user-friendly experience to content editors.*
> 4 votes

---
Tags: 7, entities, input-formats
---


title: Using drush @self alias returns nothing

text:
# Question
Title: Using drush @self alias returns nothing
According to the documentation for `drush` (version 5.9) it has a built in alias called @self.

When I attempt to use the `@self` alias in a command such as:

```
drush site-alias @self

```

Nothing is returned. However, using aliases I've defined in my `aliases.drushrc.php` the commands work as expected.

Does anyone have any ideas as to what might be going on?

# Answer
> 5 votes
In order to use the @self alias, Drush must be able to detect and bootstrap your Drupal site based on the current working directory. If your settings.php file is in the 'default' directory, then you may cd to your Drupal root directory, or any directory below it, and @self will work. If your settings.php is in some other directory, then you must either cd to the directory that the settings.php file is in, or provide a --uri option to Drush.

You can also use @self without changing your working directory if you supply --root and --uri options to Drush.

---
Tags: drush
---


# Question
Title: how can i attach a taxonomy to the users profile?
I use drupal 7 and need to attach a certain taxonomy to a user. there is module for drupal 6 but as i see there is no module for that in drupal 7. how can i do that in my module by coding?

**why do i have this question:** i sell some digital files and now i am developing a module for selling my files. i want to sell them this way: each file has a certain taxonomy. when my user buys that file he or she gets that taxonomy. once he clicks on download link i have to check whether that user has that taxonomy already or not!

# Answer
> 3 votes
Users in Drupal 7 are proper entities and fieldable.

Goto Administration » Configuration » People » Account settings » Manage Fields (admin/config/people/accounts/fields)

Add a new Field. Choose a label, and choose Term Reference as the field type. Configure as needed. This should identical for how you do it for a Content Type (ie, a node).

The click on the Manage Fields tab. Set up the display for how you need it.

Edit you users, and add in some field data. It will be in the full loaded `$user` object, and you can use it in Views over Users.

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


# Question
Title: Limit entity reference widget to unique references
I have a entity-reference field that enables multiple-references (cardinality is set to -1). The problem is that it allows multiple 'same' references =\> it is possible to save two references to one specific node.

I know I can limit that using my own validation function but I have this feeling that there has to be easier way (e.g. some settings that I don't know about).

If there's none then sorry for useless question.

# Answer
> 2 votes
I don't think the Entity Reference module ships with this feature. But the entityreference unique module should be sufficient for your need. It is in alpha mode, so I would check the issue queue to see if there are any security/critical issues with it before using it on a production env.

# Answer
> 0 votes
Looking at entityreference unique module (thanks awm) I discovered that the best way to implement it is using entityreference behavior plugin, to be more specific its validate function.

---
Tags: entities
---


# Question
Title: How to grab a user's Fivestar voting value with Rules?
On my website, users can rate nodes via comments. The Fivestar field is called 'Stars'. I'd like to use the user's voting value in a rule that's activated when a new comment has been saved. (The rule should update a radioactivity field, called 'Popularity', from the node that's commented on.)

When debugging the 'Stars' field in a comment, I'm able to get exactly the value I need via `field_stars['und'][0]['rating']`. However, I can't find a way to grab it in the Rules UI. I'm always ending up with `comment:field-stars:` in an action.

I tried adding a condition 'Entity has field: *Parameter: Entity: \[comment:node\], Field: field\_stars*'. This gave me the option to dig deeper to `comment:field-stars:user-rating`, but when I'm using it further on in my rule, it always throws an error "The variable or parameter value is empty."

What's going wrong and how can I solve this?

---

**Edit**: After reading this question, I tried solving my problem with the following rule.

```
{ "rules_new_vote" : {
    "LABEL" : "New vote",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "php", "radioactivity", "comment" ],
    "ON" : { "comment_insert--comment_node_article" : { "bundle" : "comment_node_article" } },
    "IF" : [
      { "entity_has_field" : { "entity" : [ "comment:node" ], "field" : "field_popularity" } }
    ],
    "DO" : [
      { "variable_add" : {
          "USING" : { "type" : "integer", "value" : "0" },
          "PROVIDE" : { "variable_added" : { "null" : "null" } }
        }
      },
      { "php_eval" : { "code" : "$rating = \u0026drupal_static(\u0027rating\u0027, $default_value = $comment-\u003Efield_stars[\u0027und\u0027][0][\u0027rating\u0027]);" } },
      { "radioactivity_emit" : {
          "data" : [ "comment:node:field-popularity" ],
          "value" : { "select" : "null", "php" : { "code" : "return $rating;" } }
        }
      }
    ]
  }
}

```

Unfortunately, it doesn't work properly: when saving a comment, the following error is thrown:

> Notice: Undefined variable: rating in eval() (line 1 of C:\wamp\www\mysite\sites\all\modules\rules\modules\php.eval.inc(146) : eval()'d code).

How can I solve this?

# Answer
> 2 votes
I finally found a solution for my problem. This is my exported rule:

```
{ "rules_new_vote" : {
    "LABEL" : New vote",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "php", "radioactivity", "comment" ],
    "ON" : { "comment_insert--comment_node_article" : { "bundle" : "comment_node_article" } },
    "IF" : [
      { "entity_has_field" : { "entity" : [ "comment:node" ], "field" : "field_popularity" } }
    ],
    "DO" : [
      { "variable_add" : {
          "USING" : {
            "type" : "integer",
            "value" : {
              "select" : "comment:cid",
              "php" : { "code" : "$comment = comment_load($value);\r\n$vote = $comment-\u003Efield_stars[\u0027und\u0027][0][\u0027rating\u0027\r\nif ($vote == 20) {return -4;}\ r\nif ($vote == 40) {return 2;}\r\nif ($vote == 60) {return 3;}\r\nif ($vote == 80) {return 4;}\r\nif ($vote == 100) {return 5;}" }
            }
          },
          "PROVIDE" : { "variable_added" : { "rating" : "Rating" } }
        }
      },
      { "radioactivity_emit" : { "data" : [ "comment:node:field-popularity" ], "value" : [ "rating" ] } }
    ]
  }
}

```

The trick was to store the `cid` as a new variable and to use that value in the PHP evaluation (the proposed values in my code can be changed to your needs). I've no idea why this wasn't possible in an easier way via the UI, but maybe it's a bug in the Firestar module.

---
Tags: 7, rules, comments, rating
---


# Question
Title: What is the difference between $container->get('current_user') and global $user?
I've been looking at symfony's implementation of dependency injection, and it seems like a service locator pattern.

It appears, at first blush, that the service container is not entirely different from a global namespace, and that any of the objects located within could be requested and modified in unexpected ways by some other module. It seems like symfony has built in a way around these Action at a distance anti patterns by setting Scopes on the container, (addScope, enterScope, leaveScope), but I only see one example of addScope in CoreServiceProvider.php with a 'request' namespace.

Should module developers be encouraged to scope their interaction with the container if they plan on modifying services?

# Answer
The general idea is to not use service location but define the dependencies directly in the container. There are edge cases where you need to pass along the full container, but really, try to avoid them. For objects like plugins and controllers we use a static factory pattern, on which you get the container to get your dependencies. Note: There aren't any objects which depend on those.

On top of that you also should avoid having to change services. As much as possible! Instead you should build a wrapper service which has a method like the \Drupal\Core\Session\AccountProxy ... you can set the current user on there using setAccount.

```
  public function __construct(AccountInterface $current_user) {
    $this->currentUser = $current_user;
  }

  public function doSomething() {
    $this->currentUser->setAccount(new UserSession(...));
  }

```
> 1 votes

---
Tags: 8
---


title: Is the Dutch translation incomplete?

text:
# Question
Title: Is the Dutch translation incomplete?
Using kickstart 2-rc4 I seem to miss some Dutch translations (I used the 2.x translation file).

If 'Add a product' ('Voeg een product toe') is translated, then why would 'Manage products' not be translated? The Dutch .po file does indeed not contain a translation for this, but it seems weird, if you would translate the one, why not translate the other?

Am I doing something wrong here?

# Answer
> 1 votes
You can try importing the translation file again; it is possible that the connection timed out and that some of the translations were not inserted.

However, if you check the `.po` file and you can't find the translations of those strings - it means that whoever was translating the terms did not finish them all.

You can translate missing terms yourself within Drupal at `admin/config/regional/translate/translate` or download Poedit and contribute translations back here.

# Answer
> 1 votes
To answer your question. Yes a lot of translations are missing.

My installation language overview

Translate interface

```
Language    Built-in interface  Fields                 Drupal Commerce
Dutch       4834/9902 (48.82%)  4831/4988 (96.85%)     208/208 (100%)

Language    Built-in interface  Fields                 Drupal Commerce
Dutch   8647/12281 (70.41%) 4831/4996 (96.7%)      208/208 (100%)

```

---
Tags: commerce, i18n-l10n
---


# Question
Title: Redirect timer on successful WebForm submition
I'm asked to introduce auto-redirect (to the home page) on the confirmation page of WebForm (i.e. when user sends data, he gets on the page saying "Thank you! You submition has been received, etc..." ). And I'm asked to make a redirect after some time having past, let,s say, 10 seconds.

Seems that I have to introduce some js altering but I don't know how to do this properly.

Thank you!

# Answer
Add this code in `webform-confirmation.tpl.php`

```
$(document).ready(function() {
  var delay = 10 ;
  var url = "http://google.com";
  function countdown() {
  setTimeout(countdown, 1000) ;
  $('.webform-confirmation').html("Redirecting in "  + delay  + " seconds.");
  delay --;
  if (delay < 0 ) {
  window.location = url ;
  delay = 0 ;
  }
 }
countdown() ;
});

```
> 1 votes

# Answer
Well if you are new in drupal I will explain it to you step by step:

1. first create a file in 'sites/all/themes/yourtheme/js/' called auto\_redirection.js and inside of it paste the code above. (if you do not have the js folder just create one!)
2. create a file in 'sites/all/themes/yourtheme/templates' called webform-confirmation-'form id'.tpl.php without the quotes, optional you can just let it webform-confirmation.tpl.php and it will be applied to all the webforms confirmations.
3. go to 'sites/all/modules/webform/templates/webform-confirmation.tpl.php' and copy the content of that file and paste it into your own webform-confirmation-'form id'.tpl.php you already created.

3.Inside the file webform-confirmation-'form id'.tpl.php just add this at the end

`drupal_add_js(drupal_get_path('theme', 'yourtheme') . '/js/auto_redirection.js');`

do not forget to replace 'yourtheme' for the name of your theme or subtheme... and put the php tags for the above code, for some reason I cannot write the php tags here jeje.

Thats all you need hope it helps someone
> 1 votes

# Answer
Use this script instead if you want to display a thank you message and the counter in the message.

```
    var counter = 10;
setInterval(function() {
    counter--;
    if(counter < 0) {
        window.location = 'http://www.google.com';
    } else {
        document.getElementById("count").innerHTML = counter;
         }
}, 1000);

```

add a span with id=count at the message to display the counter.

if found the script here: https://stackoverflow.com/a/12498244/3357085
> 0 votes

---
Tags: webforms, redirection
---


# Question
Title: How to theme the PAGE template for user account?
The user account page should have the title(name or username),user pic on the left, basic details like gender, city, state and country to the right. The local tasks tab should be available below those regions.

I tried page--user.tpl and page--user--profile.tpl. Doesn't work.

Am using drupal 7 with an adaptive sub theme and don't know PHP much.

# Answer
If you are looking for the right template suggestion for user page which holds all user profile data then you should go with page--user--%.tpl.

Just imagine you want to remove the title on all user pages. removing it on page--user.tpl will remove it on all user pages like user/login, user/register, user/pass, etc.

Use page--user--%.tpl to do it only on user profile pages.

Checkout what i was able to do with mine.
> 0 votes

# Answer
it can be override with `user-profile.tpl.php` file.

> Default theme implementation to present all user profile data.
>
> This template is used when viewing a registered member's profile page, e.g., example.com/user/123. 123 being the users ID.

REF here
> 1 votes

---
Tags: theming, routes
---


# Question
Title: How to add html to the "My user points" page (user points module)
I am building a Drupal 7 site using the User Points module.

I have some issues that I am not able to solve, you can see the issue here. I can go around these issues if I will be able to edit the HTML of the "my user points" page (the page that every user can see the points he got and the reason he got them).

1. Mainly, I want to add a link in this page, that will link to another page on my site.
2. In addition, I want to add some text beneath the title of the page (original title).
3. Third thing I want to do is make sure the output on the "Reason column" will be longer, and won't cut off and be too short with "..." in the end.

How can I achieve that?

Where and how I can find the HTML of this page, and edit & add some HTML code?

# Answer
You can find the menu path defined for " My User Points " page in userpoints.module file in hook\_menu implementation..

```
  $items['myuserpoints'] = array(
    'title' => 'My !points',
    'title arguments' => userpoints_translation(),
    'page callback' => 'drupal_get_form',
    'page arguments' => array('userpoints_list_transactions'),
    'access callback' => 'userpoints_access_my_points',
    'file' => 'userpoints.pages.inc',
    'type' => MENU_NORMAL_ITEM,
    'menu_name' => 'user-menu',
  );

```

As you see above..

Page callback drupal\_get\_from with arguments "userpoints\_list\_transactions" is defined in "userpoints.pages.inc" file...

```
/**
 * Displays a detailed transaction report for an individual user.
 *
 * @param $account
 *   For which account to display. Defaults to the current user.
 */
function userpoints_list_transactions($form, &$form_state, $account = NULL, $tid = NULL) {

  // If this is an AJAX request, update $_GET['q'] so that table sorting and
  // similar links are using the correct base path.
  if ($_GET['q'] == 'system/ajax') {
    $q = 'myuserpoints';
    if (!empty($account)) {
      $q = 'user/' . $account->uid . '/points';
    }
    $_GET['q'] = $q;
  }

  if (empty($account)) {
    global $user;
    $account = $user;
  }

  $settings = array(
    'show_user' => FALSE,
  );
  $header = userpoints_get_transaction_header($settings);

  $query = db_select('userpoints_txn', 'p')->extend('PagerDefault')->extend('TableSort')
    ->fields('p')
    ->condition('p.uid', $account->uid)
    ->orderByHeader($header)
    // Enforce consistent sort order.
    ->orderBy('p.txn_id', 'DESC')
    ->limit(variable_get(USERPOINTS_REPORT_LIMIT, 10));

  if (module_exists('taxonomy')) {
    $query->leftJoin('taxonomy_term_data', 't', 'p.tid = t.tid');
  }

  $unapproved_query = db_select('userpoints_txn', 'p')
    ->condition('uid', $account->uid)
    ->condition('status', USERPOINTS_TXN_STATUS_PENDING);
  $unapproved_query->addExpression('SUM(points)');

  $values = userpoints_filter_parse_input($form_state, $tid);
  $active_category = userpoints_filter_query($query, $values);
  userpoints_filter_query($unapproved_query, $values);

  if (isset($active_category)) {
    drupal_set_title(t('!Points for @username (%category category)', userpoints_translation() + array('%category' => $active_category, '@username' => format_username($account))), PASS_THROUGH);
    $total_title = t('Total !points (%category category)', userpoints_translation() + array('%category' => $active_category));
  }
  else {
    drupal_set_title(t('!Points for @username', userpoints_translation() + array('@username' => format_username($account))));
    $total_title = t('Total !points', userpoints_translation());
  }

  $rows = array();
  foreach ($query->execute() as $transaction) {
    $rows[] = userpoints_get_transaction_row($transaction, $settings);
  }

  // Store context in the output array so that modules have access to it.
  $output = array(
    '#account' => $account,
    '#attached' => array(
      'css' => array(
        drupal_get_path('module', 'userpoints') . '/userpoints.css',
      ),
    ),
  );

  $output['form'] = userpoints_filter_form($account, $values);

  $output['list'] = array(
    '#type' => 'container',
    '#id' => 'userpoints_list_wrapper',
  );
  $output['list']['table'] = array(
    '#theme' => 'table',
    '#header' => $header,
    '#rows' => $rows,
    '#empty' => t('No !Points earned', userpoints_translation()),
    '#weight' => -5,
    '#attributes' => array('class' => array('userpoints-myuserpoints-list')),
  );
  $output['list']['pager'] = array(
    '#markup' => theme('pager'),
    '#weight' => 0,
  );

  // Fetch pending (not yet approved) points according to the category filter.
  $pending = (int)$unapproved_query
    ->execute()
    ->fetchField();

  // Display both pending and approved points in a simple table.
  $output['list']['summary_table'] = array(
    '#theme' => 'table',
    '#header' => array(
      array(
        'data' => $total_title,
        'colspan' => 2,
      ),
    ),
    '#rows' => array(
      array(
        'data' => array(t('Approved !points', userpoints_translation()), userpoints_get_current_points($account->uid, isset($values['tid']) ? $values['tid'] : 'all')),
        'class' => array('userpoints-myuserpoints-total-approved'),
      ),
      array(
        'data' => array(t('Pending !points', userpoints_translation()), $pending),
        'class' => array('userpoints-myuserpoints-total-pending'),
      ),
    ),
    '#weight' => 10,
    '#attributes' => array('class' => array('userpoints-myuserpoints-total')),
  );

  // For simplicity, the generated output is passed to a custom alter function.
  // This would also be possible through hook_page_alter(), but that hook is
  // hard to use.
  drupal_alter('userpoints_list_transactions', $output);

  return $output;
}

```

In the end you can see generated output is passed to a custom alter function

```
  drupal_alter('userpoints_list_transactions', $output);

```

By implementing hook\_TYPE\_alter() in your custom module you can able to change the output.. i.e YOURMODULENAME\_userpoints\_list\_transactions\_alter function you need to implement..

```
/**
 * Implements hook_userpoints_list_transactions().
 */
function MODULENAME_userpoints_list_transactions_alter(&$output) {
  // you can now change $output directly here
}

```

$output is a form variable.. You can add a new element to $output ..

```
/**
 * Implements hook_userpoints_list_transactions().
 */
function MODULENAME_userpoints_list_transactions_alter(&$output) {
  // you can now change $output directly here
  $output['custom_text']['my_link'] = array(
    '#markup' => l("LINK", "Your Link"),
  );
  $output['custom_text']['my_text'] = array(
    '#markup' => 'Blah Blah',
  );
}

```
> 2 votes

---
Tags: userpoints
---


title: node theming doesn't work

text:
# Question
Title: node theming doesn't work
I am a Drupal beginner. I'm using Drupal 7. I created a blog using views. I'm trying to theme the blog node using `node--blog.tpl.php` but it doesn't work. When I change it to simply `node.tpl.php` it works. I don't know what is the problem. How can I make it work?

# Answer
That's a known issue in some Drupal versions: Drupal will not pick up node--blog.tpl.php from your theme directory unless there is node.tpl.php too. Just place them both in your theme, clear cache, and you should be fine.
> 0 votes

---
Tags: theming, nodes
---


# Question
Title: How to use ctools modal to popup some fields of a node on node view?
I want when a user is viewing a node, some of the node fields will be shown as a popup (without any buttons). How can I do it?

Thank You!

# Answer
> 2 votes
I know that there is no codeWriting service here, but I can try to explain (with example) the process (not a universal way.. Will work only with the content the same type and same structure (suppose we have a content type with `body`, `field_description` and `field_something`)):

* You need to customize (override) template of the content type:

**example** (node--MY\_CONTENT\_TYPE.tpl.php):

```
<div id="node-<?php print $node->nid; ?>" class="<?php print $classes; ?> clearfix"<?php print $attributes; ?>>
  <div class="body-field">
    <?php print render($content['body']); ?>
  </div>

  <div class="description-field">
    <?php print ctools_modal_text_button(t('Click to see DescriptionField'), 'show-as-a-popup/' . $node->nid .'/field_description/nojs', t('DescriptionField'), 'ctools-modal-custom-modal-style'); ?>
  </div>

  <div class="something-field">
    <?php print ctools_modal_text_button(t('Click to see SomethingField'), 'show-as-a-popup/' . $node->nid .'/field_something/nojs', t('SomethingField'), 'ctools-modal-custom-modal-style'); ?>
  </div>
</div>

```
* Create custom module
* Create a function in `my_module.module` file which includes ctools' libraries and sends javascript settings:

example:

```
function _myModuleIncludesModal() {
  static $added = FALSE;
  if ($added == FALSE) {
    $added = TRUE;

    ctools_include('modal');
    ctools_include('ajax');
    ctools_modal_add_js();

    $customModalStyle = array(
      'custom-modal-style' => array(
        'modalSize' => array(
          'type' => 'fixed',
          'width' => 800,
          'height' => 'auto',
          'addWidth' => 20,
          'addHeight' => 20,
          'contentRight' => 20,
          'contentBottom' => 20,
        ),
        'modalOptions' => array(
          'opacity' => (float) 0.6,
          'background-color' => '#000000',
        ),
        'closeText' => 'Close',
        'loadingText' => 'Loading...',
        'animation' => 'fadeIn',
        'animationSpeed' => 'fast',
      ),
    );

    drupal_add_js($customModalStyle, 'setting');
  }
}

```

example:

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

  $items['show-as-a-popup/%node/%/%ctools_js'] = array(
    'title' => 'Node Field',
    'page callback' => 'nodeFieldPopupCallback',
    'page arguments' => array(1, 2, 3),
    'access callback' => 'user_access',
    'access arguments' => array('access content'),
    'type' => MENU_CALLBACK,
  );

  return $items;
}

```
* Create a callback function:

example:

```
function nodeFieldCallback($node, $fieldType, $js = NULL) {
  if (!$js) {
    drupal_access_denied();
    drupal_exit();
  }

  ctools_include('modal');
  ctools_include('ajax');

  $nodeWrapper = entity_metadata_wrapper('node', $node);

  $output = $nodeWrapper->{$fieldType}->value();

  $return[] = ctools_modal_command_display(t('PoPUp'), $output);
  print ajax_render($return);
  drupal_exit();
}

```
* Finally call our `_myModuleIncludesModal()` in "specific" node pages:

example (template.php):

```
function MY_THEME_preprocess_node(&$variables) {
  if($variables['type'] == 'MY_CONTENT_TYPE') {
    _myModuleIncludesModal();
  }
}

```

Modal settings/options, templating and throbber templating can be found in `ctools' help` directory; Don't forget to flush the cache;

---
Tags: chaos-tool-suite, nodes, javascript
---


title: Remove "comment delete" confirm page

text:
# Question
Title: Remove "comment delete" confirm page
When I click on the "Delete comment" link, I get redirected to a page that tells me to confirm the action. How can I avoid this redirection, as I have build a pop-up that asks for confirmation?

# Answer
The comment/%/delete menu entry is wired directly to the comment\_confirm\_delete\_page form. You can modify it with with a hook\_menu\_alter, and change the function from drupal\_get\_form to a page callback of your own design that will just delete the comment.

Example:

In your module file you'd need:

```
function mymodule_menu_alter(&$items) {
  $items['comment/%/delete']['page callback'] = 'my_comment_delete_function';
  $items['comment/%/delete']['page arguments'] = array(1);
  $items['comment/%/delete']['module'] = 'mymodule';
  $items['comment/%/delete']['file'] = 'mymodule.pages.inc';
}

```

And in your mymodule.pages.inc file you'd need:

```
function my_comment_delete_function($cid) {
  if ($comment = comment_load($cid)) {
    comment_delete($comment->cid);
    drupal_set_message(t('The comment and all its replies have been deleted.'));
    watchdog('content', 'Deleted comment @cid and its replies.', array('@cid' => $comment->cid));
    // Clear the cache so an anonymous user sees that his comment was deleted.
    cache_clear_all();

    drupal_goto("node/$comment->nid");
  }
  return MENU_NOT_FOUND;
}

```
> 4 votes

---
Tags: 7, comments
---


title: How to secure individual fields

text:
# Question
Title: How to secure individual fields
I am looking for a good way to add security at a field level based on a group. Different groups will use the same content type. Does OG handle this requirement. I don't want to make the full node private.

# Answer
> -1 votes
I think you are looking for Field Permission module. It says :

> The Field Permissions module allows site administrators to set field-level permissions to edit, view and create fields on any entity.

---
Tags: users
---


# Question
Title: What are the template variables to identify that a page is a term or user?
I'm trying to modify a theme so that when the term page or user profile page are displayed it doesn't generate the title at the top. I figured out how to do it on nodes but I just can't figure out what variable is used in the following code to identify a user or term page. Any thoughts?

Here's the code from my page.tpl.php in a Bootstrap v3 theme:

```
<?php if (!isset($node)): ?>
   <h1 class="page-header"><?php print $title; ?></h1>
<?php endif; ?>

```

The above example suppresses the title when the page being viewed is a node. I'd like to get this to work for user and term pages as well.

# Answer
> 4 votes
I think a better way to hide the title on user and taxonomy term pages would be to use a preprocess\_page function in your themes template.php. This way you are keeping your page.tpl.php cleaner and separating logic.

```
/**
* Implements hook_preprocess_page
*/
function MY_THEME_preprocess_page(&$variables) {
    if( (arg(0)=='user' && arg(2)=='') || (arg(0)=='taxonomy' && arg(1)=='term' && arg(3)=='') ) {
        $variables['title'] = FALSE;
    }
}

```

This will only hide the title on the view pages, but it will still be there when editing content. This is done by checking that arg(2) is empty on user pages and arg(3) is empty on taxonomy term pages as if editing content these would contain the string "edit".

As pointed out by clive the line in your page.tpl.php would need to read:

```
<?php if ($title): ?>
   <h1 class="page-header"><?php print $title; ?></h1>
<?php endif; ?>

```

Once you have added this code then you will need to clear the cache to see the changes.

# Answer
> 3 votes
There aren't any by default, but you can add them easily enough using `hook_preprocess_page()`:

```
function MYTHEME_preprocess_page(&$vars) {
  if ( ($term = menu_get_object('taxonomy_term', 2)) ) {
    $vars['term'] = $term;
  }
  elseif ( ($account = menu_get_object('user', 1)) ) {
    // Best not to use $vars['user'], it'll only overwrite something.
    $vars['user_page_account'] = $account;
  }
}

```

And then in the template file:

```
if (isset($term)) {
  // term page
}
elseif (isset($user_page_account)) {
  // user profile
}

```

You might find false positives in there, as you'll get (for example) a term object on the `taxonomy/term/[id]/edit` page. Whether that affects you will depend on what theme you're using for what page. If it's a problem, you can use `arg()` to check what's in the URL, e.g.

```
if ( ($term = menu_get_object('taxonomy_term', 2)) && !arg(3)) {
  ...

```

# Answer
> 1 votes
I tried both of the methods indicated and for various reasons they didn't quite work. Thus I opted for a css option. I added this to my css code for users and I'll add it for nodes and terms as well. Problem solved-ish. It's not elegant and it ends up making some of my pages looks a bit odd but it does work.

```
body.page-user h1.page-header {
  display: none;
}

```

---
Tags: 7, theming
---


# Question
Title: What is the protocol for adding a new module dependency to a module that has only had a dev release?
I created a module a while ago and it has only had a 7.x-1.x-dev release on Drupal.org for the last month or so. There are a number of reported downloads and installs already for this module so I want to make sure that the handful of users that already are using this module are still considered in the next dev release I need to make. The new release will have a new module dependency that is from another project (i.e. not included as a submodule of mine). While I would normally create a 2.x version if the module had a stable release, it has only been in dev. Do I just go ahead and add the new dependency in the 1.x-dev or create a 2.x-dev?

# Answer
> 3 votes
There's no sanctioned protocol for such a case. All I think of is to minimize the impact.

Consider that even if you create a new branch, users may update and neither realize there's a new dependency, and your module may end up silently disabled because of unmet dependencies. This happened to the update of views from 6.x-2.x to 6.x-3.x where a dependency on ctools was added. In that case, the impact was low because ctools usually is present.

On documentation, in addition to changelog or upgrade doc in the project page, I suggest to add it to the release notes. Since they can be read easily when updating with drush.

Last, if the dependency you're introducing is a popular module, you can alleviate the impact by enabling the new dependency in hook\_update\_N or raising an error if not available. Here's some untested code:

```
<?php
function MODULENAME_update_7001() {
  $enabled = module_enable(array('foo', 'bar'));
  if (!$enabled) {
    throw new DrupalUpdateException('foo required.');
  }
}

```

# Answer
> 0 votes
Apart from what @jonhattan has mentioned, I would suggest one more method to do it. Add those dependency in the mymodule.info file. Lets assume you want to add new dependency to link, email and addressfield.

```
dependencies[] = link
dependencies[] = email
dependencies[] = addressfield

```

Now in hook\_requirments try to enable the modules automatically if present. Please note that since we have added dependencies in info file, those would be enabled if its a first time install. But otherwise they would appear "locked". In this case we would have to enable them automatically. Now as @jonhattan have answered you could try to do it in hook\_update\_N and throw an exception when it fails.

But the problem with the above method is the user experience. You cannot output "links" in the exception message. Another is it could be easily be avoided by letting the user know right before an update is attempted. For such case we have hook\_requirements.

I will provide an example how to use hook\_requirements for the example case i have mentioned.

```
/**
 * Implements hook_requirements.
 */
function mymodule_requirements($phase) {
  $requirements = array();
  if ($phase == 'update') {
    $enabled = module_enable(array('link', 'email', 'addressfield'));
    if( !$enabled ) {
      $t = get_t();
      $requirements['mymodule_migrate'] = array(
        'title' => $t('Mymodule Migrate Issues'),
        'value' => $t('One or more of the required modules cannot be enabled.
          If you download the modules from Drupal.org those would be enabled automatically when update script is run.
          So Please make sure following modules are present: !link, !email & !addressfield',
          array(
            '!link' => l('link', 'https://drupal.org/project/link'),
            '!email' => l('email', 'https://drupal.org/project/email'),
            '!addressfield' => l('addressfield', 'https://drupal.org/project/addressfield'),
          )
        ),
        'severity' => REQUIREMENT_ERROR,
      );
    }
  }
  return $requirements;
}

```

Now it is also possible to try to enable each module individually and craft the message properly so that only those modules that are absent are shown in the message.

---
Tags: 7
---


# Question
Title: How to use Solr Index to display node in a Google Map
For several months I am wondering how to achieve this task.

I want to display information from Solr index (preferably Search Api Solr ) directly in a map. The main goal is to have a map where is displayed some nodes, and to have the ability the use facet filters and fulltext filter.

Exactly the same as a typical use of Search Api Solr (example: http://ygerasimov.com/ajaxified-solr-search-drupal-search-api-views-panels) but using a map instead of a table.

Something like this: http://vps10937.ovh.net/x/map/node, but with Solr features. This page is part of the Location Module and the Gmap Module.

Here is two examples (not drupal) close to what I want to do:

http://www.trulia.com/for\_sale/New\_York,NY/x\_map http://www.conflicthistory.com/#/period/1495-1500

Thank you

# Answer
> 4 votes
I have been able to accomplish this task following these steps:

* Installed modules for search: search\_api, search\_api\_location, search\_api\_solr search\_api\_views, search\_api\_facetapi, Search API location views
* Installed modules for "geosearch": geofield (to store lat, lon...), addressfield (make it easier for users to enter an address and don't worry about geolocation).
* Installed modules for mapping: leaflet, leaflet\_more\_maps (for more maptiles options out of the box).
* Solr server 4.7.1 (I've just downloaded today)

So, with all these things, my goal is to have a view with an exposed full text field and show the results in a map (and afterwards be able to facet this view).

I've started like this:

1. Create a content type with address field and geofield fields
2. Set geofield field widget to "Geocode from another field" (and geocode from Address field using google geocoder). Not multivalued fields allowed here.
3. Create a solr server and make sure it runs ok.
4. Create an index connecting with the solr server (Remember this name for later)
5. Add fields to the index, just making it simple:

a) nid

b) title

c) Save changes

d) Add related fields (collapsible fieldset right bellow save button)

e) We choose "Geofield" (Watch out here, if you share the geofield field between two or more different content types, you need to add this field twice or more and it is not easy to distinguish them because they have same name in the UI)

f) Now we have added geofield as related field, we should have the option to choose "Geofiled » LatLong Pair" and as type "Latitude/longitude" as a field for indexing in solr
6. Disable the index, disable the server, enable the server and enable the index, and some clear cache between them. Important to do this.
7. Once we have server and index enabled, just index all items.
8. If we now go to the solr interface, and run a query for all results, we should see a field (among the others we have indexed) which is called something like "locs\_your\_field\_name$latlon" (Notice here that older versions use ":" instead of "$" ). If you can't see it, review before steps.
9. Now we can set up a simple view:

a) Create a new view

b) Set up a name and description for the view

c) Select "Show" (content is default, we want to change this): The name of the index that you set before, Remember?

d) Create a page: "myviewpath"

e) Save

f) Select fields: "Indexed Node: Node Id" and "Indexed Node: Geofield"

g) Filter criteria: "Search: Fulltext search" -\> Exposed filter

h) Format: Unformated list

i) Test and see if we have results, if not, something went wrong, review.

j) Format (again): "Leaflet Map"

k) Data Source: Indexed Node: Geofield

l) Title field: Indexed Node: Nid

m) Description: Indexed Node: Nid

n) Map: Choose from list the one you like the most

o) Map height: 400px

p) Save format

q) Save view. At this point, the map is not visible (in views UI), but if everything is ok...
10. Go to the path of your view: You should see all results in the map (if you have the default solr server configuration). If not, try to type some text and see if you get the expected results...

Hope this helps!

# Answer
> 0 votes
You can use the Openlayers Apachesolr integration module. This will create a map with your content. This uses apachesolr not search api solr. You can however use facet API to achieve almost what you want.

---
Tags: search, location, google-maps
---


title: add fields directly to node table?

text:
# Question
Title: add fields directly to node table?
Is it a good idea to add field directly to the node table via db\_add\_field and schema\_alter? e.g. i want to add just number of views field to it. I know the recommended approach is field api but find it kind of overkill to create a new table just for a simple field like that. Let me know your views on that approach.. has anyone done it in a project?

# Answer
Perhaps this is not drupal standard, sometimes is needed to do things like that.

I prefer to create my own entities that to modify the node entity. This way if you use entity api as base this is integrated with views out of the box. Another approach to that not require coding is ECK module, you can define properties to the entity and this will be added on the same entity table as and extra column.
> 3 votes

---
Tags: entities
---


# Question
Title: Duplicating drupal site without login info
I'm a new Drupal user.

Someone gave me a backup of their Drupal and .mysql content. I more or less followed these instructions: http://www.ostraining.com/blog/drupal/drupal-migrate/, except the site already had it's own settings.php, and so the site is now up and running.

The problem that I'm having now is that I can't log into the site to make any edits because I don't have a login. I tried to create an active user in phpmyadmin with an md5 hash password, and changed the user to an administrator. However I'm still not successfully logging in, the site says I'm still giving it the incorrect login info. When I try to recover/reset my password by email I am not receiving any emails. I am using Windows XP.

Is there any way I will be able to login to edit the site?

# Answer
> 1 votes
One way of solving your issue would be to update super admin (first user) password pragmatically, by creating a temporary php file under Drupal root folder and add the following code to it then access it from a browser.

```
<?php

define('DRUPAL_ROOT', getcwd());
require_once DRUPAL_ROOT . '/includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);

// load super admin user
$account = user_load(1);

// save user password
user_save($account, array('pass' => 'admin'));

echo "Super admin password has been changed";

```

Make sure to replace **admin** with desired password

# Answer
> 1 votes
The below SQL query would set the username and password of super admin user (uid 1) to admin and drupal respectively.

*For d6 : UPDATE users SET name='admin', pass=md5('drupal') WHERE uid = 1;*

*For d7 : UPDATE users SET name='admin', pass='$S$Drl0vgZ9yuU9uc4JyaTMHxMPriC7q/PsOUOx52fCrVQSTpI/Tu4x' WHERE uid = 1;*

where $S$Drl0vgZ9yuU9uc4JyaTMHxMPriC7q/PsOUOx52fCrVQSTpI/Tu4x is the encrypted text for password *drupal*. To generate hash text for different plain text Drupal ships with a php script password-hash.sh, cd to drupal root directory and run command "php scripts/password-hash.sh 'mynewpassword'" from command prompt to get encrypted password.

Source: http://knackforge.com/blog/sivaji/different-ways-reset-drupal-admin-password

# Answer
> 0 votes
You say:

> When I try to recover/reset my password by email I am not receiving any emails.

You first need to set the e-mail address of the admin user (that is user #1) to your *own* e-mail address. You can do that using *phpMyAdmin*. Just change the field `mail` to your address in the table `{users}` for user with `uid` = 1. Also make a note of the user name of that user (that's in the field named `name`).

Now try to login with the user name of user #1. That will of course not work, but when you get the message:

> Sorry, unrecognized username or password. Have you forgotten your password?

you can request a password reset, and it will be sent to your e-mail address.

If you have *drush* installed, the following *drush* command will also reset the admin password (provided the admin user is named `admin`):

```
drush upwd admin --password=<new_password>

```

# Answer
> -2 votes
drupal's admin uid is 1

in you phpmyadmin sql or mysql shell

view query to check admin record: select * from users where uid=1;

update query: UPDATE users SET pass = MD5('test') WHERE uid=1;

---
Tags: users, migrations
---


title: Automatic product variations pricing

text:
# Question
Title: Automatic product variations pricing
I have a site where a client wishes to sell products that have a lot of different variations (ie size, colour, length etc), but each of these will make a slight change to the price. I know about the ability to make variations of products so that the price changes when you pick different items in the drop downs, but these have to be manually entered. For my client, each time the variations are open to the end user, the price increase will always be the same.

Both have the size option available to user -the price will increase on top of the base price by the same increment based on the selection.

eg: Small = no change Medium = +£5 Large = +£10

Product A, starting price: £10 Product B, starting price: £20

So Product A with medium will be £15, Product B with large would be £30

I realise in this example it would be simple to add this in manually, but if she has 3 (or more) different options open to the end user, with upto 10 options within, multiplied by her entire product range, it would take forever to do.

What I had thought is if it was possible to add a price addition field to the product category listing, and then use a (rule/module?) to automate this price being added on. Is there anything already out there that does anything like this, or if not, how could I go about creating it.

Many thanks

# Answer
How about the Commerce Customizable Products Module. I just saw this video today, maybe it will help.

> Drupal Commerce allows you to sell customizable products that require customer input when added to the cart. Use cases for this functionality include:
>
> * Business cards that require contact information and a logo upload.
> * Event registrations that require attendee information.
> * Donations the allow the customer to specify a donation amount.
>
> The core Line Item module accommodates these scenarios by letting you add any number of fields to the Product line item type and expose them to the Add to Cart form. However, sites that sell multiple types of customizable products or a mixture of customizable and non-customizable products need to define multiple line item types to handle the different configurations of fields. That's where this Customizable Products module comes in!
>
> It gives you the ability to define new line item types on the fly at Administration \> Store \> Configuration \> Line item types. This is functionally equivalent to defining the new line item type in code, which is still recommended if you are able.
> 1 votes

# Answer
You can handle price using commerce Rules integration.

I can suggest you store your product attributes(size, color, lenght and etc) in taxonomy vocabularies.

Add custom field to your size, color, lenght and etc. vocabulary and name it for example `price_increment`.

**Step1:** Set price increment price step per each term.

E.g. Small = empty, Medium = 5, Large = 10.

**Step2:** Go to priring rules and create new one.

Set the price value using rules:

1. Get referenced term of product(e.g. color)
2. Check if term's field `price_increment` is not empty
3. Set product price to `price + price_increment`

P.S. You can create rule for each product attribute(like color, size etc). Or you can create Rule set.
> 1 votes

# Answer
theres commerce\_pricing\_attributes now, sounds like the module you want:

> This module provides some enhancements to the Commerce Product Option and Commerce Product Attributes handling by applying pricing rules to custom product attributes. So, you can add attributes to products that affect the final product price.
> 1 votes

# Answer
Based on the explanation above, I feel you need to have a module like 'product attributes' which is available for Ubercart. Using attributes you can have different level of pricing and once the customer selects one of the level that particular price will be added to cart.

Here the base price of a product will always be normal eg: $100. If you make one of the attribute as $50 the total cost of the product for that level will become $150.

similarly you can configure for other levels too.

For every attribute you can set a default value on the settings page.

While publishing the product client can select the corresponding attributes for every product.
> 0 votes

---
Tags: commerce, rules
---


# Question
Title: Multiple hook_menu_alter over-writing issue
I want to customize my menu by using hook\_menu\_alter by over-writing another installed module, which also has a hook\_menu\_alter inside.

I check the procedure using xdebug, finding that drupal execute my hook\_menu\_alter first, and then the existing hook\_menu\_alter in that module. In this case all my alteration is being over-written. How can I reverse the order of execution?

Thanks!

# Answer
> 3 votes
You can try to change the weight of the module in the systems table but doesn't always work and can cause other issues. I would use the `hook_modules_implement_alter` function. You will need to unset yours and then add yours to the top or before the other module. Here is an example I used doing a `hook_user_delete` and `hook_user_insert`

```
function users_module_implements_alter(&$implementations, $hook)
{
  if($hook == "user_insert" || $hook == "user_delete")
  {
    unset($implementations['user']);
    $user = array('users' => false);
    $implementations = $user + $implementations;
  }
}

```

Yours would be like this:

```
function users_module_implements_alter(&$implementations, $hook)
{
  if($hook == "menu_alter")
  {
    unset($implementations['mymodule']);
    $mymodule = array('mymodule' => false);
    $implementations = $mymodule + $implementations; // Also could use array_merge
  }
}

```

---
Tags: routes
---


# Question
Title: Unable to retrieve user id of edited user from $entity in hook_field_validate
I have this little problem with a custom field that is bundled with user. In its validation function I need to have access to the user id of the user whose field is being edited.

What that means is, when I edit a user, I need to get his uid in the validation function.

The problem is that hook\_field\_validate provides just $entity variable that doesn't include uid.

I know I could load the user object using his email / name (and then retrieve the uid from it) but it wouldn't properly work when email/name was being changed (I could get only the changed values from $entity and therefore wouldn't be able to load the object properly).

Any ideas?

# Answer
You can always get this information from the path, eg:

```
// you are sitting on user/#/edit

$uid=arg(1);                      // quick, or...
$account=menu_get_object('user'); // the full user object, eg the uid is in $account->uid

```
> 1 votes

---
Tags: entities
---


title: autolink body content to node

text:
# Question
Title: autolink body content to node
I want to do this: If I enter a body in content type, on save the content type body searched and automatically link to exists node title.

As example :
**body:** The drupal is one of best CMS systems,

If I have a node with title "drupal" I want the drupal link to it automatically on save, is there any module to do this? If not appreciate any idea help me to implement it.

I found Alinks module, it similar to what I want but It not link to existing nodes, it just link to some user defined word and links.

The main problem is searching for existing node title not linking to them, we have body with many word,I want if a word equal node title that exist , it link to it

# Answer
You may consider the **FreeLinking** module.

The **Freelinking** module adds a text filter for using Wiki-style markup for creating links automatically, by searching the node body for markup. It supports a number of methods for creating the link, including *Nodetitle* (which sounds like the one you're looking for). You may even add methods by adding your own link plugin.

However, you need to indicate the text you want to be considered as a *candidate* for automatic linking by markup: i.e. by surrounding it with double square brackets. This is how your example will look like:

```
The [[drupal]] is one of best CMS systems

```

It even lets you create placeholder links to pages that has not been created yet. Both internal and external links are supported by the module.

There tutorial is about using the **Freelinking** module, with a little help from the companion **WikiTools** module, here.

If the way **Freelinking** does this is not good enough for you, here are a couple of alternative solutions:

**Alternative solution #1**: You can write your own custom text filter for this. I suspect that to create something that works during node saves without freezing or killing your site will be very hard to do.

**Alternative solution #2**: If you can accept a solution that delays the creation of links, you can place new and altered links in a queue, and then use a cron job to parse them for links. This allows you to space out the parsing of node bodies over time and will avoid the performance problems a real-time text filter would create. For the record: There exists no module that does the parsing of node bodies and add links like this. You'll need to write it yourself.
> 1 votes

---
Tags: 7
---


# Question
Title: What is the right place for Product Image
We can take image of product through Product Type or Product Display content type, I just want to know what is the right place for product images fields ?

# Answer
It is related to want you want, if you want have a product display with some variation that each variation different with each other ( different image) it is better put product image field in product , but if all product variation has equal image (or you have not product display with multi variation product ) it is better put image field in product display content type .

I hope this can helped you.
> 2 votes

---
Tags: forms, commerce
---


# Question
Title: extract a field and the link to content from all nodes
i have a content type and it stores user\_email,title,body etc.

Every node has a URL alias.

How can i go through all the node, and extract the email field + the URL of that node.

any clue . thanks

# Answer
> 4 votes
If you want get node of `page` content type ,you can try another content types

```
$type = "page"; // machine name for Basic Page
$nodes = node_load_multiple(array(), array('type' => $type));
$arr=array();
foreach($nodes as $node){
     arr[$node->nid]['email']= $node->field_email['und'][0]['value'];
     arr[$node->nid]['url_alias']= drupal_get_path_alias('node/'. $node->nid);
    }

```

# Answer
> 2 votes
You can get url of any particular node using this function

```
$alias = drupal_get_path_alias('node/102');

```

Getting email of any node use following statement

```
$node = node_load(102);
$email = $node->field_email['und'][0]['email']

```

Make sure I am getting these details of NodeID 102 in above example.

---
Tags: views
---


# Question
Title: Group results of same taxonomy term with search api and views
I have couple of products which are classified with taxonomy terms.

I am using Search API with views to display search results.

I want to show the search results in this way.

**Term 1 Name**

* product 1
* product 2
* product 3

**Term 2 Name**

* product 5
* product 8
* product 3

**Term 3 Name**

* product 10
* product 25
* product 1

What should I look into? Any idea how canIi group the results based on the term? Thank you.

# Answer
Open your views, in editing mode , in formatting section, near table, select `settings`, and then in `Grouping field Nr.1` select your taxonomy field ,save ,it makes the views result goruped by selected field in `Grouping field Nr.1`.
> 3 votes

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


title: Follow up Drupal path to PHP function

text:
# Question
Title: Follow up Drupal path to PHP function
How do I figure out which PHP function is called from a Drupal path/URL (e.g. "/mysite/?q=flag/flag/like/&destination=node/1&token=xyz")?

Thx in advance!

# Answer
You can find out from the implementing module's implementation of `hook_menu`.

In your case, look for where Flag implements `hook_menu` (in the case of Flag 7.x-3.x you're looking at `flag.module` at around line 301. Next, look for where the module declares `$items['flag/%/%flag/%']`, and look for the `page callback` array key. You can see it says `flag_page`, so you can tell the menu callback is calling the `flag_page`.

You can find the Drupal 7 documentation for `hook_menu` here.
> 1 votes

---
Tags: uri
---


# Question
Title: How to give link to edit in user profile page and node page?
I have removed all tabs of user's page and node page with the help of Tab Tamer module, but i want to keep only one tab enabled i.e "Edit".

how to enabled only tab(Edit) or a link to edit profile on the user's page and edit link on node page.

# Answer
Go to admin/config/system/tabtamer and enable tabs as you want.
> 0 votes

# Answer
The module you're using (Tab Tamer) lets you individually disable and enable each tab. Navigate to *admin » config » system » tabtamer* to do it. Note that for *any* tab to show, you need to always keep the *View* tab enabled.

See illustration below for enabling the *Edit* tab and disabling the *Revisions* tab.

If you don't want the *View* tab to show, but still want to provide users with permissions to update (i.e. edit) with a link which redirect to the edit page for the node, put the follwoing code snipped in your `node.tpl.php` in the place in the template where you want the link to appear.

```
if (node_access('update', $node)) {
  // Create link to the the edit page for the current node.
  echo l(t('Edit this node'), 'node/' . $node->nid . '/edit');
}

```
> 0 votes

---
Tags: users, navigation
---


title: Hide a Prepopulated email textfield

text:
# Question
Title: Hide a Prepopulated email textfield
I am trying to prepopulate the following fields on a commerce add-to-cart form and then hide the email field:

1. Recipient name: (textfield) = field\_recipient\_name
2. Recipient email: (email field) = field\_recipient\_email

So far i have been able to pre-populate these fields using views, panels, and prepopulate modules. My challenge is this:

If the email field is already prepopulated with a value, hide this field from the user who intends to buy a gift for the recipient, otherwise the field should be exposed so that user can manually enter the email of the gift recipient. Thanks

# Answer
Perhaps you can use the Conditional Fields module to check whether the field has a value (sort of a 'not empty' check).

Conditional Fields is described as follows:

*Conditional Fields allows you to manage sets of dependencies between fields. When a field is “dependent”, it will only be available for editing and displayed if the state of the “dependee” field matches the right condition.*
> 0 votes

---
Tags: entities
---


title: How to export workflow summary view?

text:
# Question
Title: How to export workflow summary view?
I customized the workflow summary view to make multiple views for different users/workflows.

When I try to export it with features, module.views\_default.inc is not created, no error (nor notice) message is issued, and the workflow\_summary view is deselected from the feature (re)creation form. I've created a feature with only this view, and then get an empty feature.

Is there a way to export it ?

# Answer
> 0 votes
Found that it's better to clone the view to export it as usual than edit default one.

There's also an "export" button on the view definition page that can be used to copy-paste definition manually.

---
Tags: features, workflows
---


title: How to filter nodes using date field

text:
# Question
Title: How to filter nodes using date field
I have a content type of "Class" that has a date field attached to it `field_class_date`.

When a node of the type "Class" is viewed, I would like to display links to other classes that are on the same day of that particular class.

I tried doing this with views, but couldn't quite figure it out.

# Answer
> 1 votes
To solve this, **(1)** I placed code in node--class.tpl.php which retrieved the current class date

```
$date = entity_metadata_wrapper('node', $node)->field_class_date->value->value();

```

Then, **(2)** I modified that value to get the start of the day and the end of the day ($start and $end) in the following format: **Y-m-d H:i:s**

**(3)** Perform a query using EFQ to grab a list of the nodes that share the same date:

```
$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'node')
  ->entityCondition('bundle', 'class')
  ->fieldCondition('field_class_date', 'value', array($start, $end), 'BETWEEN')
  ->fieldOrderBy('field_class_date', 'value', 'ASC');
$result = $query->execute();

```

**(4)** Loop through each result and create the content I want to display later in node--class.tpl.php

```
foreach($result['node'] as $i) {
  $node = node_load($i->nid);
  $date = entity_metadata_wrapper('node', $node)->field_class_date->value->value();
  $name = entity_metadata_wrapper('node', $instructor)->field_class_instructor->value();
  // Build a string of output that I want to display later in the $content array
  $classes_today = etc...
}

```

**(5)** Finally, I added the $classes\_today string to the $content array:

```
$content['more_classes']['#prefix'] = '<h2 class="classes-on-this-day">Classes on this Day:</h2><div class="more-classes">';
$content['more_classes']['#markup'] = $more_classes;
$content['more_classes']['#weight'] = '4';
$content['more_classes']['#suffix'] = '</div>';

```

# Answer
> 0 votes
Hi for this you can simply place a filter for date field in your view.

Select Operator as " Is equal to" and then type "NOW" in the selection for filtering.

This should filter down your class content as per present/current date.

---
Tags: views, entities, datetime
---


title: Link to Existing View from another view

text:
# Question
Title: Link to Existing View from another view
Im trying to create a view that should have a field which links to a pre-existing view (And Permissioned appropriately). Ive looked into various modules and field options but cannot find it (Newbie to Drupal!).

Basically, I have a view(called, Recipe\_Filter) where I have some filters for selecting recipes based on various conditions. I have another view where I show recipes for a particular user and also want to create an "Edit" link that points to Recipe\_filter. The problem is that I dont want normal users to see the "Edit" link and only certain roles to be able to view this.

I tried suggestions like the one in this but if I do as in that link, I see a "Edit" link and clicking on it shows a "You are not authorized to access this page" text. I would like to disable the Edit Link if the user doesnt have access.

Are there modules that will allow a link to an existing view and permission it (like how the standard "Edit to content" or "View to content" works). Any help or pointers would help a lot.

# Answer
> 0 votes
I was able to solve it using Views PHP Using some custom PHP to show the "link" only if the user has permission. Not sure if thats the most elegant way.

I would like to know if there is a better approach to solving this. Thanks!

---
Tags: views
---


# Question
Title: How to add a field to a group with form_alter
I have a group in a node set as a vertical tab, and I want to add some markup into this vertical tab via code. How can I do it?

Thanks!

# Answer
> 1 votes
Let's say that you are doing this in a module named **custom**.

First, take a look at how the form is structured using **dsm($form)** in custom.module. Make sure you have the devel module enabled and that you have permissions to see devel's output.

```
<?php

custom_form_alter(&$form, &$form_state, $form_id) {
  dsm($form);
}

```

That will give you the structure of the **$form** array, which you can then add your markup to. So, let's say that you want to add some markup to the author pane in the vertical tabs. From the output from **dsm($form)**, we see that we are working with **$form\['author'\]**.

So, in **custom\_form\_alter()**, we simply add the markup element we desire using the standards documented in the Drupal 7 Form API.

In the code below, I also give the custom element (which I have aptly named "custom") a weight, so it appears above the other elements.

```
/**
 * Implements hook_form_alter().
 */
function custom_form_alter(&$form, $form_state, $form_id) {
  // Add custom markup to the "Authoring Information" tab when adding or editing a page.
  if ($form_id == 'page_node_form') {
    $form['author']['custom']['#markup'] = 'Text goes here';
    $form['author']['custom']['#weight'] = -9;
  }
}

```

Also, rather than using an if statement to target the form id, I could have used **hook\_form\_FORM\_ID\_alter()**, like this:

```
/**
 * Implements hook_form_FORM_ID_alter().
 */
function custom_form_page_node_form_alter(&$form, $form_state, $form_id) {
  // Add custom markup to the "Authoring Information" tab when adding or editing a page.
  $form['author']['custom']['#markup'] = 'Text goes here';
  $form['author']['custom']['#weight'] = -9;
}

```

# Answer
> 0 votes
Actually I found a solution:

```
$form['markup'] = array(
  '#markup' => '<div>markup</div>',
);
$form['#group_children']['markup'] = 'group_NAME';

```

---
Tags: 7, entities
---


title: how to give read more link in a block?

text:
# Question
Title: how to give read more link in a block?
I have a views block which display user's detail like name, picture and about. i want to give a read more link in "about" field, by click "read more" link the trimmed "about" will open in the same block.

"About" is a field from view, so in this field text will trim after 200 words if the about field is more then 200 words then after trimmed part there will be a read more link and after clicking this link the whole text will visible on the same position just increase the height of the block.

Thanks

# Answer
jQuery expander module will work for you.

You will have to select expander from formater options in views field configuration.
> 1 votes

---
Tags: views, blocks, users, entities
---


# Question
Title: How to connect to multiple Databases in Drupal 7?
I'm building an encyclopedia website. There are about 20 subjects that must be stored in the Database (media,library,article,translations,...) and we want to create 20 databases and allocate one DB for every subject. is it possible to do such thing? The main site has 3 sub domains and every sub domain covers specific rows of the subjects. for example the `library` is a subject and `math.mainsite.com` must have access only to the math type of the library subject.

the sub-domains must not have not any data, they all should get their data from the 20 above mentioned DBs, so every site must connect to 20 DB.

We selected this strategy because the subjects are subdomain as well, I mean `library.mainsite.com` and `article.mainsite.com` and ... are valid urls.

thanks

# Answer
Two steps:

1. Add database credentials to the `$databases` array in `settings.php` file. You can have as many additional databases as you want. Example code:

```
$databases = array (
  'default' =>
  array (
    'default' =>
    array (
      'database' => 'YOUR_DEFAULT_DATABASE',
      'username' => 'username',
      'password' => 'password',
      'host' => 'localhost',
      'port' => '',
      'driver' => 'mysql',
      'prefix' => '',
    ),
  ),
  'your_second_db_alias' =>
  array (
    'default' =>
    array (
      'database' => 'YOUR_SECOND_DB',
      'username' => 'username',
      'password' => 'password',
      'host' => 'localhost',
      'port' => '',
      'driver' => 'mysql',
      'prefix' => '',
    ),
  ),
);

```
2. Use the following code to change the database and run queries. Note that you must switch back to the original database afterwards.

```
// Change active database.
db_set_active('your_second_db_alias');
// Run queries.
$query = db_query("SELECT * FROM yourtable");
// IMPORTANT: return current active database to the default one. If you
// don't do this, everything after that point will be executed against the
// above database, and cause errors most probably. If you are connecting
// multiple Drupal installations, you can cause a pretty big mess if data is
// partially saved in the other database.
// Always double check that you have this line!
db_set_active();

```

Hope this helps!
> 5 votes

---
Tags: database, subsites
---


# Question
Title: how to integrate libraries to load third party files in themes drupal?
I just want to know how to integrate third party files with the drupal theme.

# Answer
> 1 votes
To use a CSS/JS library with the Libraries module in Drupal, there are a number of steps:

* copy the library to `sites/all/libraries/my-library`;
* Write a small custom module, which informs Drupal that the library is available;
* Add the library where's its needed, e.g. with a `MYTHEME_preprocess_html` hook.

I found a very nice recent tutorial with code samples here.

---
Tags: theming
---


# Question
Title: Modify the page title of view and set custom title for it
I am using views and drupal 7 . I pass arguments in the URL and i want this as view page title. This is possible by using override title check-box. But i want to modify this title. i.e do some formatting and some trim of the content and show only what i require as title. how can i do it.

# Answer
> 7 votes
If I'm not mistaken, you cannot do that from the user interface. However, you can implement a hook in a custom module, take the available variables, apply your own logic and set the title you want.

You can find an example on Set page title for view in Drupal.

```
function HOOK_views_pre_render(&$view) {
  if ($view->name == 'taxonomy_term' && $view->current_display == 'page') {
    drupal_set_title('Your Page Title');
  }
}

```

# Answer
> 14 votes
Found one that works

```
function MYMODULE_views_pre_render(&$view) {
  if ($view->name == 'menu') {
    $view->build_info['title'] = "TEST TITLE";
  }
}

```

# Answer
> 8 votes
I had a similar question in a slightly different context, When and where does Panels get the title out of a View?

My solution was

```
function foo_views_pre_view (&$view, &$display_id, &$args)
{
  $view->display[$view->current_display]->display_options["title"] =
  $view->display[$view->current_display]->handler->options["title"] = "Foo";
}

```

# Answer
> 5 votes
You can use `$view->set_title()`.

```
function mymodule_preprocess_views_view(&$variables) {
  $view = $variables['view'];
  if ($view->name == 'machine_name' && $view->current_display == 'display_machine_name') {
    $view->set_title('New Display Title');
  }
}

```

# Answer
> 2 votes
Instead of using a separate module, I added the following code to the theme I am using.

```
/**
 * THEME_PREPROCESS_VIEWS_VIEW
 * @param type $vars
 *
 */
function MYTHEME_preprocess_views_view(&$vars) {
  // view block
  if ($vars['view']->name == 'viewName') {
      //update your title
      $vars['view']->build_info['title'] = '---Title---';
    }
}

```

Replace MYTHEME with the machine name of the theme you are using. Add the code I shown in the template.php file of the theme.

# Answer
> 1 votes
You can implement `hook_views_pre_render()` in a module.

```
/**
 * Implements hook_views_pre_render
 */
function MYMODULE_views_pre_render(&$view) {
  switch ($view->name) {
    case 'VIEW_NAME':
      // Your code here
      break;
  }
}

```

# Answer
> 1 votes
I have the same issue. The following is the only code that worked for me.

```
function MYMODULE_NAME_preprocess_views_view(&$vars) {
  // If it is the view you want to change
  if ($vars['view']->name == 'MYMODULE_NAME') {
    // Override view's title, drupal_set_title() was not working
    $vars['view']->build_info['title'] = 'MY CUSTOM TITLE';
  }
}

```

# Answer
> 0 votes
I assume you have created a module "mymodule" and then used the `hook_views_pre_build()` implementation.

I'm not sure you can change the View title at this step but there might be other possibilities.

First, if you are trying to change the page title (currently generated by the view page) you can try to add `drupal_set_title('My new title');`.

```
function mymodule_views_pre_build(&$view) {
  if ($view->name == 'view_machine_name') {
    drupal_set_title('New title');
  }
}

```

This does not really changes the View Title, but it can help to override the page title. If it does not work, it means Views output the page title after your hook and you'll have to find another hook.

Another solution could be to use the Views arguments as titles. Views has this feature built-in, there is a field for that in the arguments settings. You can check at the first argument in the default taxonomy view prodided by views, which provides a good example.

---
Tags: 7, views
---


# Question
Title: How to pull pictures and summary information from external web pages when posting links?
When posting a link (external web page) to my Drupal blog, is there a way to have Drupal automatically pull the picture and summary information from that link and include it in the post on my Drupal blog the way Facebook does it when a person posts a link from an external web page on their Facebook wall or group?

If it is possible, can somebody please point me in the right direction on how to do it.

# Answer
AFAIK there is no module available for this specific use case. However FBSMP module has its own implementation of crawling links/image/video and other media types from the given URL.

You may need to take that as a base and develop your own version.

Below is the sample code on how its crwaling the links

```
$result = drupal_http_request($url, array('timeout' => $options['timeout']));

  if ($result->code != 200) {
    fbsmp_log_error(t("Could not connect to @url, HTTP error @error", array('@error' => $result->code, '@url' => $url)));
    return $data;
  }

  $page_url = $url;
  if (in_array($result->redirect_code, array(301, 302, 307))) {
    $page_url = $result->redirect_url;
    $data['title'] = $page_url;
  }

  if (stripos($result->headers['Content-Type'], 'image') !== FALSE) {
    $images = array();
    if (($imagesize = _fbsmp_link_validate_filesize($page_url, $options['max_imagesize'], $options['min_imagesize'], ($options['timeout'] - timer_read(__FUNCTION__) / 1000))) != -1) {
      $images[$page_url] = $imagesize;
    }

    $data['images'] = $images;
  }
  else {
    _fbsmp_link_detect_charset($result->data);

    $document = new DOMDocument();
    if (@$document->loadHTML($result->data) === FALSE) {
      fbsmp_log_error(t("Could not parse the content on @url", array('@url' => $url)));
      return $data;
    }

    $xpath         = new DOMXPath($document);

    //Get title of the page.
    $titles        = @$xpath->evaluate("//title");
    $data['title'] = trim($titles->length > 0 ? $titles->item(0)->nodeValue : $data['title']);
    //Get description of the page.
    $descriptions  = @$xpath->evaluate("//meta[@name='description']");
    $data['description'] = trim($descriptions->length > 0 ? $descriptions->item(0)->getAttribute('content') : $data['description']);

    if (!$emfield['emvideo_valid'] && !$emfield['emaudio_valid']) {
      $hrefs         = @$xpath->evaluate("/html/body//img");
      $images = array();

      if (!fbsmp_include_library('url_to_absolute.inc', 'url_to_absolute')) {
        fbsmp_log_error(t("Could not find url_to_absolute.inc file in the libraries folder"));
        return $data;
      }

      for ($i = 0; $i < $hrefs->length; $i++) {
        $image_url = $hrefs->item($i)->getAttribute('src');
        if (!isset($image_url) || empty($image_url)) {
          continue;
        }
        $abs_url = url_to_absolute($page_url, $image_url);
        if ($abs_url && ($imagesize = _fbsmp_link_validate_filesize($abs_url, $options['max_imagesize'], $options['min_imagesize'], ($options['timeout'] - timer_read(__FUNCTION__) / 1000))) != -1) {
          $images[$abs_url] = $imagesize;
        }
        if (($options['timeout'] - timer_read(__FUNCTION__) / 1000) <= 0) {
          fbsmp_log_error(t("Request timed out for @url", array('@url' => $url)));
          break;
        }
      }
      asort($images);
      $images = array_reverse($images, TRUE);
      $data['images'] = $images;
    }
  }

  //Cache the results.
  if ($options['cached']) {
    cache_set($arghash, $data, 'cache', REQUEST_TIME + $options['cache_duration']);
  }

```

You may also check following references,
> 0 votes

---
Tags: 7, navigation, meta-tags, nodes
---


# Question
Title: How to display a view on user's profile page?
I would like to select fields associated with users and display the outputs on users' profile page. In other words, when someone navigates on a user's profile page, the outputs of the selected fields get displayed.

I tried to do that with a user views and I tried setting up different types of contextual filters (such as 'user ID', Provide Default Value, User ID from URL). But nothing seems to be work, the view does not display. When I remove the contextual filter, the view does display on the page so the problem seems to originate from the filter I selected or how I set it up.

The problem is probably really simple but I'm missing something here. Any hint?

Thanks a lot!

# Answer
Looks like you may be looking for Viewfield module:

> Viewfield provides a field that holds a reference to a View and renders it whenever the entity containing the field is displayed.

Install it, and add viewfield to user profile just like you would add any other field.

Alternatively you can create a block display and choose to display only in /user/\* paths, using contextual filters. This is the way I like less, as it is more prone to fail if someone will redesign URL system on page, or choose to display users in a way other than default.

## Exact steps

As described by OP in comment below:

> 1. I created a view and added a contextual filter (Profile: User UID =\> Display all results for the specified field =\> Specify validation criteria/Basic validation);
> 2. created a view field in the Main Profile page; and
> 3. selected the token `[profile2:user:uid]` from the placeholder tokens' list and checked the box "Always use default value".
> 2 votes

# Answer
You should create a **view as block** on the page you want to display.
This will do the needful.
> 0 votes

---
Tags: views
---


title: Read Drush config file

text:
# Question
Title: Read Drush config file
I am creting a module with Drush integration. My challenge now is how to read the Drush config file in `~/.drush/myconfig.drushrc.php`.

I tried `drush_load_config_file` but it is not working.

`drush_load_config_file($context, _drush_config_file($context, 'deployment'));`

# Answer
> 1 votes
Sounds as if you are looking in the wrong place to integrate your module with Drush.

You need to create a `drush` folder within your custom module and create a `YOURMODULE.drush.inc` file inside with appropriate Drush hooks.

Here's an example code:

```
/**
 * Implements hook_drush_command().
 */
function boilerplate_drush_command() {
  $items['boilerplate-hello'] = array(
    'callback' => 'boilerplate_hello_command',
    'description' => dt('Sample Drush command for boilerplate module.'),
    'bootstrap' => DRUSH_BOOTSTRAP_DRUSH,
    'arguments' => array(
      'name' => dt('Optional. A name which will be greeted upon running the command.'),
    ),
    'aliases' => array('boilerplate-hi'),
  );

  return $items;
}

/**
 * Implements hook_drush_help().
 */
function boilerplate_drush_help($section) {
  switch ($section) {
    case 'drush:boilerplate-hello':
      return dt('Sample Drush command for boilerplate module. It will just greet you, optionally with a name you provided.');
  }
}

/**
 * Command to download the Chosen plugin.
 */
function boilerplate_hello_command() {
  $args = func_get_args();
  $name = (!empty($args[0])) ? $args[0] : FALSE;

  if ($name) {
    drush_log(dt('Hello @name!', array('@name' => $name)), 'success');
  }
  else {
    drush_log(dt('Hello there!'), 'success');
  }
}

```

This will allow you to run the command using `drush boilerplate-hello` or `drush boilerplate-hi` (alias). If you pass an argument, for example `drush boilerplate-hello ninjascorner` it will take it as an argument, which is the functionality you need.

This is taken from my Drupal module boilerplate. The Drush integration from there is working, so you can install the module and play around with it to see how it works.

---
Tags: 7, drush
---


# Question
Title: Queue doesn't enter on worker function with Elysia cron
I'm trying to use queue api with cron, everything seems work but drupal does not enter on the "worker" function. The problem there is only if I enable Elysia Cron (and I've to enable it..)

```
<?php

/**
 * Implements hook_cron_queue_info().
 */
function monitor_import_cron_queue_info() {
  $queue['monitor_import_queue'] = array(
    'worker callback' => 'monitor_import_queue_worker',
    'time' => 10,
  );
  return $queue;
}

/**
 * Implements hook_cron().
 */
function monitor_import_cron() {

  $call = new MyWS();
  $params = new getSoggettoView();
  $params->limit = '10'; //$limit;
  $params->offset = '0';
  $results = $call->getSoggettoView($params);
  $items = $results->return;
  $queue = DrupalQueue::get('monitor_import_queue'); // grab queue
  $queue->createQueue(); // initialize
  foreach ($items as $item) {
    $queue->createItem($item);
  }
}

/**
 * Worker callback
 *
 * @see mymodule_cron_queue_info().
 */
function monitor_import_queue_worker($item) {
  $a = 1;
}

```

# Answer
> 1 votes
Below code perfectly works for me...

```
/**
 * Implements hook_cron_queue_info().
*/
function drup_custom_cron_queue_info() {
  $queue['drup_custom_queue'] = array(
      'worker callback' => 'drup_custom_queue_worker',
      'time' => 10,
  );
  return $queue;
}

/**
 * Implements hook_cron().
 */
function drup_custom_cron() {
  $items = array('1', '2', '3', '4', '5', '6', '7');
  $queue = DrupalQueue::get('drup_custom_queue'); // grab queue
  foreach ($items as $i) {
    $item = new stdClass();
    $item->created = time();
    $item->sequence = $i;
    $queue->createItem($item);
  }
}

/**
 * Worker callback
 *
 * @see mymodule_cron_queue_info().
 */
function drup_custom_queue_worker($item) {
  watchdog('drup_custom', 'Queue worker processed item with @sequence created at @time',
    array(
      '@sequence' => $item->sequence,
      '@time' => date_iso8601($item->created),
    )
  );
}

```

Check your custom callback which returns results as mentioned by David in comment..

---
Tags: cron, queue
---


# Question
Title: Redirect to page in form submit and use the form data in new page
How to redirect in drupal 7 in form submission, I need to use the submitted data in next redirected page but below `video_subtitle_view` function is not printing anything

How do i do it

```
/**
 * Implements hook_menu()
 *
 */
function video_subtitles_menu() {
  $items = array();
  $items['player/video_subtitle/view'] = array(
     'page callback' => 'video_subtitle_view',
     'access callback' => 'user_access',
     'access arguments' => array('administer video_subtitles status'),
  );
  return $items;
}

```

---

```
    function video_subtitle_view($form, &$form_state){
    //    print 'video_subtitle_view';
        print_r($form);
        print_r($form_state);
    }

```

---

```
function video_upload_subtitles_form_submit($form, &$form_state) {

     $form_state['redirect'] = 'player/video_subtitle/view';
//     $form_state['redirect'] = array(
//            'player/video_subtitle/view',
//             array(
//                    'query' => array(
//                    'form' => $form,
//                    'form_state' => &$form_state,
//                   ),
//              ),
//      );

}

```

---

```
function video_subtitle_view($form, &$form_state){
//    print 'video_subtitle_view';
    print_r($form);
    print_r($form_state);
}

```

do i need to pass the form data as parameter??

# Answer
You can use server session to keep your form state something like below

```
function video_upload_subtitles_form_submit($form, &$form_state) {
    $_SESSION['my_form_data'] = $form_state;
    $form_state['redirect'] = 'player/video_subtitle/view';

}

// Then

function video_subtitle_view(){
    print_r($_SESSION['my_from_data']);
}

```
> 1 votes

---
Tags: 7, database, forms
---


# Question
Title: How do I set the exact post date timestamp as Views contextual filter?
I need to display nodes that were created within a certain period of time.

Setting `Date: Date (node) (content: post date)` as contextual Views filter works super smooth. Now when I call `archive/2014-04-01-10--2014-04-04-15` all nodes created between April 1st 10am and April 4th 3pm will be displayed.

But how can I set the granularity to also respect minutes (and seconds)? How to alter the date filter or how to write a custom timestamp contextual filter?

# Answer
I think you only have to pass the hours and minutes in to your contextual filter.

I have a View with filtering between dates and the URL is like that: http://mysite.com/myview?changed%5Bmin%5D=23-03-2013+12%3A24&changed%5Bmax%5D=23-03-2013+18%3A24

This is for the access data from 23-03-2013 12:24 to 23-03-2013 18:24.

Also, make sure you have enabled the Date submodule Date views as it provides some improvements using dates in Views.
> 3 votes

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


# Question
Title: I would like to split up the fields in the 'create new content' screen into sections
I have a content type with about thirty different fields. I would like to group them by category and I would also like to split them up so that half of the fields are filled in at the time of creation and the rest are filled in later (as a two-part work flow.) There is a strong possibility that access to the two field groups will require two different roles. Is there a good module that can do this?

# Answer
> 1 votes
You can use the Field Group module to group fields together.

You can use the Field Permissions module to only allow access to certain fields based on users roles.

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


# Question
Title: How do I debug a CKEditor installation on Drupal 7?
I installed the the CKEditor module on a site that runs on Drupal 7; I've also installed the *CKEditor JavaScript* library from their website.

However, no matter what I do, the editor don't show up as it is supposed to.

How can I debug why the editor does not show up?

# Answer
Here are, roughly in the order you should try them, some tips that may help you debugging a CKEditor configuration.

## 1. Clear the cache

Remember to clear the cache after you've changed *any* setting that has something to do with wysiwyg. Not clearing the cache is probably the most common source for CKEditor not showing up as you would expect.

## 2. Check out that roles are configured correctly

Navigate to your text formats: *Administration » Configuration » Content authoring » Text formats* and ensure the roles are configured correctly.

* Add the roles you want to use wysiwyg to *Filtered HTML* and *Full HTML*.

## 3. Check out that profiles are set up right

Navigate to your ckeditor profiles: *Home » Administration » Configuration » Content authoring » CKeditor*

Go to the profiles, and verify that the text formats for the profile are set, and the editor appearance is set properly.

* Under *Basic Setup*, check the text formats that apply
* Under *Editor Appearance*, set default state to enabled, and show the toggle.

## 4. Check the paths

Navigate to *Administration » Configuration » Content authoring » CKeditor » Global settings*. press *Edit*, and check that all the paths listed there actually exists.

## 5. Check the default text processing option

Make sure that you've selected "Filtered text" as your default text processing option. To change this, navigate to *Administration » Structure » Content types*, select the content you experience problems with and click *manage fields* and *edit* on the `body` field (and other text fields you want to use the wysywyg editor). Make sure that the preset text format for that text field is set to to one of the formats configured for wysywyg (e.g. *Filtered HTML*).

To make sure that *Filtered HTML* is selectable, you need to make sure that the setting for "Text processing" is set to *Filtered text* (not *Plain text*):

Press *Save settings* after changing this.

Make sure that when you create content, a text format that is set up to use use WYSYWYG (e.g. *Filtered HTML*) is selected. The screen dump below shows how the pull-down menu immediately below the text field for content should look like:
> 4 votes

---
Tags: 7, wysiwyg
---


title: How often does hook_cron happen?

text:
# Question
Title: How often does hook_cron happen?
How often does hook\_cron happen? what is the periodic time for executing the codes inside this hook?

# Answer
> 8 votes
As often as you like :)

* By default you can configure it on: /admin/config/system/cron (This will be executed on someone's page load, so it is importan to know that if nobody visits your site this will not be executed). This is known as poormanscron (Drupal 6).
* Calling with a internal/external cron script (wget for example) to yoursite.com/cron.php

This is a heavy process so normally you want to limit cron functions like check updates. elysia cron is very useful in this case.

> Elysia Cron extends Drupal standard cron, allowing a fine grain control over each task and several ways to add custom cron jobs to your site.

# Answer
> 2 votes
It's either:

1. What you set it as at /admin/config/system/cron *or*
2. How often you invoke the cron script externally.

It's totally under your control.

# Answer
> 1 votes
`hook_cron()` is triggered whenever Drupal's cron function runs.

The default is to trigger every 3 hours. However *you* decide when Drupal's cron function runs.

On a typical Drupal 7 site, you control this by navigating to *Administration » Configuration » System » Cron* to set the frequency. This default method of running cron is sometimes known as "Poormanscron". Poormanscron is executed upon page load, which means it may fail to trigger if your site receives very little traffic.

You may, as an alternative, use an external trigger for cron. The URL (inclusive secret key) for using an external trigger for Drupal's cron function is given on the same page, after the text: "To run cron from outside the site, go to ...". When doeing this, you may disable Poormanscron by setting the frequency to "Never".

---
Tags: cron
---


# Question
Title: Is it possible to run a module written for drupal 7 in drupal 6?
In another question I was searching for a module that provides a simple shopping cart and checkout process (Is there a simple shopping cart and checkout process module?).

I have found this simple module called Basic Card.

I am running Drupal 6.x while this module is written only for Drupal 7.x.

Is it possible to run a Drupal 7.x module on a Drupal 6.x installation?

# Answer
> 3 votes
No, it's not generally possible without back-porting the code.

The API is very different between Drupal 6 and 7. A few things have remained the same, so it's theoretically possible that a module for one version might work as-is in the other version, but generally speaking, it's not possible.

For a proper idea of the task ahead of you, take a look at Converting 6.x modules to 7.x. Not a trivial task, unfortunately.

I just had a quick look and the specific module you've mentioned definitely won't work in Drupal 6, it would need to be re-written.

# Answer
> 1 votes
The short answer is "no".

The APIs has changed, and this means that a lot of function calls is generate errors that will make your site useless.

A slightly longer answer is "maybe, if you're willing to do some work".

Many Drupal 7 modules doesn't use critical functions that *only* exists in Drupal 7. This means that you can "downgrade" them from Drupal 7 to Drupal 6 by rewriting the hooks and other functions that calls the Drupal API to conform to Drupal 6. I've done it myself with a couple of modules, and if you're familiar with both sets of APIs, it usually doable.

---
Tags: 6
---


# Question
Title: Single site with multiple user interfaces based on path and role
I'm currently working on a Drupal project that requires 3 separate interfaces.

Administrative users login to the site and all of the pages associated with their specific role start with a particular base path. Lets say it is `/path_A/*`. I'd like these users to login to the site using `www.example.com/path_A/login` and all subsequent requests to any given page would be accessed via `www.example.com/path_A/`.

The end users would access the site in the same way except the login page and all subsequent requests would begin with `www.example.com/path_B`. Users of path B should not be able to access any of the administrative functions tied to `path_A/` but administrators should be able to navigate to any `path_B/` URL and access the site in the same way as the end users.

On top of all of this, there is a public facing set of pages that should be accessed using the domain itself, it is basically a blog and information directory living at the webserver root directory (www.example.com).

Additionally none of the pages belonging to any of these specific URL paths should be available through the others, so a page `/path_A/page/3` should not be accessible via `/path_B/page/3` or `/page/3`. Multi site setup for this is not really an option since the a large piece of the database is shared by all three subsections of the site.

My initial idea is that I could use .htaccess rewrites to direct all requests to each of the paths to the drupal index file, register 2 aliases for each of the login pages using the paths module and then use context to change the interface based on the path/role. I am a bit new to drupal and this is my first major project working with it so I'm not sure if this is the best approach to this problem. And yes I realize that this might seem like a waste of time but the client really stressed this functionality.

# Answer
Role Theme Switcher does what you're asking for roles. For access to pages you could write your own custom module that implements hook\_node\_access or you could use Views permissions (which I've found to be quite easy and works well) or you could use another module that manages permissions on a per-page basis like Content Access or Nodeaccess.

Lots of options for what you want. I personally recommend trying to combine Role Theme Switcher with Views permissions. Otherwise I would go for making a custom module with hook\_node\_access. I don't recommend Content Access or Nodeaccess, they've never worked exactly right for what my needs are, but they are there for reference.

EDIT: You may also find Rules to be helpful re-directing users of certain roles to certain pages based on their role when they login.

EDIT 2: As I mentioned in the comment below, logintoboggan is another module that will allow re-directs upon user login.
> 0 votes

---
Tags: users, path-aliases, .htaccess
---


title: How to test a database connection?

text:
# Question
Title: How to test a database connection?
I'm writing a module that will have to make a connection to a seperate database. In order for the user to configure the database, I'm allowing the user to fill out the database connection info in the module configuration form.

How can I test the database connection before submitting the form?

I added the relevant code below:

```
function mymodule_form($form, &$form_state) {
  //Form code omitted
  $form['#submit'][] = 'mymodule_form_submit';
  $form = system_settings_form($form);
  return $form;
}

function mymodule_form_validate($form, &$form_state){
  // Validation code, test db connection, need help here.
}

function mymodule_form_submit($form, &$form_state) {
  $values = $form_state['values'];
  $database = array(
    'database' => $values['database_name'],
    'username' => $values['database_username'],
    'password' => $values['database_password'],
    'host' => $values['database_host'],
    'driver' => $values['database_driver'],
  );
  Database::addConnectionInfo('mymoduleDB', 'default', $database);
}

```

# Answer
I don't see anything in `Database` or `DatabaseConnection` specifically. In a pinch you can just run a query that you know won't throw an exception in a Drupal site:

```
try {
  db_set_active('mymoduleDB');
  db_query('SELECT COUNT(nid) FROM {node}');
}
catch (\PDOException $e) {
  // Berate the user.
}
// PHP5.5+ only
finally {
  db_set_active('default');
}

```
> 2 votes

# Answer
Before I give you this potential solution this: Passing db info around unencrypted seems like a bad idea. other people may have a better idea of how to do this more securely.

Using hook\_menu, you can create a function that accepts arguments via POST data.

Attach Javascript with your AJAX event using the forms API.
> 2 votes

---
Tags: database, forms
---