# Question
Title: A better way to insert preformatted snippets into content/wysiwyg?
Is there a way to insert pre-formatted objects (like a standardized sign-up form) in line in content via wysiwyg (a'la the fantastic wysiwyg-templates module), *but encapsulated and protected*...

I actually love that w-t can insert snippets, and will continue to use it, marketing likes to insert the same search form they always use and then change 2 words to test if that drives conversions. For what it does, w-t is perfect.

HOWEVER...

Having done that, I now want to pop in content in exactly the same method, except LOCKED so it can't be edited, but so I can still SEE it, and potentially move it around the page as though it were an image.

I'm not expecting too much for response, but if I end up really needing it I'd rather hear what other ideas are out there than build something myself that has already been done.

(background to be posted in a comment below for context)

# Answer
> 1 votes
The perfect solution hasn't presented itself, but I settled on using specialized content types inside a parent content type, (via Entity & Entity Reference fields) and then using Better Formats, Wysiwyg with CKE, Fieldgroup, Conditional Fields to make a user interface that presents all the myriad options in a nice clean manner.

I'm kinda proud of the result, I expect I'll eventually reuse the system somewhere more public so I can show it off.

# Answer
> 0 votes
What about an input filter?

https://api.drupal.org/api/drupal/modules!filter!filter.api.php/function/hook\_filter\_info/7

In this way, you could define a token (or similar), which would be translated into the output you need. Editors could move the token around, while not having access to the value itself. Added bonus of being able to change the output without editing all the wysiwyg content values.

---
Tags: 7, wysiwyg
---


# Question
Title: Using the youtube_uploader module, how do I upload the video as private, without hacking the module
I have been able to achieve what I need by changing the module here:

```
function youtube_uploader_get_settings_form() {
  $ret['youtube_uploader_publishing_options'] = array(
    '#type' => 'radios',
    '#title' => t('Default privacy options'),
    '#description' => t('More info on !here', array('!here' => l(t('YouTube support page'), 'http://support.google.com/youtube/bin/answer.py?hl=en&answer=157177'))),
    '#options' => array('public' => t('Public'), 'unlisted' => t('Unlisted'), 'private' => t('Private')),
    '#default_value' => strtolower(variable_get('youtube_uploader_publishing_options', 'unlisted')),
  );
  //Added: 'private' => t('Private') - being the added code.
}

```

How do I achieve this without hacking the module?

# Answer
> 0 votes
`hook_form_alter()` is what you're looking for. This function, when invoked in any module, will let you modify any form array created/rendered by Drupal's form API. For example, in a module named **mymodule** you could add the following function in **mymodule.module**.

```
function mymodule_form_alter(&$form, &$form_state, $form_id) {
  //modify youtube_uploader_get_settings_form to add Private to #options array
  if($form_id == 'youtube_uploader_get_settings_form') {
    $form['youtube_uploader_publishing_options']['#options']['private'] = t('Private');
  }
}

```

---

```
function xxxx_custom_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'field_ui_field_edit_form' && isset($form['instance']['settings']['youtube_settings']['youtube_uploader_publishing_options'])) {
    $privateOptions = array('public' => t('Public'), 'unlisted' => t('Unlisted'), 'private' => t('Private'));
    $form['instance']['settings']['youtube_settings']['youtube_uploader_publishing_options']['#options'] = $privateOptions;
  }
}

```

---
Tags: hooks, files
---


title: Using hook_language_types_info_alter

text:
# Question
Title: Using hook_language_types_info_alter
I am attempting to modify the way the language negotiation is done on a site.

I've implemented a new language negotiation method:

```
/**
 * Implements hook_language_negotiation_info()
 */
function MODULE_language_negotiation_info() {
  return array(
    'MODULE_provider' => array(
      'file'        => drupal_get_path('module', 'MODULE') . '/MODULE.module',
      'weight'      => -4,
      'name'        => t('URL (Combined)'),
      'description' => t('Determine the language from the URL (Path prefix and domain).'),
      'cache'       => 0,
      'callbacks'   => array(
        'language'    => 'MODULE_language_provider_callback',
        'url_rewrite' => 'MODULE_language_url_rewrite_callback',
      ),
    ),
  );
}

```

In the case of a single language, the $language is being detected properly, the $language\_content is being detected properly, but the $language\_url is not being detected properly.

After some digging into this, I found that in the locale.module there are three language types defined - language, language\_content and language\_url:

```
/**
 * Implements hook_language_types_info().
 *
 * Defines the three core language types:
 * - Interface language is the only configurable language type in core. It is
 *   used by t() as the default language if none is specified.
 * - Content language is by default non-configurable and inherits the interface
 *   language negotiated value. It is used by the Field API to determine the
 *   display language for fields if no explicit value is specified.
 * - URL language is by default non-configurable and is determined through the
 *   URL language provider or the URL fallback provider if no language can be
 *   detected. It is used by l() as the default language if none is specified.
 */
function locale_language_types_info() {
  require_once DRUPAL_ROOT . '/includes/locale.inc';
  return array(
    LANGUAGE_TYPE_INTERFACE => array(
      'name' => t('User interface text'),
      'description' => t('Order of language detection methods for user interface text. If a translation of user interface text is available in the detected language, it will be displayed.'),
    ),
    LANGUAGE_TYPE_CONTENT => array(
      'name' => t('Content'),
      'description' => t('Order of language detection methods for content. If a version of content is available in the detected language, it will be displayed.'),
      'fixed' => array(LOCALE_LANGUAGE_NEGOTIATION_INTERFACE),
    ),
    LANGUAGE_TYPE_URL => array(
      'fixed' => array(LOCALE_LANGUAGE_NEGOTIATION_URL, LOCALE_LANGUAGE_NEGOTIATION_URL_FALLBACK),
    ),
  );
}

```

So, pressing onward, I implement hook\_language\_types\_info\_alter and add my callback function to the list of callbacks for the language\_url language type:

```
function MODULE_language_types_info_alter(array &$language_types) {
  $language_types[LANGUAGE_TYPE_URL]['fixed'][] = 'MODULE_language_provider_callback';
}

```

The issue I am facing is that the `hook_language_types_info_alter` is called after `drupal_language_initialize`, so all of the language types have already been determined before the hook alters the language types.

Also, all of these language types are stored as variables. I could in theory modify the variable, but I would rather do this the correct way using hooks.

How do I modify the language\_url language type before drupal\_language\_initialize?

# Answer
variables was definitely the key here. In my hook\_language\_types\_info\_alter hook, simply updating the variable with my callback did the trick:

```
/**
 * Implements hook_language_types_info_alter()
 */
function MODULE_language_types_info_alter(array &$language_types) {
  $config = variable_get("language_negotiation_" . LANGUAGE_TYPE_URL);

  // put my callback first, since the first one to return a language wins.
  $newconfig['MODULE_provider']['callbacks']['language'] = 'MODULE_language_provider_callback';
  $newconfig['MODULE_provider']['file'] = drupal_get_path('module', 'MODULE') . '/MODULE.module';
  $newconfig += $config;

  variable_set("language_negotiation_" . LANGUAGE_TYPE_URL, $newconfig);
}

```
> 0 votes

---
Tags: 7, i18n-l10n
---


# Question
Title: Need a textfield required only when selectlist is set to 'Approved' within custom content type
This seems like it should be simple, but has been challenging me for a few days now. I have a custom content type which contains a selectlist which defaults to 'Pending' for new nodes. Someone will later come along and set these to 'Approved' and when they do so I need a text field to be available and required prior to saving the node again.

I have tried the available modules 'Conditional Fields' and 'Field Conditional States' but they do not seem to work to make fields actually required. I assume this is because the JavaScript Form state has no effect on server-side logic and validation.

If I was coding this outside of Drupal 7 I would probably make the textfield disabled, required, and give it a default value. Then use an .onchange to check if it is set to “Approved” and, if so, enable it and empty the default value but I am not sure how to implement this with Drupal yet.

I didn't find anything else in the way of modules that seemed to work, so I have now begun looking at the function 'drupal\_process\_states'. This seems like it might be the right path, but is going to take me a while to figure out.

Any help is appreciated. Thanks!

# Answer
> 1 votes
Field Conditional States will help you modify the *look* of the field: it will make it appear or disappear, or will add the red asterisks to make it look required. But as you noticed, making it *look* required is not the same thing as making it required. What I have done is using a combination of Field Conditional States to change the look of the field, AND Field Validation to actually make it required (so that the form returns the "Field required" error message when submitted). Field Validation has a way to return the error by checking that the field is not empty, AND checking if a different field in the form has a particular value. You need the "PHP code" type of validation for this. Take a look at the documentation for this module's PHP code option.

---
Tags: javascript
---


title: How to theme a custom block

text:
# Question
Title: How to theme a custom block
I've created a block using `hook_block_info` and `hook_block_theme` and the like. But how can I theme it?

I have it working to return an array with the keys `'subject'` and `'content'`. But I created the markup directly in the `hook_block_view()` hook and that's not what I want.

In the docs it's said that content should preferably returned as *renderable array* and not as markup. But what is this *renderable array*? They say it should be data instead of markup, but all I see in the examples is that it's just used as a wrapper for markup, so nothing gained there.

I want to be able to have a `block--MYMODULE--DELTA.tpl.php` in my theme but how do I call it and how can I pass the data to the block?

# Answer
The way I do this is as follows...

```
function MYMODULE_block_info() {

  $blocks = [];

  $blocks['my_block_machine_name'] = [
    'info'  => t('My Block Title'),
    // @see https://api.drupal.org/api/drupal/includes!common.inc/group/block_caching/7.x
    // You can use different caching options.
    'cache' => DRUPAL_NO_CACHE,
  ];

  return $blocks;
}

function MYMODULE_block_view($delta = '') {

  $block = [];

  switch ($delta) {
    case 'my_block_machine_name':
      // Good idea to check user permissions here.
      if (user_access('access content')) {
        $block['subject'] = t('My Block Title');
        $block['content'] = MY_BLOCK_CONTENT_CALLBACK();
      }
      break;
  }

  return $block;
}

function MY_BLOCK_CONTENT_CALLBACK()() {

  $items = [];

  // This is the simplest kind of renderable array.
  $items['VAR_ONE'] = ['#markup' => 'VAR_ONE_OUTPUT'];

  // Here I added a prefix and a suffix.
  $items['VAR_TWO'] = [
    '#prefix' => '<div class="foo-bar">',
    '#markup' => 'VAR_TWO_OUTPUT',
    '#suffix' => '</div>',
  ];

  // This is where the $items get sent to your my-template.tpl.php template
  // that got registered below.
  return theme('my_cool_block', ['items' => $items]);
}

function MYMODULE_theme() {

  // Here you are registering your template for the block output above.
  $module_path = drupal_get_path('module', 'MYMODULE');

  // Drupal will now look up your modules /theme folder first to grab the
  // template.
  $base = [
    'path' => "$module_path/theme",
  ];

  return [
    'my_cool_block' => $base + [
        // Leave off .tpl.php.
        'template'  => 'my-template',
        // Define variables you want to pass to the template.
        // Here I just pass items, but you can pass any other data as well.
        'variables' => [
          'items' => NULL,
        ],
      ],
  ];
}

```

And then in a subfolder in your module called `theme` there should be a file called `my-template.tpl.php` which could have this in it:

```
<?php

$items = $variables['items'];

print render($items['VAR_ONE']);
print render($items['VAR_TWO']);

```

And if you wanted to, you could actually overwrite the "default" module implementation you just made for `my-module.tpl.php` in your theme as you wish in `block--MYMODULE--DELTA.tpl.php`.
> 28 votes

# Answer
Try Theme Developer module. When you have enabled it you can check a checkbox in bottom left corner of you Drupal page. After that you can click on your block and get useful information considering theming. You can see the possible .tpl.php file namings for your block for example.

Pick one of those names. The first is the most specific one. It will only theme one block. Create a file with that name in your theme folder if it's not already there. You can put it in subfolder if you want to get organized.

Copy the content of block.tpl.php in your file and start changing things to the way you want them to be.

Save your file, clear caches and reload the page.
> 6 votes

# Answer
There's already a number of answers for this question but I have tried to provide a very simplistic approach. Hopefully identifying to devs the array structure expected by Drupal when returning your block content.

To do this I have broken the question down into separate code examples as such,

```
/**
 * Implements hook_theme().
 */
function examplemodule_theme() {
  return array(
    'examplemodule_output' => array(
      'variables' => array(
        'title' => NULL,
        'content' => NULL,
        'popular_content' => NULL,
       ),
      'template' => 'templates/examplemodule-sweet--block',
    ),
  );
}

```

Please see a full explanation here drupal 7 creating theming custom blocks
> 5 votes

# Answer
This is an old post, but I have found a better solution for overriding block templates from a custom module for Drupal 7.

Add this to your custom module:

```
/**
 * Implements hook_theme().
 */
function MYMODULE_theme($existing, $type, $theme, $path) {

  // Custom template for that overrides the default block.tpl.php.
  $themes['block__my_custom_module'] = [
    'template'      => 'block--my_custom_module',
    'original hook' => 'block',
    'path'          => drupal_get_path('module', 'my_custom_module') . '/templates',
  ];

  return $themes;
}

```

Then you need the follow code:

```
/**
 * Implements hook_block_info().
 */
function MYMODULE_block_info() {

  $blocks = [];

  $blocks['my_custom_module'] = [
    'info'  => t('My Custom Module Block'),
    'cache' => DRUPAL_CACHE_PER_ROLE,
  ];

  return $blocks;
}

/**
 * Implements hook_block_view().
 */
function MYMODULE_block_view($delta = '') {

  $block = [];

  switch ($delta) {
    case 'my_custom_module':
      $block['content'] = _my_custom_module_helper_function();
      break;
  }

  return $block;
}

/**
 * Helper function to generate HTML.
 *
 * @return string
 *   generated HTML
 */
function _my_custom_module_helper_function() {

  $output = '';

  // ...

  return $output;
}

```

All you have to do is create `templates/block--my-custom-module.tpl.php` inside your module's folder.

I have written a tutorial about this Drupal Tutorial - How to Override a Block Templates from a Custom Module
> 3 votes

---
Tags: 7, blocks, theming
---


# Question
Title: Creating Number fields (integer and decimal) manually in code for custom forms
I need to manually render a number field in Drupal 7 on a custom form. I have created the following field definition:

```
$form['num_seats'] = array(
  '#type' => 'textfield',
      '#title' => t('Number of Seats'),
      '#required' => TRUE,
      '#number_type' => 'decimal',
      '#field_name' => 'num_seats',
      '#element_validate' => array ('number_field_widget_validate'),
      '#field_parents' => array(),
      '#language' => $language->language,
      '#field_prefix' => '$',
      '#size' => 14,
      '#maxlength' => 12,
      '#default_value' => $location ? $location['num_seats'] : $node->field_workshop_num_seats[$node->language][0]['value'],
);

```

However submitting the form produces an error of the form: "preg\_replace() \[function.preg-replace\]: Compilation failed: range out of order in character class at offset 14 in number\_field\_widget\_validate() (line 391 "

If I use 'integer' instead of 'decimal' for 'number\_type', it works fine. I checked Number module's code and could see this is bcause of regex not being created correctly from field definition.

So my question is how can I manually render Fields outside of regular Drupal entity\_type context (i.e. outside node/user etc. forms) in a custom form whose submission gets stored to a custom table.

# Answer
> 3 votes
After some googling and a bit of thought of how I've used stuff in the past. You're confusing a FAPI element with a Field Widget. They are not the same thing, this has been discussed before on Drupal.StackExchange. And is fully answered there in terms of why they are different.

I think your easiest solution is to create your own `#element_validate` function and not rely on the validate function provided directly by `number_field_widget_validate` -- but I would copy its guts essentially and create your own validate function from it. The preg\_replace is failing because your FAPI element is not a Widget and has no `$field['settings']`. That's what I think is going on.

# Answer
> 1 votes
I guess after 3 years something changed. As I was able to add a decimal field without error as follow:

```
'location_crossing_mileage' => array(
    '#type' => 'textfield',
    '#title' => t('Mileage'),
    '#size' => 5,
    '#maxlength' => 12,
    '#number_type' => 'decimal',
    '#field_name' => 'location_crossing_mileage',
    '#element_validate' => array ('number_field_widget_validate'),
  ),

```

---
Tags: 7, entities
---


title: Warning: array_flip() on user_save

text:
# Question
Title: Warning: array_flip() on user_save
I am writing a custom module that takes some old data and stores it into a new user profile. However, when the `user_save` function is ran, I get the errors:

```
Warning: array_flip(): Can only flip STRING and INTEGER values! in DrupalDefaultEntityController->load() (line 175 of /.../includes/entity.inc).

EntityMalformedException: Missing bundle property on entity of type node. in entity_extract_ids() (line 7844 of /.../includes/common.inc).

```

After some troubleshooting, I realized that these errors were being thrown when I ran `user_save('', $user_fields)`. The code that writes $user\_fields is as follows:

```
    <?php
function users_migration_form_submit($form, &$form_state) {
    $id = $form_state['values']['memberId'];
    $password = $form_state['values']['password'];

    $other_database = array(
        'database' => 'old_users',      // Name/Schema
        'username' => 'old_users',      // User
        'password' => '',               // User password
        'host' => '127.0.0.1',          // DB Host
        'driver' => 'mysql',            // DB Driver
    );

    Database::addConnectionInfo('users_legacy', 'default', $other_database);
    db_set_active('users_legacy');

    //Enter in queries here
    $query = "SELECT * FROM Users WHERE password=PASSWORD('".$password."') AND memberID='".$id."'";

    $result = db_query($query);

    $user_fields = array();

    if($result) {
        //Build user variable
        $user_fields['name'] = $id;
        $user_fields['pass'] = $password;

        while($row = $result->fetchAssoc()) {
            $user_fields['mail'] = $row['email'];
            $user_fields['field_user_gender'][LANGUAGE_NONE][0]['value'] = strtolower($row['gender']); // Example: male
            $user_fields['field_user_dob'][LANGUAGE_NONE][0]['value'] = date('Y-m-d', strtotime($row['dob'])); // This is a date field. The incoming data will look like this: 01/01/1990
            $user_fields['field_user_id'][LANGUAGE_NONE][0]['value'] = $row['user_id']; // Example: loganfarr
            $user_fields['field_rank'][LANGUAGE_NONE][0]['value'] = $row['rank']; // Example: 10B
        }
    }
    else {
        print_r("No results.");
        return;
    }

    $user_fields['status'] = 1;

    db_set_active(); //Set it back to so Drupal uses the default database

    try {
        $account = user_save('',$user_fields);
    } catch (EntityMalformedException $e) {
        drupal_set_message('EntityMalformedException occured', 'error');
        dpm(debug_backtrace());
        return;
    }

    //Automatically log in as the newly created user
    if($uid = user_authenticate($id, $password)) {
        global $user;
        $user = user_load($account->uid);

        $login_array = array('name' => $id);
        user_login_finalize($login_array);

        drupal_goto('/user/edit');
    }
    else {
        print_r('user_authenticate() failed');
        return;
    }
}

```

After I ran `kpr($user_fields)` I realized that the array was populating correctly, and all the values were there.

All the fields are text fields with the exception of the field\_user\_dob, which is a date field.

I have tried using the entity\_save function (and respective setting functions via entity\_metadata\_wrapper) but I end up getting the same errors. I can provide that code as well, if necessary.

Thank you in advance!

**EDIT** I cleaned up the code for consistency. `$old_user` and `$row` were the same variable, just mis-typed when I was abstracting the code for this question.

The output of `kpr($user_fields)` is as follows:

```
... (Array, 9 elements)
    name (String, 10 characters ) FAR1234567
    pass (String, 8 characters ) password
    mail (String, 28 characters ) logan@loganfarr.com
    gender (String, 4 characters ) male
    dob (Integer) 790326000
    user_id (String, 10 characters ) 0987654321
    field_rank (String, 2 characters ) 10B

```

**UPDATE**

I have tried removing the custom fields so that only the essentials are there (name, pass, and mail) and still receive the errors.

**UPDATE #2**

I added the whole function, not just the lines relevant to `user_save`.

**UPDATE #3**

(Thanks to all who are still here with me.)

I have removed all other code and have just attempted

```
$user_fields = array();
$user_fields['mail'] = 'logan@loganfarr.com';
$user_fields['name'] = 'FAR1234567';
$user_fields['pass'] = 'password';
$account = user_save(null,$user_fields);

```

Which still gives me the error.

# Answer
> 0 votes
Okay, after some really in-depth troubleshooting, I have finally found the problem.

When a user registers, there is a rule that fires that assigns them a role based on the answer to a field (a list field that is required). I was not adding that field in the code, so the rule had nothing to work with.

There wasn't anything in the logs, code, or `debug_backtrace()` that pointed to the problem. It was only when I looked at the overall user flow that I thought of it.

Many thanks to all who helped. I really appreciated it.

# Answer
> 0 votes
This line is probably the problem:

```
$user_fields['field_verified'] = 1;

```

Assuming that's a boolean field it should be:

```
$user_fields['field_verified'][LANGUAGE_NONE][0]['value'] = 1;

```

# Answer
> 0 votes
Try this way:

```
$user_fields = array();
//Build user variable
$user_fields['name'] = $id;
$user_fields['pass'] = $password;
$user_fields['mail'] = $row['email'];
$user_fields['field_user_gender'] = strtolower($row['gender']);
$user_fields['field_user_dob']= date('Y-m-d', strtotime($row['dob']));
$user_fields['field_user_id'] = $row['user_id'];
$user_fields['field_rank'] = $old_user['rank'];
$user_fields['status'] = 1;
$user_fields['field_verified'] = 1;
$account = user_save('', $user_fields);

```

The array that you are passing should be an array of fields and values to save. For example array('name' =\> 'My name'). Key / value pairs added to the array will be serialized and saved in the {users.data} column.

**UPDATE:** Are you sure that each value is string or integer? In the piece of code that you displayed, you don't need \[LANGUAGE\_NONE\]\[0\]\['value'\] at least not for the $user\_fields array. In fact you're declaring $user\_fields as empty array at the begining.

But maybe **$row** or **$old\_user** needs it, I'm not sure from where those are coming from. You have to make sure that you are assigning only one value and not an array. Check those variables using:

```
echo "<pre>";
print_r($row);
print_r($old_user);
echo "</pre>";

```

Less probably, but also make sure that $id or $password is not an array.

# Answer
> 0 votes
Notice that in your variable dump `dob` is actually a UNIX timestamp (an Integer). In your code the function `date()` returns a **formatted date string** (a string like "2015-10-25"), not an Integer timestamp.

Check the format of `$old_user['dob']` by doing a `dpm()` of that variable. IF it shows as Integer (i.e. UNIX timestamp), you simply do this: $user\_fields\['field\_user\_dob'\] = old\_user\['dob'\];

If it's a date string, then you would need to add `strtotime($old_user['dob'])` but not `date()`.

**The other thing**: I think you were correct to add `[LANGUAGE_NONE][0]['value']` as you had it before. You may need to add that back (I'd check on that but I'm short on time right now).

---
Tags: 7, entities, users
---


# Question
Title: How to make same javascript code work on more than one same kind of field?
I am using Field collection module and added some repeated fields. Each field has one button, on clicking the button, the text area is expands(toggling kind of). But the java code is working for only first field not for rest of the fields. I have added java script code through .info method. Thanks.

```
(function ($) {
     Drupal.behaviors.myfunction = {
         attach: function(context, settings) {
            $( "#button1" ).click(function() {
              $( "#p1" ).toggle("slow");
            });

 }}})(jQuery);

```

# Answer
> 1 votes
Hmmm, this is a kind of tricky one! Because you want the element corresponding to the button you clicked to be the only one that toggles, correct? Not all of the elements?

I think you want something like this for your code, where everything between \[\] is replaced with the relevant selector. So \[BUTTON CLASS\] would become the class that you apply to all the buttons, such as "button", not the ID that only gets applied to a single button ("button1", "button2", and so on). Likewise, \[CHILD CLASS\] would be replaced with a class that you apply to all elements that you have IDs such as "p1", "p2", etc on.

```
(function ($) {
  Drupal.behaviors.myfunction = {
    attach: function(context, settings) {
      $( ".[BUTTON CLASS]" ).each(function (index) {
        $(this).click(function() {
          $(this).parent().children(".[CHILD CLASS]").toggle("slow");
        });
      });
    }
  }
})(jQuery);

```

Hope that helps!

**Edit** Updates made to the code to get the button parent and then the #p1 from there. It assumes that the #p1 and the #button1 are both children of the same element.

**Edit 2** Given the structure

```
<div class="buttoncontainer">
  <ul class="buttonlist">
    <li><button class="button1">Toggle</button></li>
    <li><a href="#"><button class="button2">Link</button></a></li>
  </ul>
  <p class="p1" style="display:none">Text to be written here</p>
</div>
<hr>
<div class="buttoncontainer">
  <ul class="buttonlist">
    <li><button class="button1">Toggle</button></li>
    <li><a href="#"><button class="button2">Link</button></a></li>
  </ul>
  <p class="p1" style="display:none">Text to be written here</p>
</div>
<hr>
<div class="buttoncontainer">
  <ul class="buttonlist">
    <li><button class="button1">Toggle</button></li>
    <li><a href="#"><button class="button2">Link</button></a></li>
  </ul>
  <p class="p1" style="display:none">Text to be written here</p>
</div>

```

The following JS does what you want, I believe:

```
$( ".button1" ).each(function (index) {
  $(this).click(function() {
    $(this).parents('.buttoncontainer').children(".p1").toggle("slow");
  });
});

```

---
Tags: javascript
---


title: Print query result on form page

text:
# Question
Title: Print query result on form page
I'm writing a custom module to obtain an online quote.

The form has an additional button and once it is clicked, a database query runs and print a value.

```
//My code for custom button
function garden_form_alter( &$form, &$form_state,$form_id ){
if ($form_id == 'webform_client_form_4208') {
$form['actions']['garden_quote']  = array(
    '#type' => 'submit',
    '#value' => t('Get online estimate'),
    '#submit' => array('mymodule_custom_submit'),
);
$form['#validate'][] = 'mymodule_custom_validate';
}
}

//Custom submit handler
function mymodule_custom_submit($form, &$form_state) {
$query = db_select('gardenvalue', 'f');
$query->fields('f', array('total_cost'))
    ->condition('meters', '2', '=');
$result = $query->execute();
dpm($result);
}

```

Once the form has been submitted dpm shows the 'meters' value as'db\_condition\_placeholder\_0' and not number 2. What can be the reason?

Also I would like to show the $result value on a new text field once the form reloads. If we assume this new text field key is 'total\_garden' how can I change its' value to $result on form reload?

Thanks in advance!

# Answer
> 0 votes
```
//My code for custom button
function garden_form_alter(&$form, &$form_state, $form_id ){
    if ($form_id == 'webform_client_form_4208') {
        $form['actions']['garden_quote']  = array(
            '#type' => 'submit',
            '#value' => t('Get online estimate'),
            '#submit' => array('garden_custom_submit'),
        );
        $form['#validate'][] = 'garden_custom_validate';
    }
}

//Custom submit handler
function garden_custom_submit($form, &$form_state) {
    $query = db_select('gardenvalue', 'f');
    $query->fields('f', array('total_cost'))
        ->condition('f.meters', 2, '=');
    $result = $query->execute();
    dpm($result);
}

```

You have spacing errors and identation errors, the condition is not pointing to a field in the table, and you have to dig into the results array to extract the value, as far as I know you only can print results in a form with

`drupal_set_message(t('your message', 'success');` instead of `dpm` hope this help you a little bit...

---
Tags: webforms, database
---


# Question
Title: Views: Link Title using Text URL field (GUID)
I've created a feed within aggretator that I am displaying using views. I have a title field and a separate GUID field, which contains the link to each specific item's audio podcast. However, **when I opt to display the Title as a link, it simply links to the RSS feed's URL**. I would like to make it link to the GUID field, which contains that title's audio URL.

*How can I use one field in Views to serve as the link of another field?*

# Answer
> 3 votes
Assuming that you know the link and can construct it from the GUID field (either by some/text/\[guid\_field\_machine\_name\]/maybe/more/text or just \[guid\_field\_machine\_name\] or what have you):

1. Using the dropdown arrow to the right of the Fields section of your view, select "Rearrange"
2. Move the GUID field above your title field and save
3. Make sure your title field no longer has the link box checked off, because we're going to use a different link box.
4. Click on the title field to pull up the settings where you unchecked the link box. This time, select the Rewrite options.
5. Select the link option under the rewrite options. This will show you a text box where you can use fields that appear above the title field in your rearranged list of fields in a link to add to the title field. In this box you should put your GUID url, using \[guid\_field\_machine\_name\] for the GUID field.

If you have questions, let me know, I can definitely provide more specific directions with a bit more information from you, like what exactly the GUID field contains and stuff.

# Answer
> 0 votes
Include both field. And in rewrite field use something like this

```
<a href="[guid-link]">[title]</a>

```

You can use replacement tokens to search for proper token. Also re-arrange the fields to list guid before title in order to show up in replacement token. also check exclude from display in guid field settings.

---
Tags: 7, views, feeds
---


title: formBuilder()->submitForm() not working

text:
# Question
Title: formBuilder()->submitForm() not working
In Drupal 8, I'm getting an exception 'InvalidArgumentException' with message 'The form argument system\_theme\_settings is not a valid form.'

The story is: I can't add custom colors to my installation profile because of the color module not setting the configuration until a form submit on the theme's settings is called, so I got the form\_id with hook\_form\_alter(), added a custom form\_submit handler and serialized the form\_state variable into a file (because form\_state was gigantic and I had no idea how to find the useful values in there) and loaded it with unserialize() in my installation profile. (Kind of reminiscent of this issue: https://www.drupal.org/node/1963922)

Then, I ran: \Drupal::formBuilder()-\>submitForm('system\_theme\_settings', $form\_state\_variable);

And was told by Drupal that 'system\_theme\_settings' isn't a valid form. But, how can this be true, if I already added a custom form submit handler to this form using this very form\_id?

If I'm not supposed to use a form\_id, but rather a specific function or something like that, where should I look to find this function?

# Answer
> 1 votes
The api documentation for `FormBuilder::submitForm` is not exactly correct. The `$form_arg` argument no longer can be a function, but it refers to the class name or form object of the form. In this case ThemeSettingsForm is the class corresponding to `system_theme_settings` per its `getFormId()` method return value.

However I am not sure that calling `FormBuilder::submitForm` will work from your question because form state may not be valid for the system theme settings form. It may be better to track down what specifically color module is requiring in order to set/save the necessary configuration instead of trying to mock form submission.

---
Tags: 8, forms
---


# Question
Title: Cannot get any tweets using Twitter Block
I have installed the twitter block module but I only occasionally get any tweets - if I do they disappear when the screen is refreshed. I have tried all browsers and it is the same everywhere!

# Answer
Have you tried using the twitter profile widget? The twitter profile widget allows you to stream a twitter feed from a specific user.

1. First you will need to log into twitter and configure a twitter widget. When you configure the twitter widget (using your twitter account) you will have output html code.
2. Once you do this you can then create a content type called twitter widget. Once this content type is created all you have to do is place the html text from your twitter widget into the content type.
3. Make sure that in your content type text box you set the text to read plain html. Once saved this will create block that can then be configured and dragged around the page.
> 1 votes

---
Tags: blocks, social-network
---


# Question
Title: How to download the files data attached to webform
I have **webform** with text fields and file **upload field**. How can i *download* the all the documents which was uploaded through this webform.

# Answer
You can do it by using these modules:

Webform Protected Downloads

> This module provides a handy solution for the following situation:
>
> * you want to offer some files for download to either anonymous or registered users
> * you don't want those files to be publicly accessible
> * you want to collect some data before granting access to the files
> * you want to be sure that the user gives a valid email address

Webform2PDF

> The Webform2PDF Drupal module is an extension of the Webform module. It can be used to generate PDF document from the results of a form. The generated PDF document can be attached to the form summary e-mail sent by Webform module, or it can be downloaded from the /Results/ page. Different PDF templates can be set for each form.
> 0 votes

---
Tags: entities, webforms, files
---


# Question
Title: CTools modal return incorrectly return html instead of ajax commands
I am trying to create custom login form using Ctools modal window. There seems to be a problem upon submitting the correct username and password.

The page callback function is supposed to return a JSON of the ajax commands. Right now it is instead returning an AJAX error, with the response as the HTML text of the user profile page (eg. user/123). The return code is 200. Which seems to suggest that the function got redirected to the user page, which shouldn't happen for AJAX call. I might be wrong on this though.

I have used the same pattern for other forms, such as register form and reset password, which work fine. Anybody has any idea why this is happening? Thank you all.

Here are my codes:

hook\_menu:

```
$items['modal/user_login/%ctools_js'] = array(
    'file'=> 'popup_login.inc',
    'page callback' => 'my_module_user_login',
    'page arguments' => array(2),
    'access arguments' => array('access content'),
    'type' => MENU_CALLBACK,
);
$items['test_ctool_popup'] = array(
    'title' => "Test Login Popup Page",
    'page callback' => 'my_module_test_login_page',
    'access arguments' => array('access content'),
    'type' => MENU_NORMAL_ITEM,
);

```

page callback function: `my_module_test_login_page`

```
function my_module_test_login_page () {
    ctools_include('ajax');
    ctools_include('modal');
    ctools_modal_add_js();
    ctools_add_js('ajax-responder');
    if(!user_is_logged_in()){
        $link = ctools_modal_text_button(
            'Log in modal',
            'modal/user_login/nojs',
            'Log in');
    } else {
        $link = 'user already logged in';
    }

    return <<< HTML
    <div class="modal-link">$link</div>
HTML;
}

```

modal callback function: `my_module_user_login`

```
function my_module_user_login ($js = null) {
if(!$js){
    return drupal_get_form('my_module_user_login_form');
}
ctools_include('ajax');
ctools_include('modal');
$form_state = array(
    'ajax' => TRUE,
    //'title' => t('Log In')
);
$output = ctools_modal_form_wrapper('my_module_user_login_form',$form_state);
if (!empty($form_state['ajax_commands'])) {
    ctools_add_js('ajax-responder');
    $output = $form_state['ajax_commands'];
}
print ajax_render($output);
}

```

form function `my_module_user_login_form`

```
function my_module_user_login_form ($form, &$form_state) {
    $login_form = user_login($form, $form_state);
    $login_form['name']['#title'] = t('Email');
    $login_form['name']['#size'] = 25;
    $login_form['pass']['#size'] = 25;
    //$login_form['#validate'][] = '_ewp_property_user_login_form_validate';
    return $login_form;
}

```

submit function `my_module_user_login_form_submit`

```
function my_module_user_login_form_submit ($form, &$form_state) {
    user_login_submit ($form, $form_state);
    unset($form_state['redirect']);
    $commands = array();
    $commands[] = ctools_modal_command_dismiss(t('Log In Successful.'));
    $commands[] = ctools_ajax_command_reload();
    //$commands[] = ctools_ajax_command_redirect('modal/dismiss_modal/nojs');
    $form_state['ajax_commands'] = $commands;
}

```

# Answer
Turns out the offending part is not the logic, but the function name. The `my_module_user_login_form` function happens to be a invoke hook form, which interferes with the modal.

Changing the function name solved the problems.
> 0 votes

---
Tags: ajax, users, chaos-tool-suite
---


title: How to get unpublished date of a node?

text:
# Question
Title: How to get unpublished date of a node?
Is there a way to get the unpublished date of a node? I want the date of unpublishing of nodes to be displayed in the view in a grid.

I need it non-programmatically (ie, tweaking the UI), but if it is only available programmatically, then how do I display it in the grid view?

A total Drupal noob here. I am using D7 btw.

# Answer
Create a View (using the Views module) that shows `Content` and displays a `Grid` of `fields` in **Display format**. Add the field `Updated date`in the list of **Fields**. Be sure to select `Published: No` in the `Filter Criteria`. You can add other fields if you want (e.g. Title). This will get you the date of the last update. If the node is not edited after being unpublished, the unpublished date will be the last update.

**EDIT:** If you specifically want to show the unpublished date, I am not aware of a module for this. I suggest another approach that is a bit circuitous, but it works. It involves creating a date field to store the unpublished date, and using Rules to set it when the node is unpublished.

1. Download the following modules: Date and Rules.
2. Edit your Content Type. Create a date field
3. Create a Rule that reacts to *After updating existing content of type XX*. Add a condition `node:status equals unpublished`
4. The *Action* should be set the date field value to `now`

That's it. Now, if you want to hide the date field in the node edit form or display, you can play around with your theme's CSS classes or explore other modules. Let me know if you have questions
> 1 votes

# Answer
One way to do it non programmatically is through the Rules module which basically is a collection of events, conditions and actions.

For example: \# Event: add event: Node: After unpublishing live content. \# Condition(filters): Node: Content is of type. \# Action: Set a data value.

You can set more than one condition to filter the nodes that fit your criteria best, and for the last bit maybe add an extra hidden date field for unpublication dates for rules to edit whenever the event is triggered.
> 1 votes

# Answer
You can get by using these modules :

Publication Date

> The Publication Date module adds a "Published on" date for each node, containing the date when it was first published.
>
> Without this, the only dates available for nodes are their created date and changed date, but these are often insufficient to meet the needs of publishing workflows. Sorting nodes by their created date doesn't account for content which is held in draft form for a time while being readied for publication. Sorting nodes by their changed date fails to account for content needing minor corrections after being published.

view\_unpublished

> This module allows you to grant access for **specific user roles** to view unpublished nodes of a **specific type**. Access control is quite granular in this regard.
>
> Additionally, using this module does not require any modifications to your existing URL structure.
> 0 votes

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


# Question
Title: How to fetch all the details of a marketplace organization's page on Drupal.org
I am new to Drupal. I am trying to fetch all the details of a marketplace organisation's page, which are visible on drupal.org.

I am using the node id to access "https://www.drupal.org/api-d7/node/xxxxxxx.json" (where "xxxxxxx" is the node id).

I am not getting all the data in the response.

Is there any way to fetch all the data of a particular page in json?

# Answer
You can check with GET method with your URL.

GET https://www.drupal.org/api-d7/node/782.json
> 0 votes

---
Tags: community-official-site
---


# Question
Title: Use ajax not working in views block displayed programmatically
I have a view with a block display. In the "OTHER" area of the view settings, I checked "Use Ajax".

I display this block programmatically inside a node in this way

```
print $view->render('block_1');

```

The block is displayed, but when I use the pager to go to the next page of the results, ajax is not used and the page is reloaded with "page=1" added to the url.

any idea? thank you

**I found the solution**

To have the "use ajax" working, you have to render the view using:

```
$view->set_display('block_1');
print $view->preview('block_1');

```

# Answer
> 0 votes
I found the solution

To have the "use ajax" working, you have to render the view using:

```
$view->set_display('block_1');
print $view->preview('block_1');

```

---
Tags: 7, views
---


title: Services CSRF Token request security

text:
# Question
Title: Services CSRF Token request security
A Drupal website that my company is maintaining has a REST endpoint, using Drupal Services (likely not that relevant). One of the systems that I'm writing has to write changes in the system to that website over REST. To do this, we first have to 'login' to the system, for which we get a session token and id, and then have to get a CSRF token from this same website. To get this token, we have to make a request to the website, giving the token and id we got earlier. After this, we can use the token and id, combined with the CSRF token, to make edit requests.

But why does having to request this CSRF token first make this system any more secure?

# Answer
> 2 votes
If you are using the services module and the user login endpoint, when you perform the login trough your app you should receive:

* sessid
* session\_name
* token
* user

(This can be investigated further checking the source code here.)

To make all subsequent calls keeping alive the session you just opened (i.e. as a registered user), you need to send the cookie session value and the csrf token value.

For example:

```
$ curl http://example.com/app/v1/endpoint --header "Content-type: application/json" --header "Accept: application/json" --header "X-CSRF-Token: X-_xz1fu5eSyHeBPqExAPDg4CdZKlHdiW6Lr7SP3N3Y" --header "Cookie: SESS40c98733719ab6b30c22a4545524a6cc=VWcWeGkTF7xgeMyoQwx5CGPHzIhttUUwmcwq_usiimk"

```

In theory you shouldn't need to make an extra call just to get the CSRF token, because it is already returned in the first response.

---
Tags: services, csrf
---


# Question
Title: Nodes created on 1st date of the month are not showing up on Calendar
I am using the following modules

1. Calendar
2. Date

There is an attendance content type with a field of type date. The nodes of this content type get pulled in a Calendar.

But, nodes which are created on the 1st date of the month are not showing up in the calendar.

# Answer
It's not clear if you are A\> using a "date contextual filter" and "page by date" or B\> you are simply showing content in a calendar.

If it's B\>, check your date filter and make sure you have "greater than or equal to" set to ensure the first day gets included.
> 0 votes

---
Tags: datetime
---


title: Add extra button on webform and Ajaxify

text:
# Question
Title: Add extra button on webform and Ajaxify
I'm building a form similar to attached image.

Customer enters values for all 3 text fields and click 'Get Online quote'. This will perform a database query (using AJAX) and display a value just below 'Get Online quote' button.

If he's happy with the quote, can ask to get contacted by clicking the second button, 'Contact me for more details'. Therefore second button act as the form submit button which will redirect to a thank you page.

So far I have coded like below.

```
// online quote button
function fence_quote_form_alter( &$form, &$form_state,$form_id ){
  if ($form_id == 'webform_client_form_4208') {
    $form['actions']['fence_quote']  = array(
    '#type' => 'submit',
    '#value' => t('Get online estimate'),
    '#submit' => array('fence_quote_custom_submit'),
    '#ajax' => array(
      'callback' => 'fence_quote_form_callback',
      'wrapper' => 'fence_quote-submit-button',
    ),
  );
    $form['#validate'][] = 'fence_quote_custom_validate';
  }
}

function fence_quote_custom_validate($form, &$form_state) {
  // your validation code
}

function fence_quote_custom_submit($form, &$form_state) {
  $query = db_select('fence_900', 'f');
  $query->fields('f', array('total_cost'));
        ->condition('meters', 2, '=');
  $result = $query->execute();
}

function fence_quote_form_callback($form, &$form_state) {

}

```
* I'm unclear on what to put under AJAX callback function. Should I have the database query in it instead of putting inside custom submit function?
* How can I display the database query value below the 'online quote' button on a new text field? I'm unable to print using $form\_state\['values'\]\['total'\]

# Answer
1. Db Query in Ajax callback. I would suggest to change type of Ajax-Button from `submit` to `button`.
2. In callback `return` instead of `print`. You should also use `->fetchAll()` for instance after `->execute()`
> 0 votes

---
Tags: ajax, webforms, forms, routes
---


# Question
Title: How do I load external JavaScript before local JavaScript?
I try to load JavaScript with `drupal_add_js()`, but it's not easy, and after fixing the loading of external JavaScript, I faced off a loading order issue: My external JavaScript is loaded after my local ones, and I would like the opposite behavior. Is it possible with Drupal 6?

Additional problem but optional: Is it possible to load these in footer instead of the header?

This is my code.

```
function d6_ce_susy2_preprocess_page(&$vars){
    //http://www.zites.net/en/load-external-javascript-files-drupal-6/
    $external_js1 = 'https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js';
   drupal_add_js('document.write(unescape("%3Cscript src=\''. $external_js1 .'\' type=\'text/javascript\'%3E%3C/script%3E"));', 'inline');
    $external_js2 = 'http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.11.3.min.js';
   drupal_add_js('document.write(unescape("%3Cscript src=\''. $external_js2 .'\' type=\'text/javascript\'%3E%3C/script%3E"));', 'inline','header');
    $external_js3 = 'http://cdnjs.cloudflare.com/ajax/libs/masonry/3.3.2/masonry.pkgd.min.js';
   drupal_add_js('document.write(unescape("%3Cscript src=\''. $external_js3 .'\' type=\'text/javascript\'%3E%3C/script%3E"));', 'inline');
   drupal_add_js(drupal_get_path('theme', 'd6_ce_susy2') . '/js/jquery_init.js','theme');
   drupal_add_js(drupal_get_path('theme', 'd6_ce_susy2') . '/js/js_jquery_new.js','theme');
   drupal_add_js(drupal_get_path('theme', 'd6_ce_susy2') . '/js/jquery_exit.js','theme');
   drupal_add_js(drupal_get_path('theme', 'd6_ce_susy2') . '/js/js_jquery_defaut.js','theme');
      }

```

# Answer
You can below preprocess function with scope and weight. You would need to set scope as footer and add the variable to html.tpl.php before body tag.

```
function paddle_theme_preprocess_html(&$variables) {
  drupal_add_js(drupal_get_path('theme', 'paddle_theme') .  '/scripts/footer.sticky.js',
  array(
    'type' => 'file',
    'scope' => 'header',
    'group' => JS_THEME,
    'every_page' => TRUE,
    'preprocess' => FALSE,
  ));
}

```

Also for Drupal 6, you can check the following reference with Advance JS aggregation or LABjs which can do the parallel loading.

http://www.drupalden.co.uk/move-render-blocking-javascript-bottom-page
> 0 votes

---
Tags: 6, javascript
---


# Question
Title: How to strip html from Elasticsearch and search API index?
I'm also using the search API autocomplete module. When I start typing, the autocomplete shows fields with html code.

What settings do I need to set to get the index to store correctly?

# Answer
i had the same problem. The solution for me came from unchecking the 'Elasticsearch direct link' checkbox in the edit form of the autocomplete tab in the search api index.
> 1 votes

---
Tags: search, ajax
---


# Question
Title: How merge two different views on single page?
How can I merge two different **views** on single page by displaying value with common filter condition for both views.

Ex: I have view1 and View2 and now I want to display both views on single page and filter condition if I select Id card number from View1 along with view1 fields the respected linked users in view2 should display.

# Answer
> 2 votes
Views Global Filter

> Use Views Global Filter on sites that feature multiple Views. You want the views to be driven by the same filter selection, for instance a country, a date range, a search term or even proximity to a post code. These views may be on the same page or scattered across several pages on your site, however you want to offer the visitor the convenience of setting the filter for all these views only once, for instance when they first land on your site. Views Global Filter implements the picked once, operates site-wide (POOS) principle. This means you can place anywhere on your site a selection widget (drop-down, check boxes etc) to globally filter all or some of your views. When the user picks a value from the global selector, the value is invisibly passed as a contextual filter to whatever views you like, even when these reside across multiple pages. This avoids you having to duplicate filters and avoids the visitor having to re-select their choice as they go from page to page.

Combine two views on one page

---
Tags: views
---


# Question
Title: How to hide install new module link on http://localhost/admin/modules page?
I want to hide **install new module** link on http://localhost/admin/modules page?

I have created a new user role he/she have all admin rights(Editor Role), but I don't want to show **install new module** link to that user so that user should not be able to install any module in the website.

# Answer
Why not just remove the `Administer modules` permission under `System` for that role?
> 4 votes

# Answer
Probably what you want is just to remove the permission **Administer software updates** from the role you mention. This way the user can still access the modules page, but won't be able to install new modules.
> 4 votes

---
Tags: users, hooks
---


title: How hook_form_alter() works in Drupal?

text:
# Question
Title: How hook_form_alter() works in Drupal?
How `hook_form_alter()` works in Drupal? It will work when the form is just loaded right ? I need to modify the form variables before submission only . Suppose i am modifying some form variables after rendering the form and the submitting it , where i can write the code for this ?

Take an example as I have a form `node_form()` , and I am modifying the form variables in `node_form_alter()` and processing the submission in `node_form_submit()` function . Will `node_form_alter` work on pre submission too ? Or is there any workarounds ?

# Answer
Yes, the code inside `hook_form_alter()` or `hook_form_FORM_ID_alter()` will be run when the `$form` array is being built, and before it is rendered.

All active modules that implement one of these two hooks will have their implementations called before the `$form` array is rendered. (They will be called in sequence according to their weights).

If you need to alter or manipulate the values **being submitted** by the form, you can use one of these two mentioned hooks to include in the `$form` array your custom **#validate** or **#submit** functions, where you can perform any kind of code processing you need.

A good source for finding examples of all these functionalities is the examples module, specifically around here.
> 2 votes

---
Tags: forms
---


# Question
Title: How to rewrite the out put of field in view
In view for title, I have rewrite the output as link and passing other view link. But after doing this also its not taking to the page link for that node.

Why is this? I am doing mistake?

# Answer
I think in your view's **Configure field** section of **Content: Title** you already checked the following option.

**Link this field to the original piece of content**

If this option is checked then mostly your **rewrite the output** won't work. Please check that.

Hope this will help you..
> 1 votes

---
Tags: views
---


title: Bulk Update Meta Tags?

text:
# Question
Title: Bulk Update Meta Tags?
I was wondering if it is possible to bulk update the meta tags for a particular content type? I have set the default to this: \[node:field\_description\]. But all of the content is in the site. I'd prefer to not go through every node to paste that in the Meta tags Description field.

Is there a bulk operation to put that placeholder token into all the nodes of a particular content type?

Using this module: https://drupal.org/project/metatag The Metatag module on Drupal 7.

# Answer
You may use combination of Metatag, Views and Editable Fileds.

* Configure node types to use own fields for meta tags like
keywords, description, abstract, etc. and create it. use Field
Permission to restrict access to this fields.
* Configure Metatag to use newly added fields for filling metatags
on Metatag admin page or node type page.
* Create view with table display, add metatag-fields. Choose
formatter "Editable" on each field settings.
* Set path for this view like admin/config/search/metatags/massedit. Save view and now you can mass edit any fields.

Also you can try Editable Views module.
> 1 votes

# Answer
Sadly there does not seem to be a way to bulk update the meta tags without some database or PHP work.

You're best bet would be to look at the structure in metatags table, and use PHP to join it with the node table on the type you want and manually update it using the database & serialize to put it back together. You may want to copy an already done serialized array from the database so you replicate the content.

But that may not be the best idea incase some have special parameters or something.
> 0 votes

---
Tags: meta-tags
---


# Question
Title: Make a carousel of every node associated with a term in a particular vocabulary
I have a vocabulary with a lot of terms in it, I want to show list of each term's nodes as a carousel using views.

I rather using OwlCarousel module to achieve this.

Can you guide me how to configure the views to achieve this?

# Answer
> 1 votes
Here are the steps

* Make a views of taxonomy terms.
* Add a relationship referencing node from that taxonomy terms
* Now you will have the required node fields available in views field
* Add the required field and change the display to carousel.

I hope this will help.

---
Tags: views, javascript
---


# Question
Title: How do I allow users to see other users' views based on taxonomy fields
I have a bunch of nodes called 'article' with a taxonomy field attached called 'publication'

I have also added the 'publication' field to the user so he/she can choose which publications they want to see - they select these and then there's a view where they can only see their own selection, based on a contextual filter.

Question is, how can I let users select the option to see other users' chosen publication view. Can this be added to their setting page, along with the actual publications - /user/1/edit?destination=admin/people

# Answer
> 0 votes
It is possible with views relationship and contextual filters. You can add a relationship that references users and publications and then add user id to filter the publication based on the result

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


title: Calculate Audio file duration

text:
# Question
Title: Calculate Audio file duration
I am using Drupal url field in which I input any external url of an MP3 file hosted on Twilio Server and I then use html5 audio tag to render it as an audio file in node display. Everything looks fine until my client asked me to calculate the duration of the audio and display it as a column in my views.

Is there any way I can achieve this?

Thanks!

# Answer
getID3 can be used to calculate the size of the file.

```
$fileinfo = getID3_analyze(drupal_realpath($name2));
$playtime_sec = round($fileinfo['playtime_seconds'] / 60);

//Generate playtime in minutes (for display only), @type String
$playtime_mins = $fileinfo['playtime_string'];

```

use the following modules to integrate with views. https://www.drupal.org/project/computed\_field https://www.drupal.org/project/getid3
> 3 votes

---
Tags: 7, views, files
---


# Question
Title: On a Drupal user application form, is it possible for the user to lookup existing users?
I'm looking to add a user lookup form to my Drupal site's application form. One question would ask the applicant/registrant to look up an already existing user on the site. What's the best way to go about something like this in Drupal?

# Answer
Yes it is possible but would require some custom code.

Assuming you already have a form element where your autocomplete search would take place, in a `hook_form_alter()` or `hook_form_FORM_ID_alter()` you could use something like:

```
  // Add ajax autocomplete.
  $form['name_of_your_text_element']['#attached']['js'][] = 'misc/autocomplete.js';
  $form['name_of_your_text_element']['#autocomplete_path'] = 'ctools/autocomplete/user';

```

Note that you will probably need to adjust some permissions in order to allow anonymous users to see your users' information. Check /admin/people/permissions if you need to fine-tune something there.

You also need to have the ctools module enabled in order to use this functionality.
> 0 votes

---
Tags: users
---


# Question
Title: Are there any modules for Profile2 revisioning/moderation
We're using Workbench moderation, and have a new requirement to add revisioning to the profile2 content. The primary reason for this is ensure that users' profile data has some degree of moderation before being made live.

If there is no current module solution for this, can anybody suggest the steps needed to create a module for this functionality.

# Answer
> 0 votes
Two options:

1. There is a patch for profile revisions here.
2. There is a Profile 2 Moderation module.

(I will update this answer as I'll be trying out both of these.)

---
Tags: users
---


title: How to create a link for field value?

text:
# Question
Title: How to create a link for field value?
I am using views in that views i can able to give only title field as a link.I want to give field value also as link.while clicking on field link i need history of that field

> > example-In my content i have one field like warnings(newbirth,live,dead).when saving the content it is saving in view after that again the same field i am updating so thats why i think to do that field as link while clicking on that link suppose it is DEAD then it should show previous data like NEWBIRTH,LIVE

any suggestions...Thanks in advance

# Answer
> 0 votes
You should have the field and the link included in your views

The steps are as follow:

* Using the dropdown arrow to the right of the Fields section of your view, select "Rearrange"
* Move the history link field above your field that you want to link and save
* Make sure your history link field no longer has the link box checked off, because we're going to use a different link box.
* Click on the field to pull up the settings, select the Rewrite options. Select the link option under the rewrite options. This will show you a text box where you can use fields that appear above the title field in your rearranged list of fields in a link to add to the title field. In this box you should put your history link, using \[history\_link\_machine\_name\] for the field.

Similar answer can be found here Views: Link Title using Text URL field (GUID)

---
Tags: views, entities, navigation
---


# Question
Title: Using hook_theme() when there is a preprocess
We had a outside company help us with our Drupal version of our site. They created the code below.

Since then we have hired another company that seems to be more professional about there code and standards.

The code below is the entire code of the module. The new company suggested that we "Implement hook\_theme and create a template for alerts, move markup from hook\_preprocess\_page to the template."

I understand a bit about Drupal modules, but I'm unsure how to accomplish what they are suggesting.

Can someone help me in this regard?

```
<?php

function foo_alerts_preprocess_page(&$vars) {
  $vars['alerts'] = '';

  if ($nid = foo_alerts_check_alerts()) {
    $node = node_load($nid);

    if (isset($_COOKIE['alert'.$node->nid]) && $_COOKIE['alert'.$node->nid] == 'closed') {
      return;
    }

    $html = '<div id="alert-bar" rel="'.$node->nid.'"><div class="inner">';
    $html .= '<h2>News Alerts:</h2>';
    if (isset($node->field_link['und'][0]['url'])) {
      $html .= l($node->title, $node->field_link['und'][0]['url'], array('attributes' => array('title' => $node->field_link['und'][0]['title'], 'class' => array('alert-link'))));
    } else {
      $html .= '<span class="alert-link">' . $node->title . '</span>';
    }
    $html .= '<a href="#" id="close-alert-bar"></a>';

    $html .= '</div></div>';
    $vars['alerts'] = $html;
  }
}

function foo_alerts_check_alerts() {
  return db_query("SELECT nid FROM {node}
    LEFT JOIN {field_data_field_dates} ON entity_id=nid
    WHERE type='alert' AND field_dates_value < NOW()
    AND field_dates_value2 > NOW() AND status = 1 LIMIT 1")->fetchField();
}

```

# Answer
So, `hook_theme` is where you define your theme implementations and templates to use for them. In your case, that would look something like:

```
foo_alerts_theme() {
  $module_path = drupal_get_path('module', 'foo_alerts');
  return array(
    'alerts_theme_name' => array(
      'path' => $module_path . '/templates',
      'template' => 'alerts-theme-template-name',
      'variables' => array(
        'node' => NULL,
      );
    ),
  );
}

```

Your template file, named `alerts-theme-template-name.tpl.php` goes in the `templates` folder in your `foo_alerts` module folder. In your page preprocess you're going to pass in the node loaded from the alerts function to the theme function, so that would look like this:

```
function foo_alerts_preprocess_page(&$vars) {
  $vars['alerts'] = '';

  if ($nid = foo_alerts_check_alerts()) {
    $node = node_load($nid);

    if (isset($_COOKIE['alert'.$node->nid]) && $_COOKIE['alert'.$node->nid] == 'closed') {
      return;
    }

    $vars['alerts'] = theme('alerts_theme_name', array('node' => $node));
  }
}

```

That leaves all of the non-template logic still in the preprocess function, and returns the output of `theme()`, which will be the html from your template. Your template would then be something like this:

```
<div id="alert-bar" rel="<?php print $node->nid; ?>">
  <div class="inner">
    <h2>News Alerts:</h2>
    <?php if (isset($node->field_link['und'][0]['url'])) : ?>
      <?php print l($node->title, $node->field_link['und'][0]['url'], array(
        'attributes' => array(
          'title' -> $node->field_link['und'][0]['title'],
          'class' => array('alert-link'),
        ),
      )); ?>
    <?php else : ?>
      <span class="alert-link"><?php print $node->title; ?></span>
    <?php endif; ?>
    <a href="#" id="close-alert-bar"></a>
  </div>
</div>

```

Does that all make sense? Do you see how the code the old dev team left you with got turned into this? If you have any questions, let me know and I'll try to explain better what I did.
> 0 votes

---
Tags: theming
---


# Question
Title: How can I copy multiple nodes and reset fields belonging to the copies in one operation?
I want to copy a list of nodes, create one copy of each node, and at the same time, reset the contents of two fields on each new copy node.

I am using Views Bulk Operations to select the nodes, and Replication with Replication UI to make copies of them.

I think I should be able to reset the two fields on my new copy nodes just with Rules, but I've been unable to work out a Rule that actually works, and several widely linked resources that refer to using VBO with Rules seem to have been deleted recently.

# Answer
I was trying to fire my Rule on the 'after replication' event supplied by Replication module, but it appears that event doesn't do what you'd think. My rule wasn't firing at all.

I fired my rule on node creation instead and in the end that worked fine with VBO, although I did consider using a component.

I asked about this on drupal.org and got some helpful comments which I link here in case they are valuable to anyone else. https://www.drupal.org/node/2254055
> 0 votes

# Answer
In my opinion is easier if you write the code in a custom module. You should create a custom form with form api with a button that call a function that select the nodes with db\_select and after does the operations, copy :

```
// Load a node
$node = node_load(1);

// unset version and node id's
unset($node->nid);
unset($node->vid);
unset($node->path);

```

and unset values of the two fields for each node and save node

```
unset($node->field1);
unset($node->field2);
node_save($node);

```

After create a custom block and in block\_view load the custom form.
> 0 votes

---
Tags: rules, views
---


# Question
Title: Cant clear cache: Table cache_rules doesn't exist
I just did a clear cache in the browser and also in the terminal with "drush cc all" and I'm getting the following error. I'm not sure what to do next as I can't clear the cache on the site, but it seems like the site is working fine. I'm on Drupal 7.32.

> PDOException: SQLSTATE\[42S02\]: Base table or view not found: 1146 Table 'phone\_drup.cache\_rules' doesn't exist: TRUNCATE {cache\_rules} ; Array()
>
> in cache\_clear\_all() (line 167 of /home/phone/public\_html/includes/cache.inc).

# Answer
> 2 votes
I ran into the same error message on an existing client Drupal install when enabling Rules through Drush. The cause was probably that the table was removed without uninstalling the module. Uninstalling it, clearing the cache and then enabling it again solved the problem. In Drush commands:

```
drush pm-uninstall rules
drush cc all
drush en rules

```

# Answer
> 2 votes
It's related to this: https://www.drupal.org/node/2160645#comment-9904817

it seems that this is a reoccurring problem for drupal 7 sites. I'm not sure why it happens but it seems the fix is to DROP the cache\_rules table and then recreate it again. But sometimes it doesnt recreate the table as it might throw an error -1 on recreation.

I went into the terminal and to the mysql console and did the following:

```
DROP TABLE cache_rules ;

```

FYI: I had to set the *engine* parameter to blackhole in order for it to work. Default it is innodb. I'm not sure what blackhole is for. Just copy and paste into the terminal:

```
CREATE TABLE IF NOT EXISTS `cache_rules` (
  `cid` varchar(255) NOT NULL DEFAULT '' COMMENT 'Primary Key: Unique cache ID.',
  `data` longblob COMMENT 'A collection of data to cache.',
  `expire` int(11) NOT NULL DEFAULT '0' COMMENT 'A Unix timestamp indicating when the cache entry should expire, or 0 for never.',
  `created` int(11) NOT NULL DEFAULT '0' COMMENT 'A Unix timestamp indicating when the cache entry was created.',
  `serialized` smallint(6) NOT NULL DEFAULT '0' COMMENT 'A flag to indicate whether content is serialized (1) or not (0).',
  PRIMARY KEY (`cid`),
  KEY `expire` (`expire`)
) ENGINE=blackhole DEFAULT CHARSET=utf8 COMMENT='Cache table for the rules engine to store configured items.';

```

# Answer
> 0 votes
Try to (temporary) disable the module that this table is related to (which created the table when it got enabled). The retry the clear cache, and enable the module again.

According to the Drupal Support forum, it seems to be the Rules module. A few options to move forward:

* Some type of fix (or at least work around), is to just drop and recreate that table.
* Perform `REPAIR TABLE cache_rules;`.
* Just create the table (if it doesn't exist).

---
Tags: 7
---


# Question
Title: How to create custom access permissions for entity form
I am using Entityforms on my site. I want to be able to create custom access permissions, which would prevent users of role 'member' from submitting more than 2 submissions. I am fine doing this programatically, but I haven't yet found a good way of doing this.

I tried using the `hook_entityform_access_alter`, but I dont see where its called. I tried printing some dpms and they never showed up anywhere:

```
/**
* Implements hook_entityform_access_alter().
*/
function wai_scholarship_access_entityform_access_alter(&$access, $op, $context) {
 dpm($access);
 dpm($op);
 dpm($context);
}

```

# Answer
The reasons the dpm()'s in your hook are not showing is that this hook function is not being called when you access the form as an administrator (administrators bypass all access restrictions). I tested this for authenticated users, and it does work. The hook is called as expected. (To test it yourself be sure to allow devel permission to the authenticated user so that you can see the output of the dpm). The hook is being called when a user accesses the form.
> 3 votes

# Answer
Alternatively, you can do something like this

```
  $count = db_result(db_query("SELECT sum(data) FROM {webform_submitted_data} WHERE nid = %d AND cid = 7", $node->nid));

  // The submission limit is 125 - if it has been exceeded...
  if ($count >= 125) {
    // Uncheck all role access for this node. This disables access so users will see
    // this message when they navigate to the form: 'Registrations are no longer being accepted as this event is full. Thank you for your interest.'
    $node->webform['roles'] = array();

    // Save the node with all roles unchecked
    node_save($node);
  }

```

the code is for webform but you will get rough idea of how to approach it
> 0 votes

---
Tags: entities
---


title: Change domain name for a multi site

text:
# Question
Title: Change domain name for a multi site
I currently have a Drupal 7 Multi-Site. In my sites folder, the domains are like this:

```
winatlife.guide
journal.winatlife.guide
store.winatlife.guide

```

I need to change the domains to this:

```
blog.blessingsjournal.com
journal.blessingsjournal.com
store.blessingsjournal.com

```

In addition, my root drupal folder is changing from `win-at-life` to `blessingsjournal`.

I have made all these changes. When I visit any of domains, I get the following error message:

```
Forbidden

You don't have permission to access / on this server.

Additionally, a 403 Forbidden error was encountered while trying to use an ErrorDocument to handle the request.

```

**What could be chasing this? I haven't changed any of the permissions on the Drupal install.**

---

## Steps I have tried

**1) Database Update**

This StackOverflower answer says that the domain is hardcoded in the database and it provides a query to fix it. I have run the query, but it does't seem to have done anything. It was written in 2010, so maybe it's for Drupal 6?

**2) Make a sites.php file**

According to this Drupal Groups thread, in Drupal 7 multisites, you need to put a file called `sites.php` in the root sites directory. (In that directory there is an `example.sites`.php which can be used as a template).

I made a `sites.php` file and used the new domains but it had no effect. (Nb I did not need to use such a file before the domain change)

**3) Checking .htaccess**

My .htaccess is set as follows:

```
  # If your site is running in a VirtualDocumentRoot at http://example.com/,
  # uncomment the following line:
   RewriteBase /

```

# Answer
I was having problems because I was making a copy of the original site and then updating the code in the copy. For some reason the code was not copying properly. The databases were also not exporting properly from PHPmyadmin.

This is how I fixed it:

1. My site was in hosting that had Cpanel. So using Cpanel I made an archive of the site. I then downloaded the archive, renamed it and then uploaded to create a new copy of the site. This copy was a perfect replica of the original, so it had no problems.
2. For the databases, I used this command to export them via mysql in the command line:

mysqldump -u DATABASEUSER -p'PASSWORD' DATABASENAME \> dump.sql

In this command, you mustn't have a space after `-p`. So your command might look like this:

```
mysqldump -u host_mary -p'pass123' marywebsite > dump.sql

```
3. I then created new databases.
4. Finally, I imported the code into the new databases using this command

mysql -u DATABASEUSER -p'PASSWORD' DATABASENAME \< dump.sql
> 0 votes

---
Tags: 7, migrations, multi-sites, installation, subsites
---


# Question
Title: How to hide empty fields on user accounts display?
Let's say a profile2 has 3 fields.

```
Weight:
Height:
Length:

```

The user only inputs 45 kg and 160 cm, **BUT** for length he inputs nothing.

Now the display is like this:

```
Weight:45kg
Height:160cm
Length:Select

```

How can I hide the field that had no input like this:

```
Weight:45kg
Height:160cm

```

Since the user didn't select any value for length, and it's not a required field. I don't want it displayed on the user profile.

I know this can be done with Views and no results behavior, but I need this for user profile display.

Here is a live example:

http://vuxi.com/users/nitap

# Answer
> 0 votes
One way to look at this use node.tpl for this node type and add a php check like the following:

```
 <?php if(!empty($content['your_field_name'])): ?>
    <div class="field-label"><strong><?php echo t('Your Label'); ?></strong></div>
    <?php print render($content['Your field Name']); ?>
 <?php endif; ?>

```

# Answer
> 0 votes
In custom module or `template.php` add:

```
function THEMENAME_preprocess_user_profile(&$variables){
  if(!isset($variables['user_profile']['field_drinking']['und'][0]['value'])){
  unset($variables['user_profile']['field_drinking']);
}

```

Replace `THEMENAME` with your themename or modulename if defined in module.

The condition may not be the right one bicause I don't know if the value is not set as `Select`. But I am sure that you get the Idea.

# Answer
> 0 votes
The reason this didn't work was because I added the "Select" field to replace the default "-None-". The default must be kept to "none" and changed via hook\_form\_alter instead.

---
Tags: entities
---


title: How to debug a MySQL error? [Updated]

text:
# Question
Title: How to debug a MySQL error? [Updated]
I have been building a Drupal 7 site on my Mac. Using PHPMyAdmin, I have exported a sql dump of the database. When I upload this sql file to my host, I get the following error message:

```
There seems to be an error in your SQL query. The MySQL server error output below, if there is any, may also help you in diagnosing the problem

ERROR: Unknown Punctuation String @ 280
STR: =,
SQL:

-- --------------------------------------------------------

--
-- Table structure for table `themekey_properties`
--

CREATE TABLE `themekey_properties` (
  `id` int(10) UNSIGNED NOT NULL,
  `property` varchar(255) NOT NULL DEFAULT '',
  `operator` varchar(2) NOT NULL DEFAULT=,
) ;

SQL query:

-- -------------------------------------------------------- -- -- Table structure for table `themekey_properties` -- CREATE TABLE `themekey_properties` ( `id` int(10) UNSIGNED NOT NULL, `property` varchar(255) NOT NULL DEFAULT '', `operator` varchar(2) NOT NULL DEFAULT=, ) ;

MySQL said: Documentation

#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '=,
)' at line 10

```

How would I go about debugging this? I have searched extensively, but not found any websites that explain how.

The website functions perfectly on my localhost. I have done this process hundreds of times before, and never had any problems.

I seem to have this exact problem when transfering other sites from my Mac to my host, so I am not sure if it is a global problem. The affected sites all use themekey module which is referenced in the error message, but I can't find anything online which indicates why themekey would be causing the problem.

---

Updated.

I followed the @Erin McLaughlin's answer, but now I get the following error:

```
CREATE TABLE `themekey_properties` (
  `id` int(10) UNSIGNED NOT NULL,
  `property` varchar(255) NOT NULL DEFAULT '',
   `operator` varchar(2) NOT NULL DEFAULT '=',
)
MySQL said: Documentation

#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ')' at line 5

```

---

Updated.

I followed @Erin McLaughlin's second suggestions, but now I get the following error:

```
SQL query:

INSERT INTO `themekey_properties` (`id`, `property`, `operator`, `value`, `weight`, `theme`, `enabled`, `wildcards`, `parent`, `module`) VALUES
(1, 'themekey_compat:module_system_triggers_theme', '=', 'static', 5, 'default', 1, 'a:0:{}', 0, 'themekey'),
(2, 'drupal:path', '=', 'user/#/edit', 2, 'default', 1, 'a:0:{}', 0, 'themekey')
MySQL said: Documentation

#1054 - Unknown column 'value' in 'field list'

```

# Answer
It has got to do with the line:

```
`operator` varchar(2) NOT NULL DEFAULT=,

```

It's because the equals sign isn't surrounded with a space and then quotes, which is breaking everything. If you want to have `=` be the default operator, that line needs to be:

```
 `operator` varchar(2) NOT NULL DEFAULT '=',

```
> 5 votes

# Answer
Erin's answer is correct to the original question, so I have marked it correct. However, the problem had nothing to do with importing the mysql code. It was to do with how I was exporting the mysql in the first place.

I was simply using PhpMyAdmin's built in export tools, but for some reason, this was creating errors.

I solved the problem by using mysql commands in the command line.

If anyone has problems where the database's don't import properly, then it might be worth exporting them using the method below:

1. Use this command in the command line:

mysqldump -u DATABASEUSER -p'PASSWORD' DATABASENAME \> dump.sql

In this command, you mustn't have a space after `-p`. So your command might look like this:

```
mysqldump -u host_mary -p'pass123' marywebsite > dump.sql

```
2. Create new databases. You can do this in PhpMyAdmin as normal.
3. Finally, import code into the new databases using this command

mysql -u DATABASEUSER -p'PASSWORD' DATABASENAME \< dump.sql
> 1 votes

---
Tags: database
---


# Question
Title: How to I place the create form for content type on a page that can save the user's id?
I'm new to Drupal. I've created a content type and I've created a view (using the Views module) to display the data.

I can add data from `Content > Add Content > Item`, which gives you a Drupal admin form.

How do I place this form on a page that can save the user's id?

# Answer
> 0 votes
First, to get rid of the "modal window", go to `admin/modules` and disable the **Overlay** module.

Second, if you want your logged in users to be able to create articles:

1. Go to `admin/people/permissions` and scroll down to the *Node* section.
2. There you will find different options to grant them *Create*, *Edit*, *Delete*, etc. permissions. For example, you can check ***Article: Create new content*** under the ***Authenticated User*** column to allow them to add new items in the *Article* content type.

Now your logged-in users can go to `node/add/article` page to find the form.

---
Tags: views, forms
---


# Question
Title: Override the body field with another field in hook_node_view
I have a node type that can be scheduled. Before the start time the page will redirect to another. This is all custom functionality and is currently working.

Now I need to create a coming soon page to allow the page to be active before the start time but not show any of the details.

I've created a coming soon field in the node and I have the logic set up correctly but I am struggling with the render array.

```
function MODULE_node_view($node, $view_mode, $langcode) {
  if ($node->type == 'TYPE') {

    // admins see the page no matter what
    if (!user_access('administer site configuration')) {

      // if not started, show coming soon page
      $coming_soon = FALSE;
      if (!STARTED) {
        $coming_soon = field_get_items('node', $node, 'field_coming_soon_body');
        if ($coming_soon) {
          $node->content['body']['#object']->body[$node->language][0]['value'] = $coming_soon[0]['value'];
        }
      }
    }
  }
}

```

This however still shows the actual body of the page and not the coming soon page. I really want to do this in hook\_node\_view as well.

How can I go about replacing the content of the page with this single field?

# Answer
Just hide your `body` field, if there's a value in your `field_coming_soon_body`:

```
    if ($coming_soon) {
      $node->content['body']['#access'] = 0;
    }

```
> 1 votes

---
Tags: 7, entities, hooks
---


title: Delete unmanaged file after download?

text:
# Question
Title: Delete unmanaged file after download?
In a custom module I create a file and then use `drupal_goto` to download it. How can I delete the file after it is downloaded? Placing a `file_unmanaged_delete` after the `drupal_goto` doesn't get executed, and `hook_file_download` happens before the download for permissions checks and such. So I'm not sure how to do this. Do I have to resort to cleaning up files in a folder with cron somehow?

# Answer
> 0 votes
The following code will remove the file after download considering that your file is located in the *tmp* directory.

```
$filename = 'foobar.xls';
$temp_path = realpath(file_directory_temp()) . '/';
if (file_exists($temp_path . $filename)) {
  // Serve file download.
  drupal_add_http_header('Pragma', 'public');
  drupal_add_http_header('Expires', '0');
  drupal_add_http_header('Cache-Control', 'must-revalidate, post-check=0, pre-check=0');
  drupal_add_http_header('Content-Type', 'application/vnd.ms-excel');
  drupal_add_http_header('Content-Disposition', 'attachment; filename=' . basename($temp_path . $filename) . ';');
  drupal_add_http_header('Content-Transfer-Encoding', 'binary');
  drupal_add_http_header('Content-Length', filesize($temp_path . $filename));
  readfile($temp_path . $filename);
  unlink($temp_path . $filename);
  drupal_exit();
}

```

---
Tags: files
---


title: Need guidance installing Drush

text:
# Question
Title: Need guidance installing Drush
I have successfully installed composer, but when i try to install drush and modify the .~/.bashrc file it returns Content-Type: text/html when i run any kinda of drush command.

Anyone seen anything like this? Sorry can't be more specific but can get you any info you need to be helpful..

# Answer
If you see `Content-Type: text/html` when running Drush commands, it means that you are running Drush with php-cgi instead of php-cli.

If you already have php-cli on your system, set the environment variable `DRUSH_PHP` to point to the full path of php-cli. If you do not have it installed yet, try installing it and see if that clears up your trouble (`sudo apt-get install php5-cli` on Ubuntu).
> 3 votes

# Answer
There are various ways for doing this:

* If you are linux/ubuntu user you can simply do it with

sudo apt-get install drush
* if you are installing it on remote server just download the latest zip file from github and paste it in you bin directory on server home folder.

Hope this helps!
> 0 votes

---
Tags: 7, drush
---


title: Add 'attributes' to an html element

text:
# Question
Title: Add 'attributes' to an html element
In my drupal 7 module which is separate from the node portion of drupal (discrete tables) I'm trying to use the array of 'attributes' to one element of table using theme().

Here's a simple example:

```
$query = "SELECT projectID, title, housestaff_needed FROM Projects";
$result = db_query($query)->fetchAll();
$header = array('name' => t('Name'), 'title' => t('Title'), 'housestaff_needed' => t('Housestaff Needed'));

    foreach ($result as $item) {
      $rows[] = array(
          $item->title,
          $item->housestaff_needed,
          array('attributes' => array('id' => array('staff-' . $item->projectID))),
          );
    }
    $theme = theme('table', array('header' => $header, 'rows' => $rows));
    return $theme;

```

As you know, this only adds another element after the housestaff\_needed data. I've used this syntax before to enclose an entire table with an attribute, but I've read and read to see how this can be done on just an element but all I've read is how you can do it in the form api using '#attribute' which doesn't seem to be the same thing and a different setup outside the forms.

I'm trying to get this so I can identify this element for a jQuery scripted and can't get to first base. Please point out what I'm not doing correctly, thx, sam

# Answer
I believe you need to add the data as an array to an associative array with the `'data'` key, and the attributes with the attribute name as the key. For instance, your code would look like:

```
$rows = array();
foreach ($result as $item) {
  $rows[] = array(
    'data' => array($item->title, $item->housestaff_needed),
    'id' => 'staff-' . $item->projectID,
  );
}
$theme = theme('table', array('header' => $header, 'rows' => $rows));
return $theme;

```

I think this will add an id to each `<tr>`. If you want to add attributes to each individual `<td>`, you would use a similar structure for `$item->title` and `$item->housestaff_needed`. That is, it would become:

```
$rows = array();
foreach ($result as $item) {
  $rows[] = array(
    'data' => array(
      array(
        'data' => $item->title,
        'id' => 'SOME_ID',
      ),
      array(
        'data' => $item->housestaff_needed,
        'id' => 'SOME_OTHER_ID'
      ),
    ),
    'id' => 'staff-' . $item->projectID,
  );
}
$theme = theme('table', array('header' => $header, 'rows' => $rows));
return $theme;

```

At least, that's how it works in d6, I beleive, so here's hoping it still works in d7.
> 2 votes

---
Tags: theming
---


# Question
Title: Image shows on home page but not other pages
I've added an image to a block that shows on every page and have the image added manually in the block like so:

```
<img src="sites/default/files/image-name" />

```

It shows fine on the home page as intended, but on the interior pages it doesn't show. I inspected element and for most pages it's using the same URL to try and access it.

I cleared cache.

Thoughts on why this might be?

# Answer
> ```
> <img src="sites/default/files/image-name" />
>
> ```

right now its appending after the url of whatever page you are on.

```
yourwebsite.com/hello/sites/default/files/image-name
yourwebsite.com/article/sites/default/files/image-name
yourwebsite.com/contact-us/sites/default/files/image-name

```

instead of appending after your domain name.

```
yourwebsite.com/sites/default/files/image-name

```

so you just need to add a `/` at the beginning, so it appends after your domain name only.

**so your code needs to be:**

```
<img src="/sites/default/files/image-name" />

```
> 3 votes

# Answer
Please check if the block has permission to display content with internal pages also like block display might have been set as the only.
> 1 votes

# Answer
If all you want to have image in block you can use image block module. Its pretty easy to use.
> 1 votes

---
Tags: media
---


title: Skip A Custom Checkout Page

text:
# Question
Title: Skip A Custom Checkout Page
So I thought I had been pretty clever when in the code for a custom checkout pane, in a custom checkout page, I did this:

```
function checkout_pane_giftaid_pane_checkout_form($form, &$form_state, $checkout_pane, $order) {
  if($showPane==1){
    //show something awesome
  }
  else {
    $checkout_pages = commerce_checkout_pages();
    commerce_order_status_update($order,'checkout_payment');
    $url = 'checkout/'. $order->order_number  . '/' . $checkout_pages['gift-aid']['next_page'];
    drupal_goto($url);
  }
}

```

If showPane is equal to 1 it displays the Pane's content, if not it directs you to the next checkout page. This however has presented an issue because I have two custom checkout pages.

The result of this is if you are on 'custom page 2' and press 'Go Back' it goes back to the previous page ('custom page 1'), but if $showPane=0 on this page then the else statement means its set to forward. So a user hits 'go back' on 'custom page 2' and what they see, is this page reload (actually it has gone back to 'custom page 1' where it is told to go to the next page, 'custom page 2').

So my question is this: clearly I have not gone about 'skipping' custom checkout pages in the right way, how would I do it properly?

# Answer
You can use hook\_commerce\_checkout\_router() to skip Commerce Checkout pages.

See the advanced example here: Skipping a Commerce Checkout page in the checkout workflow

```
/**
 * Implements hook_commerce_checkout_router().
 *
 * Skip the registration checkout page unless required.
 */
function MYMODULE_commerce_checkout_router($order, $checkout_page) {
  global $user;

  if ($checkout_page['page_id'] == 'registration' && $user->uid) {
    $registration_required = FALSE;
    $order_wrapper = entity_metadata_wrapper('commerce_order', $order);
    foreach ($order_wrapper->commerce_line_items as $line_item_wrapper) {
      $line_item = $line_item_wrapper->value();
      if ($line_item->line_item_label == 'Conference Attendee') {
        $registration_required = TRUE;
        break;
      }
    }
    if (!$registration_required) {
      $order = commerce_order_status_update($order, 'checkout_' . $checkout_page['next_page'], FALSE, TRUE, t('Conference Registration was skipped - not required for these products.'));
      drupal_goto('checkout/' . $order->order_id . '/' . $checkout_page['next_page']);
    }
  }
}

```
> 7 votes

# Answer
You may try to use Commerce Express Checkout module.

> The Express Checkout button redirects to the Checkout page directly, without going to the Cart first, It also removes the Review page and adds the Payment checkout pane to the Checkout page, so the whole checkout process is done on one page.

Alternatively you can edit one of the existing commerce views e.g. `commerce_cart_form` or `commerce_cart_summary` and develop the skip there.
> 0 votes

# Answer
This is the same answer that milkovsky posted but is a little more generic; it checks if any of the line items reference products that have registration:

```
if ($checkout_page['page_id'] == 'registration') {
    module_load_include('inc', 'commerce_registration', 'commerce_registration.rules');

    $registration_required = FALSE;
    $order_wrapper = entity_metadata_wrapper('commerce_order', $order);
    foreach ($order_wrapper->commerce_line_items as $line_item_wrapper) {
      $line_item = $line_item_wrapper->value();
      if (commerce_registration_order_has_registration($line_item)) {
        $registration_required = TRUE;
        break;
      }
    }
    if (!$registration_required) {
      $order = commerce_order_status_update($order, 'checkout_' . $checkout_page['next_page'], FALSE, TRUE, t('Registration was skipped - not required for these products.'));
      drupal_goto('checkout/' . $order->order_id . '/' . $checkout_page['next_page']);
    }
  }

```
> 0 votes

---
Tags: 7, commerce
---