# Question
Title: Views 3 - Create an archive for a given type grouped by year, then split in to months
I am trying to create an archive in Views 3 (Drupal 7) to use a filter for a given type to sort in to a list of nodes grouped in to Months, but then they are grouped in to Year:

```
Node Type
  |-Year
    |-September (node count)
    |-August (node count)
      ...
    |-February (node count)
    |-January (node count)
  |-Year
    |-December (node count)
    |-November (node count)
    |-October (node count)

```

I have looked at the default Archive view template, but that just groups by month (i.e. September 2012 (node count))

If anyone can help that would be great.

Thanks!

# Answer
Have anyone figured out how to do this. I'd be interested in finding out how to do this as well using views.
> 0 votes

---
Tags: views
---


# Question
Title: Is there a way to add a foreign key to a table?
My question is not regarding `hook_schema` but regarding `hook_update_N`: I need to add a foreign key to an existent table in drupal 7.

I was looking Here but it does not seem to exist one explicitly for foreign keys.

**Q**: How can I create a foreign key in an existent table? Which call should I do?

# Answer
> 3 votes
The underlying DBMS all support this, but Drupal7 Core doesn't really care about Foreign Keys (FKs). Views will notice them and use them abit within joins.

Drupal 7 only supports FK in documentation: http://www.interworks.com/blogs/jkhalaj/2012/04/12/drupal-7-usage-foreign-keys-schema-api-and-current-default-fk-erd

But, if you know this and understand this, then you can still use this `foreign key` defintion to create the FKs in a module.install file specific to your DBMS.

I use MySQL typically -- and I have done this for a foreign database my settings.php is aware of within a module.install file:

```
function _idremotedb_add_foreign_keys() {
  $schema = _idremotedb_schema_definition();
  db_set_active('sa_webextracts');
  foreach ($schema as $table => $table_schema) {
    if (isset($table_schema['foreign keys'])) {
      foreach ($table_schema['foreign keys'] as $fk_name => $fk_details) {
        $src_col = $fk_details['columns'][0];
        $dest_col = $fk_details['columns'][1];
        $dest_table = $fk_details['table'];
        // Create the FK using your DBMS convention. Change this as necessary
        // or add a lookup to the database handler driver type (mysql, postgres, whatever) ...
        db_query("
          ALTER TABLE $table ADD CONSTRAINT $fk_name
          FOREIGN KEY ($src_col) REFERENCES $dest_table($dest_col);
        ");
        drupal_set_message(t('...added foreign key: !fk', array('!fk' => $fk_name)));
      }
    }
  }
  // This index added for either mail-list or login.
  #db_add_index('students', 'uniqueidnumber', 'campusuniqueidnumber');
  db_set_active();
}

```

---
Tags: 7, database
---


title: show text on logo hover in over

text:
# Question
Title: show text on logo hover in over
I've been testing the various overlay modules trying to find a simple way to implement a very minimalist designed text I want to display when hovering over my logo img at http://stefanbjorklund.info/.

I'm using Zen 5.x theme

Here's what I want to achieve (see the left side under the logo, nevermind the background-color of the emaillink):

# Answer
I think that the best way to go is jQuery.

1. Create new block with text that you want to show
2. Using CSS, set block position that you want
3. Set `display:none;` for that block
4. Add jQuery script in your block (or implement on some other way).

Script should looks something like:

`jQuery("#logo").hover(
 function () {
 jQuery("#blockId").fadeIn(); //change the blockId with Id of your block
 jQuery("#block-views-projects-block").fadeTo(1000,0.5);
 },
 function () {
 jQuery("#blockId").fadeOut(); //change the blockId with Id of your block
 jQuery("#block-views-projects-block").fadeTo(1000,1);
 }
 );`

Of course, if you add this code in your block, it must to be added into `<script>...</script>` tag.
> 2 votes

---
Tags: theming, modal-dialogs
---


# Question
Title: Whitespace caused by module but cannot find why
I got thrown into taking over a project that has gone through a few different developers.

I have a problem with two spaces being output before the doctype declaration. I have confirmed it's not the template and I have isolated both of the whitespaces to be from a custom module (one I found, the other is obvious as it went away when I turned off all modules.) I already went through and verified no whitespace was caused by closing the php tag, and before it. I am confident it's caused by a module. I have error reporting turned to all and displayed but I have no PHP errors that are generated.

I used `pcregrep -rMl '\?>[\s\n]+\z' *` to find all files that had trailing whitespaces and fixed them.

When I copy and paste the whitespace into my IDE it looks like two really small dots (almost like a backtick but a dot.) When looking at it in view source of the page, it looks like two spaces.

This is an example: (Inside the single quotes, it works for copying the whitespace to see how it looks in an IDE)

```
' <!DOCTYPE html PUBLIC "-//W3C//DTD HTML+RDFa 1.1//EN">'

```

Below is a module that I can turn off to remove one of the whitespaces. Turning it back on shows the whitespace. I am not able to see what would be causing this issue. I removed the closing php tag and ensured no whitespace before the opening php tag. Flushed all cache and cleared browser cache too.

My guess is it has to be doing something that I am unaware of, perhaps a Drupal issue with the module?

**os\_registration.info**

```
name = os_registration
core = 7.x
package = Features
features[features_api][] = api:1

```

**os\_registration.module**

```
<?php

/**
 *  Implementation of hook_block_info()
 */
function os_registration_block_info() {
    $blocks['user_registration'] = array(
        'info' => t( 'User registration' )
    );
    return $blocks;
}

function os_registration_block_view( $delta = '' ) {
    $blocks = array();
    switch($delta) {
        case 'user_registration':
            global $user;
            // Don't display the form to logged in users or if registration is disabled
            if ( !$user->uid ) {
                //if (!$user->uid && variable_get('user_register', 1)) {
                return array(
                    //'subject' => t('We\'re busy working on the site right now, but Parables TV will be launching soon! <br/><br/> Submit your email address to receive information on how to get Parables.'),
                    'subject' => t( 'Not a Subscriber?<br><br>Sign Up Now for a Free 30 Day Trial!' ),
                    'content' => drupal_get_form( 'user_register_form' )
                    //'content' => theme('os_blocks_mailchimp'),
                );
            }
            break;
    }
    return $blocks;
}

/**
 *  A helper module for the Safe Streets Miami project
 */
function os_registration_menu() {
    $items = array();
    $items['login'] = array(
        'title' => t( 'Sign in' ),
        'description' => t( 'Sign in' ),
        'access callback' => 'os_registration_login_access',
        'page callback' => 'drupal_get_form',
        'page arguments' => array( 'user_login' ),
        //'type' => MENU_NORMAL_ITEM, This needs to be set when the sign in goes live
        'type' => MENU_CALLBACK,
        'weight' => 10,
        'menu_name' => 'user-menu'
    );

    return $items;
}

function os_registration_menu_alter( &$items ) {
    $items['user/login']['title'] = 'Sign In';
    $items['user/login']['weight'] = 1;
    $items['user/password']['weight'] = 2;

    // Kill the tabs on the login pages.
    //$items['user/login']['type'] = MENU_NORMAL_ITEM;
    //$items['user/register']['type'] = MENU_NORMAL_ITEM;
    //$items['user/password']['type'] = MENU_NORMAL_ITEM;

    // All these items need to be reset so that users can log in
    $items['user/login']['type'] = MENU_CALLBACK;
    $items['user/register']['type'] = MENU_CALLBACK;
    $items['user/password']['type'] = MENU_CALLBACK;
    unset( $items['user/login']['title'], $items['user/register']['title'] );
}

// handles menu item access
function os_registration_login_access() {
    return ( !isset($GLOBALS['user']) || !$GLOBALS['user']->uid ) ? true : false;
//    return ( !( $GLOBALS['user']->uid ) );
}

/**
 * IMPLENTATION OF hook_form_form_id_alter() to hook into the user
 * login form.
 */
function os_registration_form_user_register_form_alter( &$form, &$form_state ) {
    $form['account']['name']['#type'] = 'hidden';
    $form['account']['name']['#value'] = user_password();
    $form['account']['mail']['#title'] = t( 'E-mail' );

    if ( $form['#form_id'] == 'user_register_form' ) {
        // no description as it should be self evident how to use
        unset( $form['account']['mail']['#description'] );
        unset( $form['account']['pass']['#description'] );
        $form['account']['mail']['#size'] = 28;
        $form['account']['mail']['#weight'] = -10;
        // create a form field to confirm email
        $form['account']['conf_mail'] = array(
            '#type' => 'textfield',
            '#title' => t( 'Confirm e-mail' ),
            '#weight' => -9,
            '#maxlength' => 64,
            '#required' => true
        );
        $form['legal'] = array(
            '#type' => 'markup',
            '#markup' => '<div class="registration-legal"><div class="registration-legal-secure">Secure server</div><div class="registration-legal-privacy">We will not sell or rent your email address. We may contact you about the Parables service. See our <a href="/privacy-policy" target="_blank">Privacy Policy</a>.</div></div>',
            '#weight' => 200
        );
        // validate the confirm email field
        array_unshift( $form['#validate'], 'os_registration_user_form_validate' );
        os_registration_disablepwstrength_add_js();
    }

    // if the user is going to the register page then the form needs some added attention
    if ( $_GET['q'] == 'user/register' ) {
        // Have gotz to get to the front of the array
        $form['#prefix'] = '<div id="login-wrapper"><div id="login-header">' . t( '<h2>Sign Up<span> or !sign_in</span></h2>', array( '!sign_in' => l( t( 'Sign In' ), "login" ) ) ) . '</div>';
        $form['#suffix'] = '</div>';
    }
}

/**
 * Implementation of hook_form_form_id_alter() to change the submit button of the user login
 */
function os_registration_form_user_login_alter( &$form, &$form_state ) {
    drupal_set_title( '' );
    unset( $form['name']['#description'] );
    unset( $form['pass']['#description'] );
    $form['name']['#title'] = t( 'E-mail' );
    $form['name']['#element_validate'][] = 'os_registration_user_login_validate';
    $form['actions']['submit']['#value'] = "Sign in";
    //Add the forgot password link
    $form['forgot_pass'] = array(
        '#markup' => t( "!link", array( '!link' => l( t( 'Forgot your password?' ), "user/password" ) ) ),
        '#prefix' => '<div id="login-forgot-password">',
        '#suffix' => '</div>'
    );
    $form['actions']['not_registered'] = array(
        '#markup' => t( "!link", array( '!link' => l( t( 'Not a member yet?' ), "user/register" ) ) ),
        '#prefix' => '<span id="login-not-registered">',
        '#suffix' => '</span>'
    );
    // Have gotz to get to the front of the array
    $form['#prefix'] = '<div id="login-wrapper"><div id="login-header">' . t( '<h2>Sign In<span> or !sign_up</span></h2>', array( '!sign_up' => l( t( 'Sign Up' ), "user/register" ) ) ) . '</div>';
    $form['#suffix'] = '</div>';
}

/**
 * Validation function for the user regerster form
 */
function os_registration_user_form_validate( $form, &$form_state ) {
    global $user;
    // Check if email and confirm mail fields are the same
    // If they are, use elseif to check if the email exists in the
    // user database table. We are hooking into the registration process
    // here to log the person in if they have already registered. We will submit
    // this information as the submit for the login form programmatically.
    // Otherwise we will bypass this early login and let the registration
    // process finish through as normal.
    if ( $form_state['values']['mail'] != $form_state['values']['conf_mail'] ) {
        form_set_error( 'conf_mail', t( 'Your e-mail address and confirmed e-mail address must match.' ) );
        // We check to see if this submitted by someone already logged in.
        // The only logged in user submitting this form can the Editor or Administrator
        // $reg_user is just the registered user. Needed a different variable because it might
        // set the GLOBAL $user object to false.
    } elseif ( !$user->uid && $form_state['values']['mail'] && $reg_user = os_registration_user_email_exists( $form, $form_state ) ) {
        if ( user_authenticate( $reg_user->name, $form_state['values']['pass'] ) ) {
            $form_state = array();
            $form_state['uid'] = $reg_user->uid;
            user_login_submit( array(), $form_state );
            drupal_goto( '<front>' );
        }
    }
}

/**
 * Helper function to query to see if new user or not. This process does some
 * of the thinking for people who are curious about the websit but
 * haven't commited yet.
 *
 * @param mixed $form
 * @param mixed $form_state
 * @return mixed
 */
function os_registration_user_email_exists( $form, &$form_state ) {
    $query = new EntityFieldQuery();
    $query
        ->entityCondition( 'entity_type', 'user' )
        ->propertyCondition( 'mail', $form_state['values']['mail'] )
    ;
    $result = $query->execute();

    if ( !empty( $result['user'] ) ) {
        $users = entity_load( 'user', array_keys( $result['user'] ) );
        return array_pop( $users );
    }

    return false;
}

function os_registration_form_user_profile_form_alter( &$form, &$form_state, $form_id ) {
    os_registration_disablepwstrength_add_js();
}

/**
 * Add the JavaScript to disable Drupal's password strength checker.
 */
function os_registration_disablepwstrength_add_js() {
    drupal_add_js( 'Drupal.behaviors.password = function () {};', array( 'type' => 'inline', 'scope' => 'footer' ) );
}

/**
 * When the password is being reset redirct to password edit page
 *
 * Subscribers on login get sent to the live stream
 * Previous subscribers get sent to renew their subscription
 * Admins get sent to front until a dashboard is made
 * Everyone else gets sent to pricing.
 * If the $edit form
 */
function os_registration_user_login( &$edit, $account ) {
    $reset = !empty( $_POST['form_id'] ) && $_POST['form_id'] == 'user_pass_reset';
    if ( !$reset && arg( 0 ) != 'os-apps' ) {
        if ( in_array( 'previous_subscriber', $account->roles ) ) {
            drupal_goto( 'renew-pricing' );
        } elseif ( in_array( 'editor', $account->roles ) || in_array( 'administrator', $account->roles ) ) {
            drupal_goto( 'dashboard' );
        } elseif ( in_array( 'subscriber', $account->roles ) || in_array( 'promo', $account->roles ) ) {
            drupal_goto( 'live-stream' );
        } elseif ( in_array( 'family-christian', $account->roles ) ) {
            drupal_goto( 'basic-page' );
        } else {
            drupal_goto( 'pricing' );
        }
    }
}

function os_registration_user_presave( &$edit, &$account, $category ) {
    if ( !empty( $account->mail ) && !isset( $edit['name'] ) || !empty( $account->mail ) && $edit['name'] != 'admin' ) {
        $account->name = $edit['name'] = os_registration_get_new_name( $account );
    }
}

function os_registration_get_new_name( $account ) {

    // Default implementation of name generation.
    $new_name = preg_replace( '/@.*$/', '', $account->mail );
    // Remove unwanted characters.
    $new_name = preg_replace( '/[^a-zA-Z0-9.-]/', '', $new_name );

    // if username generated from email record already exists, append underscore and number eg:(chris_123)
    if ( (bool) db_query( "SELECT 1 FROM {users} WHERE uid <> :uid AND LOWER(name) = LOWER(:new_name)", array( ':uid' => $account->uid, ':new_name' => $new_name ) )->fetchField() ) {
        $name_idx = db_query_range( "SELECT SUBSTRING_INDEX(name,'_',-1) FROM {users} WHERE name REGEXP :search ORDER BY CAST(SUBSTRING_INDEX(name,'_',-1) AS UNSIGNED) DESC", 0, 1, array( ':search' => '^' . $new_name . '_[0-9]+$' ) )->fetchField();

        $new_name .= '_' . ( $name_idx + 1 );
    }
    return $new_name;
}

/**
 * Implements hook_form_FORM_ID_alter().
 */
function os_registration_form_user_pass_alter( &$form, &$form_state, $form_id ) {
    $form['name']['#title'] = t( 'E-mail' );
    $form['name']['#description'] = t( 'A password reset message will be sent to your e-mail address.' );
}

/**
 * Implements hook_form_FORM_ID_alter().
 */
function os_registration_form_user_login_block_alter( &$form, &$form_state, $form_id ) {
    $form['name']['#title'] = t( 'E-mail' );
    $form['name']['#element_validate'][] = 'os_registration_user_login_validate';
}

/**
 * Form element validation handler for the user login form.
 * Allows users to authenticate by email, which is our preferred method.
 */
function os_registration_user_login_validate( $form, &$form_state ) {
    if ( isset( $form_state['values']['name'] ) ) {
        $name = db_query( 'SELECT name FROM {users} WHERE LOWER(mail) = LOWER(:name)', array( ':name' => $form_state['values']['name'] ) )->fetchField();
        if ( $name ) {
            $form_state['values']['name'] = $name;
        }
    }
}

```

If you need any other information let me know. I am still trying to isolated this but thought more expert advice would be beneficial.

Thanks

# Answer
> 2 votes
So the solution was to save the file with a forced UTF-8 encoding and remove BOM ;)

---
Tags: 7
---


# Question
Title: How can I prevent an organic group administrator from accessing edit page of a group?
I want them to be able to post content only, not edit the group itself. I'm using og\_read\_only so they can only post content to their own group as well. This module has a problem though, you have to select which content types are read only each time you create a group, and if you add content types, you have to edit all of your groups again and check off the new content type as read only.

Is there a module that can prevent the group admin from accessing the group edit page? Would that module also be able to prevent the admin from posting to a group that they are not a member of?

I will accept an answer if it only covers preventing the group admin from accessing the edit page. I was just hoping the other issue might be covered by the same module since they both seem related to access control.

# Answer
> 0 votes
My suggestion would be to use rules to redirect users that aren't admins to another page, or use `hook_menu_alter()` to alter the access permissions to the page. Alternatively, you can use `hook_page_alter()` to check the active user's roles and redirect them if they aren't in the admin group.

---
Tags: 6, organic-groups, users
---


# Question
Title: How to remove width and height from image field images in Views?
I'm using Views to generate some HTML, and this includes a field from a Views field.

My problem is, the layout needs the images to be reponsive (height and width based on the parent element), but this is being broken by Views writing in the width and height as HTML attributes which override all the CSS.

---

I've tried the answer to this question which uses `hook_field_attach_view_alter()` to remove the width and height from the output array - but it doesn't work, the width and height are still written into the HTML.

Checking the width and height values at the time `hook_field_attach_view_alter()` is called, it seems it's a timing problem: it looks like this is called before the image preset is applied. E.g. my image preset is 190px x 190px scale and crop: at the time `hook_field_attach_view_alter()` is called, the width and height are the original width and height of the image, then the 190 gets written over whatever changes the hook makes.

Is there another hook I can use for the same effect?

---

I also tried using **Rewrite results** in Views to re-create the image from its component parts. The problem is, it has access to everything *except* the actual image URL or URI:

Is there a way to access the image URL or URI in the replacement patterns for Views rewrite for an image field?

# Answer
> 3 votes
It feels clumsier than I'd hoped and requires a module, but I found a solution:

1. Install `image_url_formatter` module, which creates an image field display that is just the url but still allows you to choose from available image styles
2. Change the image field in the view to use the new "Image URL" display.
3. Use the Views rewrite feature to rebuild the image (`<img src="[field_image]" alt=... />`).

---
Tags: views, entities
---


title: Implement i18n menu's programmatically

text:
# Question
Title: Implement i18n menu's programmatically
I am programmatically creating primary menu's which has the node content as links . So as soon as the node content is created, a primary menu link to that node content is created.

So while creating menu's ,I am also setting the languages of menu to which it belongs. So lets say if the node content created is in french, then a primary menu link is created with the language set to french.

The problem is despite the menu item's language is set, Still it gets displayed in all the other two languages as-well (English, German). I have installed Menu translation module as well but still its not working.

So how to implement multilingual menu's programmatically?

Tks Vil

# Answer
> 1 votes
Ensure the `i18n_menu` module is enabled and the menu to which you're adding links is configured to "Translate and Localize" on the Menu edit page:

For example, the setting for the main menu would be found at the following url:

```
/admin/structure/menu/manage/main-menu/edit

```

The configuration option looks like this:

---
Tags: routes, i18n-l10n
---


title: View Filter based on condition

text:
# Question
Title: View Filter based on condition
I have a View that is using the Table format to show all users who have uploaded content under a particular node. This view will be visible to anyone in the *Authenticated User* role. Users in *Administrator* role (about 4 users) also contribute to this, but I don't want their details to be visible to anyone else in the table. This is **not** intended to be an exposed filter.

So basically, if the current logged in user is in the *Authenticated User* role, then he should not see the admins.

If the current logged in user is in the *Administrator* role, then he should see everyone.

Possible? Thank you

# Answer
by the sounds of it, you're looking for Views Conditional module:

> Views Conditional is a simple module that allows you to define conditionals (if xxx then yyy) with fields in views. Conditions include:
>
> ```
>  Equal To
>  Not Equal To
>  Greater Than
>  Less Than
>  Empty
>  Not Empty
>
> ```
>
> Views conditional allows you to output text based on the result of the condition.
> 1 votes

---
Tags: 7, views
---


title: Drupal Commerce Barcode Scanner module

text:
# Question
Title: Drupal Commerce Barcode Scanner module
I've installed Barcode module and Commerce Barcode Scanner module. The first is for generete barcodes to products. The second is supposed to read barcode labels. I couldn't test Commerce Barcode Scanner yet because I don't have a Barcode Scanner by now.

But I've been searched how Commerce Barcode Scanner works and I don't find anything.

Do I have to position cursor in a specific field from front-end or back-end of my site or is really only necessary to stay in some page of my site to Commerce Barcode scanner redirect to the Product Display (as that is the behavior setted up by default in rules)?

# Answer
> 0 votes
No, you do not need focus on a specific input field. The code that listens for keystrokes is as follows:

```
$(document).bind('keydown', function(e) {

```

The module itself is quite small and self contained, so you shouldn't to my knowledge encounter any stability issues. From a high level standpoint the module does the following:

* Listens for keystrokes on the website that happen in a user defined interval.
* Creates a path at barcode-scanner/trigger-event/XXX to receive the barcode from the browser.
* Triggers a rules event with the context of a product and product display.

You will need to configure a rule to respond to the barcode scans and you will also need to assign the "trigger commerce barcode events" appropriately, only users who are assigned that permission will be able to trigger the configured rules events.

If you would like to test the module without a barcode scanner on hand, visit "admin/commerce/barcode-scanner" and then set the "Keypress Interval" setting to something large like "5000". This will give you 5 seconds between each keypress before it is discounted as a "scan". This is because barcode scanners usually enter their keys in very fast, so it prevents normal use of the website from being detected as a scan.

Then simply type in your SKU and hit return to simulate a real barcode scan.

# Answer
> 0 votes
You know that only 17 sites currently report using this module? And that last revision is reported to be from 2013-Oct-27? So it is old thing, and hardly used. I advise caution.

This bugreport suggest that all you need to do is to have focus anywhere on your page, and it will work... except when you hit the bug itself.

---
Tags: 7, commerce
---


# Question
Title: Exposed Filter Results Displaying in Nested DIVs (using view-dom-id-<?php print $dom_id; ?>)
I am trying to create a page that displays a bunch of resources with a filter to allow the end-user to sort the resources by type. I am using the following versions:

* Drupal 7.28
* Views 7.x-3.8
* Semantic Views 7.x-1.0-alpha1
* Bootstrap 3

VIEWS SETTING:

* Format: Semantic Views
* Show: Semantic Views: Fields
* Filter Criteria: Content: Resource Type (exposed)
* Exposed form in block: Yes
* Exposed form style: Basic
* Use AJAX: Yes

The functionality works and the results are displayed based on what's selected in the resource type drop-down filter. However, the results are displaying in nested divs each time the form gets submitted and I can't figure out why. :(

SOURCE CODE BEFORE SUBMISSION

```
<div class="region region-content">
  <section id="block-system-main" class="block block-system clearfix">
    <div class="resources-container container-fluid">
      <div class="container">
        <div class="view-dom-id-a9b31cdd0f34c14b5d87837cb4d072cc jquery-once-1-processed">
          <div class="row resources-Wrapper">
            [script for the $rows]

```

SOURCE CODE AFTER 1st SUBMISSION

```
<div class="region region-content">
  <section id="block-system-main" class="block block-system clearfix">
    <div class="resources-container container-fluid">
      <div class="container">
        <div>
          <div class="resources-container container-fluid">
            <div class="container">
              <div class="view-dom-id-65d9abf32d69cd0ef0cf53a48be512f6 jquery-once-1-processed">
                <div class="row resources-Wrapper">
                   [script for the $rows]

```

SOURCE CODE AFTER 2nd SUBMISSION

```
<div class="region region-content">
  <section id="block-system-main" class="block block-system clearfix">
    <div class="resources-container container-fluid">
      <div class="container">
        <div>
          <div class="resources-container container-fluid">
            <div class="container">
              <div>
                <div class="resources-container container-fluid">
                  <div class="container">
                    <div class="view-dom-id-5ce84e5f739ed6ab5c8f11ade31e3e96 jquery-once-1-processed">
                      <div class="row resources-Wrapper">
                        [script for the $rows]

```

To theme the exposed filter as a block, I did the following: copied the ‘views-exposed-form.tpl.php’ file in sites/all/modules/views/theme and pasted it in my theme directory and renamed accordingly (views-exposed-form--\[view name\].tpl.php). I did not edit the script in the template. (My reference: http://timonweb.com/how-display-views-exposed-filter-block-and-theme-it)

Then in my views-view--\[view name\].tpl.php, I added the following script:

```
<?php if ($rows): ?>
<div class="resources-container container-fluid">
    <div class="container">
        <div class="view-dom-id-<?php print $dom_id; ?>">
            <div class="row resources-Wrapper">
                <?php print $rows; ?>
            </div>
        </div>

    </div>
</div>
<?php elseif ($empty): ?>
  <div class="view-empty">
    <?php print $empty; ?>
  </div>
<?php endif; ?>

```

I don't really understand what view-dom-id- does even after reading a bunch of articles...but I added in as a div after reading the following post: https://www.drupal.org/node/690748. If I don't have it in the views template, then the filter doesn't work.

DEFAULT SCRIPT IN views-exposed-form--\[view name\].tpl.php

```
<?php if (!empty($q)): ?>
  <?php
   // This ensures that, if clean URLs are off, the 'q' is added first so that
   // it shows up first in the URL.
    print $q;
 ?>
<?php endif; ?>
<div class="views-exposed-form">
  <div class="views-exposed-widgets clearfix">
     <?php foreach ($widgets as $id => $widget): ?>
      <div id="<?php print $widget->id; ?>-wrapper" class="views-exposed-widget views-widget-<?php print $id; ?>">
    <?php if (!empty($widget->label)): ?>
      <label for="<?php print $widget->id; ?>">
        <?php print $widget->label; ?>
      </label>
    <?php endif; ?>
    <?php if (!empty($widget->operator)): ?>
      <div class="views-operator">
        <?php print $widget->operator; ?>
      </div>
    <?php endif; ?>
    <div class="views-widget">
      <?php print $widget->widget; ?>
    </div>
    <?php if (!empty($widget->description)): ?>
      <div class="description">
        <?php print $widget->description; ?>
      </div>
    <?php endif; ?>
  </div>
<?php endforeach; ?>
<?php if (!empty($sort_by)): ?>
  <div class="views-exposed-widget views-widget-sort-by">
    <?php print $sort_by; ?>
  </div>
  <div class="views-exposed-widget views-widget-sort-order">
    <?php print $sort_order; ?>
  </div>
<?php endif; ?>
<?php if (!empty($items_per_page)): ?>
  <div class="views-exposed-widget views-widget-per-page">
    <?php print $items_per_page; ?>
  </div>
<?php endif; ?>
<?php if (!empty($offset)): ?>
  <div class="views-exposed-widget views-widget-offset">
    <?php print $offset; ?>
  </div>
<?php endif; ?>
<div class="views-exposed-widget views-submit-button">
  <?php print $button; ?>
</div>
  <?php if (!empty($reset_button)): ?>
  <div class="views-exposed-widget views-reset-button">
    <?php print $reset_button; ?>
  </div>
  <?php endif; ?>
</div>
</div>

```

I've spent 2 days trying to debug, so any guidance would be greatly appreciated!!

Thank you for taking the time to read

# Answer
> 1 votes
UPDATE: I realized my issue -- In my Views template, I needed to place my divs outside of the :-p

Thank you, Molot, for leading me in the right direction! My original thought was that it was an AJAX issue, but after the issue disappeared when I used a pre-built theme, I looked more into the template.php and my template files (views-view--\[view name\].tpl.php). It works now with the following:

```
<div class="resources-container container-fluid">
<div class="container">
    <div class="view-content">
        <div class="row resources-Wrapper">
            <?php if ($rows): ?>
              <div class="view-content">
                <?php print $rows; ?>
              </div>
            <?php elseif ($empty): ?>
              <div class="view-empty">
                <?php print $empty; ?>
              </div>
            <?php endif; ?>
        </div>
    </div>
</div>
</div>

```

---
Tags: blocks, views
---


title: Drupal 7 Age Gateway

text:
# Question
Title: Drupal 7 Age Gateway
I have a website that will need an age gateway because it contains content about alcohol. I'm looking for an easy way to do this, without needing to create a custom module because I haven't done any and the deadline is looming.

It would need to redirect to a page gathering age information, and only allow access to the site if \>= 21 years old. Specific pages would be exempt.

If anyone knows a module that takes care of this, or has any ideas I'm open to suggestion.

# Answer
Please try module Terms of Use . It won't check user age directly but the user has to sign understanding your website terms of service before registration.
> 2 votes

# Answer
I grabbed a module from the OpenBrewery theme and tweaked it to be a yes or no form. Pretty easy.
> 0 votes

---
Tags: 7
---


# Question
Title: How to filter a view when day, month and year are separate fields
I am trying to filter a view to show content that happened today on this day in previous years.

We have **day**, **month** and **year** fields but they are not dates.

How can I filter on day = today's day and month = today's month without converting them to date fields.

Current fields are:

* Day - integer
* Month - List (integer)
* Year - integer

# Answer
> 2 votes
You can do that with views php.

Construct your view to take two contextual filters. Do not append any placeholder (%) to the path.

**First filter**: Add the month field as a contextual filter. Select from the section that reads: When the filter value is not in the url, Provide a default value. A select list Type opens up and from it you select PHP Code and in the PHP contextual filter code you enter:

```
date('F');

```

This will match it against today's month in the format of a full string ie. January. Adjust it if your month format is different (if for 3 letter abbrev, use date('M');)

Test this by typing in the month for a node that exists in the Preview with contextual filters text box at the bottom and update preview. It should show you your nodes filtered by month.

**Second Filter**: Add the day field as a contextual filter, and as above select PHP Code for default value. Add this code:

```
date('j');

```

This will filter on the day in the format of 1-31. If you want 01-31 then use date('d');

Test this by typing in the month/day for a node that exists in the Preview with contextual filters text box at the bottom and update preview. It should show you your nodes filtered by month and day.

You can also access the view as such: VIEWPATH/MONTH/DAY and it will show you a result for the values you provided. If you just access the view by VIEWPATH it will give you the result for the date of today.

---
Tags: 7, views
---


# Question
Title: Programmtically add image to custom image field User
I can't figure out how to add image to a custom image field on a sepcific user.

```
    $f = file_save_data($user['thumbnailphoto'][0], 'private://profile/'. $data['name'] .'.jpg', FILE_EXISTS_REPLACE);
    $fid = $f->fid;

    //Add to virtual map 'Profile images'
    $file_entity = file_load($fid);
    $file_entity->status = 1;
    $file_entity->field_folder['und'][0]['tid'] = 180;
    file_save($file_entity);

    $user = user_load(334);

    $details['field_profile_picture'] = array(
                                        'und' => array(
                                            0 => array(
                                            'fid' => $fid,
    )));

    $u = user_save($user, $details);

```

But nothing get saved? Field\_profile\_picture is just an image field.

Thx!

# Answer
In Drupal 7 you can use system\_retrieve\_file()

> **system\_retrieve\_file** : This function will download a file from a remote source, copy it from temp to a specified destination and optionally save it to the file\_managed table if you want it to be managed.

```

  $usr_info = user_load(334); //load user object
  if (!empty($usr_info)) {//assign only if user exist
    $image_url = 'http://g-raph.be/sites/all/themes/g_raph_/images/image03.jpg'; //image URL to save. If image already saved in the drupal system then get the file ID(fid)
    //I have used picture folder to store images using image field settings
    $file_info = system_retrieve_file($image_url, 'public://pictures/', TRUE, FILE_EXISTS_REPLACE); //storing image inside picture folder
    if ($file_info->fid) {//if fid exist then image is saved from URL.
      //$usr_info->picture = file_load($file_info->fid); //for default profile pic
      $usr_info->field_profile_picture[LANGUAGE_NONE][0]['fid'] = $file_info->fid; //for custom profile pic
    }
    user_save($usr_info);
  }

```
> 0 votes

---
Tags: 7, users, media
---


# Question
Title: FullCalendar does not display events except in the current month
I successfully got FullCalendar to work on a local test site (D7.26). It worked great with events of this month, and I can even go to next month and return back in my view and now I don't get errors. BUT when I make events for next month, the calendar will not show them when advancing to that month. I don't get any errors as others reported, but I just get a totally blank month. I can search for the events and sure-nuff, they're there in the database or list of events. It doesn't make any difference if I gave it an end date/time or not. They all just will not show when I go forward to next month in my view. Any help would be greatly appreciated. I'm near the time that this site needs to go live.

Dave N

# Answer
My solution, I switch in the view the 'contextual filter' the value 'when the filter values is NOT in the URL' from 'Provide default value' Type 'Current date' to 'Display all results for the specified field'.
> 1 votes

# Answer
I found that I have the same problem if views settings (advanced, other) "Use Ajax" is set to yes. if I change that to No, it seems to work fine. Curiously, there is documentation on Drupal.org at https://www.drupal.org/node/1237808 where it says, "NOTE: if you're working with a big dataset it is advised to turn on the ajax setting." This doesn't apppear to be correct.
> 0 votes

---
Tags: 7, javascript
---


title: Exposed filters - block?

text:
# Question
Title: Exposed filters - block?
Is it possible to create a block that allows users to sort the nodes in a view? I've only been able to achieve this in a page using the menu in page settings but so far haven't had any luck with blocks. The thing is I need the block to appear on most of the site's pages. Any ideas...?

# Answer
All you need to do is set up the exposed filters and then click Exposed form in block in the Basic Settings. This will then give you a block to use.
> 3 votes

# Answer
There is hidden trick although "Exposed filters will not appear on block displays unless 'Use Ajax' is set to TRUE"

As of this issue: https://www.drupal.org/node/690748
> 2 votes

---
Tags: 6, views
---


# Question
Title: Code to output individual fields in a Theme view
I know this question seems to have been half answered a few times but I'm finding it difficult to apply a working solution. I have created a new theme from scratch to use for a view I have created. I can get the view content to display in the Theme by using:

> print render($page\['content'\]);

However because of the complexity of my theme layout I need to display the fields in the view individually.

I understand that I need to create a file in the theme folder called something like: views-view-field--viewname.tpl.php and add some php, then add some code to this but I just can't seem to find the correct code that is needed plus the correct syntax I add to the theme page.tpl.php to show the individual fields. Could anyone please help? Thanks.

# Answer
OK, I sorted this out. I didn't quite understand that I need to make layout changes in the appropriately named views-view-fields--viewname.tpl.php. I was hoping to just add some php to the page.tpl.php theme file I have developed for my views.

It's quite a learning curve with Drupal!
> 0 votes

---
Tags: views, theming
---


# Question
Title: Cannot edit any content Panes in Panopoly installation, getting JS error
When I try editing any pane on my site, I get this:

The following error is in my Web Inspector console:

> TypeError: 'undefined' is not a function (evaluating '$('.panopoly-textfield-autosubmit, .panopoly-textarea-autosubmit', context) .once('ctools-auto-submit')')
>
> TypeError: 'undefined' is not a function (evaluating '$("select.ctools-master-dependent") .once('ctools-dependent')') \`

I've tried changing Jquery Update settings, updating Panopoly to the newest version (along with the modules). No luck.

# Answer
> 0 votes
I had a such problem with the module jquery\_update when we used a library upper jQuery1.7 . Try use different jQuery versions for User interface and the Admin interface. And do not mix them.

---
Tags: panels, distributions
---


# Question
Title: Overriding css file in theme.info not working as expected
I am trying to remove nice menus css, as per the notes in my Zen theme .info file. I have added the below to the info file, and I haven't provided replacements in my theme so they should be removed.

```
stylesheets[all][] = nice_menus.css
stylesheets[all][] = nice_menus_default.css

```

However they are still being imported. Cache cleared.

Thanks

EDIT: I'm aware this can be achieved using hooks, but would like to do it at theme .info file level, unless I am mistaken and it is not possible to remove contrib module .css in the theme .info file.

# Answer
> 0 votes
You can remove the css file of particular module

```
function MY_MODULE_css_alter(&$css) {
unset($css[drupal_get_path('module', 'views') . '/css/views.css']);
$css = array_diff_key($css, $exclude);
}

```

# Answer
> 1 votes
Try disable/enable theme. Yes it likes a trick. It seems info files are parsed when modules/themes are enabled/disabled.

# Answer
> 1 votes
you can remove(alter) css files with hook\_css\_alter, here is a simple example:

```
function MY_MODULE_OR_THEME_css_alter(&$css) {
    // dpm($css);
    unset($css[drupal_get_path('module','system').'/system.menus.css']);
}

```

---
Tags: theming, .info
---


# Question
Title: View Field Display placing table label on top of the description
So I have this table created with display suit and table group.

How am I going to make it look like this?

The label is already set to be above, but that doesn't seem to work.

I'm not really good in CSS nor Drupal. Consider me a newbie and willing to learn.

# Answer
> 0 votes
Use list formatting with custom CSS.

---
Tags: views, entities, display-suite
---


title: Change ubercart default path

text:
# Question
Title: Change ubercart default path
My clients really really insist that the path of the cart pages will be store/\* instead of cart/\*

Also, an alias is not good enough. They want a totally unrelated page to appear in the path: cart

Crazy? yes. Challenging? you bet.

# Answer
> 0 votes
Rewrite all needed paths by `hook_menu_alter`. It is invoked by `menu_router_build()`.

---
Tags: 7, routes, ubercart
---


# Question
Title: How to display blocks depending on the logged in user?
How can I display blocks depending on the logged in user?

Let's say I have a Block1 and Block2. When user1 is logged in, that user should only see Block1, but user2 should only see Block2

I found the Logic Block module, but it doesn't seem to work *for what I'm trying to do*.

# Answer
You could go to blocks setting and there are Roles tab. If you check "anonymous user" - this block will visible only for not loggined user. If you check " authenticated user" - block will be visible loggined user.
> 3 votes

# Answer
You can use the Context module. There you can compare current user id, user role etc to show blocks.
> 1 votes

---
Tags: blocks
---


title: Pager in Render Array

text:
# Question
Title: Pager in Render Array
In a custom module I have a block defined and the function that builds the block returns a render array. In that render array I am looking to create a pager for my content since it is a listing of items.

If I run pager\_default\_initialize during my query building like so this automatically adds a pager to the **top** of the block.

```
$total = $query->countQuery()
  ->execute()
  ->fetchField();

$page = pager_default_initialize($total, $per);

$query->extend('PagerDefault')
  ->limit($per)
  ->range($page * $per, $per);

```

I want to have more control over the pager, like adding it to the bottom of the block. If I remove the `pager_default_initialize` from the query building code like so, I can stop the pager from automatically being added.

```
$total = $query->countQuery()
  ->execute()
  ->fetchField();

$page = pager_find_page();

$query->extend('PagerDefault')
  ->limit($per)
  ->range($page * $per, $per);

```

So, the question is, how do I add the pager to my render array so it renders the pager at the bottom of the block?

My render array currently looks like this:

```
$content['results'] = array(
  '#type'       => 'container',
  '#attributes' => array(
    'class' => 'results',
  ),
);

if ($data->rowCount()) {
  foreach ($data as $record) {
    $content['results'][] = array(
      '#theme' => 'CUSTOM_NODE_THEME',
      '#node'   => node_load($record->nid),
    );
  }
  if ($per > 0) {
    $content['results']['pager'] = array(
      '#theme' => 'pager',
    );
  }
}

```

The theme\_pager() is not being run when the block is rendered.

Any help would be awesome!

# Answer
> 0 votes
Here is the solution. I knew as soon as I asked the question I would find the answer!

First off, the query building code must not run `pager_default_initialize`, like so:

```
$total = $query->countQuery()
  ->execute()
  ->fetchField();

$page = pager_find_page();

$query->extend('PagerDefault')
  ->limit($per)
  ->range($page * $per, $per);

```

The pager render array should be created like so:

```
$content['results']['pager'] = array(
  '#pre_render' => array('CUSTOM_PRE_RENDER'),
  '#theme' => 'pager',
  '#variables' => array(
    'total' => $total,
    'per' => $per,
  ),
);

```

And then run `pager_default_initialize` in the custom pre render function:

```
function custom_pre_render_intialize_pager($_element) {
  pager_default_initialize($_element['#variables']['total'], $_element['#variables']['per']);

  return $_element;
}

```

This code will only work to add a single pager to the block and may not work if there is more then one pager on the page.

---
Tags: 7, theming
---


# Question
Title: How to prevent newline character in textarea
I'm building a form in a module for Drupal 7 and I want to add a textarea as I would like it to be multiline so that text overflows on the next line, etc. but I don't want users to be able to create a new line if that makes sense. How can I achieve this?

Also, I would like to add a "Select All" button for the textarea and I have followed this article but it doesn't seem to have worked.

I know have the first part of my question solved, but still can't get the "Select All" button working. I have confirmed that the Javascript function does run by adding `console.log`, but it doesn't do the job. All that happens is the page reloads and no text is selected in the text area.

# Answer
> 3 votes
If using jQuery is an option for you, you can do something like this:

```
$('#yourTextAreaID').keyup( function() {
  $(this).val( $(this).val().replace( /\r?\n/gi, '' ) );
});

```

This code will replace the newline character on the fly, after the user types it. This code can be added in a custom.js file of your theme that you include in every page of your site, or you can alternatively use a hook\_form\_FORM\_ID\_alter in your custom module in conjunction with the drupal\_add\_js function to add the specific js file only in the specific form's edit page.

Keep in mind that if Javascript is disabled in the user's browser, he will be able to insert newline characters. In order to prevent this, you will have to add a custom validation function in your form. A very good tutorial on how to do this can be found here. The most important parts are:

1) Use a hook\_form\_FORM\_ID\_alter (in the tutorial he uses the old-school approach with hook\_form\_alter).

2) Add an extra validation function with something like:

```
array_unshift($form['#validate'], 'MYMODULE_form_validate');

```

3) Write your custom validation function (name it: MYMODULE\_form\_validate) that checks for \r?\n in the value of the textarea in the $form\_state variable and return a descriptive error if there is a newline character.

Regarding the second part of your question, you should add some more information about what exactly didn't work. Did you clear the cache after following the steps? Do you get any errors in the log messages? Did you add console.log in your Javascript to verify that is being executed?

---
Tags: 7, forms, javascript
---


# Question
Title: How to send auto login email using Email Auto Login drupal module?
I have enabled Email Auto login Module on drupal 7. How can I send an auto login email using the above module.
I have enabled the module and then saved the settings from the link http://www.example.com/admin/config/system/email\_auto\_login.
I have even checked the README file but could not find a way to send a auto login email using token
How can I send the auto login email using this module?

# Answer
First of all to send out an email automatically you will need a triggering event – and probably also some condition, under which the action of 'sending' should be fired. Otherwise drupal will not know when to send out an email – and to whom.

I suppose you have a look at the Rules Module (https://www.drupal.org/project/rules). It might first look quite complex, but basically it consists of these three main elements you have to configure to add a new Rule to your webpage: Event, Condition and Action. With that you can automate almost everything, especially sending reminder-emails etc. – and most probably you can also trigger Email Auto login.
> 1 votes

---
Tags: 7, emails, users
---


# Question
Title: ckeditor underline not allowed on filtered HTML
I have a problem whereby I cant underline text using ckeditor whilst in Filter HTML, it works fine with Full HTML. I can also use Bold and Italic with Filter HTML but not Underline. Is there a configuration setting for this, so a User set up with just permission for Filter HTML can add underline?

# Answer
> 2 votes
You have to allow `<u>` HTML tags in 'Filtered HTML' filter (/admin/config/content/formats/filtered\_html).

---
Tags: wysiwyg
---


# Question
Title: How can a module detect when the "access denied" page is output?
How is it possible for a module to detect when Drupal is outputting the "access denied" page?
I know how to do it with Drupal 6; I need to know how to do it with Drupal 7.

# Answer
> 12 votes
I do this in Boost 7.x. It's not pretty, but it does get the job done.

```
function boost_page_delivery_callback_alter(&$callback, $set = FALSE) {
  if ($callback == 'drupal_deliver_html_page') {
    $callback = 'boost_deliver_html_page';
  }
}

function boost_deliver_html_page($page_callback_result) {
  global $_boost;

  // Menu status constants are integers; page content is a string or array.
  if (is_int($page_callback_result)) {
    // @todo: Break these up into separate functions?
    switch ($page_callback_result) {

      // …

      case MENU_ACCESS_DENIED:
        // 403 page.
        $_boost['menu_item']['status'] = 403;
        break;

      // …

    }
    // …
  }
  // …
}

```

# Answer
> 13 votes
You can set which pages are displayed when 403 & 404 errors occurs (admin/settings/error-reporting).

I guess you can add a new page in your `hook_menu()`, then set this page as the 403 error callback. When your custom menu callback is hit, you know you're outputting the "access denied" page!

# Answer
> 10 votes
In Drupal 7, the function that returns the already set HTTP headers is drupal\_get\_http\_header(), which requires the HTTP header name as parameter. Looking at authorize\_access\_denied\_page(), and drupal\_fast\_404() code makes clear which values to pass to that function.

```
  // authorize_access_denied_page()
  drupal_add_http_header('Status', '403 Forbidden');
  watchdog('access denied', 'authorize.php', NULL, WATCHDOG_WARNING);
  drupal_set_title('Access denied');
  return t('You are not allowed to access this page.');

```

```
// drupal_fast_404()
if ($fast_paths && preg_match($fast_paths, $_GET['q'])) {
  drupal_add_http_header('Status', '404 Not Found');
  $fast_404_html = variable_get('404_fast_html', '<html xmlns="http://www.w3.org/1999/xhtml"><head><title>404 Not Found</title></head><body><h1>Not Found</h1><p>The requested URL "@path" was not found on this server.</p></body></html>');
  // Replace @path in the variable with the page path.
  print strtr($fast_404_html, array('@path' => check_plain(request_uri())));
  exit;
}

```

When the "Status" header starts with *403*, then Drupal output an access denied page.

Make sure the call to `drupal_get_http_header('Status')` happens late. Calling during `hook_init()` is too soon, but calling it during `hook_page_alter()` (or any theme preprocess hook) will have the updated header information.

# Answer
> 4 votes
Your module could intercept the value of "`Default 403 (access denied) page`" which is modified by the page "`Administer > Site configuration > Error reporting`":

1. In `hook_enable`, using `variable_get`/`variable_set`, **copy the existing value** to a secondary variable and **replace the variable by your own** path (which you registered using `hook_menu`).
2. **alter the "Error reporting" form** using `hook_form_FORM_ID_alter` to read from/write to the secondary variable
3. If you want to be completely invisible to the user, your page callback to could call `drupal_goto( the_value_of_the_secondary_variable )`.
4. In `hook_disable`, **restore the value** from the secondary variable.

---

And that's it, your module gets notified **in a clean way** (and invisible to the user) when "Access denied" is triggered.

# Answer
> 2 votes
Surely you could use PHP's `get_headers()` function?

> http://php.net/manual/en/function.get-headers.php

The first element in the array returned will be the response code. If it contains '403' then Drupal returned an "access denied" page.

I'm not sure where the best place to call it would be. Probably `hook_exit()`, depending on your needs:

> http://api.drupal.org/api/drupal/developer--hooks--core.php/function/hook\_exit/6

# Answer
> 2 votes
This is the simplest way to detect Access Denied (403) and Page Not Found (404) in Drupal 7.

```
// get the menu router item for the current page
$router_item = menu_get_item();

// if there is no router item, this page is not found
$is_page_not_found_404 = empty($router_item);

// if 'access' is empty for the router item, access is denied
$is_access_denied_403 = empty($router_item['access']);

```

# Answer
> -2 votes
You can use the Panels module for this.

> The Panels module allows a site administrator to create customized layouts for multiple uses. At its core it is a drag and drop content manager that lets you visually design a layout and place content within that layout. Integration with other systems allows you to create nodes that use this, landing pages that use this, and even override system pages such as taxonomy and the node page so that you can customize the layout of your site with very fine grained permissions.

---
Tags: 7
---


title: Redirect to value from select list

text:
# Question
Title: Redirect to value from select list
I'm having a problem redirecting a user on login. I have a user field `field_redirect_field`, that is a **select list (text)**.

I want to have a list of links of my site and the user can select in a list where he redirects after logging in. (I create the list manually)

this is an example of my values list:

> user/me/edit|me

The key is **user/me/edit** and the label is **me**. Now the problem is in my rule I have a redirect to the field **\[account:field\_redirect\_field\]**. But he redirects to the label and not to the key.

This is what I've tried:

I've tried to change the display of the redirect field by going to **Manage Display** and set the redirect field to show the **Key** instead of the label. But the strange thing is that he still shows the value when I want to edit a user.

How can I fix this?

# Answer
> 1 votes
Go to **Manage Display**, on "CUSTOM DISPLAY SETTINGS" enable the checkbox "Token"

---
Tags: rules, redirection
---


# Question
Title: Save multi value in multi value field programmatically
**apologize every one , my code was correct , I had a mistake in content type .2 similar content type with 2 similar image field :P**

**but I let it and don't delete this because maybe be useful in futures**

I want to save multi image in multi image field programmatically(I set number of value to 5)

Part of my code

```
        $node = new stdClass(); // Create a new node object
        $node->type = "prodcut_gift_display"; // Or page, or whatever content type you like
        $node->uid = $user->uid;
        $uri = file_build_uri($geturipath);
        $file = new stdClass;
        $file->uid = $user->uid;
        $file->filename = basename($uri);
        $file->uri = $uri;
        $file->filemime = file_get_mimetype($uri);
        $file->filesize = filesize($mainimg_url);
        $file->status = 1;
        file_save($file);
        $node->field_gift_image['und'][0] =(array) $file;
        /***************************************/
        foreach ($upimg_uri_path as $inx=>$upimgtemp){
        unset($file);
        $uri = file_build_uri($upimgtemp);
        $file = new stdClass;
        $file->uid = $user->uid;
        $file->filename = basename($uri);
        $file->uri = $uri;
        $file->filemime = file_get_mimetype($uri);
//        $file->filesize = filesize($mainimg_url);
        $file->status = 1;
        file_save($file);
        $node->field_gift_image['und'][$inx+1]=(array) $file;
        }

        /***************************************/

```

Then I try to get `drupal_json_output` , it seems node and image field with 2 value is ok but only one value saved in field.**where is the problem?**(I check and sure that my image field is set multi and can get 5 value )

**update** Also I try

```
$uri = file_build_uri($geturipath);

        $imgs_paths[]=file_create_url($uri);
        /***************************************/
        foreach ($upimg_uri_path as $inx=>$upimgtemp){
        unset($file);
        $uri = file_build_uri($upimgtemp);
        $imgs_paths[]=file_create_url($uri);
        }

   foreach ($imgs_paths as $i=>$img) {
    $file_info = system_retrieve_file($img, 'public://pictures/', TRUE, FILE_EXISTS_REPLACE); //storing image inside picture folder
    if ($file_info->fid) {//if fid exist then image is saved from URL.
      $node->field_gift_image['und'][$i]['fid'] = $file_info->fid; //assign image
    }
  }
        /***************************************/
        $node->field_product['und'][0]['product_id'] = $my_prodcut->product_id;
        $node->title = arg(1) . '-' . rand(1, 999999);
        $node->language = 'fa';
        $node = node_submit($node);
        node_save($node);

```

Also my field settings

# Answer
> 1 votes
As per my understanding you are trying to create a new article content type with multiple images. Assuming that you have the path of the images. In Drupal 7 you can use the below code

```

  $node = new stdClass(); // We create a new node object
  $node->type = "article"; // Or any other content type you want
  $node->title = "Article title";
  $node->language = LANGUAGE_NONE; // Or any language code if Locale module is enabled. More on this below *
  //$node->path = array('alias' => 'your node path'); // Setting a node path
  node_object_prepare($node); // Set some default values.
  $node->uid = 1; // admin id
  // Let's add standard body field
  $node->body[$node->language][0]['value'] = 'This is a body text';
  $node->body[$node->language][0]['summary'] = 'Here goes a summary';
  $node->body[$node->language][0]['format'] = 'filtered_html'; // If field has a format, you need to define it. Here we define a default filtered_html format for a body field
  // Add images
  $image_limit = 5;
  $images = array(//images to attach to node
    '0' => 'http://cf.juggle-images.com/matte/white/280x280/drupal-logo-primary.jpg',
    '1' => 'http://cdn.flaticon.com/png/256/37187.png',
    '2' => 'https://www.drupal.org/files/project-images/logo-128x128.jpg',
    '3' => 'http://guillermocerezo.com/sites/default/files/field/image/drupal-logo_0.jpg',
    '4' => 'http://drupalcrafters.org/sites/default/files/DrupalCraft-logo_0.png'
  );
  for ($i = 0; $i < $image_limit; $i++) {
    $file_info = system_retrieve_file($images[$i], 'public://pictures/', TRUE, FILE_EXISTS_REPLACE); //storing image inside picture folder
    if ($file_info->fid) {//if fid exist then image is saved from URL.
      $node->field_multiple_images[LANGUAGE_NONE][$i]['fid'] = $file_info->fid; //assign image
    }
  }
  $node = node_submit($node); // Prepare node for a submit
  node_save($node); // After this call we'll get a nid
  drupal_set_message('article  saved !!!');
  watchdog('info', 'Article node created');

```

# Answer
> 1 votes
I guess you need check the image field settings. There is set a mode - Single value, change it to unlimited for an example.

---
Tags: entities, media
---


# Question
Title: Programatically trigger a click on an AJAX enabled form field (button, select, etc)
Using `jQuery`, I need to programmatically click / select Form items (radios, select lists, checkboxes, etc). This field item has an `'#ajax'` action / callback defined using Form API.

The following code from a similar question works for submit buttons (Programatically trigger a click on an AJAX enabled form submit button):

`jQuery('#edit-submit').mousedown()`

However, this does not work for radio buttons. I have also tried creating a copy of the element and making my own AJAX call using the following code from another similar question (Use Drupal7 AJAX goodness programmatically):

```
          base = 'edit-my-radio-button';
          element = '<input type="radio" id="'+base+'" name="cat-selector" value="garfield" class="form-radio ajax-processed">';
          element_settings = Drupal.ajax[base].element_settings;
          myAjax = new Drupal.ajax(base, element, element_settings);
          myAjax.eventResponse(element, 'click');

```

The AJAX call is made, but the screen does not update as if the user clicked it. How can I programmatically select a radio button or select list using `jQuery` and cause Drupal to execute the AJAX call?

Please note: I have purposely kept this question as open ended as possible. My hope is that there is a more general way to do this for all form element types and that future answers regarding these can be considered relevant so that we have a single resource for this problem.

# Answer
> 1 votes
In order to select radio buttons using `jQuery` I came up with the following solution:

```
base = 'edit-my-radio-button';
id = '#'+base;
$(id).click();
Drupal.ajax[base].eventResponse($(id), 'click');

```

After some digging around in `misc/ajax.js`, I found that Drupal AJAX stores the result of `new Drupal.ajax(base, element, element_settings)` in the `Drupal.ajax[]` JavaScript Array. This led me to realize that I did not need to create a fake `element` or an `element_settings` object as the Use Drupal7 AJAX goodness programmatically answer suggested. While that simplified my code, and `eventResponse()` created a successful AJAX request, the AJAX commands being returned still did not execute.

On a hunch, I decided to use `.click()` followed by `.eventResponse()` because I noticed that `false` was being printed on the console.

After looking at the `.eventResponse()` code, I am not 100% sure where it is looking for the element to be currently selected. After stepping through the function calls, I believe `jquery.form.js` is checking to see if the item is selected, but since this file is minified by default, I have not gone through it yet. If anyone else can shed light on this or be willing to step through the function calls, that would be great!

FYI: If I run these commands manually in the console, `.eventResponse()` still returns `false`, so don't be alarmed when you see that.

# Answer
> 0 votes
@MD3 Did you try to explicitly check the radio button before clicking it?

`$(id).attr('checked', true);`

I've had the same problem as you and doing that solved it.

---
Tags: 7, ajax, javascript
---


# Question
Title: Error: include_once(): Failed opening './includes/unicode.entities.inc'
I am working on a D6 site and I have created some fields programatically, and it looked like it worked fine (code below). The fields show up in the database and on the UI screen. However, I found that after adding these field types, when I tried editing data in that content type, it wouldn't save. Looking at the error logs, I saw this:

```
include_once(./includes/unicode.entities.inc): failed to open stream: No such file or directory in /srv/www/usni.utdev.com/htdocs/includes/unicode.inc on line 339.

```

and

```
include_once(): Failed opening './includes/unicode.entities.inc' for inclusion (include_path='.:/usr/share/php:/usr/share/pear') in /srv/www/usni.utdev.com/htdocs/includes/unicode.inc on line 339.

```

and I can't figure out why I could be causing these errors.

```

function createCckFields($csv) {
  foreach ($csv as $key => $value) {
    list($category, $label, $fieldName, $sampleValue, $fieldType, $cardinality) = $value;
    if ($fieldType == 'text' || $fieldType == 'number_integer' || $fieldType == 'number_float' || $fieldType == 'date') {
      createField($category, $label, $fieldName, $sampleValue, $fieldType, $cardinality);
    }
  }
  return;
}

function createField($category, $label, $fieldName, $sampleValue, $fieldType, $cardinality) {
  if ($fieldType == 'text') {
    $module = 'text';
    $widget_type = 'text_textfield';
    $widget_module = 'text';
    $field_name = 'field_' . $fieldName;
  }
  elseif ($fieldType == 'number_integer' || $fieldType == 'number_float') {
    $module = 'number';
    $widget_type = 'number';
    $widget_module = 'number';
    $field_name = 'field_' . $fieldName;
  }
  elseif ($fieldType == 'date') {
    $module = 'date';
    $widget_type = 'date_popup'; //options: date_popup, date_text
    $widget_module = 'date';
    $field_name = 'field_' . $fieldName;
  }
  elseif ($fieldType == 'N/A' && $fieldName == 'RelatedProducts') { //@TODO TAKE OUT HARDCODED FIELDNAME, NEED TO DEAL WITH REVIEW QUOTES TOO
    //this is for fields which have a cardinality of  $field_name,
    'type_name' => 'product',
    'display_settings' => array(
      'label' => array(
        'format' => 'hidden',
        'exclude' => 0,
      ),
      'teaser' => array(
        'format' => 'hidden',
        'exclude' => 1,
      ),
      'full' => array(
        'format' => 'default',
        'exclude' => 0,
      ),
    ),
    'widget_active' => 1,
    'type' => $fieldType, //options: text, number_integer, date
    'required' => 0,
    'multiple' => $cardinality,
    'db_storage' => 1,  //not sure what this does
    'module' => $module, //options: text, number, date
    'active' => 1,
    'locked' => 0,
    'widget' => array(
      'label' => $label,
      /*'default_value' => array(
        0 => array(
          'value' => $sampleValue,
          '_error_element' => 'default_value_widget][' . $field_name . '][0][value',
        ),
      ),*/
      'weight' => 2,
      'description' => 'ie: ' . $sampleValue,
      'type' => $widget_type, //options: text_textfield, optionwidgets_onoff
      'module' => $widget_module, //options: text, optionwidgets
    ),
  );

  if ($fieldType == 'date') {
    $field['granularity'] = array(
      'year' => 'year',
      'month' => 'month',
      'day' => 'day',
    );
    $field['timezone_db'] = '';
    $field['tz_handling'] = 'none'; //this is set to none, since we are not tracking hour and minute in the granularity
    $field['todate'] = '';
    $field['repeat'] = 0;
    $field['repeat_collapsed'] = '';
    $field['default_format'] = 'medium';
    $field['widget']['default_value_code'] = "";
    $field['widget']['default_value2'] = 'blank';
    $field['widget']['default_value_code2'] = '';
    $field['widget']['input_format'] = 'Y-m-d:i:s';
    $field['widget']['input_format_custom'] = 'Ymd'; //the format set for the date fields in onix is YYYYMMDD
    $field['widget']['increment'] = 1;
    $field['widget']['text_parts'] = array();
    $field['widget']['year_range'] = '-3:+3';
    $field['widget']['label_position'] = 'above';
  }
  elseif ($fieldType == 'nodereference') {
    $node_types = node_get_types('names');
    foreach($node_types as $type=>$value) {
      $node_types[$type] = 0;
    }
    $node_types['product'] = 'product';
    $field['referenceable_types'] = $node_types;
    $field['advanced_view'] = '--';
    $field['advanced_view_args'] = '';
    $field['widget']['autocomplete_match'] = 'contains';
    //$field['widget']['size'] = 60;
    //field['widget']['default_value'] = null;
  }
  module_load_include('inc', 'content', 'includes/content.crud');
  if (content_fields($field, 'product')) {
    //content_field_instance_update($field);
    drupal_set_message('Did not create field_' . $fieldName . ' of type ' . $fieldType);
  }
  else {
    content_field_instance_create($field);
    drupal_set_message('Created  field_' . $fieldName . ' of type ' . $fieldType);
  }
  return;
}

```

# Answer
I'm not sure what is causing those errors, but that was not the issue. I found out that the issue was that I had been creating fields with field names longer than 32 characters, which Drupal doesn't like. I added a 32 character limit to the names, and everything worked fine.
> 0 votes

---
Tags: 6, entities
---


title: Finding pages through FTP

text:
# Question
Title: Finding pages through FTP
Our YMCA organization just redesigned a new website as a static site. The old site was in Drupal. The domain and hosting have already been transferred. I have access to the old site through FTP and am trying to find specific pages in order to pick up content. Can anyone tell me where the web pages are in the FTP directory? Thanks!

# Answer
As @Beebee pointed out, Drupal stores its pages in a Database. That means the actual "pages" aren't going to be available via FTP.

The first thing you need to verify is, do you have a copy of the old Drupal website's database? If not, try reaching out to your old website host to see if they can recover it for you.

If the database isn't available, then your best bet to see the old website would be to use:

https://archive.org/web/

If you do have the old database, here's how you can set up and see the old website:

1. On your website host, set up a *subdomain* through cPanel (e.g. `drupal.example-ymca.com`)
2. Place a copy of all the old Drupal files inside this new subdomain directory (e.g. `~/www/drupal` \- so the index.php file that comes with Drupal lives here: `~/www/drupal/index.php`)
3. Create a new MySQL database, user and password through cPanel (take note of each while doing so)
4. Import the Drupal database into this empty database
5. Open the `~/www/drupal/sites/default/settings.php` file and input your database credentials in the database config section
6. Visit your old website, e.g. `http://drupal.example-ymca.com/`

Here's a Google Search Result set that has additional topics:

https://www.google.com/search?client=ubuntu&channel=fs&q=drupal+transferring+from+host+to+host&ie=utf-8&oe=utf-8

I'd also like to point out, that it is possible to create/edit pages in Drupal by writing custom code (via an FTP if you wish) by using hook\_menu(). This is a slightly more advanced topic, but nonetheless, a very important one to understand when working with Drupal. Once your site is up and running, locate any custom modules that implement hook\_menu() to see custom pages (if any) that were created this way.
> 3 votes

---
Tags: files, 7
---


title: how to create an AJAX field widget

text:
# Question
Title: how to create an AJAX field widget
I'm trying to create a field widget which is a collection of multiple fields. I'm using `hook_field_widget_info()` and `hook_field_widget_form()`, something like this:

```
function module_field_widget_form(&$form, &$form_state, $field, $instance, $langcode, $items, $delta, $element) {
  $element += array(
    '#type' => 'container',
    '#element_validate' => array('custom_validation_function'),
  );

  $options = array('some values here');
  $element['existing'] = array(
    '#type' => 'select',
    '#title' => 'Recipient & delivery address',
    '#options' => $options,
    '#ajax' => array(
      'wrapper' => $wrapper_id,
      'callback' => '_my_custom_ajax_callback'
    )
  );
  $element['new'] = array(
    '#prefix' => '<div id="' . $wrapper_id . '">',
    '#suffix' => '</div>',
  );

  $new_entity = entity_create('entity_type', array('type' => 'bundle'));

  field_attach_form('entity_type', $new_entity, $element['new'], $form_state);

  return $element;
}

function _my_custom_ajax_callback($form, &$form_state) {
  return $form['new'];
}

```

The problem is that in the ajax callback the $form array is different than the one in the hook\_field\_widget\_form(). In the ajax callback the form array is the entire form structure, not just the one defining that widget...

Any ideas?

# Answer
> 3 votes
I've tried to do this a few times and never really got very far (for the reasons you've already mentioned).

The way I found to do it instead was to install the Field Collection module (and Field Collection Table for a better UX), and use that to group the fields I need into a single field, which is represented as a single widget.

Then I just hook into the particular form that's showing the field and add the AJAX that way. As coincidence would have it I've just done exactly this a few hours ago. I know this is out of context but here's a (slightly anonymised) dump of the code I used; hopefully it'll give you a place to start if you choose to go down this route:

```
function MYMODULE_form_directory_listing_node_form_alter(&$form, &$form_state, $form_id) {
  $selected_country_tid = $form['field_address'][LANGUAGE_NONE][0]['field_country'][LANGUAGE_NONE]['#default_value'][0];

  $form['field_address'][LANGUAGE_NONE][0]['field_country'][LANGUAGE_NONE]['#ajax'] = array(
    'wrapper' => 'directory-form-county-wrapper',
    'callback' => 'MYMODULE_form_directory_listing_country_ajax'
  );

  $form['field_address'][LANGUAGE_NONE][0]['field_county'][LANGUAGE_NONE]['#prefix'] = '<div id="directory-form-county-wrapper">';
  $form['field_address'][LANGUAGE_NONE][0]['field_county'][LANGUAGE_NONE]['#suffix'] = '</div>';

  $selected_country_term = taxonomy_term_load($selected_country_tid);

  $options = array();
  foreach (_MYMODULE_get_country_counties($selected_country_term) as $county) {
    $options[$county->tid] = $county->name;
  }

  $form['field_address'][LANGUAGE_NONE][0]['field_county'][LANGUAGE_NONE]['#options'] = $options;
}

function MYMODULE_form_directory_listing_country_ajax(&$form, &$form_state) {
  return $form['field_address'][LANGUAGE_NONE][0]['field_county'][LANGUAGE_NONE];
}

```

`field_address` in the above example is the Field Collection field.

# Answer
> 0 votes
I know this is an answer to an old question but I was struggling with this issue myself and came to the realisation that for whatever reason, somehow AJAX properties don't seem to work when declared as part of a field widget. What I did instead was built the basic skeleton of the widget then added the AJAX stuff using `hook_form_alter`. The following isn't a complete example but it should give an idea of how to go about this for anyone looking in.

Firstly, build the basic outline of your form. In my case I had 3 select elements in the one widget, the latter 2 being populated based on the previous select element's values using the AJAX parameters. Note that initially the latter 2 select elements aren't actually declared as select elements until the AJAX kicks in.

```
/**
 * Implements hook_field_widget_form().
 */
function myfield_field_widget_form(&$form, &$form_state, $field, $instance, $langcode, $items, $delta, $element) {
  // Make the parent element a fieldset.
  $widget = array(
    '#type' => 'fieldset',
    '#title' => t('My field'),
  );
  // The top level myfield select element.
  $widget['myfield_1'] = array(
    '#type' => 'select',
    '#default_value' => $myfield_1_defaults,
    '#multiple' => TRUE,
    '#options' => $myfield_1_options,
    '#delta' => $delta,
  );
  // The second select element.
  $widget['myfield_2'] = array(
    '#prefix' => '<div id="myfield-2-wrapper">',
    '#suffix' => '</div>',
  );
  // The third select element.
  $widget['myfield_3'] = array(
    '#prefix' => '<div id="myfield-3-wrapper">',
    '#suffix' => '</div>',
  );
  // Assign the $widget variable back to the $element variable.
  $element['myfield'] = $widget;
  // I don't know if this is necessary but I added it just in case.
  $element['#tree'] = TRUE;
  // Don't forget to return it!
  return $element;
}

```

Now using `hook_form_alter` I added the AJAX parameters and the logic for dealing with it. You might not need to do all the checks I did but I figured it was the best way of finding out if the element could even be present on the form and if it could be then to check if it was actually there.

```
/**
 * Implements hook_form_alter().
 */
function myfield_form_alter(&$form, &$form_state, $form_id) {
  // Firstly, check if this is an entity form or not.
  if (isset($form['#entity_type'])) {
    // Check if there is a bundle declared.
    if (isset($form['#bundle'])) {
      // If so, get a list of bundles containing the myfield field.
      // Note that myfield_active_bundles is a helper function that utilises field_info_field_map() to return any
      // entities/bundles that contain our field.
      $bundles = myfield_active_bundles();
      // Is the current bundle present in the bundles array?
      if (isset($bundles[$form['#bundle']])) {
        // Get the language.
        $lang = $form['language']['#value'];
        // Add the AJAX attributes to the myfield_1 form element.
        $form['field_myfield'][$lang]['myfield']['myfield_1']['#ajax'] = array(
          'callback' => 'myfield_2_ajax_callback',
          'wrapper' => 'myfield-2-wrapper',
          'event' => 'change',
          'method' => 'replace',
          'effect' => 'fade',
        );
        // Get the values from myfield_1.
        $myfield_1_values = '';
        $myfield_1_values = '';
        if (isset($form_state['values']['field_myfield'][$lang]['myfield']['myfield_1'])) {
          $myfield_1_values = $form_state['values']['field_myfield'][$lang]['myfield']['myfield_1'];
        }
        // If there have been values set on myfield_1, build myfield_2.
        if (!empty($myfield_1_values)) {
          // Build the form element - we rewrite the whole element using a helper function that simply returns a Form
          // API array. I used a helper function to reduce initial overhead and for tidyness.
          $form['field_myfield'][$lang]['myfield']['myfield_2'] = _myfield_2_form_build($form, $form_state, $myfield_1_values);
        }
        // Get the values from myfield_2.
        $myfield_2_values = '';
        if (isset($form_state['values']['field_myfield'][$lang]['myfield']['myfield_2'])) {
          $myfield_2_values = $form_state['values']['field_myfield'][$lang]['myfield']['myfield_2'];
        }
        // If there have been values set on myfield_1, build myfield_2.
        if (!empty($myfield_2_values)) {
          // Build the form element as described above.
          $form['field_myfield'][$lang]['myfield']['myfield_3'] = _myfield_3_form_build($form, $form_state, $myfield_2_values);
        }
      }
    }
  }
}

```

---
Tags: 7, entities
---


title: Theming views data export XLS button

text:
# Question
Title: Theming views data export XLS button
I have a view that I have attached a data export view to. I want to change the default orange icon that shows XLS at the bottom of the view, to another button with text "Download View". How can I achieve this?

# Answer
This image is set in function views\_data\_export\_views\_plugins(), in views\_data\_export.views

Implement your own hook\_views\_plugins() and override `['style']['views_data_export_xls']['export feed icon']` with your own value. Just make sure your module fires after Views Data Export.
> 1 votes

# Answer
**Revised Answer:** Seems dreadfully hacky, but it is a fix in one place where my earlier answer was CSS and preprocess. I found that as soon as the CSV link had filter arguments appended then the CSS `a[href$='.csv']` targeting broke.

```
THEMENAME_preprocess_views_view($vars){

    if(!empty($vars['feed_icon'])){

    $vars['feed_icon'] = str_replace('sites/all/modules/views_data_export/images/csv.png', drupal_get_path('theme', 'THEMENAME').'/images/feed-icon-csv.png', $vars['feed_icon']);
    $vars['feed_icon'] = str_replace('sites/all/modules/kml/images/kml.png', drupal_get_path('theme', 'THEMENAME').'/images/feed-icon-kml.png', $vars['feed_icon']);

    }
}

```

---

**Old answer** that does not work if the view has query parameters:

I did the following to strip out those images but leave the links:

```
THEMENAME_preprocess_views_view($vars){
    if($vars['view']->name == 'view_name'){

        $vars['feed_icon'] = strip_tags($vars['feed_icon'], '<a>');

    }
}

```

Then in my CSS I could easily add:

```
.feed-icon a[href$='.csv'] {
    display: inline-block;
    background: url('images/feed-icon-csv.png');
    width: 94px;
    height: 27px;
}

```

Yes I know it is not great for accessibility but hooks were really not working for me.
> 1 votes

# Answer
You can simple hook into the \_views\_data\_export\_feed\_icon Function (like above). The Function above doesn't work for me.

So here is mine:

```
function YOURMODULEORTHEME_views_data_export_feed_icon($variables)
{
    extract($variables, EXTR_SKIP);
    $url_options = array('html' => TRUE, 'attributes' => array('class' => 'YOURCLASS-button'));
    if($query) {
        $url_options['query'] = $query;
    }
    return l($text, $url, $url_options);
}

```

You could specify your own class to style the Button.

The "alt" Text (defined in the View) is now your Link.
> 0 votes

# Answer
Similar to what was posted above, however, you need to do it in hook\_views\_plugins\_alter() rather than defining your own plugin in hook\_views\_plugins().

Set the export feed icon to your updated icon:

```
function MYMODULE_views_plugins_alter(&$plugins) {
  $plugins['style']['views_data_export_xls']['export feed icon'] = [PATH_TO_MY_ICON];
}

```
> 0 votes

# Answer
override theme\_views\_data\_export\_feed\_icon function in your theme template.php

Example :

```
function themename_views_data_export_feed_icon($image_path, $url, $query = '', $text = '') {

    $url_options = array('html' => true, 'attributes' => array('class' => 'csv-export'));
    if ($query) {
       $url_options['query'] = $query;
    }
    return l(t('Download View'), $url, $url_options);
}

```
> -2 votes

---
Tags: 7, views
---


title: Field Collection module Ajax error

text:
# Question
Title: Field Collection module Ajax error
I'm utilizing the Field Collection module to allow me to associate objects of one content type (say, Authors) with another content type (say, Books).

When viewing the Edit page for one of my specific Book objects, whenever I try to use the "Add another item" or "Remove" buttons within the Authors section -- which operate via Ajax -- I'm getting an Ajax "403 Forbidden" error on the following URL:

```
field_collection/ajax

```

One key piece of information is that this happens with *only one specific object*; the functionality of those buttons works perfectly fine on the edit pages of other Books.

When I visit the Recent Log Messages page -- admin/reports/dblog -- it displays the following error message:

```
Notice: Undefined index: form_build_id in ajax_get_form() (line 320 of .../includes/ajax.inc).

```

I checked though, and the form\_build\_id does, in fact, appear to be included with the POST data being submitted to field\_collection/ajax.

Is it possible that that form\_build\_id is somehow invalid?

I'm sort of at a loss here. Any thoughts?

**UPDATE:**

I set up watchdog to log the POST data, and it seems like there's absolutely no data available in $\_POST once it hits the field\_collection\_remove\_js function within the Field Collection module code...

Is there a chance I'm hitting some sort of POST length/size limit? The node in reference does, in fact, have a whole bunch of data associated with it.

# Answer
In case it helps anyone else, I believe I was running into memory limit issues in PHP. Adding the following to my sites/default/settings.php seems to have resolved the issue:

```
ini_set('memory_limit', '128M');

```
> 1 votes

---
Tags: 7, ajax, entities
---


# Question
Title: Assign Node To Other Menus Besides Main Menu
Is there a module or technique which will allow us to assign a node to a menu -besides- the Main Menu. Users find it annoying that the only menu they can assign a new page to has to be based on the Main Menu. We have many custom menu blocks and it would be nice if the user could set up the page menu in one step rather than having to save the page, then go to the Admin/Structure/Menus and assign the page to the link.

BTW: We're using Kickstart 2 Omega theme if that makes any difference.

Can this be done?

# Answer
> 3 votes
Restricting the menus to which a Content Type can be added is configured on the Content Type itself (Structure -\> Content Types -\> Edit or `admin/structure/types/manage/[content-type]`) within the "Menu settings" tab:

By default, only the Main menu is selected. Simply check off additional menus to make them available on the node add/edit page for that Content Type.

---
Tags: routes
---


# Question
Title: fonts not applied to high ASCII characters
After installing the @fontyourface module and adding some Korean fonts locally, the fonts are not being applied to high ASCII characters (which makes no sense as the font is specifically for those characters). The fonts ARE applying to the regular ASCII characters, though.

# Answer
As I suspected, the issue was NOT off-topic. It turns out that the downloaded fonts were not set for Unicode. Most likely, they were using the euc-kr character set. Since the site uses utf-8, the ranges for the characters in utf-8 are different from euc-kr, so the default font was being used to display.

I downloaded a different version that specifically listed the font as Unicode and now the characters display correctly for that font.
> 1 votes

---
Tags: 7, theming
---


# Question
Title: How to prevent image files being duplicated while importing nodes with the Feeds module?
I have a large catalog import where the items often refer to a single common image (such as "brand\_logo"). When I import the images via CSV parser, if the item refers to the same image file, an incremented duplicate is created.

Example: Using the example files supplied with the module, I modified 2 books to use the same image file, which are imported to `files/field/image/` as `51JQbhO0MmL.jpg` and `51JQbhO0MmL_0.jpg`.

This causes the images directory to balloon to 20 times the size it should be (lots of shared images).

Honestly, what I would prefer to do is to upload the images to the site separately (manually, via FTP etc.) and just import the links to the images, but I haven't figured that one out either.

*(The data (files) is not being replicated, just the **images** are replicated.)*

# Answer
I found a solution to this. What you need to do is to install the Media Feeds module.

In your CSV file there is a column called e.g. `image` and reference the image using `public://myimage.png`.

Then in your mapping delete the original image mapping and create a new image mapping. When you do this you will have a new option for the image mapping. Make sure you set the target configuration to "**Source is exactly the filename**".

No more duplicated images.
> 1 votes

# Answer
There is some movement to resolve this issue (still in dev right now):

Apparently the official way going forward (will not apply to 7.x-2.0-alpha8 without errors): "Allow user to choose the method of file handling" https://drupal.org/node/1171114

Alternatively, this patch will apply to 7.x-2.0-alpha8 but will not be committed: "Allow the reuse of existing file entities instead of creating new ones" https://drupal.org/node/2093829
> 0 votes

# Answer
After banging my head against this issue for a while, my best option was to stop importing images into the nodes as files, but rather using imagecache\_external module to reference the external image url and generating image styles from there. The module adds an Imagecache External Image formatter that behaves just like a normal image formatter in views and node displays.
> 0 votes

---
Tags: feeds, media
---


title: Views Filters Populate + Autocomplete

text:
# Question
Title: Views Filters Populate + Autocomplete
I want to search in one text field on **2 values**. I'm using the Views Filters Populare module for this. This works perfectly. But how can I have an **autocomplete** on this one text field and show both the fields that are searched for?

This is what I have now in my View:

# Answer
with the same views you can use filters in global variables and this module https://www.drupal.org/project/views\_autocomplete\_filters you can make this
> 1 votes

---
Tags: views, ajax
---


title: Drupal 7 Fields Not Showing Up

text:
# Question
Title: Drupal 7 Fields Not Showing Up
I have a Drupal 7 install that acts as a user network site. Users have 'member' permissions but are not administrators.

Some user fields are hidden via the field permissions module, but the rest should be viewable and editable by the user.

After updating the OG module, as well as the Webforms module, all custom fields added to the user node disappeared, both for registered members and new applicants (http://member.clevergirlscollective.com/drupal/?q=user/register , there should be several additional fields here).

I've adjusted permissions both at the field level and at the user node level, but for some reason this still happens.

Any ideas you have would be great!

# Answer
> 1 votes
There are several issues that could be plaguing you related to various configurations. However as a starting point, let's start with the basics:

1. Clear all caches. This will clear most issues caused by upgrades.
2. Rebuild permissions. Sometimes new access permissions or changes to old ones occur during upgrades. Since the fields still exist, but are not seen in the content view, it's possible that a permissions error is in your way.

http://www.example.com/admin/reports/status/rebuild
3. Check your PHP logs. Sometimes issues can occur with PHP where upgrades adding new features break things in a subtle way. Running out of memory, or breaching the 'max\_input\_vars' threshold are common issues I've seen.

# Answer
> 0 votes
When you say "After updating the OG module", from which version to which version? Did you update to a development version? If so, was this absolutely necessary?

My experiences with the latest OG dev versions are that there are a lot of things they break in my install and things still need to be fixed. Also, the "Organic groups access control" greatly affects content permissions and I've noticed some funky things going on with that module alone even on the production module.

# Answer
> 0 votes
You didn't explicitly mention that you did this, so I'll throw this out there: did you clear your cache? I always do that after updating modules as sometimes funky behavior can occur if you do not.

---
Tags: entities, users, organic-groups
---


# Question
Title: Need "carat" for currently active Superfish menu item
I have a Drupal 7 Superfish menu (from the Superfish module) that I would like to add a "carat" to for the currently active menu item.

Here is my current menu:

But I would like a menu where the currently active menu item has a "carat" instead. Here is what I would like: (altered in photoshop to give carat)

I'm looking for the easiest way to do this in Drupal 7. Any ideas?

# Answer
> 0 votes
Your best bet would be to just use CSS. You can create that effect using absolutely positioned pseudo elements with some border tricks. For example:

```
.sf-menu li {
  position: relative;
}

.sf-hover:after,
.active-trail:after {
  content: "";
  display: block;
  position: absolute;
  width: 100%;
  height: 20px;
  border-left: 20px solid transparent;
  border-right: 20px solid transparent;
  border-top: 20px solid #369;
}

```

---
Tags: 7, routes, navigation
---


# Question
Title: Does performing $entity->save() on field collection programmatically clears the page cache of it's node host?
I am using $entity-\>save() on a custom hook\_cron that runs every minute. Does anyone knows if by doing $entity-\>save() , Drupal will clear the page cache of the nodes/views/panels housing it?

# Answer
I know that node\_form\_submit will clear ALL page caches. Sounds like what you're looking for is something like the expire module.
> 1 votes

---
Tags: 7, caching, entities, cron
---


# Question
Title: Node titles are erased when I update a field with entity_metadata_wrapper
I've written a script which fetches data from a REST API and uses it to update a field in a node. The website is multilingual (Canada English, Canada French, Australia English and US English) with US English as the default language. When I run the script with drush, it updates field\_gj\_metro\_id with the correct value from the REST API, but for all nodes with languages other than US English, it deletes the node title.

What am I missing in my script that would take care of the language settings so that the titles will be unaffected?

```
function fetch_metros() {
  return gj_api_request('GetMetroList', $arguments = array());
 }

$metros = array();
$metros = fetch_metros();
foreach ($metros as $metro) {
  $query = new EntityFieldQuery();
  $query
    ->entityCondition('entity_type', 'node')
    ->entityCondition('bundle', 'gj_locations')
    ->propertyCondition('status', 1)
    ->propertyCondition('title', $metro['metroName'])
    ->propertyOrderBy('created', 'DESC')
    ->fieldCondition('field_display_in_listing', 'value', TRUE);
  $result = $query->execute();

  if (!empty($result)) {
    $nids = array_keys($result['node']);
    $node = node_load($nids[0]);
    $node_wrapper = entity_metadata_wrapper('node', $node);
    $node_wrapper->field_gj_metro_id->set($metro['metroID']);
    $node_wrapper->save();
  }
}

```

# Answer
> 0 votes
I tried calling resetCache but the problem persisted. In the end I created a page for each language and used the PHP filter to add the script to the page. By switching to each language, setting the value of propertyCondition('language','') to the loaded language and loading the corresponding page, I was able to import the metroIDs and update the pages, one language at a time, without deleting the titles.

---
Tags: i18n-l10n, entities
---


# Question
Title: How do I get a data value after all AJAX calls are complete?
I'm modifying the content of the modal window that pops up when using Linkit module in a WYSIWYG.

This modal uses AJAX so I have to use Drupal.behaviors for the first time. My code is structured basically like this:

```
(function ($) {
  Drupal.behaviors.mymoduleLinkit = {
    attach: function (context, settings) {
      $('#linkit-dashbaord-ajax-wrapper').once('linkitSelects', function() {
        //do cool stuff
      });
    }
  }
})(jQuery)

```

Now, I need to get the existing value of an input box here, so I simply do this:

```
var $existingData = $('.form-item-linkit-rel input').val();

```

Then try to return that value, but it's always undefined. I *think* it's because this page seems to do a few AJAX calls in a row and I am trying to get the value before it is actually loaded into that field and available.

To ensure that waiting until AJAX is loaded is actually the problem I wrapped my code in a timeout() in order to wait for the loading to finish. This isn't a good solution, but it confirms everything is working once things are loaded. It looked like this:

```
   //wait so data is loaded via ajax
  setTimeout(function() {
    //set our select list to any pre-existing values
    var existingData = $('.form-item-linkit-rel input').val();
    if(existingData != ""){
      var $parts = existingData.split('_');
      $('.form-item-linkit-rel .size-select').val($parts[0]);
      $('.form-item-linkit-rel .type-select').val($parts[1]);
    };
  }, 500);

```

So the question is: Instead of using a timeout, how can I fire this code only after the initial ajax calls are done?

You can view the full code here including the timeout stuff but please don't get distracted by all the other stuff going on (or my poor coding)...Everything else in here works and I'm really just concerned with getting the data in the question above.

# Answer
> 1 votes
Seems that you are building the elements of the form some parts using ajax and some parts using what you show on JsFiddle.

To run commands after success of an Ajax callback you could use he Ajax framework and Ajax framework commands API documentation. Here is a brief example. You will the hook\_form\_alter to alter the linkit\_dashboard\_form and add the commands. This alternative is more accurate to execute the commands after a specific ajax call but would require many changes adding hooks and custom functions.

**Another alternative** is to use .ajaxComplete() and check if the ajax call retrieves the linkit form elements. Example:

```
$(document).ajaxComplete(function(event,request, setting) {
 // Add same check you use on your setTimeout to make sure that "form-item-linkit-rel" input exists.
 // You could also use some of the values of the "setting" param of ajaxComplete() function to use additional checks.
});

```

Note: In case that the problem is caused by something declared inside of Drupal.behaviors.mymoduleLinkit, try to debug your Js code with Chrome/Firefox DevTools. Add some breakpoints to find out what is causing the issue.

---
Tags: javascript
---