# Question
Title: Views Slideshow: keeps showing all images below slider
It shows the normal slider on top... and then all of the images that are suppose to be sliding are stacked below it.

I've gone through several different tutorials and done them all the same way, and I'm still getting this. There has to be something simple that I'm doing wrong here.. but I don't know what it is.

I wanted to post a picture, but my reputation is only a 6..

Edit: Just realized when you hover over these they change the top slide, like thumbnails normally do. But I have no idea how to turn them off or change them to a different size. I created an image style for this, but it apparently isn't working.

Edit x2: It has nothing to do with the thumbnails. It just keeps showing all content that's suppose to be cycling. For example, it's showing every number and every title. Is there no CSS at all with Views Slideshow to not display things?

# Answer
Figured this out. I guess all I needed to do was make a post about it. On the toolbar go to Structure \> Views \> Your\_Slider (whatever it's called) Under Format click on settings beside slideshow Scroll to the bottom. Go to Widgets and make sure there are no pagers selected here. Save and you're done.
> 0 votes

---
Tags: views
---


# Question
Title: Drupal performance issue - too much time to establish a connection!
My drupal site was working fine. Then i disabled access to public with some session thing, After a week or something , it is taking more than 12 second to establish a connection, then the loading is real quick.

```
79 requests  ❘  35.47KB transferred  ❘  14.87s (onload: 14.87s, DOMContentLoaded: 13.06s)
home
12.24s

css_6b268b79fc331b4fe1492e8a55b94a94.css
/sites/default/files/css
206ms

cometchatcss.php
394ms

........

```

another thing is its better for garland theme, so possibly theme problem , what what may cause this much waiting? not db\_query as i checked even with **blank page.tpl** its taking 8+ sec! Please help!

# Answer
> 3 votes
Finally found problem - panel templates in my theme

**for those who experience same , can follow these steps**

* my site is optimized with APC and mod\_deflate, so in pagespeed for chrome test, its 93/100
* real problem was waiting time . chrome network analysis shows first GET took approx 18+ sec , then loading of other elements is real quick
* after several test, i found my theme is causing delay. so i put a blank page.tpl in my theme. And you know it took 12+ sec to load that blank page! so it was not any db query problem!
* so problem must be with .info, disabled css, then js, still no improvement
* finally removed panel template declaration from .info , and now site took .3 sec to load!
* next i tried with only one panel template in my theme, site took 1-2 sec

I have 10 panel templates in my theme.so panel templates affects site performance!

# Answer
> 0 votes
I have been facing such issues. I had spent many hours in profiling and finding which module is causing problem. Unless you find the bottleneck you cannot fix it. I had explained it in a post. http://www.mindyourcode.com/php/drupal-profiling-performance-analysis-for-optimization-finding-the-performance-bottlenecks-in-your-application-at-core-level/

---
Tags: 6, performance
---


# Question
Title: How to make a view that only shows content a user has not voted on
I'm working on a project that asks a group of users with a specific role to vote on content produced by users with a different role.

The group who votes is supposed to try and vote on each item, so I'm trying to make a view that will give them pages of the content.

I would like the view to only show the content that they have *not yet voted on*, so when they have voted on all items, nothing is displayed in the view.

# Answer
> 4 votes
An effective solution to this problem can be found in http://drupal.org/node/513088.

As suggested by Cthos, one should first set up a "Relationship" in the view setting ("advanced" settings in Drupal 7), then use this relationship as a regular filter (no need for contextual filter here).The proposed procedure is:

```
Relationships
    Node: Votes
        "Require this relationship": no
        "Value type": No filtering
        "Vote tag": Normal vote
        "Restrict to current user": yes
Filters
    (Votes) Votes: Value
        "Relationship": use the one from above
        "Operator": "Is empty (NULL)"

```

---
Tags: views, rating
---


# Question
Title: print.module error - Warning: file_put_contents
I am using the print.module and dompdf to convert the PDF files. I am getting the following warning on my pages. How would I go about fixing this?

> Warning: file\_put\_contents(/home/mysite/public\_html/sites/all/modules/print/lib/dompdf/lib/fonts/php\_Times-Bold.afm): failed to open stream: Permission denied in Cpdf-\>openFont() (line 2354 of /home/mysite/public\_html/sites/all/modules/print/lib/dompdf/lib/class.pdf.php).
>
> Notice: Constant DOMPDF\_TEMP\_DIR already defined in require\_once() (line 73 of /home/mysite/public\_html/sites/all/modules/print/lib/dompdf/dompdf\_config.inc.php).
>
> Notice: Constant DOMPDF\_ENABLE\_PHP already defined in require\_once() (line 185 of /home/mysite/public\_html/sites/all/modules/print/lib/dompdf/dompdf\_config.inc.php).
>
> Notice: Constant DOMPDF\_ENABLE\_REMOTE already defined in require\_once() (line 196 of /home/mysite/public\_html/sites/all/modules/print/lib/dompdf/dompdf\_config.inc.php).

# Answer
> 2 votes
Take a look at the INSTALL.txt file. You need to give the webserver write access to the dompdf/lib/fonts directory.

In my case, I chowned it to apache:apache. Make it mirror how you have your sites/default/files directory set up.

---
Tags: files
---


title: Display block on certain page

text:
# Question
Title: Display block on certain page
I want to display a block on the user/\* page. I checked "only the listed pages" and entered "user/*" but the block also appears on "user/*/relationships" for example.

How can I keep the block on just the first path?

# Answer
> 3 votes
If you want more control on this, you can choose the option "**Pages on which this PHP code returns TRUE (experts only)**" and you can write the following similar code snippet the the box.

```
<?php
if( arg(0) == 'user' /* && you may add more conditions here by checking arg(1), arg(2) */) {
    return TRUE; // will display the block
}
return FALSE; // will not display the block
?>

```

The alternative way is to check the path with regular expression:

```
<?php
if( preg_match('/^user\/[[:digit:]]$/', current_path()) ) {
    return TRUE; // will display the block
}
return FALSE; // will not display the block
?>

```

This will show your block only at the path **user/\***.

# Answer
> 1 votes
Check "Pages on which this PHP code returns TRUE (experts only) in block settings" and paste:

```
<?php
if ((arg(0) == 'user') && is_numeric(arg(1)) && (arg(2) == NULL)) {
   return TRUE;
}
else {
   return FALSE;
}
?>

```

---
Tags: blocks
---


title: Move drag and drop handle to other side

text:
# Question
Title: Move drag and drop handle to other side
I want to move the drag and drop handle to the other side of a form, to the same location as the row weight selections. I am talking about the tabledrag handles, as shown below:

I am using Corolla if it makes a difference.

# Answer
two changes i made

```
form .field-multiple-table td.field-multiple-drag { width: 30px; padding-right: 0; position: absolute; left:0px; /*LTR*/ } form .field-multiple-table td.field-multiple-drag a.tabledrag-handle { padding-right: 0em; position: absolute; left: 520px; /*LTR*/

```
> 0 votes

---
Tags: theming, entities
---


# Question
Title: How to add a media type to drupal_add_css in custom module
I’ve got a question about adding CSS to a custom module.

Originally I’ve been given this line:

```
link rel="stylesheet" type="text/css" media="screen and (max-width: 640px)"    href="mobile.css"

```

And I’ve converted it into:

```
drupal_add_css(drupal_get_path('module', 'savingsscore') . '/css/mobile.css', 'screen and          (max-width: 640px');

```

The file is being attached, but the media setting is wrong and I don’t know what it should be. I’m in Drupal 6.

Thanks!

# Answer
> 1 votes
drupal\_add\_css() is defined as:

```
drupal_add_css($path = NULL, $type = 'module', $media = 'all', $preprocess = TRUE)

```

and in your example, you are doing:

```
drupal_add_css(drupal_get_path('module', 'savingsscore') . '/css/mobile.css', 'screen and          (max-width: 640px');

```

which appears to have two problems:

1. You are skipping the $type argument,
2. You aren't closing the max-width parenthetical.

I'd suggest trying:

```
drupal_add_css(drupal_get_path('module', 'savingsscore') . '/css/mobile.css', 'module', 'screen and (max-width: 640px)');

```

and seeing it that fixes things up.

# Answer
> 0 votes
Why not put the media query inside your style sheet?

Wrap everything in:

```
@media only screen and (max-device-width: 640px) {
  /* Contents of mobile.css goes here. */
}

```

---
Tags: theming, 6
---


# Question
Title: how would i go about creating variable menu links
I would like to display different menu links on each page depending on the content and relevance of each page. How would I do this?

# Answer
You should try Context

> Context allows you to manage contextual conditions and reactions for different portions of your site. You can think of each context as representing a "section" of your site. For each context, you can choose the conditions that trigger this context to be active and choose different aspects of Drupal that should react to this active context.
> 0 votes

---
Tags: 7, routes
---


# Question
Title: Content type data becomes the field label for another content type
I'm using Drupal 7, and on my Drupal website I've created a content type. This content type has 2 fields: field name, and code. I need to create another content type, and (on this content type) fields based on the data of the "Name" field of the previous content type.

For example:

* Content type ABC: content

```
Name  | Code
AAAAA | A
ABABA | B
ACACA | C

```
* Content type DEF: fields

+ AAAAA (widget: textfield)
    + ABABA (widget: textfield)
    + ACACA (widget: textfield)

How can I achieve this?

# Answer
> 0 votes
A better way is to use Entity reference

> Provides a field type that can reference arbitrary entities:

---
Tags: 7, nodes
---


title: Help on Drupal table prefix

text:
# Question
Title: Help on Drupal table prefix
I just installed Drupal 7 and made some content and configuration.

After that, I just realized I did not put any table prefix on installation.

My problem is:

Is there anyone here that knows the SQL to add table prefix on Database `drupl`?

Example

* current table: variable
* must be: drupal\_variable

I want to change all my table and add prefix.

# Answer
> 2 votes
If you have access to phpMyAdmin, you can do that manually following this steps:

1. Login to PhpMyAdmin
2. Select all drupal tables
3. With selected: Replace table prefix
4. From: *{empty}*, To: **yourprefix\_**
5. in settings.php (sites/default/settings.php) change in the database configuration: `'prefix' => '',` to `'prefix' => 'yourprefix_',`
6. Run cron.

# Answer
> 0 votes
DISCLAIMER : Not a Drupal Developer, Just a MySQL DBA

You have a database called `drupl`

You want to prefix every table in that database with the `drupal_`

Here is the SQL to generate the script

```
SET @tableprefix = 'drupal_';
SET @dbtofix = 'drupl';
SELECT CONCAT('ALTER TABLE ',db,'.',tb,' RENAME ',db,'.'@tableprefix,tb,';')
FROM (SELECT table_schema db,table_name tb
FROM information_schema.tables WHERE table_schema=@dbtofix) A;

```

Here is how you script it in the OS

```
echo "SET @tableprefix = 'drupal_';" > Script.sql
echo "SET @dbtofix = 'drupl';" >> MakeScript.sql
SQLSTMT="SELECT CONCAT('ALTER TABLE ',db,'.',tb,'"
SQLSTMT="${SQLSTMT} RENAME ',db,'.'@tableprefix,tb,';')"
SQLSTMT="${SQLSTMT} FROM (SELECT table_schema db,table_name tb"
SQLSTMT="${SQLSTMT} FROM information_schema.tables"
SQLSTMT="${SQLSTMT} WHERE table_schema=@dbtofix) A"
mysql -u... -p... -ANe"${SQLSTMT}" >> MakeScript.sql
mysql -u... -p... < MakeScript.sql > AddPrefix.sql
mysql -u... -p... < AddPrefix.sql

```

Give it a Try !!!

---
Tags: database
---


# Question
Title: how can I have Infinite pager in mini_page views?
I need my minipager to go infinite. I mean when it get to the last record to jump to the the first one. If it goes to the last one jump to the first one? How can I achieve this. I am using views to display my information. But I just want it to use it in a particular view. I don't want it to be default for all my views.

# Answer
I use this reference views mini pager. In order to do this in your template.php you need to call the function for that view mini pager. In order to find out which is the best for you, use the theme developer module.

The trick is to change what happens when empty($li\_previous)) and (empty($li\_next)). If there is a better way to accomplish this, please let me know.

```
function my_theme_name_views_mini_pager__yourview($variables){

```

> global $pager\_page\_array, $pager\_total;

```
$tags = $vars['tags'];
  $element = $vars['element'];
  $parameters = $vars['parameters'];
  $quantity = $vars['quantity'];

  // Calculate various markers within this pager piece:
  // Middle is used to "center" pages around the current page.
  $pager_middle = ceil($quantity / 2);
  // current is the page we are currently paged to
  $pager_current = $pager_page_array[$element] + 1;
  // max is the maximum page number
  // first is the first page listed by this pager piece (re quantity)
  $pager_first = $pager_current - $pager_middle + 1;

  $pager_last = $pager_current + $quantity - $pager_middle;
  // max is the maximum page number

  $pager_max = $pager_total[$element];
  // End of marker calculations.

  if ($pager_total[$element] > 1) {
  $li_previous = theme('pager_previous',
  array(
  'text' => (isset($tags[1]) ? $tags[1] : t('')),
  'element' => $element,
  'interval' => 1,
  'parameters' => $parameters,
)
);

if (empty($li_previous)) {
  $li_last = theme('pager_last',
   array('text' => (isset($tags[4]) ? $tags[4] : t('')),
  'element' => $element,
  'parameters' => $parameters));

  $li_previous =$li_last;

}

$li_next = theme('pager_next',
  array(
  'text' => (isset($tags[3]) ? $tags[3] : t('')),
  'element' => $element,
  'interval' => 1,
  'parameters' => $parameters,
)
);

if (empty($li_next)) {
  $li_first = theme('pager_first', array('text' => (isset($tags[0]) ? $tags[0] : t('')), 'element' => $element, 'parameters' => $parameters));
  $li_next = $li_first;

}

$items[] = array(
  'class' => array('pager-previous'),
  'data' => $li_previous,
);

$items[] = array(
  'class' => array('pager-current'),
  'data' => t('@current of @max', array('@current' => $pager_current, '@max' => $pager_max)),
);

$items[] = array(
  'class' => array('pager-next'),
  'data' => $li_next,
);

return theme('item_list',
  array(
  'items' => $items,
  'title' => NULL,
  'type' => 'ul',
  'attributes' => array('class' => array('pager')),
)
);

```

}

```
}

```
> 0 votes

---
Tags: 7, views
---


# Question
Title: How to use ajax to display database records using a select list?
I have used a select list in my custom form to select a product code and display data corresponding to that code. I am using AJAX for this task but it does not display any record.

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

  // Change the description of a form element.
  $items['examples/webform_module/report'] = array(
    'title' => 'Report',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('webform_module_report'),
    'access callback' => TRUE,
    'weight' => 0,
  );
   return $items;
}

function webform_module_report($form, &$form_state) {
  $result = db_query("SELECT o.nid, o.sku FROM {formmodule_order} o ");
  $options = array();

  foreach($result as $row) {
    $options[$row->nid] = $row->sku;
  }

  $form['select'] = array(
    '#title' => 'Option',
    '#type' => 'select',
    '#options' => $options,
    '#ajax' => array(
      'wrapper' => 'some-form-results-wrapper',
      'callback' => 'webform_module_display'
    )
  );

  $form['results'] = array(
    '#prefix' => '<div id="some-form-results-wrapper">',
    '#suffix' => '</div>'
  );

  // If the form has been submitted, build up your results and display them
  if (isset($form_state['values']['select'])) {
    $rows = db_select('formmodule_order', 't')
      ->fields('t')
      ->condition('t.sku', $form_state['values']['select'])
      ->execute()
      ->fetchAll();

    $header =  array(t('Product ID'), t('Product Code'), t('Product Stock'), t('Product Purchased'), t('Created'));

    $form['results']['#markup'] = theme('table', array('header' => $header, 'rows' => $rows));
  }
  else {
    $form['results']['#markup'] = '<p>The results will appear here when you change the dropdown option.</p>';
  }

  return $form;
}

function webform_module_display($form, $form_state) {
  return $form['results'];
}

```

**Update**: after debugging the query under if statement `$rows = db_select('formmodule_order', 't') ->fields('t') ->condition('t.sku', $form_state['values']['select']) ->execute() ->fetchAll();` does not print any result. It just says array(). What does that mean?

# Answer
> 0 votes
## Display recrd from database when selected from select list Using AJAX

## yourmodule.module file

```
<?php

```

**hook\_menu implementation**

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

  // Change the description of a form element.
  $items['examples/webform_module/report'] = array(
    'title' => 'Report',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('webform_module_report'),
    'access callback' => TRUE,
    'weight' => 0,
  );
   return $items;
}

function webform_module_report($form, &$form_state) {
**query to fetch data in a select list**
$result = db_query("SELECT o.nid, o.sku FROM {formmodule_order} o ");

    $options = array();
   foreach($result as $row) {
      $options[$row->nid] = $row->sku;

    }

 //drupal_set_message('<pre>' . print_r($options, true) . '</pre>');
 $form['select'] = array(
    '#title' => 'Option',
    '#type' => 'select',
    '#options' => $options,    **//option will be displayed here**
    '#ajax' => array(
      'wrapper' => 'some-form-results-wrapper',
      'callback' => 'webform_module_display'
    )
  );

```

**This will form the header of the table below which the data will be displayed**

```
  $form['results'] = array(
    '#prefix' => '<div id="some-form-results-wrapper">',
    '#suffix' => '</div>',
    '#tree' => TRUE,
    '#theme' => 'table',
    '#header' => array(t('Product ID'), t('Product Code'), t('Product Stock'), t('Product Purchased'), t('Created')),
    '#rows' => array(),

  );
  // drupal_set_message('<pre>header:' . print_r($form['results'], true) . '</pre>');

  **// If the form has been submitted, build up your results and display them**
  if (isset($form_state['values']['select'])) {

    drupal_set_message('<pre>select_option:' . print_r($form_state['values']['select'], true) . '</pre>');

  $query = db_select('formmodule_order', 't')
      ->fields('t')
      ->condition('nid', $form_state['values']['select']);

     $result = $query->execute();
     // drupal_set_message('<pre>option1:' . print_r($result, true) . '</pre>');
    **// loop through to display result**
   while($row = $result->fetchAssoc()) {

    //$debug .= '<br/>Header Record #'.' <pre>' . print_r($row, true) . '</pre>';
  $nid = array('#id' => 'id',
                 '#type' => 'markup',
                 '#markup' => '<b>' . $row['nid']. '</b>',
                 );
    //drupal_set_message('<pre>' . print_r($nid, true) . '</pre>');
    $sku = array('#id' => 'sku',
                     '#type' => 'markup',
                    '#markup' => '<b>' . $row['sku'] . '</b>',
                 );
    //drupal_set_message('<pre>' . print_r($sku, true) . '</pre>');
   $orderin = array('#id' => 'orderin',
                 '#type' => 'markup',
                 '#markup' => '<b>' . $row['orderin']. '</b>',
                 );
            //   print_r($orderin);
    //drupal_set_message('<pre>' . print_r($nid, true) . '</pre>');
    $orderout = array('#id' => 'orderout',
                     '#type' => 'markup',
                    '#markup' => '<b>' . $row['orderout'] . '</b>',
                 );
    //drupal_set_message('<pre>' . print_r($orderOut, true) . '</pre>');
    $created = array('#id' => 'created',
                     '#type' => 'markup',
                    '#markup' => '<b>' . $row['created'] . '</b>',
                 );

    $form['results'][] = array('nid' => &$nid,
                                'sku' => &$sku,
                                'orderIn' => &$orderin,
                                'orderOut' => &$orderout,
                                'created' => &$created,
                                );
    $form['results']['#rows'][] = array(array('data' => &$nid),
                                         array('data' => &$sku),
                                         array('data' => &$orderin),
                                        array('data' => &$orderout),
                                         array('data' => &$created),
                                         );
    unset($nid);
    unset($sku);
    unset($orderin);
    unset($orderout);
     unset($created);

    }

  }

 else {
   $form['results']['#rows'] = '<p>The results will appear here when you change the dropdown option.</p>';
    }

      return $form;
    }

**callback function**
   function webform_module_display($form, $form_state) {

      return $form['results'];

    }

```

---
Tags: forms, ajax
---


# Question
Title: Undefined index: method in drupal_prepare_form()
I am getting this strange notice

> Undefined index: method in drupal\_prepare\_form()

in my Drupal 7 application but only on production server. It is really weird, on my development PC I have PHP 5.4.6 and on my server I have 5.3.3 and this is probably the only difference. I cannot get this error on my dev PC, so I really don't have any idea what is wrong and how to repair this.

I couldn't find anything good on the web, only that it could be connected with localization modules.

thanks!

# Answer
> 1 votes
I hope, this can be useful, to you

http://drupal.org/node/1024298

Probably, there is new patch introduced, please go through the blog above.

---
Tags: forms
---


# Question
Title: How do I create a hidden field programatically?
I've got a module that is creating fields programatically, all working so far. The code is below. This may be useful as-is if you are trying to create checkboxe fields from an array of values:

```
    /**
     * Helper function to create fields for workflow approvers
     *
     */

    function _create_approval_fields($approverRolesClean){
      $fieldPrefix = 'wf_';

      // TODO: If an existing field is removed, delete it.

      foreach ($approverRolesClean as $approverRole) {
        $cleanRole = preg_replace('/[^a-z]/', "", strtolower($approverRole));
        $fieldName = $fieldPrefix.$cleanRole;
        if (!field_info_field($fieldName)) {
          $field = array(
            'field_name' => $fieldName,
            'type' => 'list_boolean',
            'widget' => array(
              'type' => 'options_onoff',
              'settings' => array(
                'display_label' => '1',
              ),
            ),
            'settings' => array(
              'allowed_values' => array(
                '0' => 'No',
                '1' => 'Yes',
                ),
              ),
            );
          field_create_field($field);
        }
        //Hardcoded:
        if (!field_info_instance('node', $fieldName, 'contenttype')) {
          $instance = array(
            'field_name' => $fieldName,
            'entity_type' => 'node',
            'label' => 'Approved by ' . $approverRole,
            //Hardcoded:
            'bundle' => 'contenttype',
            'widget' => array(
              'type' => 'options_onoff',
              'settings' => array(
                'display_label' => '1',
              ),
            ),
          );
          field_create_instance($instance);
        }
      }
    }

```

I set the value of the fields outside the Edit screen - so they never need to show there. I'm sure there is a settings parameter that I can add to hide it, but not sure where to find the doc. I don't think no\_ui is what I need.

Otherwise I can use the form api to hide it at render time, but that doesn't seem as elegant.

Thanks,

Jack

# Answer
> 0 votes
If it's a regular Field API field, you can easily hide it with

hook\_field\_access

e.g:

```
/**
 * Implements hook_field_access
 */
function mymodule_field_access($op, $field, $entity_type, $entity, $account) {
  if ($field['field_name'] == 'field_wf_admin' && $op == 'edit') {
    // Only allow admins to edit field value
    return user_access('administer nodes', $account);
  }
  return TRUE;
}

```

Alternatively, there's the field\_extrawidgets module for hidden and readonly Field API fields

# Answer
> 1 votes
I don't follow the example 100%, but to answer the question - in D7 you can set `'#type' => 'hidden', '#value' => 'foo'` or just do `'#my_custom_key' => 'my custom value'` and it will be available to you in the submit handler (or elsewhere, such as hook\_field\_attach\_submit()).

---
Tags: 7, entities
---


# Question
Title: How does the "User has role" visibility rule work in Panels?
I'm using Panels and I have added a "User has role" visibility rule to a pane.

I want to show the pane only if the user does not have Role A or Role B.

I configured the rule as follows:

* User: **Logged in user**
* Roles: **Role A**, **Role B**
* I then checked **Reverse (NOT)**

However, this doesn't work. I tested with a user who does not have Role A or Role B, but the pane still appears. Even if I only check **Role A** and not **Role B**, the pane still appears.

How can I configure a pane to show only if a user does not have either of two roles?

# Answer
Try to uncheck all criteria must pass and check only one criteria must path

you will find it clicking settings under add new rule tab
> 0 votes

---
Tags: panels
---


# Question
Title: Display language in entity reference field
I am running a multilanguage website and I have some content types using entity references. Now, the problem is that when I am adding content, if I have two content with the same name but different languages (a product name for instance), I have no way to know which one I am choosing in the entity reference field. So I want to be able to display language in the entity reference select box. Something like this :

```
Lorem Ipsum (EN)
Lorem Ipsum (IT)
...

```

Is there any module I can use for that or some hooks?

# Answer
You can do this with views. Views allows you to add a "Reference" display. There you can choose how your title or your reference entry should look like. The view can then be chosen from the settings of the node reference field.
> 4 votes

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


# Question
Title: Change plid of existing administration menu items
I'm building an internal portal for an organisation and I want to change the standard administration menu, putting a number of the front-facing website options under a menu item called 'Website' and the rest under 'Drupal Config'.

So I'm simply trying to change the plid of 'admin/content', but it's not working. Could somebody guide me on where I'm going wrong please?

```
function eac_sponsorship_menu_alter(&$items) {

    $items['admin/content']['plid'] = 592; //592 is id of 'Website' menu item
    menu_link_save($items);

}

```

Also are there likely to be any repercussions from doing this?

Note that in the final solution the plid wont be hard coded as "592", but will use a DB look up to get the mlid of the 'Website' menu.

Also it is not a cache issue, when checking the DB the plid of admin/content remains to be '1'.

# Answer
In my example here I'm using `hook_flush_caches` instead of `hook_menu_alter`.

Also you can replace/alter db\_select to return list of menu links you need to change.

```
/**
 * Implements hook_flush_caches().
 */
function eac_sponsorship_flush_caches() {

  $mlid = db_select('menu_links', 'ml')
    ->fields('ml', array('mlid'))
    ->condition('menu_name', 'management')
    ->condition('link_path', 'admin/content')
    ->execute()
    ->fetchField();

  if($mlid) {

    $item = menu_link_load($mlid);
    $item['customized'] = 1;
    $item['plid'] = 592; //592 is id of 'Website' menu item
    menu_link_save($item);
  }
}

```

also don't forget to clear/flush Drupal cache.
> 2 votes

# Answer
If you want your own top level admin menu group, you should probably create your own parent menu item and section there using hook\_menu

e.g `admin/website` and put your menu items under that.

```
/**
 * Implements hook_menu
 */
function my_module_menu(){

  $items = array();

  // Provide own admin configuration menu section
  // using system_admin_menu_block_page for item groups
  // Top level section
  $items['admin/website'] = array(
    'title' => 'Website',
    'description' => 'Local website configuration.',
    'page callback' => 'system_admin_menu_block_page',
    'access arguments' => array('access administration pages'),
    'file path' => drupal_get_path('module', 'system'),
    'file' => 'system.admin.inc',
  );
  // Child admin menu group
  $items['admin/website/config'] = array(
    'title' => 'Configuration',
    'description' => 'Configure website settings.',
    'page callback' => 'system_admin_menu_block_page',
    'access arguments' => array('access administration pages'),
    'type' => MENU_NORMAL_ITEM,
    'weight' => 50,
    'file path' => drupal_get_path('module', 'system'),
    'file' => 'system.admin.inc',
  );
  // Child group menu item
  $items['admin/website/config/advanced'] = array(
    'title' => 'Advanced settings',
    'description' => 'Configure advanced website settings.',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('mymodule_website_settings_form'),
    'access arguments' => array('administer site configuration'),
    'type' => MENU_NORMAL_ITEM,
    'file' => 'includes/my_module.admin.inc',
  );

  return $items;

}

```

See system\_menu for an example hook\_menu using system\_admin\_menu\_block\_page
> 3 votes

# Answer
I am using this https://drupal.stackexchange.com/a/53531/12153

That way I tweak menus depending on weather the user logged in or not. I also used it to slightly change the secondary menu.

Together with menu\_rules which allows me to add new links, I have full control over what my menus do. So far I had no issues with this solution.
> 0 votes

---
Tags: routes
---


# Question
Title: Customizing views exposed filter drop down list with css
I have a view with few exposed filters. They are all "choose 1 term" type of filters with appearing dropdown list when you click on right side of them.

I want to style appearing dropdown lists. It looks ok in chrome, but it's especially ugly looking in IE. Also, i can't find them in the code, they just dissapear when i try to "inspect" them.

How can i customize those drop-down lists' appearances? Do they have any css classes? Any other ideas?

# Answer
Unfortunatelly, every browser has its own rendering of drop downs (as well as fileupload boxes). So direct CSS styling of a dropdown element won't work in all browsers.

What you need to do is to use module called Uniform (http://drupal.org/project/uniform). It provides intergration with uniform library which automatically replaces drop downs, fileuploads, checkboxes and radios with custom styled elements.

This will give you ability to style these custom elements and make dropdown lists look the way you want in almost any browser. Just check if this works for you.
> 1 votes

# Answer
try this css code and change it to your requirement

```
.form-select {
   background: transparent;
   width:95px;
   padding: 4px;
   border: 1px solid #d8d9da;
   cursor:pointer;
   border-radius:4px;
    color: #8C8C8C;
    font: 13px "Times New Roman";
    font-style:italic;
     -webkit-transition-duration: 0.1s;
-moz-transition-duration: 0.1s;
-o-transition-duration: 0.1s;

}

.form-select:hover{

    background-color:#CC0;

}

```
> 0 votes

---
Tags: views, theming
---


title: Author only access to tab menu of node

text:
# Question
Title: Author only access to tab menu of node
I have created one menu tab in the node page to show statistics of the article using my custom module.

I have implemented hook\_menu() as follows:

```
function mymodule_menu() {

    $items = array();

    $items['node/%node/menu_title'] = array(
        'title' => 'Page Title',
        'page callback' => 'get_statstics',
        'page arguments' => array(1),
        'access callback' => TRUE,
        'type' => MENU_LOCAL_TASK,
    );

    return $items;
}

```

It is working fine. But I wanted only author of the node to have access to this link and also for specific content type. Now it is showing this link to every node and for every user.

How can I restrict it to specific content type and for author only?

-- Many thanks for your time

# Answer
> 3 votes
Under `access callback` you have `TRUE`, just change this to a function that evaluates whether the current user is the author of the current node. The function would look like this

```
function yourmodule_check_author() {
  global $user;
  $node = menu_get_object();
  return $node->uid == $user->uid;
}

```

Check this post. You will get more insight on the inner workings of the function.

# Answer
> 3 votes
This is what I have done:

```
function mymodule_menu() {

    $items = array();

    $items['node/%node/menu_title'] = array(
        'title' => 'Page Title',
        'page callback' => 'get_statistics',
        'page arguments' => array(1),
        'access callback' => 'my_access_callback',
        'access arguments' => array(1),
        'type' => MENU_LOCAL_TASK,
    );

    return $items;
}

function my_access_callback($node = NULL) {
   if($node->type == "article" && $node->uid == $GLOBALS['user']->uid)
     return TRUE;
   else
     return FALSE;
}

```

May help some other.

---
Tags: 7, routes, users
---


# Question
Title: Using the Commerce Kickstart distribution to sell non-standard products
I've been using the Commerce Kickstart distribution for physical products and it work great.

Now I find myself in a situation which could be the common for many of us.

I need to start a new project where the product to sell is a **Parcel Delivery Service**. Very similar to this one: http://www.parcel2go.com/

Then, from my point of view, the process is:

> 1) The user enters required data (Collection, Destination, Weight, etc)
>
> 2) Clicks the button "quote"
>
> 3) System generates a single product with a calculated price (based on the data entered by the user)
>
> 4) The user add the product to the cart and follows the checkout in the standard way

The difference is that there is no previously created products in this site. I think that there is just one product which I can call "Delivery Service" but this product has no **price**. This price will be generated **on the fly** by a formula using the data entered by the user.

Is this the right approach?

Can I use the Commerce Kickstart distribution for this case? If so, which other module could be useful for this case?

# Answer
> 2 votes
Not really an answer, but only my point of view.

I would create a dummy item without price and add the calculated price to the carrier fees. You can trigger almost every action you need from Rules.

* Add FOO item to cart.
* Add the transport fee to the order.

This rules are already there in Kickstart, you will only have to tune the Carrier fee calculation rules to fit your use case. Of course I don't think Kickstart is designed with selling services in mind but I don't think you are going to find any major problem in going this way. Think of a store with only one product that ships worlwide with different transport fees. The carrier can well be a variation type of your product.

My 2 cents.

---
Tags: commerce
---


title: Subscribing to events calendar updates

text:
# Question
Title: Subscribing to events calendar updates
I've implemented an events calendar to my drupal 7 site. How would I offer the option for users to subscribe for event calendar updates?

# Answer
A couple of options, for example:

1. Provide an RSS feed of the calendar events.
2. Provide email notifications with something like http://drupal.org/project/subscriptions
> 1 votes

---
Tags: views, datetime
---


# Question
Title: Show sharethis twice on a page with different layouts
I'm using Sharethis, is there any way to show sharethis as horizontal counter on the articles content type teaser display and then show it as large chicklets on a block?

# Answer
> 1 votes
You can do it in node.tpl file, by using the sharethis custom code(get it from sharethis.com) and choose your horizontal style

below is the code to display only in teaser(paste this code in node.tpl)

```
<?php if ($teaser): ?>
    <span class='st_email_hcount' displayText='Email'></span>
    <span class='st_sharethis_hcount' displayText='ShareThis'></span>
    <span class='st_plusone_hcount' displayText='Google +1'></span>
    <span class='st_facebook_hcount' displayText='Facebook'></span>
    <span class='st_twitter_hcount' displayText='Tweet'></span>
    <span class='st_linkedin_hcount' displayText='LinkedIn'></span>
<?php endif;?>

```

for block again choose your style from sharethis.com and paste it in the block

hope you can get ideas from the above!

# Answer
> 0 votes
I think you can implement this using hook\_node\_view().

Make **ShareThis** settings as block at **admin/config/services/sharethis** by choosing the button style **Large Chicklets** and choosing **Context » Location » Block**.

To display the ShareThis in the node view, you would need to implement `hook_node_view()`. The ShareThis module has `sharethis_node_view()`.

Copy `sharethis_node_view()` and rename it to `mymodule_node_view()`. Then, update it as you need. The main trick is `$data_options['buttons'] = 'stbc_hcount';` which shows horizonal counters buttons.

```
function mymodule_node_view($node, $view_mode = 'full', $langcode = NULL) {
    if($view_mode == 'full'){
      // First get all of the options for the sharethis widget from the database:
      $data_options = sharethis_get_options_array();
      // horizonal country button type
      $data_options['buttons'] = 'stbc_hcount';

      // This looks to see if the path variable has been posted by some rewrite module.
      // This is not super efficient, O(N), but N is often less than 20.
      $is_path = FALSE;
      foreach ($node as $k => $v) {
        if ($k == "path") {
          $is_path = TRUE;
        }
      }
      // This will choose the path to use.
      if ($is_path) {
        $path_module = $node->path;
      }
      else {
        $path_module = "/node/" . $node->nid;
      }

      // Pathauto integration !
      if (module_exists('pathauto')) {
        $path_module = '/' . drupal_lookup_path('alias',"node/" . $node->nid);
      }

      global $base_url;
      // Get the full path to insert into the Share Buttons.
      $mPath = $base_url . $path_module;
      $mTitle = $node->title;

      // Only display the ShareThis buttons if this node fits all the requirements
      if (strpos($data_options['nodeType'], $node->type) !== FALSE) { // Make sure this is the right type of node.
        if (($data_options['viewMode'] == "1") && ($view_mode == "teaser")) {
          // If "don't show for teaser" is enabled, and this is a teaser, don't do anything
          // Do nothing.
        }
        else {
          // Check where we want to display the ShareThis widget.
          $node->content['sharethis'] = array(
            '#tag' => 'div', // Wrap it in a div.
            '#type' => 'html_tag',
            '#attributes' => array('class' => 'sharethis-buttons'),
            '#value' => sharethis_get_button_HTML($data_options, $mPath, $mTitle),
            '#weight' => intval(variable_get('sharethis_weight', 10)),
          );
        }
      }
    }
}

```

---
Tags: social-network
---


# Question
Title: Show all terms that are children of term with argument tid
I need a view that shows all terms that are children of the argument tid.

```
term 1
-term 2
-term 3
term 4
-term 5

```

view/4 should return term 5

I must be missing something fundamental because no matter how I mess with contextual filters and relationships I never come close to actually filtering my results by the context.

# Answer
> 1 votes
Normally Answers that are just links are frowned upon, but the answer in my comment can be found here on StackOverflow Drupal - On term page show child terms?.

The image on that answer is also posted below:

It would be good if people could head to the original answer and throw the author an upvote if this is helpful to anyone.

# Answer
> 1 votes
If you add a contextual filter for taxonomy term with depth modifier, it should work, e.g terms/1/1

---
Tags: views
---


# Question
Title: How to orderBy joined table after ordered main in db_select
I have 3 joined tables - The query search some string on main table then join other by entity\_id. I want to orderBy records in order first second third tables result, but no success now. At this time I have order by only for main table.

My query:

```
$query = db_select('field_data_field_cg_w', 'w');

$query -> join('field_data_field_cg_h', 'h', 'w.entity_id = h.entity_id');
$query -> fields('h', array('entity_id', 'field_cg_h_value'));

$query -> join('field_data_field_cg_g', 'g', 'w.entity_id = g.entity_id');
$query -> fields('g', array('entity_id', 'field_cg_g_value'));

$query -> fields('w', array('entity_id', 'field_cg_w_value'))
  -> condition('w.field_cg_w_value', $options['string'] . '%', 'LIKE')
  -> orderBy('w.field_cg_w_value', 'ASC');

$records = $query->execute();

```

EDIT: The result (last part of query) after Clive's answer:

```
$query -> fields('w', array('entity_id', 'field_cg_w_value'))
  -> condition('w.field_cg_w_value', $options['string'] . '%', 'LIKE')
  -> orderBy('w.field_cg_w_value', 'ASC')
  -> orderBy('h.field_cg_h_value', 'ASC')
  -> orderBy('g.field_cg_g_value', 'ASC');

```

# Answer
> 1 votes
Not sure I understand but you're not limited to a single `orderby()` in a `SelectQuery` so you would just add another one with the correct alias, e.g.

```
$query -> fields('w', array('entity_id', 'field_cg_w_value'))
  ->condition('w.field_cg_w_value', $options['string'] . '%', 'LIKE')
  ->orderBy('w.field_cg_w_value', 'ASC')
  ->orderBy('g.entity_id', 'DESC');

```

---
Tags: 7, database
---


# Question
Title: Migrate doesn't update destination files if source files have changed content
I'm using Migrate 7.x-2.5 to keep Commerce products synchronized between a legacy system and a Drupal ecommerce website.

I setup two migration methods, one for Commerce Products entities and one to generate nodes for product display. Migration tasks are supposed to be run every night, because people during the day add new products, update some, and delete others. So both migration tasks are run with the "update" checkbox checked. I take care to delete obsolete content at postImport() and all is good.

Everything is working for me, except for product images. When source files are updated with different pictures, filename doesn't change (that's a legacy system behaviour). Migrate doesn't seem to notice that the file has changed, so it doesn't migrate it and pictures don't get updated.

Anyone can help dealing with this file updating issue?

Here's the relevant migration part where files are handled.

```
$this->addFieldMapping('field_image', 'immagine'); //this field gets populated in prepareRow()
$this->addFieldMapping('field_image:file_class')
        ->defaultValue('MigrateFileUri');
$this->addFieldMapping('field_image:source_dir')
        ->defaultValue(SRC_IMG_PATH);
$this->addFieldMapping('field_image:file_replace')
        ->defaultValue(FILE_EXISTS_REPLACE);

```

# Answer
It turns out that files are actually updated. So there's nothing to edit in my migration code.

Problem is that a flush on image styles is required.

I was triggering flush manually, but I could not see updated images in webpages.

Flushing was not working due to file permissions on resized images, so I still see the old "styled" images.
> 0 votes

---
Tags: 7, files, migrations
---


title: ADD MORE option in form element

text:
# Question
Title: ADD MORE option in form element
I am working with WEBFORM module, and I provided only one text area for the user to enter his choice but I want a "ADD MORE" button in my form element so that my user can enter his second choice also. I want to know what I can do to achieve described action?

# Answer
Not possible at the moment with Webform, but hey, do you really need a webform module to achieve what you need?

You could create a custom content type with any fields set you can imagine (single and multiple) and give users permission to create nodes of this type. So this way you'd be able to gather form submissions as separate nodes.
> 0 votes

# Answer
A possible workaround would be to use Webform Conditional module (presuming you're using webform module version prior to 7.x-4.x which is still in alpha).

Instead of having a "add more" button, you could have a "add more" checkbox, and when this checkbox is checked, Webform Conditional would display your second textarea...
> 0 votes

---
Tags: 7, forms, webforms
---


# Question
Title: List nodes from a taxonomy based on a field
I'm looking for the most "Drupal" way to create either a view/block (not sure about either) that contains a list with the top level items being the parent taxonomies from a certain vocabulary (4 parents in total), and then nested under each taxonomy, the first 5 products that have a certain field on them set to true.

Essentially a "featured products"-esque block that will have 4 tabs.

# Answer
> 2 votes
So you need to do the following:

1) **Create a view for products**

2) **Create a taxonomy view**

* Create taxonomy view, set display as block, so you could output it in a block
* Add 'taxonomy term parent' filter and make it equal to 0. This way you'll select only parent terms
* Select Views Field View in Fields and set it to output a view for products
* Save

So now you should have a block which outputs parent taxonomy terms and under each term you have a list of products.

Let me know how it works.

---
Tags: 7, views, taxonomy-terms, entities, blocks
---


# Question
Title: Prevent cache when updating with field_attach_update
I have a problem with caching. I've set up a menu hook for an URL like `/user/USER_ID/some_info`, which automatically receives the entire user object because of the way I set up my menu hook (see below).

The problem I'm facing is that I have all caching modules enabled in Drupal (including EntityCache) and the `$usr` variable gets passed from the cache. So naturally if I update a field and save it using `field_attach_update`, the data is saved into the DB, but the old data is shown on the form, confusing the admins (the checkbox is checked, even though I just unchecked it, and it's value in the DB is in fact 0).

Is there a way I can disable caching for this particular object (`$usr`) in this particular function?

Note: on my local machine where caching is pretty much disabled, it works fine, both the UI and DB get updated.

My menu hook:

```
$items['user/%user/some_info'] = array(
    'title' => 'Some Info',
    'description' => 'Edit',
    'page callback' => 'mymodule_edit_user',
    'page arguments' => array(1),
    'access arguments' => array('administer users'),
    'file' => 'mymodule.pages.inc',
    'type' => MENU_LOCAL_TASK,
    'weight' => 8
);

```

The function that gets executed:

```
function mymodule_edit_user($usr){
    // check if POST and validation here
    if(isset($_POST['somefield'])) //checkbox
        $usr->field_somefield[LANGUAGE_NONE][0]['value'] = 1;
    else
        $usr->field_somefield[LANGUAGE_NONE][0]['value'] = 0;

    field_attach_update('user', $usr);
}

```

# Answer
Sorry I didn't do more digging before asking this, but going to answer my own question in case someone else finds this.

I've taken a look inside the `user_save` function, and seen that it does some invoking, so I did it too. Surprise: it worked (EntityCache was the bad guy who was caching everything BTW).

Here's my code for reference:

```
$usr->field_somefield[LANGUAGE_NONE][0]['value'] = 0;
field_attach_presave('user', $usr);
module_invoke_all('entity_presave', $usr, 'user');
module_invoke_all('entity_update', $usr, 'user');
field_attach_update('user', $usr);

```
> 2 votes

---
Tags: 7, caching
---


# Question
Title: Get default image directory with styles large?
My images are saved in folder

```
sites/all/default/files/styles/large/public/field/image

```

But to make this future save i dont want to hardwire the path? Is there a drupal function to get the images in a proper way? I played around with

```
image_style_url(uri)

```

But i just need the default dir to pass it to javascript, I dont have image uris yet...

Thanks a lot!

# Answer
> 1 votes
I'm not sure this will get you exactly what you want, but the 'default' path is just `public://`, so.

```
$url = image_style_url('large', 'public://');

```

will return

```
http://yoursite.com/sites/default/files/styles/large/public

```

I think it's more likely you're looking for a specific path, e.g.

```
$url = image_style_url('large', 'public://field/image');

```

which returns

```
http://yoursite.com/sites/default/files/styles/large/public/field/image

```

---
Tags: files
---


title: Custom jQuery scroll

text:
# Question
Title: Custom jQuery scroll
I'm new to drupal 7 and I'm having issues getting the smooth div scroll to work. What I'm going for is this! I also need it to be on every page of the site.

I downloaded the Zip file which is actually for this! I figured I'll alter the **js** and **css files** later. I placed in both sites/all/libraries and sites/all/modules. I copied the jquery-ui-1.8.23.custom.min file to /modules folder.

I then pasted this code to my template.php :

```
function best_responsive_preprocess_page(&$vars) {

//  if we are at frontpage, add some jquery code to do the animation
   if ($vars['is_front']) {
      drupal_add_js('sites/all/modules/jquery-ui-1.8.23.custom.min');
      drupal_add_js('sites/all/libraries/SmoothdivScroll/js/jquery.smoothdivscroll-1.3-min.js');
      drupal_add_css('sites/all/libraries/SmoothdivScroll/css/smoothDivScroll.css');
       $vars['script'] = drupal_get_js();
       $vars['styles'] = drupal_get_css();
   }
}

```

But that didn't do the trick.

What could be the issue here, or perhaps there is an another way to achieving this?

Many thanks.

# Answer
is your function called ? put a `drupal_set_message('hello');` in it to see.

remove these to lines, they're not needed

```
$vars['script'] = drupal_get_js();
$vars['styles'] = drupal_get_css();

```

then - you need to add some custom JS, where you tell which of your div should be modified:

```
drupal_add_js('jQuery(document).ready(function () { $("#logoParade").smoothDivScroll({
    autoScrollingMode: "always",
    autoScrollingDirection: "endlessLoopRight",
    autoScrollingStep: 1,
    autoScrollingInterval: 25
});

// Logo parade event handlers
$("#logoParade").bind("mouseover", function() {
    $(this).smoothDivScroll("stopAutoScrolling");
}).bind("mouseout", function() {
    $(this).smoothDivScroll("startAutoScrolling");
}); });', 'inline')

```

is this div already setup ?

else - add it in page.tpl.php or whereever you like to ..
> 0 votes

---
Tags: theming
---


title: wysiwyg editors malfuction

text:
# Question
Title: wysiwyg editors malfuction
First, the problem: I create a new Basic Page content with simple text and a couple of carriage returns, for example:

this
is
my
content.

I save the content using "Filtered HTML". When I then try to edit that content (still with "Filtered HTML") the content in the body of the editor has lost all the carriage returns (and formatting if applied) and looks like this:

this is my content.

If I save this content it still looks like the above.

This does not happen with the WYSIWYG module installed but no editor added. When I add TinyMCE and configure with any buttons, then I get the above problem. This also happens with CKEditor.

I've tried three new clean installs of test sites (two on my local server and one remote) and I get the same results when I try to configure an editor with WYSIWYG.

The only non-core modules I have installed are chaos tool and WYSIWYG.

Very perplexing. Can anyone help?

# Answer
> 0 votes
Put `<br/>` in view source mode of your field as your line separators.

---
Tags: wysiwyg
---


# Question
Title: Drupal7 - How to display both summary and body on full view?
It probably has an easy solution, but I couldn't figure out how. I have the original "Article" content type with an image and a summary field. Summary is readily displayed on front page, but in full view, only the body is displayed, but I want to display both the summary and the body. I will have articles where the summary is an eye-catch for the article, but I want to display and style it differently on the full view page too. I am free to edit templates or modify drupal settings so any method vill be fine with me.

Edit: I managed to print the summary with

```
print render($content['body']['#items'][0]['safe_summary']);

```

Is this a good way to print the summary?

# Answer
It would be better to use `print drupal_render( field_view_field('node', $node, 'safe_summary') );`.

This will also handle i18n.
> 1 votes

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


# Question
Title: Multiple AJAX "add more" buttons on one form, with default_value from db
I have a custom content type that contains multivalued string fields (one for primary education, one for secondary education and one for tertiary education).
In order for the user to enter multiple values for each field, I have an AJAX callback that creates additional textfield elements as per the code in the example module (with very minor modifications, to allow multiple such fields).

Adding and removing fields for fresh content works fine. However, the next step is to allow the user to edit such a node. When I specify default values for the fields (and the number entries for each field) the adding and removing fields stops working (I'm assuming it's because the elements get repopulated from database again, so the adding/removing gets overridden - See the `// LOAD ALL THE EXISTING VALUES FROM DB` code below).

Can anyone advise as to how I would be able to provide edit functionality to the user?

hook\_menu code:

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

  $items['education/edit/%'] = array(
    'title'            => 'Edit Education Information',
    'page callback'    => 'education_edit',
    'page arguments'   => array(2),
    'access arguments' => array('access content'),
    'type'             => MENU_CALLBACK,
);

```

The callback to load the form (and send along the node id):

```
function education_edit($id) {
  return drupal_get_form('education_form', $id);
}

```

The form:

```
function education_form($form, &$form_state, $id = '') {
  $form = array();

  if ($id != '') {
    $profile = node_load($id);
    if (isset($profile->field_education_id[$profile->language][0]['value'])) {
      $education = node_load($profile->field_education_id[$profile->language][0]['value']);

      if (isset($education->field_primary_education[$education->language])) {
        // LOAD ALL THE EXISTING VALUES FROM DB
        foreach ($education->field_primary_education[$education->language] as $v) {
          $form_state['values']['primary_fieldset']['primary_education'][] = $v['value'];
        }
        $form_state['num_primary'] = count($education->field_primary_education[$education->language]);
      }

     // SNIPPED SIMILAR CODE FOR SECONDARY AND TERTIARY EDUCATION

  }

  $form['#tree'] = TRUE;
  $form['profile_id'] = array(
    '#type'  => 'hidden',
    '#value' => $id,
  );

  $form['primary_fieldset'] = array(
    '#type'   => 'fieldset',
    '#title'  => t('Primary Education Institutions'),
    '#prefix' => '<div id="primary-fieldset-wrapper">',
    '#suffix' => '</div>',
  );

  // Build the fieldset with the proper number of primary education institutions. We'll use
  // $form_state['num_primary'] to determine the number of textfields to build.
  if (empty($form_state['num_primary'])) {
    $form_state['num_primary'] = 1;
  }
  for ($i = 0; $i < $form_state['num_primary']; $i++) {
    $form['primary_fieldset']['primary_education'][$i] = array(
      '#type'          => 'textfield',
      '#title'         => t('Primary Education'),
      '#default_value' => (isset($form_state['values']['primary_fieldset']['primary_education'][$i]) ?
        $form_state['values']['primary_fieldset']['primary_education'][$i] : ''),
    );
  }

  $form['primary_fieldset']['add_primary'] = array(
    '#type'   => 'submit',
    '#value'  => t('Add one more'),
    '#submit' => array('education_primary_add_more_add_one'),
    '#name'   => 'add_primary',
    '#ajax'   => array(
      'callback' => 'education_primary_add_more_callback',
      'wrapper' => 'primary-fieldset-wrapper',
    ),
  );

  if ($form_state['num_primary'] > 1) {
    $form['primary_fieldset']['remove_primary'] = array(
      '#type'   => 'submit',
      '#value'  => t('Remove one'),
      '#submit' => array('education_primary_add_more_remove_one'),
      '#name'   => 'remove_primary',
      '#ajax'   => array(
        'callback' => 'education_primary_add_more_callback',
        'wrapper'  => 'primary-fieldset-wrapper',
      ),
    );
  }

  // SNIPPED SIMILAR CODE FOR SECONDARY AND TERTIARY EDUCATION

  $form['submit'] = array(
    '#type'  => 'submit',
    '#value' => 'Save',
  );

  return $form;
}

```

Callback functions for adding/removing elements:

```
function education_primary_add_more_callback($form, $form_state) {
  return $form['primary_fieldset'];
}

function education_primary_add_more_add_one($form, &$form_state) {
  $form_state['num_primary']++;
  $form_state['rebuild'] = TRUE;
}
function education_primary_add_more_remove_one($form, &$form_state) {
  if ($form_state['num_primary'] > 1) {
    $form_state['num_primary']--;
  }
  $form_state['rebuild'] = TRUE;
}

```

PS: First post here ... so be gentle if I forgot to include some information :(

# Answer
Only do the load thing the first time the form is built, not when it is rebuilt because of the add/remove buttons - i.e. when `$form_state` is empty, or more explicitely, when the `$form_state['values']['primary_fieldset']` is not already set.

Also, in the add/remove submit handlers, instead of setting num\_primary to +1/-1, you should be able to directly add/remove an element in `$form_state['values']['primary_fieldset']['primary_education']`

And instead of setting `#tree` on the whole form, consider setting it on just the primary\_education subarray. That will simplify `$form_state['values']['primary_fieldset']['primary_education']` to `$form_state['values']['primary_education']` for example...
> 1 votes

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


title: How are menus rendered?

text:
# Question
Title: How are menus rendered?
When Drupal renders a menu, it shows only those links that the current user has the right to actually click on and visit. Instead of that behavior, I would like to see permissible pages as clickable links and non-permissible pages as non-clickable menu item titles, so that the user can see what they cannot yet click.

I have code that so far loads menu links and creates a list like this, but it doesn't support hierarchy, expanded/collapsed, site-wide menu theming, etc. because all it does is build a \<ul\> with a \<li\> item for each menu link title. If you want to look a the code so far, it's Foreshadow Menu (in my Github account). My goal is to render my version of the menu in a way that is consistent with and retains the features of the Drupal-rendered menus.

My question is: how does Drupal render menus? Specifically, how does it determine whether to show/hide a link? Does it use `show()` and `hide()` somewhere internally, where I could override and change the menu output? Or am I going about this all wrong?

# Answer
`_menu_tree_check_access()` should go a long way towards understanding what Drupal does internally.

It declares a new array of items, then loops through each item currently in the menu and checks access. Only if the current user has the correct access is the item added to the new array. At the end of the function, only the new array is returned. So Drupal's method is actually a bit more low-tech than I think you were going for.

Just so the process is a bit more obvious the functions are called in this order:

If you're looking to emulate the way Drupal builds its menus, I think `menu_build_tree()` is probably the best place to start.
> 2 votes

---
Tags: routes, users, theming
---


# Question
Title: How to display the output of my module without clearing cache and refresh page?
I created a very simple module which generates a tag cloud based on user input; you can see the code here.

```
// wow.module
function wow_menu() {
    $items = array();
    $items['wall/of/words'] = array(
        'title' => 'Wall of Words',
        'page callback' => 'wow_page',
        'access arguments' => array('access content'),
        'file' => 'wow.inc',
        'weight' => 1,
    );
    $items['admin/settings/wall/of/words'] = array(
        'title' => 'On this date module settings',
        'description' => 'Description of your On this date settings page',
        'page callback' => 'wow_admin_page',
        'page arguments' => array('wow_admin'),
        'access arguments' => array('administer wow settings'),
        'type' => MENU_NORMAL_ITEM,
    );
    return $items;
}

function wow_admin_page() {
    return 'hey';
}

// wow.inc
function wow_page() {
    $output = array(
        'form' => drupal_get_form('wow_cake'),
        'words' => _getWords(),
        'min_count' => 0,
        'max_count' => 999
    );
    drupal_add_js(drupal_get_path('module', 'wow') . '/js/jquery.tagcloud.js');
    drupal_add_js('jQuery(function(){jQuery("#wow-container .cloud a").tagcloud({size:{start:20,end:40,unit:"pt"},color:{start:"#46A7E3",end:"#0969A3"}})})', 'inline');
    return theme('wow_template', array('output' => $output));
}

function wow_theme($existing, $type, $theme, $path) {
    return array(
        'wow_template' => array(
            'template' => 'wow_template'
        ),
    );
}

function wow_cake($form, &$form_state) {
    $form = array();

    $form['title'] = array(
        '#type' => 'textfield',
        '#title' => t('Thank you for...'),
        '#size' => 60,
        '#maxlength' => 128,
        '#required' => TRUE,
    );

    $form['buttons']['submit'] = array(
        '#type' => 'submit',
        '#value' => t('Submit'),
    );
    return $form;
}

function wow_cake_validate(&$form, &$form_state) {

    if (empty($form_state['values']['title'])) {
        form_set_error('title', t('Please leave a thank you message in highlighted field below.'));
    }
}

function wow_cake_submit(&$form, &$form_state) {

    if (_create_node($form_state['values']['title'], $form_state['values']['title'])) {
        drupal_set_message(t('Thank you for your kind words!'), 'status');
    }
}

function _getWords() {
    $query = new EntityFieldQuery();
    $query->entityCondition('entity_type', 'node', '=')
            ->propertyCondition('status', 1, '=')
            ->propertyCondition('type', 'wall_of_words', '=');
    $result = $query->execute();
    $nodes = $result['node'];
    $fields = field_info_instances('node', 'wall_of_words');
    $field_id = $fields['body']['field_id'];
    field_attach_load('node', $nodes, FIELD_LOAD_CURRENT, array('field_id' => $field_id));
    $wall = '';

    foreach ($nodes as $node) {

        if (!empty($node->body['und']['0']['value'])) {

            $wall .= trim($node->body['und']['0']['value']);
            $wall .= " ";
        }
    }
    if (!empty($wall)) {
        $cloud = explode(" ", $wall);
    }

    return array_count_values($cloud);
}

function _create_node($title = "", $body = "", $language = "und") {

    $node = (object) array();
    $node->type = 'wall_of_words';
    $node->status = 1;
    $node->promote = 0;
    $node->sticky = 0;
    $node->revision = 0;
    $node->language = $language;
    $node->title = $title;
    $node->body[$language][0] = array(
        'value' => $body,
        'format' => 'full_html',
    );
    if ($node = node_submit($node)) {
        node_save($node);
    }

    return $node;
}

```

My issue: when I visit another page and come back to the page that I generated with my module the output of the content does not get displayed unless I clear the cache and visit the page again.

# Answer
> 0 votes
there's this method here :

drupal\_page\_is\_cacheable

actually i never used it, but cacheexclude module does, maybe you have to hook\_init too and check for your path there !

# Answer
> 0 votes
If you get different results between generating a page from scratch and fetching from cache, then that generally means that something in the page generation cycle is not stored in cache. The fact that cacheexclude does not solve the problem suggests that it isn't the page cache that's the problem.

One thing I note is that you are declaring a template for your output, but it's not shown. The declaration in your hook\_theme() function is missing the variables argument, so this may well be a theme-related problem.

On a stylistic note, all functions in a module should be named either modulename\_otherstuff or \_modulename\_otherstuff, to minimise the chance of duplicates.

---
Tags: 7, caching
---


# Question
Title: Drupal 6 CCK fields export/import in between environments
I have a Drupal 6 website that uses a lot of custom content types and along with a lot of CCK fields. Now with each new hotfix/patch/amendment new content types and CCK fields are added. Once the new code is developed in DEV Server it is moved to another to test. Then again after testing it is moved to QA then to the Production.

But with the increasing Content Types and CCK fields we are finding very hard to manage all those in moving to server to server. So I googled and found http://www.lullabot.com/articles/moving-cck-field-changes-from-dev-to-live But the problem is, this tutorial is based on Drupal 5 and an older version of devel module packaged with macro module. Now a days, macro is a separate module and it is not working as expected, its giving a lot of errors and the available patches are not able to solve it.

So is there any way to track all the Content Type Addition or Changes and the New Field or Existing Field addition or changes?

It would be really helpful if any solution is provided. Thanks!

# Answer
Take a look at the Features module. Exporting your CCK fields as a feature set creates a new module in which the fields are defined in code. You can then deploy the code to another server and enable the feature there. Every time you make a change you export the feature again to update its code, deploy it, then revert it on the other server.

Features is very useful, but takes some practice to get used to its limitations and quirks. Once you get past that point it'll save you a lot of time.
> 1 votes

---
Tags: nodes, entities
---


title: Which is the best form builder?

text:
# Question
Title: Which is the best form builder?
I'm pretty unsure which form builder I should use (Webform, Form Builder etc.)

Which one are you using? Which one is still updated and so on? I want to build a form and edit entries and show them on a drupal site.

# Answer
**Webform responses are NOT content!** Responses from the webform module cannot be placed into pages on your site; only administrator users can see results (or specific user roles). You can put answers into Views. (Maybe now that is possible.)

What you want to consider is either webform\_entity or the EntityForms module. When to use 1 of these modules is talked about on this docs page. These 2 modules make responses into entity content you can place as content on your site.

Also, webform\_entity or entity\_forms responses are NOT Drupal nodes; they are custom entities. You cannot moderate their content with say the Workbench module. Good luck auditing submissions before they are made live on your site.
> 4 votes

---
Tags: forms
---


# Question
Title: What's a good module for moderating content submissions?
Drupal 7.x. I'm looking for a module where it allows me to moderate any content submissions prior to them being published. For example:

I have writers, editors, and publishers groups. I want the writer to create the content, then the editors MUST look over the content to check for errors/mistypes, and THEN publishers take a last look and push the content to be published.

Is there a module that can handle this task for Drupal 7.x?

# Answer
> 3 votes
Perhaps Content Access will accomplish what you need. I am not sure of your exact workflow requirements.

# Answer
> 5 votes
The Workbench module will help you. You could set up some Rules to accomplish the same tasks.

# Answer
> 0 votes
Another good option to accomplish this is using the Workflow module.

# Answer
> 0 votes
And also you can simply use views, and make something like dashboard for anyone of your groups and add it to their menu (limit the access for other roles)

---
Tags: 7, users, nodes
---


title: Create a view of views?

text:
# Question
Title: Create a view of views?
I love Drupal views and tags but I'm having a bit of trouble figuring out how to do this.

We have several online seminars with multiple sessions in each.

For example: Refocusing on Family part 1, Refocusing on Family part 2, True Womanhood part 1, etc.

For each of these articles I have a view created that will return all the articles in that category.

For example, when you click on Refocusing on Family you get a page with teasers and links for:

* Refocusing on Family part 1
* Refocusing on Family part 2
* etc.

What I would like to do is create a new view (something like "Life Academy" for example) that had a description and link to each of the top level views (which, in turn, link to the articles).

So the user would go to the Life Academy page and see links and descriptions for Refocusing on Family, True Womanhood, and any future seminar groups. Clicking on these links will then take you to the view page (with links to the articles) for the appropriate group.

What I want to avoid is having to manually update the page every time a new seminar category is added.

Any help is greatly appreciated!

# Answer
Sounds like you just want a taxonomy term view. Then output the name field and and use the Rewrite Results, "Output this field as a link". You'll want to make the links for the other view predictable by using arguments like TID. Then you can set your link to use tokens like seminar/tid. I think you can use term name as well with a little bit of magic on the contextual filter.

If you just want to display all categories and seminars on the same page, create a view that outputs seminars and add the taxonomy term field. Then group by the term.
> 2 votes

---
Tags: views
---


# Question
Title: What (basically) does views/includes/plugins.inc line 9 views_include('base') actually do?
I ran into an issue today where I started getting the following white screen of death error:

> PHP Fatal error: Call to undefined function views\_include() in /\*/sites/all/modules/views/includes/plugins.inc on line 9

I found several various bug reports and questions with similar errors. Some said it was a bug in views, some said it was a bug in VBO, and some reported it being issues with a specific module (like finder) none of which am I really concerned about.

My question is, since most of the solutions had to do with either commenting or uncommenting a particular line. Line 9 in views/views/includes/plugins.inc `views_include('base')`, what does this line actually do? Furthermore, what is the harm/benefit of having it commented or uncommented?

For my personal part, I was able to comment out the line (which cleared the error) then clear my cache and uncomment the line without the error returning, which seems awfully bizarre.

I the code is generally something with including (libraries/functions?) for views plugins, but further explanation would be much appreciated.

# Answer
> 3 votes
From views.module:

```
/**
 * Include views .inc files as necessary.
 */
function views_include($file) {
  static $used = array();
  if (!isset($used[$file])) {
    require_once './' . drupal_get_path('module', 'views') . "/includes/$file.inc";
  }

  $used[$file] = TRUE;
}

```

so to your question, it is trying to load up base.inc out of the Views module includes directory. Unfortunately, for whatever reason, the views module itself doesn't appear to be loading up (and thus defining the function to begin with).

---
Tags: views
---


# Question
Title: Rate/VotingAPI - Add class to button if user has voted
I want to add a class to a button after the user has voted to display another picture.

This was posted here as a solution for Drupal 6.

```
<?php
  // Print all rate buttons
  foreach ($links as $link) {
    if ($results['user_vote'] == $link['value']) {
      // user has voted
      $class = 'voted';
    }
    else {
      // user has not voted
      $class = 'not-voted';
    }
    print theme('rate_button', $link['text'], $link['href'], $class);
  }
?>

```

I couldn't get it to work, so I assumed that I had to convert it to D7 first. However, I have no skills of converting code, so a little help would be nice.

# Answer
This change will only work for "Thumbs up" widget. You can place this code in your template.php under your custom theme or in a custom module.

```
function MODULE_NAME_OR_TEMPLATE_NAME_process_rate_template_thumbs_up(&$variables) {
  extract($variables);

  $classes = 'rate-thumbs-up-btn-up';

  if (isset($results['user_vote']) && $results['user_vote'] == $links[0]['value']) {
    $classes .= ' user-voted';
  } else {
    $classes .= ' user-not-voted';
  }

  $variables['up_button'] = theme('rate_button', array('text' => $links[0]['text'], 'href' => $links[0]['href'], 'class' => $classes));
}

```

Make sure to replace `MODULE_NAME_OR_TEMPLATE_NAME` with an actual template name or module name.
> 1 votes

---
Tags: 7, rating
---


title: Add line item showing total cost

text:
# Question
Title: Add line item showing total cost
How can I add a line item in Ubercart 2 that adds up the total cost of all items, not the sell price? I have tried to clone the generic line item hook, and add something like this for the callback:

```
for each($op->products as item){
  $cost += $item->cost;
}

```

I need this line item to appear in the cart (I'm using the ajax cart), in the order pane before the user completes checkout, and in the emails that the store owner and user get. Do I need to create a little module for this code outside of uc\_order? I don't remember the code exactly as it's on my work computer, but I think I'm putting it in the wrong place. Thanks for any pointers.

# Answer
> 1 votes
I created a line item using hook\_uc\_line\_item() then added the line item in the hook\_uc\_order().

Final products looks something like:

```
/*
 * Implement hook_uc_line_item()
 */
function my_module_uc_line_item() {

  $items[] = array(
    'id' => 'handling_fee',
    'title' => t('Handling Fee'),
    'weight' => 5,
    'stored' => TRUE,
    'calculated' => TRUE,
    'display_only' => FALSE,
  );
  return $items;
}

/**
 * Implement hook_uc_order()
 */
function my_module_uc_order($op, $order, $arg2) {

  // This is the handling fee. Add only if the user is a professional and there
  // are shippable products in the cart.
  if  ($op == 'save') {
    global $user;

    if (in_array('professional', array_values($user->roles))) {

      // Determine if the fee is needed. If their are shippable items in the cart.
      $needs_fee = FALSE;
      foreach ($order->products as $pid => $product) {
        if ($product->shippable) {
          $needs_fee = TRUE;
        }
      }

      $line_items = uc_order_load_line_items($order);

      // Determine if the fee has already been applied.
      $has_fee = FALSE;
      foreach ($line_items as $key => $line_item) {
        if ($line_item['type'] == 'handling_fee') {
          $has_fee = $line_item['line_item_id'];
        }
      }

      // If the cart does not already have the fee and their are shippable items
      // add them.
      if ($has_fee === FALSE && $needs_fee) {
        uc_order_line_item_add($order->order_id, 'handling_fee', "Handling Fee", 9.95 , 5, null);
      }
      // If it has a fee and does not need one delete the fee line item.
      elseif ($has_fee !== FALSE && !$needs_fee) {
        uc_order_delete_line_item($has_fee);
      }
    }
  }
}

```

---
Tags: ajax, ubercart
---


# Question
Title: Programatically retrieve a block and print it in a page
I have a form, generated by the Webform module, which is available as block. Now I want to retrieve the form itself and print it in a page.

How can I achieve this, programmatically? I'm using Drupal 7.

# Answer
I'm not sure on which page you want to print the block. This is an example that prints the block in a custom page.

```
/**
 * Implements hook_menu().
 */
function mymodule_menu() {
  $items = array();
  $items['my/page/path'] = array(
    'title' => 'Block in A Page',
    'page callback' => 'mymodule_block_page',
    'access callback' => TRUE,
  );

  return $items;
}

/**
 * The page callback which display the block
 */
function mymodule_block_page(){
  $block = module_invoke($module_name, 'block_view', $delta);

  return $block['content'];
}

```

`hook_menu()` registers a menu path which will display the block. `mymodule_block_page()` is invoked when the menu path is accessed like http://example.com/my/page/path.

`module_invoke($module_name, 'block_view', $delta);` will return the block ready to render. Please find out the module name and delta. I guess `$module_name` would be **webform**. If you go to the block configuration, e.g. admin/structure/block/manage/comment/recent/configure, the module name is *comment* and the delta is *recent*.

If you want to print the block on every page except the front page, create a variable in `hook_preprocess_page()` of template.php.

```
function MYTHEME_preprocess_page(&$variables) {
  if (!drupal_is_front_page()) {
    // It is not the front page.
    $block = block_load('module_name', 'block-delta');
    $variables['myblock'] = _block_get_renderable_array(_block_render_blocks(array($block)));
  }
}

```

In page.tpl.php, you can place the following code snippet where you want.

```
<?php if (isset($myblock)): ?>
  <?php print render($myblock); ?>
<?php endif; ?>

```
> 3 votes

---
Tags: 7, blocks
---


# Question
Title: Collapsing some fields in add content page
I want to use the drupal Collapse style for some fields.
For example: while writing a story in my drupal 7 site, on the content publishing form user will has an option like **"I want to sell this story"** Now, if the user click on it then some filed's will show-up like \[**Story Price**\] \[**Story License**\] \[**Topic Summary**\], so that they can provide all those necessary information's to sell the story. Either, if the user don't want to sell the story, they need not face those fields instead of **"I want to sell this story"** link! Any idea? Thanks

# Answer
> 1 votes
You could try the Field group module. You can set field group settings "collapsed" and deselect "Mark group for required fields". It collapsed the field group by default.

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

---
Tags: entities, theming, nodes
---


# Question
Title: Go to specific page in view using node id
I have a view composed of single nodes with a pager. Is there any way to link to a specific page in this view using the node id? I can see that the pager uses a page variable in the url, but that carries no information about the node. I can go to a specific node in the view using contextual filters, but if I don't want to filter the results, I just want to jump to a page in the pager by using the node id. Filtering makes the pager disappear (of course).

Is there a way to pass in a node id to the view, use that information to set the pager to that node, and not lose the pager?

# Answer
> 1 votes
You want to link to a node title thats in a view from another page, and not loose your pager ? (correct my summary if thats incorrect) ...

You can do this by using an `ID anchor` when building the link to the node.

If needed, use a Views field to output an html anchor per node title:

* add field Node NID, exclude from View output
* add field Node NID, rewrite HTML as `<a name=[node:nid]>`

Then build a link to your View including the anchor reference.

`$vars['view-scroll-to-node'] = l('some node title', '/your/view/path#'.$nid);`

---
Tags: 7, views, paging
---


# Question
Title: Ajax on Add another item of field collection
I'm calling an Ajax function in a field collection. But after hitting 'Add another item' button, form looses Ajax effect. I want to bind the Ajax with form event after clicking on 'Add another item' button. Can anyone help?

# Answer
Actually on reload of page Ajax looses its effect. So we solved this problem through form alter.

`$form['#after_build']` gives us all the detail after save so that helps to retrieve values again and filter.
> 1 votes

# Answer
Sounds like you need to use Drupal.behaviors and not just document.ready for your javascript.

> Drupal uses a "behaviors" system to provide a single mechanism for attaching JavaScript functionality to elements on a page. The benefit of having a single place for the behaviors is that they can be applied consistently when the page is first loaded and then when new content is added during AHAH/AJAX requests.

More info on Drupal.behaviors here
> 2 votes

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


title: Theme and subtheme basics

text:
# Question
Title: Theme and subtheme basics
I am a newbie to Drupal, and I really don't understand the difference between sub-theme and base theme. Why can't I directly edit the base theme?

I am working on a website which is live and has bartik as default theme. I don't know where to start.

# Answer
> 6 votes
You haven't really asked a question. But i'll assume that you want to know what a base and sub-theme is in drupal.

## **TLDR version**

A drupal subtheme inherits the template files (\*.tpl.php) and assets (javascript, css, images) of the base theme. If you need to modify or change the template files.

### **More on subthemes**

I think your best bet is to google it. I googled, "drupal subtheme" and found you drupal documentation regarding subthemes:

> Sub-themes are just like any other theme, with one difference: They inherit the parent theme's resources. There are no limits on the chaining capabilities connecting sub-themes to their parents. A sub-theme can be a child of another sub-theme, and it can be branched and organized however you see fit. This is what gives sub-themes great potential.

Source: Creating a sub-theme (drupal.org)

In addition to the node page, if you're more inclined to watch a video this is probably a good bet: Drupal Subthemes (youtube.com)

### **Why should you avoid modifying a base theme**

* Flexibility: Base themes maintain flexibility. If there is an update, your child theme inherit these changes
* Losing your changes: Modifying your base theme means that when an update to the theme comes along your modifications could potentially be lost
* Maintain simpler code base: The base theme allows you to abstract a lot of functionality and reduce the code base. This means less maintenance in the long run.

### **Best Practices with subthemes:**

* Copy files from the base theme or use the drush command (when available)
* Utilize subtheme theme hooks to override your theme

# Answer
> 0 votes
Besides the reasons stated on the other answer, you should not modify the base themes because of updates.

Think about a situation where you get a base theme and heavily modify it, then a bug, or worse a security bug is found in the base theme. If you apply the update, you will loose the changes made to that theme and if you don't apply the update, well who knows what could happen.

More here about upgrading and subtheming in general.

---
Tags: theming
---


# Question
Title: Deleted FAVICON from themes folder is showing up
**I have deleted the favicon.ico from the themes folder.**

**But its still showing up the same favicon**. I totally confused.

**Steps I have taken:** But nothing works... :-(

1. Checked whether I am in the right directory.
2. Cleared browsers cache.
3. Cleared Drupal Cache.
4. Use the default shortcut icon is checked. (No custom favicon selected)
5. favicon is located in the sites/all/themes/theme\_name/favicon.ico

Could you guys please advice me is there any other way to check or resolve.

Any help will be thankful and grateful...

# Answer
Now Its corrected...

**On Themes Global Settings I have mentioned the same favicon in differnet folder.**

Thats why the deleted favicon dispalyed even after deleting it from the themes folder.

Thanks for your efforts friends...
> 1 votes

---
Tags: 7
---


# Question
Title: How to define text css style in my themes folder to work with wysiwyg editor?
Bold text and Italic text are not working in ckeditor and I think it is because I have sites/all/themes/mytheme/styles/mytheme.css somehow not communicating with it.

Other text formats like strikethrough and underline are working fine for ckeditor.

So do I need to declare a property in mytheme.css to allow the editor to work?

I don't have the eric meyer reset file included or anything , just the add on css changes I made to my theme but don't see how that is stopping the strong and italic tags from not working because my changes were made for specific div ids.

# Answer
i usually add a separate .css file for the editors, this is only possible via the WYSIWYG module, in the settings of that text-format. you can even add special classes and block-formats the user can choose then.

to see what's happening, you can inspect the editor normally in your browser, and should see the problem.
> 0 votes

---
Tags: theming
---


# Question
Title: Migrate Drupal7 to local, user login link redirect to live, how to redirect it to local?
I have changed cookies name and base URL for my local environment, I have also emptied all cache tables, but still it redirects to the live site.

Like `http://server1/mysitename/user` to `https://www.mysitename/user`

# Answer
finally found my answer... by google search.. :)

```
UPDATE variable SET value = 's:1:"0";' WHERE name = 'securepages_enable';

```

pass this query in db and flush all cache.. :)
> 0 votes

# Answer
My guess is your using the secure login module.

Either:

```
drush vset securelogin_base_url "http://server1/mysitename/user"

```

or

```
drush dis securelogin

```
> 2 votes

---
Tags: users, uri
---


# Question
Title: POST request trying to make a Session authentication in the REST SERVER return a HTML error 406 Not acceptable
I have a REST server in drupal working. I get data if I go to the server endpoint.

In Navigator:

```
http://localhost/drupal-7.19/restserver/user/

```

Work fine.

I have created a PHP to make the Session authentication:

```
<?php
// REST Server URL

/*
* Server REST - user.login
*/

// REST Server URL
$request_url = "http://localhost/drupal-7.19/restserver/user/login";

// User data
$user_data = array(
  "username" => "test",
  "password" => "test",
);
$user_data = http_build_query($user_data);

// cURL
$curl = curl_init($request_url);
curl_setopt($curl, CURLOPT_HTTPHEADER, array("Accept: application/json")); // Accept JSON response
curl_setopt($curl, CURLOPT_POST, 1); // Do a regular HTTP POST
curl_setopt($curl, CURLOPT_POSTFIELDS, $user_data); // Set POST data
curl_setopt($curl, CURLOPT_HEADER, FALSE);  // Ask to not return Header
curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($curl, CURLOPT_FAILONERROR, TRUE);

$response = curl_exec($curl);
$http_code = curl_getinfo($curl, CURLINFO_HTTP_CODE);

// Check if login was successful
if ($http_code == 200) {
  // Convert json response as array
  $logged_user = json_decode($response);
}
else {
  // Get error msg
  $http_message = curl_error($curl);
  die($http_message);
}
echo "END php \n";

?>

```

But I getting this error:

```
TestAuth.php The requested URL returned error: 406

```

# Answer
> 1 votes
First of all make sure you choose the appropriate Data types for `request formatters` and `parsers` for your resource. You will find it under `admin/structure/services/list/your_resource_name/server`. Having said that, this works for me :

```
// .xml asks for xml data in response, choose what you need here
$service_url = 'http://localhost/your-endpoint/user/login.xml';
$post_data = array(
    'username' => 'admin',
    'password' => 'pass',
);
// We format post data as application/x-www-form-urlencoded so make
// sure that you tick it under the rest server parser options.
$post_data = http_build_query($post_data, '', '&');
// Initialize the request
$curl = curl_init($service_url);
// We want curl to return a string
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
// Choose method POST
curl_setopt($curl, CURLOPT_POST, true);
// Feed the data to POST to curl
curl_setopt($curl, CURLOPT_POSTFIELDS, $post_data);
// Make it verbose for debugging.
curl_setopt($curl, CURLOPT_VERBOSE, true);
// Go!
$response = curl_exec($curl);
curl_close($curl);
print "LOGIN RESPONSE:\n";
var_dump($response);
// parse the response we get (in XML see above)...

```

---
Tags: users, 8
---


# Question
Title: Is this possible to allow creating nodes only for Administrator via interface but for others in custom code?
As author of my content type I can choose any user (current user, even anonymous).

Nodes will created programmatically, so:

$node-\>uid = $current\_user-\>uid;

However I want to allow access to node/add/custom\_type (node form) only for Administrator or even block for everyone.

I am no totally sure that Drupal checks permissions before node\_save(), so that's why I am asking.

# Answer
> 2 votes
If what you are asking is...

How can I allow nodes of a certain type to be created programmatically by everyone, but, at the same time, disallow everyone but the Administrator from creating them from the UI?

...the quickest way might be for you to use Rules to create a redirect away from `node/add/custom_type` for everyone but the Administrator.

However, if you are already creating custom module code, you could also do this pretty simply in hoot\_init(), eg, something along the lines of:

```
global $user;
if ($_GET['q']=='node/add/custom_type') {
   if ($user->uid != 1) { // or whatever logic you want to use to determine the Administrator
     drupal_goto('somewhere else');
   }
}

```

In either case, you'd have to set up permissions to allow any user to create these types of nodes.

---
Tags: 7, nodes, users
---


title: How can I slideDown with #states?

text:
# Question
Title: How can I slideDown with #states?
I have a form using "#states" (in the Relation module), and it works, but it kind of jumps around. A nice slideDown would be so much better.

How can I do that instead of just making it visible?

# Answer
Building on Mike's post, the code above only made the element side down, not back up again. To get it to slide up and down I added e.stopPropagation(); so the full code is:

```
jQuery(document).ready(function($) {
    $('form.slide').bind('state:visible', function(e) {
        if(e.trigger) {
            $(e.target).closest('.form-item, .form-submit, .form-wrapper')[e.value ? 'slideDown' : 'slideUp']();
            e.stopPropagation();
        }
    });
});

```
> 3 votes

# Answer
I assume you're using the visible state?

The code that is responsible for doing this is in states.js:

```
$(document).bind('state:visible', function(e) {
    if (e.trigger) {
      $(e.target).closest('.form-item, .form-submit, .form-wrapper')[e.value ? 'show' : 'hide']();
    }
  });

```

As you can see, it calls show/hide without any configurable parameters, which means that it can't be easily changed.

However, the comment above that block is interesting:

```
/**
 * Global state change handlers. These are bound to "document" to cover all
 * elements whose state changes. Events sent to elements within the page
 * bubble up to these handlers. We use this system so that themes and modules
 * can override these state change handlers for particular parts of a page.
 */

```

If I understand this correctly, you can override the event handler for your specific page element, e.g. the form or even single form elements, by adding something like this:

```
$('form.your-form-class').bind('state:visible', function(e) {
  if (e.trigger) {
    $(e.target).closest('.form-item, .form-submit, .form-wrapper')[e.value ? 'slideDown' : 'slideUp']();
  }
});

```

I guess you will need to return FALSE to prevent that the event bubbles up further in the DOM tree.
> 10 votes

# Answer
Building on Berdir's post, I was able to tweak it and get it working in a custom module.

So in my .module file I added this line under the hook\_init() function

```
function er_init(){
    drupal_add_js('custom.js');
}

```

Then in the custom.js file,

```
jQuery(document).ready(function(){
  jQuery('form#user-profile-form').bind('state:visible', function(e) {
    if (e.trigger) {
      jQuery(e.target).closest('.form-item, .form-submit, .form-wrapper')[e.value ? 'fadeIn' : 'fadeOut']();
    }
});

```

})

Of course, in this case, it will only apply to the User Profile.
> 0 votes

---
Tags: javascript
---


# Question
Title: How to remove the status bar from CKeditor?
It seems that the module CKeditor doesn't offer in the UI the option to remove the status bar which includes the HTML path (eg: `body p strong`) and the re-size button.

# Answer
> 4 votes
I managed to remove the status bar for a profile (`admin/config/content/ckeditor/edit/some_profile`) by adding this code in **Advanced Settings** \> **Custom JavaScript configuration **:

```
config.removePlugins = 'elementspath';
config.resize_enabled = false;

```

Code found here on the CKeditor forum.

---
Tags: wysiwyg
---


# Question
Title: How to translate a view and keep contextual filters?
I'm building a bilingual website (French/English). I created the "user biography" for me to display later in the view. The biography is translated.

The view is called in the page : biography.php?id\_author=405 with a contextual filter (405 in this example). Now when we click to see the other language version, we are redirected to "biographie.php" (in french), but we lose the parameter.

How can i keep the parameter ?

Thanks

# Answer
I decided to "patch" the code, by adding the paramaters using Javascript.

```
 if($('.language-link').length > 0 && location.search != ""){
        $('.language-link').each(function(){
            var href = this.href;
            if (href.indexOf('?') != -1) {
                href = href + location.search;
              }
              else {
                href = href + location.search;
              }
              $(this).attr('href', href);
        });
    }

```
> 0 votes

---
Tags: views, i18n-l10n
---


# Question
Title: Drush minimal bootstrap only for variables for vget
How do you make drush bootstrap minimal. How do you specify the bootstrap method like DRUPAL\_BOOTSTRAP\_VARIABLES, DRUPAL\_BOOTSTRAP\_CONFIGURATION in the drush command?

**Background:**

I just want to have the drupal variable value in a shell script variable. I can use vget, but i donot want to make the full bootstrap.

# Answer
> 4 votes
The *general* answer to your question is that you cannot change the bootstrap level of a Drush command as a user; Drush has already specified the minimum bootstrap level in each command's command record. Running a command at a lower bootstrap than it needs will cause it to fail.

However, in the case of variable-get, it looks like you are correct. vget is set to use a full bootstrap, but it would probably work just fine with DRUSH\_BOOTSTRAP\_DRUPAL\_DATABASE. This could be classified as a Drush (performance) bug.

If you would like to help out here, you could submit an issue to the Drush issue queue. Add DRUSH\_BOOTSTRAP\_DRUPAL\_DATABASE to the variable commands, test it and post a patch, and the maintainers would be happy to commit it.

Here's what the record for variable-get would look like:

```
  $items['variable-get'] = array(
    'description' => 'Get a list of some or all site variables and values.',
    'arguments' => array(
      'name' => 'A string to filter the variables by. Variables whose name contains the string will be listed.',
    ),
    'examples' => array(
      'drush vget' => 'List all variables and values.',
      'drush vget user' => 'List all variables containing the string "user".',
      'drush vget site_mail --exact' => 'Show the variable with the exact key "site_mail".',
    ),
    'options' => array(
      'format' => array(
        'description' => 'Format to output the object. Use "print_r" for print_r (default), "export" for var_export, and "json" for JSON.',
        'example-value' => 'export',
      ),
      'pipe' => 'A synonym for --format=export. Useful for pasting into code.',
      'exact' => 'Only get the one variable that exactly matches the specified name.',
    ),
    'bootstrap' => DRUSH_BOOTSTRAP_DRUPAL_DATABASE,
    'aliases' => array('vget'),
  );

```

---
Tags: drush, bootstrapping
---